var $j = jQuery; //If you will experiment some incompatibility issues with other frameworks append .noConflict() after jQuery

var scrnshots_currentPos = [];
var register_status = new Object();
var creationtimer;
var register_busy = false;
var formparams = ''; //temporarily store the reg information, until we submit it with ajax
var have_a_team = false;
var uid = 0;
var sid = 0;
var max_rounds = 9; //Wait for max ~1.5 min
var curr_round = max_rounds;

document.onkeydown = keyCheck; //Linking the function keyCheck to the window event keydown
function keyCheck(e){
  var keyID = (window.event) ? event.keyCode : e.keyCode;
  if(keyID == 27){ //If ESC then close all powerboxes
    clearLightboxes();
  }
}

//We will call this function to close all lightboxes and set the variable lightboxIsActive to false, otherwise we might have problems when login
function clearLightboxes(){
  powerboxCloseAll(false);
}

function scrnshot_doAction(action)
{
  if(typeof(myShow)!="undefined" && typeof(myShow.doAction)=='function')
    myShow.doAction(action);
}
function scrnshot_openWindow()
{
  if(myShow.slideshow)
  {
    scrnshots_currentPos = myShow.getImagePosCurrent();
    scrnshot_lightbox(myShow.getCurrentImage(), scrnshots_currentPos[0], myShow.getImagePosMax());
    scrnshot_doAction('hold');
  }
}

function scrnshot_navigationPrev(showname)
{
  if(typeof(showname)!="undefined" && typeof(showname.navigationRight)=='function')
    showname.navigationRight(true);
}
function scrnshot_navigationNext(showname)
{
  if(typeof(showname)!="undefined" && typeof(showname.navigationLeft)=='function')
    showname.navigationLeft(true);
}

function scrnshot_lightbox(image, imageposCurrent, imageposMax)
{
  lightboxInit();
  scrnshot_IsActive = true;
  scrnshot_showContent(["","closebutton","notitle"], "<table width=512><tr><td align=center><img src=\"img/ajax_loader.gif\" alt=\"Loading\" width=\"16\" height=\"16\"></td></tr></table>");
  additional = "";
  if(!scrnshot_imageList)
    additional = "&getimagelist=true";
  ajaxCall('ajax_com/start.php','val=getScreenShotTemplate&defaultimg=' + image + '&current=' + imageposCurrent + '&max=' + imageposMax + additional, 'scrnshot_ajaxResponse', '');
}

function scrnshot_showContent(title, body)
{
  lightboxShow(512, title, body, "", "", "", "", "scrnshot_close();" );
  lightboxSetPosY(90);
}

function scrnshot_close()
{
  scrnshot_IsActive = false;
  myShowBig.stop();
  myShowBig = null;
  myShow.onhold = false;
  scrnshot_doAction('continue');
}

function scrnshot_ajaxResponse(readyState, response, responseParameter)
{
  if (readyState == 4 && scrnshot_IsActive) {
    eval(response);
    if (typeof scrnshot_Template == "object") {
      scrnshot_Title    = doTheReplace(scrnshot_Template["title"]);
      scrnshot_Body     = doTheReplace(scrnshot_Template["body"]);
      scrnshot_showContent([scrnshot_Title,"closebutton"], scrnshot_Body);
      myShowBig = new Slideshow('slideshowBig', { type: 'fade', resize: true, duration: [100000, 1000000], width: 400, height: 400, imgtype: 'jpg',  hu: 'img/start/', imageprogress: ['scrnshotimgstatus', 'current max'], captionarea: 'scrnshotcaption'});
      myShowBig.addimages(scrnshot_imageList);
      myShowBig.addtexts(scrnshot_textList);
      myShowBig.setImagePos(scrnshots_currentPos);
      myShowBig.start();
    }
    else {
      alert("internal error");
    }
  }
}

