var t=0;
function onInitpage(){
  generalInit()
}
function generalInit(){
  initInPlaceEdit();
  $(".drawersystem .drawerhandle .openctl, .drawersystem .drawerhandle .closectl").click(function (){
    $(this).parent().children(".openctl, .closectl").toggle();
    //$(".drawersystem .drawerhandle .openctl").toggle();
    //$(".drawersystem .drawerhandle .closectl").toggle();
    $(this).parents(".drawersystem").filter(':first').children(".drawer").toggle('normal');
    //$(".drawersystem .drawer").toggle('normal');
    });
}
function onInithomepage(){
  initInPlaceEdit();
}
function onInitgestiondusitepage(){
  generalInit();
}
function saveInPlaceEdit(){
  postSingleAction('{"name":"getusers","searchparams":{"fn":"'+fn+'","ln":"'+ln+'","email":"'+em+'"}}',handleFoundUsers,handleJSONFailure);  
}
function initInPlaceEdit(){
  $(".savebtn, .savelink").click(function () {
    themod = $(this).parents(".module");
    pageid = themod.find(".pageid").val();
    editorid = themod.find(".tinymce").attr('id');
    data = tinyMCE.get(editorid).getContent();
    varname = themod.find(".tinymce").attr("name");
    //alert("Page id is: "+pageid);
    postSingleAction('{"name":"savecontent","module":{"pageid":"'+pageid+'","name":"'+varname+'","data":"'+escape(data)+'"}}',cbIPEditSuccess,cbIPEditFailed);
    themod.find(".content").html(data);
    themod.find(".savelink").css("display", "none");
    themod.find(".editlink").css("display", "block");
    themod.find(".editor").css("display", "none");
    themod.find(".content").css("display", "block");
    return false;
  });
  $(".previewbtn").click(function () {
    themod = $(this).parents(".module");
    //data = themod.find(".tinymce").html();
    //data = themod.find(".tinymce").get('text').getContent();
    //data = tinyMCE.activeEditor.getContent();
    //data = themod.find(".tinymce").getContent();
    editorid = themod.find(".tinymce").attr('id');
    data = tinyMCE.get(editorid).getContent();
    themod.find(".content").html(data);
    themod.find(".content").css("display", "block");
    themod.find(".editor").css("display", "none");
    themod.find(".editlink").css("display", "block");
    themod.find(".savelink").css("display", "block");
    return false;
    //varname = themod.find(".tinymce").attr("name");
  });
  $(".cancelbtn").click(function () {
    location.reload();
    /*themod = $(this).parents(".module");
    themod.find(".content").css("display", "block");
    themod.find(".editor").css("display", "none");
    themod.find(".editlink").css("display", "block");
    themod.find(".savebtn").unbind('click');*/
    return false;
  });
  $(".editlink").click(function () {
    $(this).parents(".module").find(".editlink").css("display", "none");
    $(this).parents(".module").find(".savelink").css("display", "none");
    $(this).parents(".module").find(".content").css("display", "none");
    $(this).parents(".module").find(".editor").css("display", "block");
    data = $(this).parents(".module").find(".content").html();
    $(this).parents(".module").find(".tinymce").val( data );
    $(".module.editmode").css("display", "block");
    $('textarea.tinymce').tinymce({
			// Location of TinyMCE script
			script_url : '/s/js/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "safari,pagebreak,style,table,save,advhr,advimage,advlink,iespell,inlinepopups,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking",

			// Theme options
			theme_advanced_buttons1 : "save|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,|,fullscreen",
      theme_advanced_buttons2 : "cut,copy,paste|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,image,cleanup,code,|,forecolor,backcolor",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			// Example content CSS (should be your site CSS)
			content_css : "/css/hlsl.css"

			// Drop lists for link/image/media/template dialogs
			//template_external_list_url : "lists/template_list.js",
			//external_link_list_url : "lists/link_list.js",
			//external_image_list_url : "lists/image_list.js",
			//media_external_list_url : "lists/media_list.js"
		});
	});

}
function onInitLeaguepage(){
  $(".adminbtn").click(function () {
    $(".adminctl").toggle('slow');
    $(".adminbtn .opctl").toggleClass('shown');
    $(".adminbtn .clctl").toggleClass('shown');
  });
}
function onInitgestiondusagerpage(){
  if($(".usersearch").length){
    $("#fe_fn").keyup(function(){
      onSearckKeyHit();
    });
    $("#fe_ln").keyup(function(){
      onSearckKeyHit();
    });
    $("#fe_email").keyup(function(){
      onSearckKeyHit();
    });    
  }
  if($("#ACOpicker").length){
    initACOpicker()
  }
}
function onInitAccountpage(){
  if($(".usersearch").length){
    $("#fe_fn").keyup(function(){
      onSearckKeyHit();
    });
    $("#fe_ln").keyup(function(){
      onSearckKeyHit();
    });
    $("#fe_email").keyup(function(){
      onSearckKeyHit();
    });    
  }
  if($("#ACOpicker").length){
    initACOpicker()
  }
}
function onInitloginpage(){
  $('#password').keyup(function(e) {
    if(e.keyCode == 13) {
      Login();
    }
  });
}
function onInitregistrationpage(){
}
function onInitblogpage(){
  generalInit();
  $('textarea.tinymce').tinymce({
    // Location of TinyMCE script
    script_url : '/s/js/tiny_mce/tiny_mce.js',

    // General options
    theme : "advanced",
    plugins : "safari,pagebreak,style,table,save,advhr,advimage,advlink,iespell,inlinepopups,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking",

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,|,fullscreen,|,link,unlink,image,cleanup,code,|,forecolor,backcolor,|,undo,redo",
    theme_advanced_buttons2 : "cut,copy,paste|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media",
    theme_advanced_buttons3 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,
    // Example content CSS (should be your site CSS)
    content_css : "/css/hlsl.css"

    // Drop lists for link/image/media/template dialogs
    //template_external_list_url : "lists/template_list.js",
    //external_link_list_url : "lists/link_list.js",
    //external_image_list_url : "lists/image_list.js",
    //media_external_list_url : "lists/media_list.js"
  });
}
function onInitgameresultspage(){
  $(".nogamechk").click(function(){
    var elClicked = this;
    /*vaschecked = $(".nogamechk").attr("checked");
    $(".nogamechk").attr("checked", "");
    this.checked = !vaschecked;*/
    $(':checkbox.nogamechk').each(function(){
    if(elClicked != this)
    this.checked = false;
    });
 });   
}
function onInitschedulepage(){
}
function onInituberleaguepage(){
  generalInit();
}
function onInitclassementpage(){
}
function onSearckKeyHit(){
  var strFn = $("#fe_fn").attr("value");
  var strLn = $("#fe_ln").attr("value");
  var strEmail = $("#fe_email").attr("value");
  clearTimeout(t);
  t = setTimeout("handleUserString('"+strFn+"','"+strLn+"','"+strEmail+"')",300);
}
function handleUserString(fn,ln,em){
  postSingleAction('{"name":"getusers","searchparams":{"fn":"'+fn+'","ln":"'+ln+'","email":"'+em+'"}}',handleFoundUsers,handleJSONFailure);  
}
function postSingleAction(action,goodcb, badcb) {
	var jsout='{"action":'+action+'}';
  var data = "format=json&jso="+escape(jsout);
  $.ajax({
    type: "POST",
    url: "/proc.php",
    success: goodcb,
    error: badcb,
    timeout: 10000,
    data:data});
}
function initACOpicker(){
  $("#ACOpicker").change(function(){
    $("#chosenACO").html($("#ACOpicker :selected").text());
    });
}
function initUserSearchResTable(){
  $("#usersearchres TR").hover(function(){
     $(this).children("TD").addClass("hover");
  },function(){
    $(this).children("TD"). removeClass("hover");
  });
  $("#usersearchres TR").click(function(){
    fname = $(this).children(".fn").html();
    lname = $(this).children(".ln").html();
    email = $(this).children(".em").html();
    $("#fe_fn").attr("value",fname);
    $("#fe_ln").attr("value",lname);
    $("#fe_email").attr("value",email);
    $("#chosenUser").html(fname+" "+lname+", &lt;"+email+"&gt;");
    onSearckKeyHit();
  });
}

