var curpage=0, bVacation=0, bLevelBlock=0, bLoggedin=0, bNeedAddress=0, bReady4CB=0, showhelp=0, initcalled=0;
var t=0, currTID = 0, currStatus="", el2updt=0;
var arrAllGames=new Array();
var bHaveGameData=false,bListChanged=false;
var arrFoundGames=new Array();
var arrGamesNoLongerHad=new Array();
var arrGamesOwned=new Array(), arrGamesWanted=new Array();
var modalDlg=null;
$j.ajaxSetup({
  timeout: 15000  
});
function onOfferListcheckbox(hid,value) {
  $j.ajax({
    type: "POST",
    url: "/proc.php",
    data: "action=offer_game&hid="+hid+"&value="+value,
    success: function(resp){},
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert("Although truely regrettable, an error prevented your library from being modified. Please try again.");
    }
  }); 
}
function onTradeResp(tid, s, el) {
  if(tid == -1){
    tid = currTID;
  }else{
    currTID = tid;
  }
  currStatus = s;
  if(s == 'intransit'){
    postTradeStatus(tid, s, 0);
    cbTradeResp(tid, s, el, "")
  }else{
    bReady4CB=0;
    //Slower but smoother on most browsers to finish the transition before posting
    $j(el).fadeOut("fast",function(){
      $j(this).html(document.getElementById("tradectlswait").innerHTML);
      $j(this).fadeIn("fast");
      postTradeStatus(tid, s, cbTradeResp);
      bReady4CB=1;
    });
  }
}

function cbTradeResp(tid, s, el, response){
  //alert("In callback cbTradeResp tid="+tid+" state="+s+" resp="+response);
  try{
    if(response){
      var tempstr ="resp = "+response;
      eval(tempstr);
    }else{
      resp = {"s": "OK"};
    }
    if(el){
      if(resp.s == "OK"){
        if(s == 'accepted'){
          $j(el).fadeOut("medium",function(){
            $j(this).html(document.getElementById("offeraccepted").innerHTML);
            $j(this).fadeIn("medium");
          });
        }else if(s == 'delete'){
          $j(el).fadeOut("medium",function(){
            $j(this).html("This trade has been deleted.");
            $j(this).fadeIn("medium");
          });    
        }else if(s == 'rejected'){
          $j(el).fadeOut("medium",function(){
            $j(this).html(document.getElementById("offerrejected").innerHTML);
            $j(this).fadeIn("medium");
          });
        }else if(s == 'intransit'){
          if($j(el).parents(".offer").find(".get_product").find(".cost").length){
            $j(el).fadeOut("medium",function(){
              $j(this).html(document.getElementById("otherwillsend").innerHTML);
              $j(this).find(".otheruser").html( $j(el).parents(".offer").find(".get_product").find(".userhandle").html() );
              $j(this).fadeIn("medium");
            });            
          }else{
            $j(el).fadeOut("medium",function(){
              $j(this).html(document.getElementById("haveyoureceived").innerHTML);
              unregisterTIPControls();
              registerTIPControls();
              $j(this).fadeIn("medium");
            });
          }
        }else if(s == 'executed'){
          $j(el).fadeOut("medium",function(){
            $j(this).html(document.getElementById("rateui").innerHTML);
            unregisterTIPControls();
            registerTIPControls();
            $j(this).fadeIn("medium");
          });    
        }else{
          $j(el).fadeOut("medium",function(){
            $j(this).html("Thank you for responding");
            $j(this).fadeIn("medium");
          });
        }
      }else{
        var eltoshow = "tradectlsfailed";
        if(s == 'executed'){
          eltoshow = "receivedbeforesent";
        }else if(s == 'delete'){
          eltoshow = "toolatetodelete";
        }else if(s == 'rejected'){
          eltoshow = "rejectfailed";
        }
        $j(el).fadeOut("medium",function(){
          $j(this).html(document.getElementById(eltoshow).innerHTML);
          $j(this).fadeIn("medium");
        });
      }
    }
  }catch(e){
    alert("Sorry, your action was not processed due to an error. Please reload the page and try again.");
  }  
}