function scrnshot_ajaxStartResponse(readyState, response, responseParameter)
{
  if (readyState == 4) {
    eval(response);
    myShow = new Slideshow('slideshow', { type: 'fade',resize: true, duration: [2000, 4000], width: 150, height: 120, imgtype: 'gif',  hu: 'img/start/', onclick: true });
    myShow.addimages(scrnshot_imageList);
    myShow.start();
  }
}

function scrnShotSlideShow()
{
  ajaxCall('ajax_com/start.php','val=scrnshot_getJSImageList', 'scrnshot_ajaxStartResponse', '');
}


function getHelpClose()
{
  getHelpedIsActive = false;
}

function prepareHelp(readyState, response, responseParameter)
{
  if(readyState==4)
  {
    eval(response);
    lightboxShow(460, [templates['help']['title'],"lefttitle", "closebutton"], templates['help']['body']);
    lightboxSetPosY(90);
    help_forgotpwd_Body        = doTheReplace(templates["help"]["forgotpwd_body"]);
    help_forgotpwd_Win         = doTheReplace(templates["help"]["forgotpwd_win"]);
    help_reghelp_Body          = doTheReplace(templates["help"]["reghelp_body"]);
    help_reghelp_Win           = doTheReplace(templates["help"]["reghelp_win"]);
    help_ipprobs_Body          = doTheReplace(templates["help"]["ipprobs_body"]);
    help_ipprobs_Win           = doTheReplace(templates["help"]["ipprobs_win"]);
    layer_write('divhelp_forgotpwd', help_forgotpwd_Body);
    layer_write('divhelp_reghelp', help_reghelp_Body);
    layer_write('divhelp_ipprobs', help_ipprobs_Body);
    reenableButton("helpsendemail");
    reenableButton("helpsendreghelp");
    reenableButton("helpsendproblem");
    if(templates["help"]["panel"])
      help_swaplayer(templates["help"]["panel"]);
  }
}

function help_swaplayer(type)
{
  if (type == "forgotpwd") {
    if (help_forgotpwd_Body != help_forgotpwd_Win)
      help_forgotpwd_Body = help_forgotpwd_Win;
    layer_write("divhelp_forgotpwd",help_forgotpwd_Body);
    divsShowOnly('help_forgotpwd', 'help_');
  }
  else if (type == "reghelp") {
    if (help_reghelp_Body != help_reghelp_Win)
      help_reghelp_Body = help_reghelp_Win;
    layer_write("divhelp_reghelp",help_reghelp_Body);
    divsShowOnly('help_reghelp', 'help_');
  }
  else if (type == "ipprobs") {
    if (help_ipprobs_Body != help_ipprobs_Win)
      help_ipprobs_Body = help_ipprobs_Win;
    layer_write("divhelp_ipprobs",help_ipprobs_Body);
    divsShowOnly('help_ipprobs', 'help_');
  }
}

function help_response(readyState, response, responseParameter)
{
  if(readyState==4)
  {
    if(response.indexOf("templates")==0)
    {
      eval(response);
      if(templates && templates['help'] && templates['help']['response'])
      {
        layer_write(templates['help']['target'], templates['help']['response']);
      }
    }

    if(templates['help']['panel'])
    {
      help_swaplayer(templates['help']['openpanel']);
    }

    reenableButton("helpsendemail");
    reenableButton("helpsendreghelp");
    reenableButton("helpsendproblem");
  }
}

function help_submit(type)
{
  params = "";
  if(type=="forgotpwd")
  {
    layer_write('responseemail', '');
    email = document.getElementById("forgotemail").value;
    params = "type=password&sender=responseemail&email=" + email;
  }
  else if(type=="reghelp")
  {
    layer_write('responsereghelp', '');
    reginfo = document.getElementById("reginfo").value;
    params = "type=reghelp&sender=responsereghelp&reginfo=" + reginfo;
  }
  else if(type=="ipproblem")
  {
    layer_write('responseipproblem', '');
    email = document.getElementById("email").value;
    apply_country = document.getElementById("apply_country").value;
    freetext = document.getElementById("freetext").value;
    params = "type=ipproblem&sender=responseipproblem&email=" + email + "&apply_country=" + apply_country + "&freetext=" + escape(freetext);
  }
  ajaxCall('ajax_com/start.php','val=submitHelp&' + params, 'help_response', '');
}

