var cookiejar = $.cookieJar("cookiejar");

/*
function preloadimages(preloaddiv) {
  for (imageurl in [ "right-arrow-over.gif",
                     "left-arrow-over.gif",
                     "filter-stuffed-toys-on.gif",
                     "filter-pets-animals-on.gif",
                     "filter-collectibles-on.gif",
                     "filter-kids-babies-on.gif",
                     "filter-stuffed-toys-off.gif",
                     "filter-pets-animals-off.gif",
                     "filter-collectibles-off.gif",
                     "filter-kids-babies-off.gif",
                     "captcha-loading.gif",
                     "captcha-checking.gif",
                     "blank-captcha.gif"
                   ] )
    $(preloaddiv).append( $("<img>").attr("src","images/"+imageurl) )
}
*/

function refreshvotetable() {
  $("#votebuttons").load("create-vote-table.spyce?cutesterid="+cutesterid)
}

// cutesterid is declared outside
function vote(v) {
  $("#vote"+v).html("<small>sending&nbsp;&nbsp;<br/>vote...&nbsp;&nbsp;</small>")
  $.ajax( { url:     "cast-vote.spyce?cutesterid="+cutesterid+"&vote="+v,
            success: function(data) { refreshvotetable() },
            cache: false /* needed for IE!!!!! */
          } )

}

// cutesterid is declared outside
function updateprevnext() {
  $.ajax ( { url: "refresh-prev-next.spyce?cutesterid="+cutesterid,
             dataType: "json",
             success: function (data) {
                        $("#prevcutester a").attr("href","cutester"+data["previd"]+"/")
                        $("#nextcutester a").attr("href","cutester"+data["nextid"]+"/")
                        //~ $("#prevcutester").html("<a href='cutester"+data["previd"]+"'><img border='0' src='images/left-arrow.gif'></a>")
                        //~ $("#nextcutester").html("<a href='cutester"+data["nextid"]+"'><img border='0' src='images/right-arrow.gif'></a>")
                      }
            } )
}

function sharecutester() {
  $.post( "share-cutester.spyce",

          { cutesterid:cutesterid,
            captcha:$("#captchabox").val(),
            shareemail:$("#shareemail").val(),
            sharemessage:$("#sharemessage").val() },

          function(data) {
            switch (data["status"]) {
              case "WRONG_CAPTCHA_VAL":
                refreshcaptcha()
                break;
              case "OK":
                $("#captchabox").val("")
                $("#captchaimg").attr("src","images/captcha-loading.gif")
                $("#sharesubmitbtn").attr("disabled","true")
                $("#sharecancelbtn").css("display","none")
                hideshareform()
                resetshareform()
                break
            }
          },

          "json"
        )

}

function submitcomment() {
  $.post( "post-comment.spyce",

          { cutesterid:cutesterid , comment:$("#commentbox").val(), captcha:$("#captchabox").val() },

          function(data) {
            switch (data["status"]) {
              case "WRONG_CAPTCHA_VAL":
                refreshcaptcha()
                break;
              case "OK":
                $("#captchabox").val("")
                $("#captchaimg").attr("src","images/captcha-loading.gif")
                $("#commentsubmitbtn").attr("disabled","true")
                $("#commentcancelbtn").css("display","none")
                hidecommentform()
                resetcommentform()
                appendcomment(data["commentbody"],data["commenter"])
                break
            }
          },

          "json"
        )

}

function battlevote(battleid, cutesterid) {
  $.post( "cast-battle-vote.spyce",

          { battleid:battleid, cutesterid:cutesterid },

          function(data) {
            switch (data["status"]) {
              case "OK":
                location.reload(true)
                break
            }
          },

          "json"
        )
}


function confirmchallenge(id) {
  ok = confirm("Ya sure you wanna fight this cutester?")

  if(ok) {
    $.post( "create-challenge.spyce",
            { opponentid: cutesterid, challengerid: id },

            function(data) {
              switch (data["status"]) {
                case "OK":
                  $("#challengebox").css("display", "none")
                  $("#battlelink").html("<a href='battle.spyce?battleid="+data["battleid"]+"'>Click here to go to the battle</a>")
                  $("#challengestatus").css("display", "block")
                  break
              }
            },

            "json"
          )

  } else {
    alert("Chicken! :P")
  }
}

function showchallengers() {
  strChallengers = $("#challengeroster").html()

  if (strChallengers.length > 0) {
    /* do not get from the database again, just set display property */
    $("#challengebox").css("display", "block")
    return;
  }
  $.post( "show-challengers.spyce",
          { cutesterid: cutesterid },

          function(data) {
            switch (data["status"]) {
              case "COMPLETE":
                $("#challengeroster").html(data["itemscode"])
                $("#challengenote").css("display", "block")
                $("#challengebox").css("display", "block")
                break
              case "NO_CUTESTERS":
                $("#challengeroster").html("You don't have any cutesters that can battle with this cutester :( Remember: you can only battle cutesters under the same category as yours.<br/><br/><a href='addcandidate.php'>Click here to upload a cutester</a>")
                $("#challengenote").css("display", "none")
                $("#challengebox").css("display", "block")
                break
              case "INVALID_LOGIN":
                $("#challengeroster").html("You are not logged in. Please log in or <a href='register.php'>click here to register</a>")
                $("#challengenote").css("display", "none")
                $("#challengebox").css("display", "block")
                break
              default:
                $("#challengeroster").html("Error. Please contact meister [at] cutenotcute [dot] com to report the problem</a>")
                $("#challengenote").css("display", "none")
                $("#challengebox").css("display", "block")
                break
            }
          },

          "json"
        )
}