function onMakeOffer(myiid, otheriid, el){
  if(bVacation){
    $j("#vacationblock_dlg").css("left", $j(el).offset().left-150);
    $j("#vacationblock_dlg").css("top", $j(el).offset().top-150);
    $j("#vacationblock_dlg").fadeIn("fast");
    $j("#vacationblock_dlg .btn-close").click(function(){
      $j("#vacationblock_dlg").fadeOut("fast");
      $j("#vacationblock_dlg .btn-close").unbind('click');
    });
    return;
  }
  if(bNeedAddress){
    $j(".w_popup_enter_email").css("left", $j(el).offset().left-250);
    $j(".w_popup_enter_email").css("top", $j(el).offset().top-50);
    $j(".w_popup_enter_email").css("z-index", 1000);
    $j(".w_popup_enter_email").fadeIn("fast");
    $j(".w_popup_enter_email .btn-close").click(function(){
      $j(".w_popup_enter_email").fadeOut("fast");
      $j(".w_popup_enter_email .btn-close").unbind('click');
    });
    return;
  }
  if(bLevelBlock){
    $j("#levelblock_dlg").css("left", $j(el).offset().left-150);
    $j("#levelblock_dlg").css("top", $j(el).offset().top-150);
    $j("#levelblock_dlg").fadeIn("fast");
    $j("#levelblock_dlg .btn-close").click(function(){
      $j("#levelblock_dlg").fadeOut("fast");
      $j("#levelblock_dlg .btn-close").unbind('click');
    });
    return;
  }  
  window.ptmyiid = myiid;
  window.otheriid = otheriid;
  window.moel = el;
  if(window.noconfonmo){
    onMakeOfferConfirmed();
    $j("#makeoffer_dlg").css("display", "none");
  }else{
    showMakeOfferDlg(el);
  }
}
function onMakeOfferConfirmed(){
  postMakeOffer($j("#fc_makeoffer_hide").attr("checked"));
  $j("#makeoffer_dlg").css("display", "none");
  if(window.moel){
    //window.moel.parentNode.innerHTML = document.getElementById("offermade").innerHTML;
    $j(window.moel.parentNode).fadeOut("slow",function(){
      $j(this).html(document.getElementById("offermade").innerHTML);
      $j(this).fadeIn("slow");
    });        
  }
}
function onClearOffer(myiid, otheriid, el){
  window.ptmyiid = myiid;
  window.otheriid = otheriid;
  window.coel = el;
  toggleClearTradeDlg(el);
}
function onClearForever(){
  postClearOffer("permanent");
  $j("#popup_clear_dlg").css("display", "none");
  if(window.coel){
    //window.coel.parentNode.innerHTML = document.getElementById("offercleared").innerHTML;
    $j(window.coel.parentNode).fadeOut("slow",function(){
      $j(this).html(document.getElementById("offercleared").innerHTML);
      $j(this).fadeIn("slow");
    });
  }
}
function onClear7days(){
  postClearOffer("temporary");
  $j("#popup_clear_dlg").css("display", "none");
  if(window.coel){
    //window.coel.parentNode.innerHTML = document.getElementById("offercleared").innerHTML;
    $j(window.coel.parentNode).fadeOut("slow",function(){
      $j(this).html(document.getElementById("offercleared").innerHTML);
      $j(this).fadeIn("slow");
    });    
  }
  
}
function postMakeOffer(setconfirmoff){
  var ncomo = setconfirmoff?"1":"0";
  if(ncomo)
    window.noconfonmo = ncomo;
  $j.ajax({
    type: "POST",
    url: "/proc.php",
    data: "action=set_trade2&mygameid="+window.ptmyiid+"&othergameid="+window.otheriid+"&noconfonmo="+ncomo,
    success: function(resp){},
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert("There was an error when trying to create this trade Please reload the page and try again.");
    }
  });
}
function postClearOffer(type){
  $j.ajax({
    type: "POST",
    url: "/proc.php",
    data: "action=set_make_offer_filter&myiid="+window.ptmyiid+"&otheriid="+window.otheriid+"&type="+type,
    success: function(resp){},
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert("There was an error when trying to create this trade Please reload the page and try again.");
    }
 });  
}
function postTradeStatus(tid, s, cb) {
  window.tid = tid;
  if(s == "delete"){
    $j.ajax({
      type: "POST",
      url: "/proc.php",
      data: "action=delete_trade&tid="+tid,
      success: function(resp){
        if(cb){
          if(bReady4CB){
            cb(window.tid, currStatus, window.el2updt, resp);
            bReady4CB = 0;
          }else{
            window.resp = resp;
            callCB();
          }          
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("There was an error when trying to submit your response to this trade. Please reload the page and try again.");
      }
   });
  }else{
    //alert("Going to AJAX post to the server.");
    var datatosend="";
    if(s == "rejected"){
      var otheriid = $j(window.el2updt).parents(".offer").find(".get_product").find(".iid").html();
      var myiid = $j(window.el2updt).parents(".offer").find(".give_product").find(".iid").html();
      datatosend = "action=set_offer_filter&myiid="+myiid+"&otheriid="+otheriid+"&type=temporary&page=acceptoffer";
    }else{
      datatosend = "action=set_trade_status&status="+s+"&tid="+tid;
    }
    
    $j.ajax({
      type: "POST",
      url: "/proc.php",
      data: datatosend,
      success: function(resp){
        //alert("the server has responded.");
        if(cb){
          //alert("the server has responded. cb=1. sync var="+bReady4CB+" window.tid="+window.tid);
          if(bReady4CB){
            cb(window.tid, currStatus, window.el2updt, resp);
            bReady4CB = 0;
          }else{
            window.resp = resp;
            callCB();
          }
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("There was an error when trying to submit your response to this trade. Please reload the page and try again.");
      }
   });
  }
}
function callCB(){
  //alert("In callCB with sync var="+bReady4CB);
  if(bReady4CB){
    cbTradeResp(window.tid, currStatus, window.el2updt, window.resp);
    bReady4CB = 0;
  }else{
    setTimeout("callCB()", 300);
  }
}
function nextPrintLabelStep(tid){
  document.getElementById("container").style.cursor="wait";
  $j.ajax({
    type: "POST",
    url: "/proc.php",
    data: "action=haspaidforlabel&tid="+tid,
    success: function(resp){
      document.getElementById("container").style.cursor="default";
      var tempstr ="res = "+resp;
      eval(tempstr);
      if(res.s == "OK" && res.paid){
        onclickPrintLabelWithPostage();
      }else{
        $j(".popup_print_label").css("display", "block");
      }
      },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert("There was an error when trying to submit your response to this trade. Please reload the page and try again.");
    }
 });

  
}
// END: AJAX for trade accept/reject
//------------------------------------

var handleSuccessReportDlg = function(o) {
	var response = o.responseText; 
	alert(response);
};
var  handleFailureReportDlg = function(o) {
	alert("Submission failed: " + o.status);
};
function showReportDlg(trade_id) {

	if ( document.getElementById("trade_issue_id") != null){
		var form_input = document.getElementById("trade_issue_id");
		form_input.value = trade_id;
	}
    YAHOO.container.reportdlg.show();
}
function onClickReportLink(trade_id,e1){
    showReportDlg(trade_id);
	handleReport(e1);
}
function handleReport(el){
    el.parentNode.parentNode.innerHTML = "Trade in dispute.";
}

function showPrintLabelDlg(tid) {
  currTID = tid; 
  YAHOO.container.printlabeldlg.show();
}
function handleCancelPrintLabelDlg() {
  YAHOO.container.printlabeldlg.hide();
}
function handleFailurePrintLabelDlg(){
}
function onclickPrintLabel(){
  $j(".popup_print_label").css("display", "none");
  window.open("/printlabel.php?postage=0&tid="+currTID, "AddressWindow", "status=0, resizable=1, scrollbars=0, toolbar=1, location=0, menubar=1, directories=0, height=250 width=400");
}
function onclickPrintLabelWithPostage(){
  $j(".popup_print_label").css("display", "none");
  window.open("/printlabel.php?postage=1&tid="+currTID, "AddressWindow", "status=0, resizable=1, scrollbars=1, toolbar=1, location=1, menubar=1, directories=0, height=600 width=400");
}

//XXRW  Login script moved here
function Login(){
  var state 		= document.getElementById('lss');
  if(parseInt(state.value))
    return false;
  state.value = 1;
  
	var key 		= document.getElementById('key');
	var handle 		= document.getElementById('handle');
	var password 	= document.getElementById('password');
	var login_message = document.getElementById('login_message');
	var indicator 	= document.getElementById('indicator');
  $j.ajax({
    type: "POST",
    url: "/proc.php",
    data: "action=login&getkey=1&handle="+handle.value,
    success: function(resp){
      if(resp !== undefined){
        var handle_lower=handle.value;
        handle_lower=handle_lower.toLowerCase();
        var code_string = handle_lower+'|'+password.value+'|'+resp.replace(/^\s*|\s(?=\s)|\s*$/g, "");
        key.value=MD5(code_string);
        password.value='';
        document.login_form.submit();
      }      
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert("There was an error when trying to log you in. Please reload the page and try again.");
    }
  });
	return false;
}
/* --------------------------------------- */
/* begin: WANT PAGE  */
  function onRemove(id) {
    document.getElementById("fc_action").value = "wantlist_del";
    document.getElementById("fc_wantid").value = id;
    document.getElementById("wantlistform").submit();
  }
  function onMoveToTop(wantid) {
    document.getElementById("fc_action").value = "wantlist_movetotop";
    document.getElementById("fc_wantid").value = id;
    document.getElementById("wantlistform").submit();
  }
  function onMoveToTop2(iid) {
    document.getElementById("fc_action").value = "wantlist_movetotop2";
    document.getElementById("fc_iid").value = iid;
    document.getElementById("wantlistform").submit();
  }  
  function handleOnSubmit(){
    var found=true,i,n,el;
    for (i=0;found;i++) {
        try{
            el = document.getElementById("in_"+i);
            el.value = el.value-1;
        }catch(e){
            found = false;
            break;
        }
    }
    return true;
  }
/* end: WANT PAGE  */
function launchACW(step){
  var strElId = "#popup_step"+step;
  if( step==2 || step==3 ){
    $j.ajax({
      type: "GET",
      url: "/userdata.js.php",
      dataType: "script",
      async: false
    });
    if(step == 2){
      curpage=2;
      getGameInfo();
      setTimeout("renderSelectedList(arrGamesOwned,'selectedlist','have')",50);
    }
    if(step == 3){
      curpage=3;
      getGameInfo();
      setTimeout("renderSelectedList(arrGamesWanted, 'selectedlist','want')",50);
    }
    $j(strElId).addClass("activedlg");
    $j(".activedlg .acw_btn_next").click(function(){
      if($j(this).parents("#popup_step2").length || $j(this).parents("#popup_step3").length){
        if(!$j(this).parents(".popup_container").find(".gameadded").length){
          $j(this).parents(".popup_container").find(".acw_error_msg").html("Whoa there cowboy, you didn't enter any games. Please enter at least one game to continue.");
          $j(this).parents(".popup_container").find(".acw_error_msg").slideDown("normal");
          return;
        }
      }
      nextpageACW(curpage+1)
    }); 
    $j(".activedlg #searchbox").keyup(function(){
      onSearckKeyHit();
    });
  }
  $j("#popup_step4 .done").click(function(){
    submitACW();
    //document.accupdate.submit();
  });  
  modalDlg = $j(strElId).modal();
  if(step==1){
    $j("#frm_name").select();
  }
}
function nextpageACW(step){
  hideWizardPage()
  curpage=step;
  getGameInfo();
  if(step == 2){
    setTimeout("renderSelectedList(arrGamesOwned,'selectedlist','have')",50);
  }else if(step == 3){
    setTimeout("renderSelectedList(arrGamesWanted, 'selectedlist','want')",50);
  }  
  showWizardPage("#popup_step"+step);
  /*curpage=3;
  $j(strElId).addClass("activedlg");
  $j(strElId).modal();*/
}
function hideWizardPage(){
  $j(".activedlg .acw_btn_next").unbind('click');
  if(modalDlg)
    modalDlg.close();
  var strElId = "#popup_step"+curpage;
  $j(strElId).removeClass("activedlg");
}
function showWizardPage(strId){
  $j(strId).addClass("activedlg");
  $j(".activedlg .acw_btn_next").click(function(){
    //if($j(this).parents("#popup_step2").length || $j(this).parents("#popup_step3").length){
    if($j(this).parents("#popup_step"+curpage).length){
      if(!$j(this).parents(".popup_container").find(".gameadded").length){
        $j(this).parents(".popup_container").find(".acw_error_msg").html("Whoa there cowboy, you didn't enter any games. Please enter at least one game to continue.");
        $j(this).parents(".popup_container").find(".acw_error_msg").slideDown("normal");
        return;
      }
    }    
    nextpageACW(curpage+1)
  });
  $j(".activedlg #searchbox").keyup(function(){
    onSearckKeyHit();
  });
  modalDlg = $j(strId).modal();
}
function submitACW(){
  if( $j("#popup_step4 input:visible[value!='']").length ){
    document.accupdate.submit();
  }else{
    if(modalDlg)
      modalDlg.close();
    document.location.href = "/index.php";
  }
}
/* Begin: Account creation, Have, Want  */
  function findGames(str){
    //var re = new RegExp("\"+str+"\i");
    if(str.length < 3){
      arrFoundGames.length = 0;
      return;
    }
    var re = new RegExp(str,"i");
    arrFoundGames.length = 0;
    //str = "/"+str+"/";
    for (var i=0,j=0,k=0;(i<arrAllGames.length);i++) {
      if(arrAllGames[i].n.match(re)){
        arrFoundGames.push(i);
        j++;
      }
      if(j>30)
        break;
    }
    //alert("ending search with i="+i+"  j="+j);
  }
  function renderFoundGames(page, pagesize){
    //var el = document.getElementById('foundgames');
    //$j(".activedlg #foundgames").empty();
    var el = $j(".activedlg #foundgames");
    el.empty();
    var platforms = new Array();
    platforms = {0:"360", 1:"PS3",2:"DS",3:"PSP",4:"PS2",5:"XBOX",6:"GBA",7:"GC",8:"WII"};
    var outstr="";
    //alert("Found "+arrFoundGames.length+"games");
    if(!arrFoundGames.length){
        outstr +=
          '<tr class="gamefound">'+
          '  <td class="column1">no results</td>'+
          '  <td class="column2"></td>'+
          '  <td class="column3"></td>'+
          '</tr>';
    }else{
      var cl="btn-add";
      for(var i=page*pagesize, j=0; ((i<arrFoundGames.length)&&(i<page*pagesize+pagesize)); i++){
        var row = el[0].insertRow(j);
        row.className="gamefound";
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);
        if(!i) row.className = "first gamefound";
        cell1.className="column1";
        cell1.innerHTML = arrAllGames[arrFoundGames[i]].n;
        cell2.className="column2";
        cell2.innerHTML = platforms[parseInt(arrAllGames[arrFoundGames[i]].t)-1];
        cell3.className="column3";
        if((window.curpage == 2) || (window.curpage == 100)){
          if(isIdInArray(arrAllGames[arrFoundGames[i]].id,arrGamesOwned))
            cl="btn-add-disabled";
          else
            cl="btn-add";
          cell3.innerHTML = '<div class="popup_wrapper"><a class="'+cl+'" href="javascript:void(0)" title="Add" onclick="onAddHaveBtn(this,'+arrFoundGames[i]+');" >Add<span></span></a></div>';
        }else{
          if(isIdInArray(arrAllGames[arrFoundGames[i]].id,arrGamesWanted))
            cl="btn-add-disabled";
          else
            cl="btn-add";
          cell3.innerHTML = '<div class="popup_wrapper"><a class="'+cl+'" href="javascript:void(0)" title="Add" onclick="addIndexedGameToWantList(this, '+arrFoundGames[i]+');selSearchBox();" >Add<span></span></a></div>';
        }
        j++;  
      }
    }
  }
  function selSearchBox(){
    var el = $j(".activedlg #searchbox")[0];
    if(el){
      el.focus();
      el.select();
    }
  }
  function handleGameString(str){
    //alert("I'm in handleGameString with: "+str);
    findGames(str);
    renderFoundGames(0, 30);
  }
  
  function onSearckKeyHit(e)
  {
    //var el = document.getElementById('searchbox');
    //if(!el) return false;
    var str = $j(".activedlg #searchbox").attr("value");
    clearTimeout(t);
    t = setTimeout("handleGameString('"+str+"')",500);
  }
  function addIndexedGameToHaveList(idx){
    var bInArr = false;
    for(var i=0; i<arrGamesOwned.length; i++){
      if(arrGamesOwned[i].id == arrAllGames[idx].id){
        bInArr = true;
        break;
      }
    }
    if(!bInArr){
      addGameToHaveList(arrAllGames[idx].id);
      arrGamesOwned.push(arrAllGames[idx]);
      bListChanged=true;
      renderSelectedList(arrGamesOwned,'selectedlist','have');
    }
  }
  function addGameToHaveList(id){
     $j.ajax({
      type: "POST",
      url: "/proc.php",
      data: "action=addgametohavelist&iid="+id
    });
  }
  function addIndexedGameToWantList(el, idx){
    var bInArr = false;
    for(var i=0; i<arrGamesWanted.length; i++){
      if(arrGamesWanted[i].id == arrAllGames[idx].id){
        bInArr = true;
        break;
      }
    }
    if(!bInArr){
      addGameToWantList(arrAllGames[idx].id);
      arrGamesWanted.push(arrAllGames[idx]);
      bListChanged=true;
      renderSelectedList(arrGamesWanted, 'selectedlist','want');
      $j(el).removeClass("btn-add");
      $j(el).addClass("btn-add-disabled");
    }
  }
  function addGameToWantList(id){
     $j.ajax({
      type: "POST",
      url: "/proc.php",
      data: "action=addgametowantlist&iid="+id
    });
  }  
  function onRemoveGameIHave(id){
     $j.ajax({
      type: "POST",
      url: "/proc.php",
      data: "action=havelist_del&iid="+id
    });
    for(var i=0; i<arrGamesOwned.length; i++){
      //if(arrGamesOwned[i]==id){
      if(arrGamesOwned[i].id==id){      
        arrGamesOwned.splice(i,1);
        break;
      }
    }
    var el = document.getElementById("searchbox");
    if(el){
      el.value = "";
      handleGameString("");
    }
    
    bListChanged=true;
    renderSelectedList(arrGamesOwned,'selectedlist','have');
  }
  function onRemoveGameIWant(id){
     $j.ajax({
      type: "POST",
      url: "/proc.php",
      data: "action=wantlist_del&iid="+id
    });
    for(var i=0; i<arrGamesWanted.length; i++){
      if(arrGamesWanted[i].id==id){      
        arrGamesWanted.splice(i,1);
        break;
      }
    }
    bListChanged=true;
    renderSelectedList(arrGamesWanted,'selectedlist','want');
  }
  function renderSelectedList(arr, listid,type){
    var outstr="", i=0;
    var el = $j(".activedlg #"+listid)[0];
    //var el = document.getElementById(listid);
    if(!el) return false;
    for(i=el.rows.length; i>0; i--){
      el.deleteRow(i-1);
    }
    for(i=0; i<arr.length; i++){
      var row = el.insertRow(i);
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      var cell3 = row.insertCell(2);
      row.className="gameadded";
      cell1.className="column1";
      cell1.innerHTML = arr[i].n;
      cell2.className="column3";
      if(type=='have')
        cell2.innerHTML = '<a href="javascript:onRemoveGameIHave('+arr[i].id+')" title="Remove '+arr[i].n+'">Remove<span></span></a>';
      else
        cell2.innerHTML = '<a href="javascript:onRemoveGameIWant('+arr[i].id+')" title="Remove '+arr[i].n+'">Remove<span></span></a>';
    }
  }
  function onNextAccCreationPage(curpage){
    if(curpage==1){
      document.accinfo_step1.submit();
    }
    if(curpage==2){
      if(!arrGamesOwned.length){
        alert("No games were entered. You must have at least 1 game to start Mooching.");
      }else{
        addNewPageEx('/popup_accinfo_step3.php', function(){
          window.curpage = 3;
          renderSelectedList(arrGamesWanted, 'wantedlist','want');
        });
      }
    }
    if(curpage==3){
      if(!arrGamesWanted.length){
        alert("No games were entered. You must want at least 1 game to start Mooching.");
      }else{
        //addNewPage('/popup_accinfo_step4.php');
        addNewPageEx('/popup_accinfo_step4.php', function(){
          window.curpage = 4;
        });
      }
    }
  }