function showhelppanel(panelname)
{
  lightboxHide();
  layer_hide('helpLayer');
  ajaxCallLightboxLoading('ajax_com/start.php', 'val=getHelpTemplates&panel=' + panelname, 'prepareHelp', '');
}


function sendRegisterForm(sportname) {
  if(sportname == undefined)
    if(sport != undefined)
        sportname = sport;
    else
        sportname = 'soccer'; //protection against late faults

  var othersport = '';
  if(sportname == 'soccer')
    othersport = 'hockey';
  else
    othersport = 'soccer';

  var other_class_name = 'choosesport_'+ othersport +'disabled';
  var other_id_name = 'choosesport_'+ othersport;
  var this_id_name = 'choosesport_'+ sportname;

  if (document.getElementById(other_id_name)) {
    document.getElementById(other_id_name).onclick = '';
    document.getElementById(other_id_name).className = other_class_name;
  }

  document.getElementById(this_id_name).onclick = '';

  //We want to show loading, as it can sometimes take some time before the response appears
  if(document.getElementById('waiting_info_marker') != undefined) {
    document.getElementById('waiting_info_marker').innerHTML = "<table width=435><tr><td align=center><img src=\"img/ajax_loader.gif\" alt=\"Loading\" width=\"16\" height=\"16\"></td></tr></table>";
    document.getElementById('wait_message').innerHTML = str_wait_loading;
  }
  document.forms['logindata']['sport'].value = sportname; //we store the sport for the login
  //We show info before committing
  ajaxCall("ajax_com/start.php", 'val=registerUser' + formparams + sportname, 'registerReturn', "");
}

function storeRegisterForm() {
  if(curr_round < 1)
		curr_round = max_rounds;

  ajaxLoaderControl("regform","block");
  formparams = getRegformParams(true);
  if (templates['regselectsport']) {
    lightboxShow(590, [templates['regselectsport'][0], "closebutton"], templates['regselectsport'][1]);
    lightboxSetPosY(130);
  }
  //$j('#overlay').unbind("click",clearLightboxes); //Do not close the light/powerbox if clicking outside if we are that close to the end
  return false;
}


function getRegformParams(register)
{
  var sport = register_status.sport;
  var lf = document.forms["login"];
  var lf2 = document.forms["logindata"];
  md5c = lf['md5c'].value;
  var usr = document.forms["reg_form"]["username"].value;
  document.forms['logindata']['username'].value = usr; //We store the loginname in the login form too, for the auto login
  var pwd = document.forms["reg_form"]["password"].value;
  document.forms['logindata']['password'].value = pwd;  //We store the passowrd in the login form too, for the auto login
  var email = document.forms["reg_form"]["email"].value.toLowerCase();
  var year = document.forms["reg_form"]["y"].value;
  var month = document.forms["reg_form"]["m"].value;
  var day = document.forms["reg_form"]["d"].value;
  var extraparam = "";
  if(document.getElementById("subcountry") != undefined)
    extraparam += "&subcountry="+document.forms["reg_form"]["subcountry"].value;
  if (document.forms["reg_form"]["raf_code"])
    extraparam += "&raf_code="+document.forms["reg_form"]["raf_code"].value;
  if (document.forms["reg_form"]["secrecy"])
    extraparam += "&secrecy="+document.forms["reg_form"]["secrecy"].value;
  if (register)
  {
    extraparam += "&password="+pwd;
  }
  else {
    //We tell what js thinks about the password.
    if(jsCheckAttribute('password',pwd) && pwd.length >= 6 && pwd.length <= 20) {
      var pwdchk = 1;
    } else {
      var pwdchk = 0;
    }
    extraparam += "&pwdchk="+pwdchk;
  }
  var md5 = hex_hmac_md5(md5c, pwd.toLowerCase());
  if (usr == "" && (pwd.length < 6 || pwd.length >= 20))
    md5 = "";
  var params = "&username="+ usr +"&md5="+ md5 +"&md5c="+ md5c +"&email="+ email +"&y="+ year +"&m="+ month +"&d="+ day + extraparam +"&sport=";

  if(sport != undefined && sport.length>1)
  	params = params + sport;
  return params;
}