function hidechallengers() {
  $("#challengebox").css("display", "none")

}

var cb;

function resetembedradios() {
 $('#embedpiconly,#embedvotecard,embedchallengecard').attr('checked', '');
}

function showembedform() {
  if (window.pageYOffset<265 && window.innerHeight<850) window.scrollTo(0,305)
  hidecommentform()
  hideshareform()
  $("#captchadiv").hide("fast")
  $("#embedform").show("slow")
}

function hideembedform() {
  $("#battlecard").hide("fast")
  $("#embedform").hide("fast")
  $("#leftembeddiv").hide("fast")
  $("#embedform").css("padding-bottom", "10px")
  resetembedradios()
}

function showcode(filepath) {
  $("#leftembeddiv").show("fast")
  $("#embedcode").val("<a href=\"http://www.cutenotcute.com/cutester"+cutesterid+"\"><img src=\"http://www.cutenotcute.com/pics/"+filepath+"\" /></a>")
  $("#embedcode").show("fast")
  $("#battlecard").html("Will look like:<br/><img src='pics/"+filepath+"' width='140' alt='Loading...' />")
  $("#battlecard").show("fast")
  $("#embedform").css("padding-bottom", "205px")
}

function showcard(type) {
  $("#leftembeddiv").show("fast")
  $("#embedcode").val("<a href=\"http://www.cutenotcute.com/cutester"+cutesterid+"\"><img src=\"http://www.cutenotcute.com/show-battle-card.php?id="+cutesterid+"&type="+type+"\" /></a>")
  $("#embedcode").show("fast")
  $("#battlecard").html("Will look like:<br/><img src='show-battle-card.php?id="+cutesterid+"&type="+type+"' width='140' alt='Loading...' />")
  $("#battlecard").show("fast")
  $("#embedform").css("padding-bottom", "205px")
}

function showshareform() {
  if (window.pageYOffset<265 && window.innerHeight<850) window.scrollTo(0,265)

  hidecommentform()
  hideembedform()

  if ($("#captchabox").val()) {
    $("#shareform").show("slow")
    $("#shareemail").focus()
  } else {
    getcaptchaval()
    cb=showshareform
  }
}

function showcommentform() {
  if (window.pageYOffset<265 && window.innerHeight<850) window.scrollTo(0,265)

  hideshareform()
  hideembedform()

  if ($("#captchabox").val()) {
    $("#commentform").show("slow")
    $("#commentbox").focus()
  } else {
    cb=showcommentform
    getcaptchaval()
  }
}

function hideshareform(speed)  {
  if (speed) $("#shareform").hide(speed)
  else       $("#shareform").hide("slow")
}

function hidecommentform(speed) {
  if (speed) $("#commentform").hide(speed)
  else       $("#commentform").hide("slow")
}

function resetshareform() {
  $("#sharesubmitbtn").removeAttr("disabled")
  $("#sharecancelbtn").css("display","inline")
  $("#sharemsbbox").val("")
}

function resetcommentform() {
  $("#commentsubmitbtn").removeAttr("disabled")
  $("#commentcancelbtn").css("display","inline")
  $("#commentbox").val("")
}

function getcaptchaval() {
  refreshcaptcha()
  $("#captchadiv").show("fast")
  $("#captchabox").focus()
}

function captchaentered() {
  if ($("#captchabox").val().length==2) {
    $("#captchaimg").attr("src","images/captcha-checking.gif")
    captchaval=$("#captchabox").val()
    $("#captchabox").val("")
    $.post ( "verify-captcha.spyce",
             { captcha:captchaval },
             function(data) {
               if (data["status"]=="OK") {
                 $("#captchadiv").hide("slow")
                 $("#captchabox").val(captchaval)
                 cb()
               } else
                 refreshcaptcha()
             },
             "json"
           )
  }
}



function refreshcaptcha() {
  $("#captchaimg").attr("src","images/captcha-loading.gif")
  $.ajax( { url:      "gen-captcha-val.spyce",
            dataType: "json",
            success:  function(data) {
                        $("#captchabox").val("");
                        $("#captchaimg").attr("src","captcha-img.php?chars="+data["captchaval"]) }
          } )
}



function appendcomment(commentbody,commentername) {
  $("#commentsdiv .commentbox:last ").after(
      "<div class='commentbox'><div class='commentbody'>"+
      "<b>"+commentername+"</b> said...<br/>"+
      "<div style='margin-top:5px'>"+commentbody+"</div>"+
      "</div></div>"
    )
}


function cancellogin() {
  $("#loginform").hide("slow")
  $("#loginmsg").html("")
  $("#loginmsg").css("display","none")
}


function submitlogin() {
  $("#loginmsg").html("Please Wait... Checking your Login Info")
  $("#loginmsg").css("display","inline")

  $.post( "login.spyce",

          { useremail:$("#useremail").val(), password:$("#password").val()},

          function(data) {
            switch (data["status"]) {
              case "OK":
                //window.location.href="http://www.cutenotcute.com/random-cutester.spyce" //reload()
                $("#loginmsg").html("OK! Logging you in...")
                $("#loginmsg").css("display","inline")
                $("#loginmsg").css("color","green")
                location.reload(true)
                break
              case "INVALID_USER":
                $("#loginmsg").html("Invalid Login")
                $("#loginmsg").css("display","inline")
                break
              case "INVALID_PASSWORD":
                $("#loginmsg").html("Invalid Login - <a style='color:red' href='email-password.php?email="+$("#useremail").val()+"'>Email my password</a>")
                $("#loginmsg").css("display","inline")
                break
            }
          },

          "json"
        )

}