function initWantButtons(){
  $j(".btn_want").click(function(){
    var gid = $j(this).attr("id").split("_",2)[1]
    addGameToWantList(gid);
    disableGameInLists(gid);
    $j(this).css("display", "none");
    $j(this).next().css("display", "block");
    $j(this).next().addClass("disabled_want");
    var el = $j(this).parents(".game").find(".numwanted").get(0);
    if(el){
      var curval = parseInt($j(el).html());
      $j(el).html(curval+1);
    }
    if($j(".ctr_gamewanted").length){
      var curval = parseInt($j(".ctr_gamewanted").html());
      $j(".ctr_gamewanted").html(curval+1);      
    }
    if($j("#wantlist").length){
      el = $j("#wantlist tbody").get(0);
      if(el){
        for(var i=0; i<arrRecs.length; i++){
          if(arrRecs[i].id == gid)
            break;
        }
        if(i && i<arrRecs.length){
          var currNumRows = $j(el).find("tr").length;
          var row = el.insertRow(currNumRows);
          $j(row).prev().removeClass("last");
          $j(row).addClass("last");
          var cell0 = row.insertCell(0);
          var cell1 = row.insertCell(1);
          var cell2 = row.insertCell(2);
          var cell3 = row.insertCell(3);
          var cell4 = row.insertCell(4);
          cell0.innerHTML = '<strong><a href="/game.php?iid='+arrRecs[i].id+'">'+arrRecs[i].name+'</a></strong>';
          cell1.innerHTML = arrRecs[i].platform;
          cell2.innerHTML = '<strong>'+arrRecs[i].points+'</strong>';
          cell3.innerHTML = '<a class="find-trade" href="/outgoing.php?iid='+arrRecs[i].id+'" title="Find Trade">Find Trade<span></span></a>';
          cell4.innerHTML = '<a class="remove" href="?action=wantlist_del2&amp;iid='+arrRecs[i].id+'" title="Remove">X<span></span></a>';
        }
        /*<td>
            <input id="in_7" name="7" value="8" type="text">
            <input name="wantsid_7" value="160" type="hidden">
          </td>
          <td><strong><a href="/game.php?iid=5796">Mister Slime</a></strong></td>
          <td>DS</td>
          <td><strong>148</strong></td>
          <td><a class="find-trade" href="/outgoing.php?iid=5796" title="Find Trade">Find Trade<span></span></a></td>
          <td><a class="remove" href="?action=wantlist_del&amp;wantid=160" title="Remove">X<span></span></a></td>
          <td><a class="move-to-top" href="#" title="Move to top" onclick="onMoveToTop(160)">top<span></span></a></td>
        */    
      }
    }
  });
}
function initHomeLoggedIn(){
  initLeveler();
  initWantButtons();
  initRecsCarrousel();
  initNewRelsCarrousel();
}
function initHomeLoggedOut() {
  if(bShowOverlay == 1){
    $j("#popup_login_badpassword").css("top", $j("#password").offset().top - 42);
    $j("#popup_login_badpassword").css("left", $j("#password").offset().left - 340);
    $j("#popup_login_badpassword").css("display", "block");
    $j("#popup_login_badpassword .close_popup a").click(function(){
      $j("#popup_login_badpassword").css("display", "none");
    });
  }else if(bShowOverlay == 2){
    $j("#popup_login_badhandle").css("top", $j("#handle").offset().top - 42);
    $j("#popup_login_badhandle").css("left", $j("#handle").offset().left - 340);
    $j("#popup_login_badhandle").css("display", "block");
    $j("#popup_login_badhandle .close_popup a").click(function(){
      $j("#popup_login_badhandle").css("display", "none");
    });    
  }else if(bShowOverlay == 3){
    launchACW(createstep);
  }
  initLoggedOutCtls();
  $j(".ACWStep4").click(function(){
    document.location.href = "/index.php";
    return false;
    });
}
function initLoggedOutCtls(){
  $j("input[type='text']:first", document.forms[0]).focus();
  $j(".blkrlnch").click(function () {
    $j(".popup_logged_out").css("display", "none");
    $j(this).next().css("display", "block");
  });
  $j(".btn_no_thanks").click(function() {
    $j(".popup_logged_out").css("display", "none");
  });
  $j(".ACW_launcher").click(function() {
    launchACW(createstep);
  });
  $j("#forgotpass_btn").click(function(){
    $j("#popup_login_forgotpass").css("top", $j(this).offset().top - 45);
    $j("#popup_login_forgotpass").css("left", $j(this).offset().left - 350);
    $j("#popup_login_forgotpass").fadeIn("medium");
  });
  $j(".close_forgotpass_dlg").click(function () {
    $j(this).parents(".popup_login_error").fadeOut("medium");
	 	//$j("#popup_login_forgotpass").fadeOut("medium");
	});
  $j("#submit_forgotpass").click(function () {
    
    $j.ajax({
      type: "POST",
      url: "/proc.php",
      data: "action=passwordlost&em="+document.getElementById("fc_emailforgotpass").value,
      success: function(resp){
        $j("#popup_login_forgotpass").fadeOut("medium");
        $j("#popup_login_forgotpass_thankyou").css("top", $j("#popup_login_forgotpass").offset().top);
        $j("#popup_login_forgotpass_thankyou").css("left", $j("#popup_login_forgotpass").offset().left-100);        
        $j("#popup_login_forgotpass_thankyou").fadeIn("medium");
        setTimeout('$j("#popup_login_forgotpass_thankyou").fadeOut("medium");', 5000);
        },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("There was an error trying to extract the game information. Please reload the page or try again later.");
      }
    });
    
	 	
	});  
  $j('#password').keyup(function(e) {
    if(e.keyCode == 13) {
      Login();
    }
  });
}
function initInProgress(){
  if(initcalled)return;
  initcalled=1;
  initLeveler();
  registerTIPControls();
  initInPageHelp();
  //offer-clear
  initWhatarepointsDlg();
  initClosepopupBtn();
  $j(".user-details").click(function () {
    handleGetUserDetails($j(this).get(0));
  });
  $j(".ununcheckable").click(function(){
    $j(this).attr("checked", 1);
    });
}
function unregisterTIPControls(){
  $j(".what_is_mailing_label").unbind("click");
  $j(".print_label").unbind("click");
  $j(".btndeltrade").unbind("click");
  $j(".reprint_label, .print_label").unbind("click");
  $j(".user_details").unbind("click");
  $j(".ratebadbtn").unbind("click");
  $j(".rategoodbtn").unbind("click");
  $j(".alert_track").unbind("click");
  $j(".report_problem").unbind("click");
  $j(".submit_report").unbind("click");
  $j(".cancel_report").unbind("click");
}
function registerTIPControls(){
  //IE sucks: I can't register this after injecting in DOM with innerHTML, so I had to move to an oldstyle onclick. Seems to be due to the fact that it's a checkbox...
  //$j(".ihavemailed").click(onIHaveMailed(this));
  //$j(".ihavereceived").click(onIHaveReceived);
	$j(".what_is_mailing_label").click(function () {
	  if($j(this).next().css("display") == "none"){
	 	$j(".popup_alert_track").css("display", "none");
		$j(".popup_what_is_mailing_label").css("display", "none");
		$j(".popup_user_detail").css("display", "none");
        $j(this).next().css("display", "block");
	  }else{
	 	$j(this).next().css("display", "none");
	  }
	});  
  $j(".btndeltrade").click(function(){
    currTID = $j(this).attr("id").split("_",2)[1];
    window.el2updt = $j(this).parents(".controls").get()[0];
    onTradeResp(currTID, "delete", $j(this).parents(".controls").get()[0])
    });
	$j(".print_label").click(function () {
    currTID = $j(this).attr("id").split("_",2)[1];
    postTradeStatus(currTID, "printed", 0);
    window.el2updt = $j(this).parents(".controls").get()[0];
    $j(window.el2updt).fadeOut("fast",function(){
      $j(this).html(document.getElementById("haveyoumailed").innerHTML);
      unregisterTIPControls();
      registerTIPControls();
      $j(this).fadeIn("fast");
    });
    
	});  
	$j(".reprint_label, .print_label").click(function () {
    var tid = $j(this).attr("id").split("_",2)[1];
    if(tid == -1)
      tid = currTID;
    else
      currTID = tid;
	  if($j(".popup_print_label").css("display") == "none"){
      $j(".popup_alert_track").css("display", "none");
      $j(".popup_what_is_mailing_label").css("display", "none");
      $j(".popup_user_detail").css("display", "none");
      nextPrintLabelStep(tid);
	  }else{
	 	$j(".popup_print_label").css("display", "none");
	  }
	});
  $j(".ratebadbtn").click(function(){
      var tid = $j(this).attr("id").split("_",2)[1];
      if(tid == -1)
        tid = currTID;
      var taproc = new TradeActionProc(tid, $j(this).parents(".controls").get()[0]);
      taproc.RateTrade("bad");
    });
  $j(".rategoodbtn").click(function(){
      var tid = $j(this).attr("id").split("_",2)[1];
      if(tid == -1)
        tid = currTID;
      var taproc = new TradeActionProc(tid, $j(this).parents(".controls").get()[0]);
      taproc.RateTrade("good");
    });  
	$j(".alert_track").click(function () {
	  if($j(".popup_alert_track").css("display") == "none"){
		$j(".popup_what_is_mailing_label").css("display", "none");
		$j(".popup_user_detail").css("display", "none");
		$j(".popup_print_label").css("display", "none");
        $j(".popup_alert_track").css("display", "block");
	  }else{
	 	$j(".popup_alert_track").css("display", "none");
	  }
	});
	$j(".report_problem").click(function () {
    var tid = $j(this).parents(".offer").attr("id").split("_",2)[1];
    if(tid == -1)
      tid = currTID;
    else
      currTID = tid;
    window.el2updt = this.parentNode.parentNode;  
	  if($j(".popup_report_problem").css("display") == "block"){
      if($j(this).attr("rel") == "active"){
        $j(".report_first_page").css("display", "none");
        $j(".report_problem").attr("rel","")
      }else{
        $j(".popup_what_is_mailing_label").css("display", "none");
        $j(".popup_user_detail").css("display", "none");
        $j(".popup_print_label").css("display", "none");
        $j(".popup_alert_track").css("display", "none");
        $j(".report_second_page").css("display", "none");
        $j(".popup_report_problem").fadeIn("medium");
        $j(".report_problem").attr("rel","")
        $j(this).attr("rel","active");
      }
    }else{
      $j(".popup_what_is_mailing_label").css("display", "none");
      $j(".popup_user_detail").css("display", "none");
      $j(".popup_print_label").css("display", "none");
      $j(".popup_alert_track").css("display", "none");
      $j(".report_second_page").css("display", "none");
      
      var namegame1 = $j(this).parents(".offer").find(".get_product").find(".gamename").html();
      var namegame2 = $j(this).parents(".offer").find(".give_product").find(".gamename").html();
      var otherusername = $j(this).parents(".offer").find(".get_product").find(".username").html();
      $j("#prbldlg_gameiget").html(namegame1?namegame1:"Points");
      $j("#prbldlg_gameigive").html(namegame2?namegame2:"Points");
      $j("#prbldlg_otheruser").html(otherusername?otherusername:"Other User");
      $j(".popup_report_problem").css("top", $j(this).offset().top - 200);
      $j(".popup_report_problem").fadeIn("medium");
      $j(".report_problem").attr("rel","")
      $j(this).attr("rel","active");
	  }
  });
  
	$j(".submit_report").click(function(){
    $j(".popup_report_problem").fadeOut("medium");
    var datastr = "action=trade_report_issue&trade_issue_id="+currTID;
    datastr += "&trade_issue="+document.getElementById("fc_trade_issue").value;
    datastr += "&reportissuetxt="+document.getElementById("fc_reportissuetxt").value;
    $j.ajax({
      type: "POST",
      url: "/proc.php",
      data: datastr,
      success: function(resp){
        
        },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("There was an error submitting your issue. Please reload the page or try again later.");
      }
    });
    $j(window.el2updt).html("<br /><p>Problem Reported</p>");
  });
	
	$j(".cancel_report").click(function () {
	 	$j(".popup_report_problem").fadeOut("medium");
	});
  $j("#prtwithpostage_btn").click(onclickPrintLabelWithPostage);
  $j("#prtwithoutpostage_btn").click(function(){
    if(window.nsa_pstg){
      onclickPrintLabel();
    }else{
      $j("#confirmfreelabel_dlg").css("left", $j(this).offset().left - 100);
      $j("#confirmfreelabel_dlg").css("top", $j(this).offset().top - 100);
      $j("#confirmfreelabel_dlg").fadeIn("medium");
    }
  });
  $j("#prtwithoutpostage_confirm_btn").click(function(){
    if($j("#fc_nsa_pstg").attr("checked")){
      window.nsa_pstg = true;
      $j.ajax({
        type: "POST",
        url: "/proc.php",
        data: "action=setcookie&name=nsa_pstg&val=1"
      });
    }
    $j(this).parents(".dialog").fadeOut("medium");
    onclickPrintLabel();
  });
}
function onIHaveReceived(el){
  onCallOnTradeResp(el,"executed");
}
function onIHaveMailed(el){
  onCallOnTradeResp(el,"intransit");
}
function onCallOnTradeResp(el,s){
  var lid = $j(el).attr("id").split("_",2)[1];
  if(lid == -1)
    lid = currTID;
  window.el2updt = $j(el).parents(".controls").get()[0];
  onTradeResp(lid, s, $j(el).parents(".controls").get()[0]);
}