function formDisableEnable(theForm,status)
{

  if(theForm == undefined)
  	return;

  var statuses = new Object();
  statuses["true"] = "";
  statuses["false"] = "true";
  var inputs = theForm.getElementsByTagName("input");
  for(i=0;i<inputs.length; i++) {
    if (status != undefined)
      inputs[i].disabled = status;
    else
      inputs[i].disabled = statuses[inputs[i].disabled];
  }
}


function regformChecked(readyState, response, responseParameter)
{
  if (readyState == 4) {
    eval(response);

    if (typeof regstatus == "object") {
      showFormStatus(regstatus, true, responseParameter);
    }
    //ajaxLoaderControl("regform","none");
    //formDisableEnable(document.getElementById("reg_form"),""); //This function would block the form while we are ajaxing
    //focusToNext(document.getElementById("reg_form"),responseParameter);
  }
}


function registerReturn(readyState, response, responseParameter)
{
  if (readyState == 4) {
    eval(response);
    ajaxLoaderControl("regform","none");
    //formDisableEnable(document.getElementById("reg_form"),""); //This function is quite annoying blocking and unblocking when ajaxing
    if (typeof regstatus == "object") {
      if (regstatus[0] == "ok_finished") {
       //call function that checks if we have a team
        var uidL = regstatus[2].length;
        uid = regstatus[2].substr(0, uidL - 4);
        var sidL = regstatus[3].length;
        sid = regstatus[3].substr(0, sidL - 4);
       	checkTeam(); //We start checking for teams
	  } else if(regstatus[0] == "error") {
	  	if(document.getElementById('waiting_info_marker') != undefined)
		  	document.getElementById('waiting_info_marker').innerHTML = "";
		    alert("Something went wrong, please reload the page and try again or contact support@managerzone.com  Error: ".regstatus[1]);
		    return false;
      } else {
      	document.getElementById('wait_message').innerHTML = regstatus[1].substr(0, regstatus[1].lenght - 4);
        document.getElementById('waiting_info_marker').innerHTML = "";
      }
    }
  }
}

function autoLogin() {
	if(setMd5(document.forms["login"],document.forms["logindata"]) == false){
		return false;
	}
  loginSport(document.forms['logindata']['sport'].value);
	return true;
}

var checkTeamTimeout;
function checkTeam() {
	if(curr_round-- < 1) {
		document.getElementById('waiting_info_marker').innerHTML = "";
		document.getElementById('wait_message').innerHTML = str_team_error_msg;
		clearTimeout(checkTeamTimeout);
		return;
	}
	if(have_a_team == false)
		ajaxCall("ajax_com/start.php", 'val=haveIaTeam&uid='+ uid +'&sportId='+ sid, 'setTeamStatus', "");

	if(have_a_team == true) {
		clearTimeout(checkTeamTimeout);
		autoLogin();
	} else {
		checkTeamTimeout = setTimeout("checkTeam()", 10000);
	}
}

function setTeamStatus(readyState, response, responseParameter) {
	//check if we have got a yes response
  if (readyState == 4) {
    eval(response);
    if (typeof regstatus == "object")
		if (regstatus[0] == "yes_team")
			have_a_team = true;
  }
}

function focusToNext(theForm,lastobj_id)
{
  var obj = document.getElementById(lastobj_id);
  obj.focus();
  var inputs = theForm.getElementsByTagName("input");
  for(i=0;i<inputs.length; i++) {
    if (inputs[i].id == lastobj_id) {
      if ((i+1) < inputs.length)
        inputs[i+1].focus();
    }
  }
}