function onInitAccountpageOld(){
  var password = $("#password"),
      newpassword = $("#newpassword"),
      newpassword2 = $("#newpassword2"),
      allPasswordFields = $([]).add(password).add(newpassword).add(newpassword2);

  $("#showchpswd_btn").click(function(){
    $('#changepassbox').dialog('open');
  });

  $("#changepassbox").dialog({
    bgiframe: true,resizable: false,
    autoOpen: false,
    height: 250,
    modal: true,
    buttons: {
      Cancel: function() {
        $(this).dialog('close');
      },      
      'OK': function() {
        var bValid = true;
        allPasswordFields.removeClass('ui-state-error');

        bValid = bValid && checkLength(password,"password",5,16);
        bValid = bValid && checkLength(password,"newpassword",5,16);
        bValid = bValid && checkLength(password,"newpassword2",5,16);
        bValid = bValid && checkRegexp(newpassword,/^([0-9a-zA-Z])+$/,"Password field only allow : a-z 0-9");
        
        if (bValid) {
          $('#users tbody').append('<tr>' +
            '<td>' + name.val() + '</td>' + 
            '<td>' + email.val() + '</td>' + 
            '<td>' + password.val() + '</td>' +
            '</tr>'); 
          $(this).dialog('close');
        }
      }
    },
    close: function() {
      allPasswordFields.val('').removeClass('ui-state-error');
    }
  });
}
function checkLength(o,n,min,max) {
  if ( o.val().length > max || o.val().length < min ) {
    o.addClass('ui-state-error');
    updateTips("Length of " + n + " must be between "+min+" and "+max+".");
    return false;
  } else {
    return true;
  }
}
function Login(){
  var key 		= document.getElementById('key');
  var handle 		= document.getElementById('handle');
  var password 	= document.getElementById('password');
  var prehash 	= document.getElementById('prehash');
  $.ajax({
    type: "POST",
    url: "/proc.php",
    data: "action=login&getkey=1&handle="+handle.value,
    success: function(resp){
      if(resp !== undefined){
        var tempstr ="resp = "+resp;
        eval(tempstr);
        if(resp.status == "OK"){
          var handle_lower=handle.value;
          handle_lower=handle_lower.toLowerCase();
          var code_string = handle_lower+'|'+password.value+'|'+resp.key.replace(/^\s*|\s(?=\s)|\s*$/g, "");
          key.value=MD5(code_string);
          password.value='';
          document.login_form.submit();
        }else if(resp.status == "passwordexpired"){
          /*$("#messages").css("display","none");
          $("#messages").html("<div class='alert'>"+resp.msg+"</div>");
          $("#messages").fadeIn(1000);
          $.ajax({
            url: "/proc.php",type: "POST",
            data: ({'action':'loadtemplate','name':'element_setpassform.tpl', 'lang':lang}),
            cache: false,
            success: function(html){
              $(".nullwrapper").fadeOut(1000,function(){
                $(".nullwrapper").html(html);
                $(".nullwrapper").fadeIn(1000);
              });
            }
          });*/
        }else{
          alert(resp.msg.fr);
        }
      }      
    },
    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;
}
//----- CALLBACKS ----------- CALLBACKS ----------- CALLBACKS ----------- CALLBACKS ----------- CALLBACKS ------
function cbIPEditSuccess(data, textStatus){
}
function cbIPEditFailed(XMLHttpRequest, textStatus, errorThrown){
}
function handleJSONFailure(XMLHttpRequest, textStatus, errorThrown) {
  if(XMLHttpRequest.status == "403")
    alert("Sorry, you don't seem to be logged-in. Perhaps something happened to your cookies. Go to the home page and log-in. "+XMLHttpRequest.status);
  else
    alert("Sorry, there was an error. Please try again. "+XMLHttpRequest.status);  
}
function handleFoundUsers(data, textStatus){
  var retData = eval( '(' +data+ ')' );
  var el = $("#usersearchres");
  el.empty();
  if(retData.s == "OK"){
    if(!retData.users.length){
    }else{
      if(retData.users.length==1){
        //found just 1, so we are good to go
        $("#uid").val(retData.users[0].id);
      }
      for(var i=0; i<retData.users.length; i++){
        var row = el[0].insertRow(0);
        if(!i) row.className = "first userfound";
        row.className="userfound";
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);
        cell1.innerHTML = retData.users[i].fn ? unescape(retData.users[i].fn) : "";
        $(cell1).addClass("fn");
        cell2.innerHTML = retData.users[i].ln ? unescape(retData.users[i].ln) : "";
        $(cell2).addClass("ln");
        cell3.innerHTML = retData.users[i].email;
        $(cell3).addClass("em");
      }
      initUserSearchResTable();
    }
  }
}