/* --------------------------------------- */
function initOutgoingPage() {
  if(initcalled)return;
  initcalled=1; //I don't know why, ready gets called twice for this page.
  initLeveler();
  initInPageHelp();
  initWhathappensDlg();
  initWhatarepointsDlg();
  initClosepopupBtn();
  $j("#fc_gamefilter").change(function(){
    var el = document.getElementById("fc_gamefilter");
    if(el.selectedIndex)
      document.gamefilter.submit();
    else document.location.href = "/outgoing_pickwanted.php";
  });
}  
/* --------------------------------------- */
function initIncomingPage() {
  if(initcalled)return;
  initcalled=1; //I don't know why, ready gets called twice for this page.
  initLeveler();
  initInPageHelp();
  initWhatarepointsDlg();
  initClosepopupBtn();
  $j(".comments-popup-title > p > a").hover(
		function () {
		  $j(this).parent().next().css("display", "block");
		},
		function () {
		  $j(this).parent().next().css("display", "none");
		}
	);
  $j(".controls .btn-accept").click(function(){
    var tid = $j(this).attr("id").split("_",2)[1];
    handleAccept(tid, this);
  });
  $j(".controls .btn-reject").click(function(){
    window.tid = $j(this).attr("id").split("_",2)[1];
    window.el2updt = this.parentNode;
    onTradeResp(window.tid, 'rejected', window.el2updt);  
  });  
  $j(".user-details").click(function () {
    handleGetUserDetails($j(this).get(0));
  });
  $j("#fc_gamefilter").change(function(){
    var el = document.getElementById("fc_gamefilter");
    if(el.selectedIndex)
      document.gamefilter.submit();
    else document.location.href = "/incoming.php";
  });  
}
function handleGetUserDetails(el){
  var uid = $j(el).attr("id").split("_",2)[1];
  $j("#user_detail_dlg").css("left", $j(el).offset().left-55);
  $j("#user_detail_dlg").css("top", $j(el).offset().top-102);
  $j("#dyn_user_details").html("");
  $j("#user_detail_dlg").fadeIn("medium");

  $j.ajax({
    type: "POST",
    url: "/proc.php",
    data: "action=getUserDetailDlgHTML&uid="+uid,
    success: function(resp){
      $j("#dyn_user_details").html(resp);
      },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert("There was an error trying to exactract the game information. Please reload the page or try again later.");
    }
  });      
}
function handleAccept(id, el){
  if(bNeedAddress){
    $j(".w_popup_enter_email").css("left", $j(el).offset().left-250);
    $j(".w_popup_enter_email").css("top", $j(el).offset().top-50);
    $j(".w_popup_enter_email").css("z-index", 1000);
    $j(".w_popup_enter_email").fadeIn("fast");
    $j(".w_popup_enter_email .btn-close").click(function(){
      $j(".w_popup_enter_email").fadeOut("fast");
      $j(".w_popup_enter_email .btn-close").unbind('click');
    });
    return;
  }
  if(bVacation){
    $j("#vacationblock_dlg").css("left", $j(el).offset().left-150);
    $j("#vacationblock_dlg").css("top", $j(el).offset().top-50);
    $j("#vacationblock_dlg").fadeIn("fast");
    $j("#vacationblock_dlg .btn-close").click(function(){
      $j("#vacationblock_dlg").fadeOut("fast");
      $j("#vacationblock_dlg .btn-close").unbind('click');
    });
    return;
  }
  if(bLevelBlock){
    $j("#levelblock_dlg").css("left", $j(el).offset().left-150);
    $j("#levelblock_dlg").css("top", $j(el).offset().top-150);
    $j("#levelblock_dlg").fadeIn("fast");
    $j("#levelblock_dlg .btn-close").click(function(){
      $j("#levelblock_dlg").fadeOut("fast");
      $j("#levelblock_dlg .btn-close").unbind('click');
    });
    return;
  }
  var taproc = new TradeActionProc(id, $j(el).parents(".controls").get()[0]);
  taproc.AcceptTrade();  
}
/* --------------------------------------- */
function initAvailable() {
  initLeveler();
  $j(".controls .btn-accept").click(function(){
    var tid = $j(this).attr("id").split("_",2)[1];
    handleAccept(tid, this);
  });
  $j(".controls .btn-reject").click(function(){
    window.tid = $j(this).attr("id").split("_",2)[1];
    window.el2updt = this.parentNode;
    onTradeResp(window.tid, 'rejected', window.el2updt);  
  });    
  $j("#fc_gamefilter").change(function(){
    var el = document.getElementById("fc_gamefilter");
    if(el.selectedIndex)
      document.gamefilter.submit();
    else document.location.href = "/available_pickhave.php";
  });
  $j(".user-details").click(function () {
    handleGetUserDetails($j(this).get(0));
  });
  initClosepopupBtn();
}
/* --------------------------------------- */
function initPageGamesIHave(){
  initLeveler();
  initWantButtons();
  window.curpage = 100;
  $j(".btn-add_a_game").click(openAddGamesToHaveDlg);
  if(autoopen)
    openAddGamesToHaveDlg();
  initRecsCarrousel();  
}
function openAddGamesToHaveDlg(){
  getGameInfo();
  $j("#addgame_dlg").addClass("activedlg");    
  renderSelectedList(arrGamesOwned,'selectedlist','have');
  $j("#searchbox").keyup(function(){
    onSearckKeyHit();
  });
  openAddGameDlg();  
}
function initPageGamesIWant(){
  initLeveler();
  initWantButtons();
  window.curpage = 200;
  $j(".btn-add_a_game").click(openAddGamesToWantDlg);
  if(autoopen)
    openAddGamesToWantDlg()
  $j(".update-priority").click(function(){
    document.wantlist.submit();
  });
  initRecsCarrousel();
}
function openAddGamesToWantDlg(){
  getGameInfo();
  $j("#addgame_dlg").addClass("activedlg");
  renderSelectedList(arrGamesWanted,'selectedlist','want');
  $j("#searchbox").keyup(function(){
    onSearckKeyHit();
  });
  openAddGameDlg();
}
/* --------------------------------------- */
function initListPage() {
  initLeveler();
  window.curpage = 300;
  $j(".btn_want").click(function(){
    //alert($j(this).attr("id").split("_",2)[1]);
    addGameToWantList($j(this).attr("id").split("_",2)[1]);
    $j(this).next().css("display", "block");
    $j(this).next().addClass("disabled_want");
    var el = $j(this).parents(".game").find(".numwanted").get(0);
    var curval = parseInt($j(el).html());
    $j(el).html(curval+1);
  });
  $j(".btn_have").click(function(e){
    onAddHaveBtn(this,$j(this).attr("id").split("_",2)[1])
    window.ctlToDisable = $j(this).next();
    if($j(".ctr_gamehad").length){
      var curval = parseInt($j(".ctr_gamehad").html());
      $j(".ctr_gamehad").html(curval+1);      
    }
  });
  if(!bLoggedin){
    initLoggedOutCtls();
  }
  $j('#password').keyup(function(e) {
    if(e.keyCode == 13) {
      Login();
    }
  });  
}
function initGamePage(){
  initLeveler();
  initWantButtons();
  $j(".btn_have").click(function(e){
    onAddHaveBtn(this,$j(this).attr("id").split("_",2)[1])
    //window.ctlToDisable = $j(this).next();
    window.ctlToDisable = $j(this);
  });  
  //Game detail page: image gallery
  var form_account_state = 0;
  $j(document).ready(function(){
    $j(function() {
      $j(".jMyCarousel").jMyCarousel({
        visible: '3',
        eltByElt: true,
        evtStart: 'mousedown',
        evtStop: 'mouseup'
      });
    });
    $j("#thumbnails_gallery a").click(
      function(){
        img = $j(this).children();
        $j("#preview_image img").attr({src: $j(img[0]).attr("src")});
      }
    );
  });
  if(bLoggedin){
    initRecsCarrousel();
  }else{
    initLoggedOutCtls();
  }  
}
function openAddGameDlg(){
  modalDlg = $j("#addgame_dlg").modal({onClose: function (dialog) {
    dialog.data.removeClass("activedlg");
    $j('#hbm_popup').css('display','none');
      dialog.container.slideUp('medium', function () {
        $j.modal.close();
        if(bListChanged){
          setTimeout("reload()", 50);
          //window.location.href = window.location.pathname;
        }
      });
    return false;  
  }});
  $j("#searchbox").focus();
}
function reload(){
  document.location.href = document.location.href;
  return false;
}
function getGameInfo(){
  if(!bHaveGameData){
    $j.ajax({
      type: "POST",
      url: "/proc.php",
      data: "action=getgameinfo",
      success: function(resp){
        var agvar ="arrAllGames = "+resp;
        eval(agvar);
        bHaveGameData=true;
        onSearckKeyHit();
        },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("There was an error trying to exactract the game information. Please reload the page or try again later.");
      }});
  }
}
function initWhathappensDlg(){
  $j(".what-happens").click(function () {
    if($j("#what-happens-dlg").css("display") == "none"){
      $j(".wrapper-what-happens").css("display", "none");
      $j(".offer-by").css("display", "none");
      $j(".what-are-points").css("display", "none");
      $j(".popup-warning-trade_not_available").css("display", "none");
      //$j(this).next().css("display", "block");
      $j("#what-happens-dlg").css("left", $j(this).offset().left - 120);
      $j("#what-happens-dlg").css("top", $j(this).offset().top - 310);
      $j("#what-happens-dlg").css("display", "block");
    }else{
    $j("#what-happens-dlg").css("display", "none");
    }
  });
}
function showMakeOfferDlg(el){
  $j(".wrapper-what-happens").css("display", "none");
  $j(".what-are-points").css("display", "none");
  $j("#makeoffer_dlg").css("left", $j(el).offset().left - 320);
  $j("#makeoffer_dlg").css("top", $j(el).offset().top - 130);
  $j("#makeoffer_dlg").css("display", "block");
}