function verifyRegFormAjax(lastobj_id)
{
  //ajaxLoaderControl("regform","block");
  //formDisableEnable(document.getElementById("reg_form"), "true");
  var params = getRegformParams(false);
  ajaxCall("ajax_com/start.php", 'val=verifyRegform' + params, 'regformChecked', lastobj_id);
  return true;
}

var clickedRegister = false;

//This function verify one by one all reg form areas
function verifyFullRegForm(){
  clickedRegister = true;
  var reg_form  = document.forms["reg_form"];

  if($j("#confirm_password").val().length == 0)
    showFormStatus("invalid_confirm_password", true);

  verifyRegFormAjax(reg_form["username"]);

  if(register_status.username == undefined || register_status.password == undefined
    || register_status.email == undefined || register_status.secrecy == undefined
    || register_status.birthdate == undefined || register_status.confirm_password == undefined
    || register_status.username == false || register_status.password == false
    || register_status.email == false || register_status.secrecy == false
    || register_status.birthdate == false || register_status.confirm_password == false)
    return false;
  else
    storeRegisterForm();
  return true;
}

//The following function validates per field, so it's good for onChange events.
//To validate the whole form and submit use function verifyFullRegForm instead
function verifyRegForm(obj)
{
  var shall_ajax_check = true;
  var lastobj_id = obj.id;
  if (register_status.username == undefined)
    register_status.username = false;
  if (register_status.password == undefined)
    register_status.password = false;
  if (register_status.email == undefined)
    register_status.email = false;
  if (register_status.secrecy == undefined)
    register_status.secrecy = false;
  if (register_status.birthdate == undefined)
    register_status.birthdate = false;

  if (obj.id == "password" || obj.id == "confirm_password") {
    shall_ajax_check = verifyRegFormPassword();
  }
  else if (obj.id == "email") {
    verifyRegFormEmail(obj.value);
  }
  else if (obj.id == "secrecy") {
    if (obj.value.length == 5) {
		verifyRegFormAjax(lastobj_id);
    } else {
		register_status.secrecy = false;
    }
  }else if (obj.id == "y" || obj.id == "m" || obj.id == "d"){
    verifyRegFormBirthdate();
    shall_ajax_check = false;
  }

  if(obj.id == "raf_code" && obj.value.length==0) //An empty raf_code is OK!
    showFormStatus("ok_raf_code", true);

  if (obj.id != "secrecy" && obj.value.length>0 && shall_ajax_check) {
    verifyRegFormAjax( lastobj_id );
  }
}

var yearSetByUser = false;
var monthSetByUser = false;
var daySetByUser = false;
var completeDateSetByUser = false; //A flag for us to know when the user has played with all the date fields

function verifyRegFormBirthdate(){
  var formYear = parseInt($j("#y").val());
  var formMonth = parseInt($j("#m").val());
  var formDay = parseInt($j("#d").val());

  //Flaggin the user action regarding birhdate
  if(!isNaN(formYear))
    yearSetByUser = true;
  if(!isNaN(formMonth))
    monthSetByUser = true;
  if(!isNaN(formDay))
    daySetByUser = true;
  if(yearSetByUser && monthSetByUser && daySetByUser)
    completeDateSetByUser = true; //Flag that will avoid the feedback for the birthdate to be shown until the user has played with all date fields

  if(!isNaN(formYear) && !isNaN(formMonth) && !isNaN(formDay))
  {
    if(formDay > 30 && (formMonth == 4 || formMonth == 6 || formMonth == 9 || formMonth == 11) || (formMonth == 2 && formDay > 29))
    {
      showFormStatus("invalid_birthdate", true);
    }else //Date is valid
      showFormStatus("ok_birthdate", true);
  }else if(clickedRegister || (yearSetByUser && monthSetByUser && daySetByUser)){ //User set all fields at least once but date is invalid, or clicked the register button
    showFormStatus("invalid_birthdate", true);
  }
}

function verifyRegFormEmail(email)
{
  if (email.length > 0) {
    if (verifyContact("mail", email) )
      showFormStatus("ok_email");
    else
      showFormStatus("invalid_email");
  }else{
      showFormStatus("invalid_email");
  }
}