function toggleClearTradeDlg(el){
  if($j("#popup_clear_dlg").css("display") == "none"){
    $j(".wrapper-what-happens").css("display", "none");
    $j(".what-are-points").css("display", "none");
    //$j("#popup_clear_dlg").css("left", $j(this).offset().left - 320);
    //$j("#popup_clear_dlg").css("top", $j(this).offset().top - 130);
    $j("#popup_clear_dlg").css("left", $j(el).offset().left - 320);
    $j("#popup_clear_dlg").css("top", $j(el).offset().top - 130);
    $j("#popup_clear_dlg").css("display", "block");
  }else{
    $j("#popup_clear_dlg").css("display", "none");
  }
}
function initWhatarepointsDlg() {
	$j(".what-are").click(function (e) {
	  if($j("#what-are-points-dlg").css("display") == "block"){
      if($j(this).attr("rel") == "active"){
        $j("#what-are-points-dlg").css("display", "none");
        $j(".what-are").attr("rel","")
      }else{
        var mpX = e.pageX;
        var mpY = e.pageY; 
          
        $j("#what-are-points-dlg").css("display", "block");
        $j("#what-are-points-dlg").css({"left":(mpX-300)+"px","top":(mpY-245)+"px","right":"auto","z-index":"9999999"});
         
        $j(".popup-warning-trade_not_available").css("display", "none");
        $j(".offer-by").css("display", "none");
        $j(".wrapper-what-happens").css("display", "none");
        
        $j(".what-are").attr("rel","")
        $j(this).attr("rel","active");
      }
	  }else{
      var mpX = e.pageX;
      var mpY = e.pageY; 
      $j("#what-are-points-dlg").css({"left":(mpX-190)+"px","top":(mpY-335)+"px","right":"auto","z-index":"9999999"});
      $j("#what-are-points-dlg").css("display", "block");
      $j(".popup-warning-trade_not_available").css("display", "none");
      $j(".offer-by").css("display", "none");
      $j(".wrapper-what-happens").css("display", "none");
      $j(this).attr("rel","active");
		//alert(mpX +', '+ mpY); 
	  }
	});
}
function initClosepopupBtn(){
	$j(".close_popup > a").click(function () {
		$j(".popup_user_detail").css("display", "none");
		$j(".popup_what_is_mailing_label").css("display", "none");
	 	$j(".popup_print_label").css("display", "none");
	 	$j(".popup_report_problem").css("display", "none");
    $j("#what-are-points-dlg").css("display", "none");
    $j("#what-happens-dlg").css("display", "none");
    $j("#popup_clear_dlg").css("display", "none");
	});
	
  $j(".close_popup").click(function () {
	 	$j(".popup_alert_track").css("display", "none");
	});
  $j(".closedialog").click(function(){
    $j(this).parents(".dialog").fadeOut("medium");
  });
}
//---------------------------------------------------------
//Has box and manuel (hbm) popup.
function hbm_popup_chk_indlg(){
	if($j('#chk1_yes').attr("checked") && $j('#chk2_yes').attr("checked")){
    addIndexedGameToHaveList(window.id);
    $j("#hbm_popup").css({display:"none"});
    if(window.ctlToDisable){
      window.ctlToDisable.css("display", "block");
      window.ctlToDisable.removeClass("btn-add");
      window.ctlToDisable.addClass("disabled_have");
      window.ctlToDisable.addClass("btn-add-disabled"); //so that the same code works for both add-btn and have-btn
    }
    if(window.eltoinc){
      var curval = parseInt($j(window.eltoinc).html());
      $j(window.eltoinc).html(curval+1);
    }
    selSearchBox();
	}
}
function hbm_popup_chk(){
	if($j('#chk1_yes').attr("checked") && $j('#chk2_yes').attr("checked")){
    addGameToHaveList(window.id);
    $j("#hbm_popup").css({display:"none"});
    if(window.ctlToDisable){
      window.ctlToDisable.css("display", "block");
      window.ctlToDisable.addClass("disabled_have");
    }
    if(window.eltoinc){
      var curval = parseInt($j(window.eltoinc).html());
      $j(window.eltoinc).html(curval+1);
    }
    if($j(".ctr_gamehave").length){
      var curval = parseInt($j(".ctr_gamehave").html());
      $j(".ctr_gamehave").html(curval+1);      
    }
	}
}
function hbm_popup_chk_gp(){
	if($j('#chk1_yes').attr("checked") && $j('#chk2_yes').attr("checked")){
    addGameToHaveList(window.id);
    $j("#hbm_popup").css({display:"none"});
    if(window.ctlToDisable){
      window.ctlToDisable.css("display", "none");
      $j(window.ctlToDisable).next().css("display", "block");
    }
    if(window.eltoinc){
      var curval = parseInt($j(window.eltoinc).html());
      $j(window.eltoinc).html(curval+1);
    }
	}  
}
function hbm_popup_no(){
	$j("#game_details_confirm").css({display:"none"});
	$j("#game_details_close").css({display:"block"});
}
function onAddHaveBtn(o,idp){
  var targetX = $j(o).offset().left;
  var targetY = $j(o).offset().top;
  
	window.id = idp; //watch out! this could be an idx. Just pass it through - yes, this code is totally terrible
  var el = $j(o).parents(".game").find(".numavail").get(0);
  window.eltoinc = el ? el : 0;
  window.ctlToDisable = $j(o);
  $j("#hbm_popup").css({"left":(targetX-235)+"px","top":(targetY-40)+"px","right":"auto","z-index":"9999999"});
	$j("#hbm_popup").css({display:"block"});
	$j("#game_details_close").css({display:"none"});
	$j('#game_details_confirm').css({display:"block"});
	$j('#chk1_yes').attr("checked",false);
	$j('#chk2_yes').attr("checked",false);
	$j('#chk1_no').attr("checked",false);
	$j('#chk2_no').attr("checked",false);
}
function initNewRelsCarrousel(){
  window.newrelCarrousel = new gameCarrousel(arrNewrels, document.getElementById("newrelsCarrousel"));
  $j("#newrelsCarrousel .btn-go_right").click(function(){
    window.newrelCarrousel.goRight();
  });
  $j("#newrelsCarrousel .btn-go_left").click(function(){
    window.newrelCarrousel.goLeft();
  });  
}
function initRecsCarrousel(){
  window.recCarrousel = new gameCarrousel(arrRecs, document.getElementById("recsCarrousel"));
  $j("#recsCarrousel .btn-go_right").click(function(){
    window.recCarrousel.goRight();
  });
  $j("#recsCarrousel .btn-go_left").click(function(){
    window.recCarrousel.goLeft();
  });
  if($j("#wantlist").length){
  }
}
function gameCarrousel(games, carrEl){
  var m_games = games;
  var m_elContainer = carrEl;
  var m_elContent = $j(carrEl).find("ul").get()[0];
  var m_curPos = 0;
  
  this.goRight = function(){
    Redraw(++m_curPos)
  }
  this.goLeft = function(){
    Redraw(--m_curPos)
  }
  function Redraw(curPos){
    var outstr = "";
    for(var i=(m_curPos*5); (i<m_curPos*5+5)&&i<m_games.length; i++){
      outstr += createOutput(i);
    }
    $j(m_elContent).hide();
    $j(".btn_want").unbind("click");
    $j(m_elContent).html(outstr);
    initWantButtons();
    $j(m_elContent).show();
    showhideArrows()    
  }
  function createOutput(pos){
    var outstr = "";
    outstr += '<li>';
    if(m_games[pos].disable){
      outstr += '<a href="/game.php?iid='+m_games[pos].id+'">';
      outstr += '<img alt="'+m_games[pos].name+'" src="'+m_games[pos].cover+'"/>';
      outstr += '</a>';
      outstr += '<a href="javascript:void(0)" class="btn_want" id="wantbtn_'+m_games[pos].id+'" style="display: none">Want</a>';
      outstr += '<span class="disabled_want" style="display: block"/>';
    }else{
      outstr += '<a href="/game.php?iid='+m_games[pos].id+'">';
      outstr += '<img alt="'+m_games[pos].name+'" src="'+m_games[pos].cover+'"/>';
      outstr += '</a>';
      outstr += '<a href="javascript:void(0)" class="btn_want" id="wantbtn_'+m_games[pos].id+'">Want</a>';
      outstr += '<span class="disabled_want"/>';
    }
    outstr += "</li>";
    return outstr;
  }
  
  function showhideArrows(){
    if(!m_curPos){
      $j(m_elContainer).find(".btn-go_left").css("visibility","hidden");
    }else{
      $j(m_elContainer).find(".btn-go_left").css("visibility","visible");
    }
    if(m_curPos*5 < m_games.length-5){
      $j(m_elContainer).find(".btn-go_right").css("visibility","visible");
    }else{
      $j(m_elContainer).find(".btn-go_right").css("visibility","hidden");
    }
  }
}
function disableGameInLists(id){
  try{
    var i=0;
    if(arrRecs){
      for(i=0; i<arrRecs.length; i++){
        if(arrRecs[i].id == id){
          arrRecs[i].disable = true;
          break;
        }
      }
    }
    if(arrNewrels){
      for(i=0; i<arrNewrels.length; i++){
        if(arrNewrels[i].id == id){
          arrNewrels[i].disable = true;
          break;
        }
      }    
    }
  }catch(e){
    return i;//arrays are not always defined. This is fine, this is a safe function.
  }
  return i;
}
function initLeveler(){
	max_level = $j("#level_user").eq(0).text();
	lvl_usr = parseInt($j("#level_user").eq(0).text());
	sub_lvl_usr = parseInt($j("#sub_level_user").eq(0).text());
	if(lvl_usr > 17) { 
		if(lvl_usr == 18) {
			if(sub_lvl_usr > 0) {
				$j("#level_image_inside").css({ left:"0" });	
				$j("#level_image_inside").css({ top:"0" });
			} else {
				$j("#level_user").html(max_level.replace(max_level,"MAX"));
				$j("#level_image_inside").css({ left:"-792px" });	
				$j("#level_image_inside").css({ top:"-44px" });
			}
		} else {
			$j("#level_image_inside").css({ left:"0" });	
			$j("#level_image_inside").css({ top:"0" });	
		}
	} else { 
		leveler_lvl_usr = lvl_usr*44;
		leveler_sub_lvl_usr = (sub_lvl_usr+1)*44;
		$j("#level_image_inside").css({ left:"-"+leveler_lvl_usr+"px" });	
		$j("#level_image_inside").css({ top:"-"+leveler_sub_lvl_usr+"px" });	
	}
  $j("#level_image_inside").click(function(){
		$j(".w_popup_dashboard").css({ left:"200px" });	
		$j(".w_popup_dashboard").css({ top:"200px" });
    $j(".w_popup_dashboard").css("display", "block");
    $j(".w_popup_dashboard .close_popup").click(function(){
      $j(".w_popup_dashboard").css("display", "none");
      $j(".w_popup_dashboard .close_popup").unbind('click');
    });
  });
}
function initInPageHelp(){
  if(showhelp){
    modalDlg = $j(".popup_help").modal(
      {onClose: function (dialog) {
        dialog.container.slideUp('fast', function () {
          dialog.overlay.fadeOut('fast', function () {
            var name = $j("#hidehelp_cbox").attr("name");
            if($j("#hidehelp_cbox").attr("checked")){
              //alert("inside "+ischecked);
              $j.ajax({
                type: "POST",
                url: "/proc.php",
                data: "action=setHelpPageOff&helppagecode="+name,
                success: function(resp){}
              });
            }
            if(name == "showhelpao"){
              $j.ajax({type: "POST",url: "/proc.php",data: "action=blockhelpao"});
            }else if(name == "showhelpaan"){
              $j.ajax({type: "POST",url: "/proc.php",data: "action=blockhelpaan"});
            }else if(name == "showhelpmo"){
              $j.ajax({type: "POST",url: "/proc.php",data: "action=blockhelpmo"});
            }else if(name == "showhelptip"){
              $j.ajax({type: "POST",url: "/proc.php",data: "action=blockhelptip"});
            }else 
            $j.modal.close();
            showhelp=0;
          });
        });
      }}
    );  
  }
}
//Please don't be a fool and call this with arr that is not an array with "id"s.
function isIdInArray(id,arr){
  for(var i=0;i<arr.length; i++){
    if(arr[i]['id'] == id)
      return true;
  }
  return false;
}