function verifyRegFormPassword()
{
  var reg_form  = document.forms["reg_form"];
  var usr       = trim(reg_form["username"].value);
  var pwd       = reg_form["password"].value;
  var cfm_pwd   = reg_form["confirm_password"].value;

  //Check password is between 6 and 20, no spaces
  if (pwd.length < 6 || pwd.length >= 20 || !jsCheckAttribute('password',pwd) ||
      (usr.length && (pwd.indexOf(usr) != -1 || usr.indexOf(pwd) != -1)) ) {
    showFormStatus("invalid_password", true);
    return false; //no need to ajax, invalid password
  }

  if (pwd == cfm_pwd) {
    showFormStatus("ok_confirm_password");
  } else if (cfm_pwd.length > 0) {
    showFormStatus("invalid_confirm_password", true);
    return false; //no need to ajax, missmatched password
  }
  //OK to make a ajax check
  return true;
}


function showFormStatus(feedback, updbtn, lastobj_id)
{
  var divobj;
  var retest = false;
  if (typeof feedback == "object")
  {
    for (var m=0 ; m<feedback.length ; m++)
    {
      if (processFieldStatus(feedback[m]))
        retest = true;
    }
  }
  else
    if(processFieldStatus(feedback))
      retest = true;

  if (retest && lastobj_id != undefined)
    verifyRegFormAjax( lastobj_id );
}


function processFieldStatus(msg)
{
  var res = msg.split("_");
  if (res.length > 2)
    res[1] = res.slice(1).join("_");
  var formElement; //The thing where we have information
  var groupClass; //The thing to highlight
  if(res[1] != "birthdate"){
    formElement = $j("#reg_form #"+res[1]); //If it's not the birthdate we select by Id
    singleElement = true;
  }else{
    formElement = $j(".register_birth"); //For birthdate we select by class
    singleElement = false;
  }

  if (msg.substr(0,3) == "ok_") {
    eval("register_status."+res[1]+" = true;");
    if(formElement != undefined) {
      formElement.removeClass("failure"); //Removing the CSS class of the failure since now it's fine
      formElement.addClass("valid"); //Removing the CSS class of the invalid since now it's fine
    	showFeedback(res[1], "", false);
    	if(res[1] == "username")
    		showFeedback("internal", str_block_allsports, false);
    }
  }
  else if (msg.substr(0,8) == "invalid_" || msg.substr(0,6) == "taken_") {
    eval("register_status."+res[1]+" = false;");
    //If it's not a singleElement then there is no point in checking val()
    if ((singleElement && (clickedRegister || formElement.val() != "")) || res[1] == "raf_code" ||
      (res[1] == "birthdate" && ( completeDateSetByUser || clickedRegister)))
    {
      formElement.removeClass("valid");
      formElement.addClass("invalid"); //Adding a CSS class to show the field as having invalid
      showFeedback(res[1], eval("str_"+res[0]+"_"+res[1]), true);
    }
  }
  else if (msg.substr(0,7) == "change_") {
    if (eval("register_status."+res[1]) != undefined) {
      eval("register_status."+res[1]+" = false;");
      showFeedback(res[1], eval("str_"+res[0]+"_"+res[1]), true);
    }
    else {
      // Got team in sport, option to change sport to register in.
      if ( confirm( str_change_sport.replace("%s",res[1])) ) {
        return sendRegisterForm(res[1]);
      }
      else
        lightboxHide();
    }
  }
  else if (msg.substr(0,6) == "block_"){
    if (register_status.username != undefined) {
      register_status.username = false;
      showFeedback("internal", eval("str_"+res[0]+"_"+res[1]), true);
    }
  }
  else if (msg.substr(0,4) == "key_") {
    document.forms["login"]["md5c"].value = res[1];
    return true;
  }
  return false;
}


function showFeedback(field, msg, show)
{
  var id = "#reg_feedback_"+field;
  if (show) {
    $j(id).html(msg);
    $j(id).css('visibility','visible');
  }
  else {
    //Just enough if I hide it, I save time by don't changing the html in the div
    $j(id).css('visibility','hidden');
  }
  return true;
}

var allowCodeRequest = true;
var allowRequestTimeout;
/********************************************************************************************
 * Funtion to change the image code and allow a new request
 *******************************************************************************************/
function callbackRefreshCode(data){
  $j('#secretCodeImage').html(data); //Change image
  allowCodeRequest = true; //Change flag so we allow a new request
  return true;
}

/********************************************************************************************
 * Ajax call for a new code that handles the status and feedback of the secrecy
 *******************************************************************************************/
function ajaxRequestRefreshCode(){
  $j('#secrecy').val('').removeClass("invalid"); //Cleaning the previous code and changing style to normal
  $j('#secrecy').val('').removeClass("valid");
  showFeedback('secrecy', '', false); //Hidding feedback
  register_status.secrecy = false; //Changing validation status
  if(allowCodeRequest){ //Checking if we should request or not
    allowCodeRequest = false; //Flagging so we are waiting for a request, don't send a new one too soon
    clearTimeout(allowRequestTimeout); //Clearing a possible previous timeout
    allowRequestTimeout = setTimeout("allowCodeRequest=true;",10000); //Just in case the response got lost, we will automatically allow a new request in 10 seconds
    $j.get("ajax_com/start.php", {val: 'refreshSecretCode'}, callbackRefreshCode);
  }
}


function prepareRegistration(readyState, response, responseParameter)
{
  if (readyState == 4) {

    //Once a registration window is activated we will disable all tabindexes for the reg tabindexes to be the only ones
    //avoiding "conflicts"
    $j("a").attr("tabindex",-1);
    $j("input").attr("tabindex",-1);

    eval(response);
    if (templates['regselectsport']) {
      lightboxShow(900, [templates['regform'][0], "lefttitle", "closebutton"], templates['regform'][1]); //regform
      lightboxSetPosY(130);
      //setTimeout( "document.reg_form.username.focus()", 100); //By uncommenting this line you'll have an autofocus on username
      //disableButton("savebutton");
    }

    var yPos = 30; //Just a little padding down
    if($j('#partnerTop').length){ //If we are in a branded site let's move the thing down
      partnerHeight = parseInt($j('#partnerTop').height());
      yPos = yPos + partnerHeight;
    }

    $j('#lightbox_old').css({'display': 'block','position': 'absolute','top' : yPos});
    $j('#lightbox_old').draggable({ handle:'.mz_powerboxTop', cursor: 'move' }); //Making the 'pop-up' draggable

    $j('.mz_powerboxTitle').addClass("welcomeHeader");

    $j('#secretCodeRefresh').click(ajaxRequestRefreshCode); //Even onClick for ajaxing a new secret code

    //$j('#overlay').bind("click", clearLightboxes);//Overlay is the name of the dark layer around the lightbox, so on click we close all powerboxes
    $j(window).bind("resize",centerRegisterLightbox); //When the window will be resized, we'll readjust the position of the lightbox
  }
}

function centerRegisterLightbox(){
    var yPos = 30; //Just a little padding down
    if($j('#partnerTop').length){ //If we are in a branded site let's move the thing down
      partnerHeight = parseInt($j('#partnerTop').height());
      yPos = yPos + partnerHeight;
    }
    windowWidth = $j(window).width();
    lightBoxObj = $j('#lightbox_old');
    xPos = (windowWidth - lightBoxObj.width())/ 2;
    lightBoxObj.css({'display': 'block','position': 'absolute','top' : yPos, 'left': xPos});
    $j("#overlay").width(windowWidth);
}

/*
function showRegForm(sport, email)
{
  if (sport != undefined)
    register_status.sport = sport;
  else
    register_status.sport = ajaxSport;
  lightboxShow(900, [templates['regform'][0], "lefttitle", "closebutton"], templates['regform'][1]);
  //lightboxSetPosY(130);
  setRegFormSport(sport);
  //setTimeout( "document.reg_form.username.focus()", 100);
  //disableButton("savebutton");
  if (email != undefined) {
    populateRegForm(email);
  }
}
*/

/*
function setRegFormSport(sport)
{
  if (document.getElementById("regformsportimg") && templates['regformtitle_'+sport] != undefined) {
    document.getElementById("regformsportimg").src = templates['regformtitle_'+sport];
    return true;
  }
  return false;
}
*/


function populateRegForm(email)
{
  var logindata = document.forms["logindata"];
  var reg_form  = document.forms["reg_form"];
  if (logindata && reg_form) {
    reg_form["username"].value = logindata["username"].value;
    reg_form["password"].value = logindata["password"].value;
    reg_form["email"].value = email;
    verifyRegForm(reg_form["username"]);
  }
}


function validateTeamStatus(readyState, response, responseParameter)
{
  if(readyState==4)
  {
    if(response.indexOf("templates")==0)
    {
      eval(response);
      if(templates['creationstatus'] && templates['creationstatus']['body']!="")
      {
        lightboxShow(450, ["", "closebutton"], templates['creationstatus']['body']);
        lightboxSetPosY(130);
        if(templates['creationstatus']['continue'])
        {
          startcreationcheck();
        }
      }
    }
    else if(response.indexOf("window")==0)
    {
      eval(response);
    }
  }
}

function checkCreationStatus()
{
  ajaxCall('ajax_com/start.php', 'val=getTeamCreationStatus&act=' + templates['creationstatus']['act'], 'validateTeamStatus', '');
}

function stopcreationcheck()
{
  clearTimeout(creationtimer);
}

function startcreationcheck()
{
  creationtimer = setTimeout("checkCreationStatus()",15000);
}

/*************************************************************
 * jquery registration code
 *************************************************************/

//This function makes all divs belonging to className to be hidden
function hideAllOfAClass(className){
  $j("."+className).css('visibility','hidden');
  return true;
}

/**************************************************************************
 * This function gets an ID which is a related to the same ID but with _exp,
 * where "ID_exp" is a contextual help div which is going to be shown close
 * to ID
 *************************************************************************/
function showExplanation(id, side){

  var leftPos;
  var topPos;

  var expId = "#" + id + "_exp";
  var position = $j("#"+id).position();
  var size = $j(expId).width();

  //If we detect the window size/resolution is too little then
  //we invert the original design for the contextual help items, so they are displayed within the lightbox
  if($j(window).width() < 1281){
    if(side == "left")
      side = "right";
    else
      side = "left";
  }

  if(side == "left"){
    leftPos = position.left - ( size + 5);
    $j('#'+id+'_arrow_right').css({'visibility:':'visible','display':'block'});
    $j('#'+id+'_arrow_left').css({'visibility:':'hidden','display':'none'});
  }else{
    leftPos = position.left + $j("#"+id).width() + 10;
    $j('#'+id+'_arrow_left').css({'visibility:':'visible','display':'block'});
    $j('#'+id+'_arrow_right').css({'visibility:':'hidden','display':'none'});
  }
  topPos = position.top;

  if(id == "birth"){
    topPos = topPos + 24; //There is a little error for the birthdate selects we are fixing here
    if(side == "right")
      leftPos = position.left + $j("#d").width() + $j("#m").width() + $j("#y").width() + 35;
  }


  $j(expId).css({
     'display': 'block',
     'position': 'absolute',
     'top' : topPos,
     'left': leftPos,
     'visibility' : 'visible'
  });
}

function showRafContent(){

  workingElement = $j('.rafCellDefault').addClass('inputCell');

  displayStyle = ($j.browser.msie)?'inline':'table-cell';

  //Making the 'click to display' invisible
  $j('.toggleRaf').css({
     'display': 'none',
     'visibility' : 'hidden'
  });
  //Making the RAF input visible
  $j('.rafContent').css({
     'display': displayStyle,
     'visibility' : 'visible'
  });
  return true;
}

