/**
 * custom.js
 * 
 * Include the sidebar world clock in the time div.
 * table sorter : allow to sort tables with click on 
 * hide manifest : fancy effect to minimize manifest sidebar box
 * ajaxify the modification forms of the user_profile view and treat em with modify_profile controller.
 * 
 * ~/public/scripts/custom.js
 */

/* PATH CONFIG */
if (window.location.hostname == "www.elementsofnocturne.info"){
	var JS_URL_ROOT = "http://www.elementsofnocturne.info/";
} else {
	var JS_URL_ROOT =  "http://" + window.location.hostname + "/Zend/eoN/";
}

function strtok (str, tokens) {
    // Tokenize a string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/strtok
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: Use tab and newline as tokenizing characters as well
    // *     example 1: $string = "\t\t\t\nThis is\tan example\nstring\n";
    // *     example 1: $tok = strtok($string, " \n\t");
    // *     example 1: $b = '';
    // *     example 1: while ($tok !== false) {$b += "Word="+$tok+"\n"; $tok = strtok(" \n\t");}
    // *     example 1: $b
    // *     returns 1: "Word=This\nWord=is\nWord=an\nWord=example\nWord=string\n"
    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    // END REDUNDANT

    if (tokens === undefined) {
        tokens = str;
        str = this.php_js.strtokleftOver;
    }
    if (str.length === 0) {
        return false;
    }
    if (tokens.indexOf(str.charAt(0)) !== -1) {
        return this.strtok(str.substr(1), tokens);
    }
    for (var i=0; i < str.length; i++) {
        if (tokens.indexOf(str.charAt(i)) !== -1) {
            break;
        }
    }
    this.php_js.strtokleftOver = str.substr(i+1);
    return str.substring(0, i);
}

/* cookies functions */
function setCookie(name, value, days) {
    var expDate = new Date()
    expDate.setTime(expDate.getTime() + (days * 24 * 3600 * 1000))
    document.cookie = name + "=" + escape(value)
        + ";expires=" + expDate.toGMTString()
    }

function getCookie(nom) {
    deb = document.cookie.indexOf(nom + "=")
    if (deb >= 0) {
        deb += nom.length + 1
        fin = document.cookie.indexOf(";",deb)
        if (fin < 0) fin = document.cookie.length
        return unescape(document.cookie.substring(deb,fin))
        }
    return null
    }

/* the gmt-cet-local clock */
function time(){
	var myClock = getCookie("clock");
	
	if (!document.getElementById('timebox')) {
		$("#time").append("<form id=\"fadetime\"><select></select></form>");
		if ((myClock != null && myClock == "gmt")
			|| myClock == null ){
			$("#time select").append('<option value="gmt" selected="selected">GMT</option>');
		}else{
			$("#time select").append('<option value="gmt">GMT</option>');
		}
		if (myClock != null && myClock == "cet"){
			$("#time select").append('<option value="cet" selected="selected">CET</option>');
		}else{
			$("#time select").append('<option value="cet">CET</option>');
		}
		if (myClock != null && myClock == "cest"){
			$("#time select").append('<option value="cest" selected="selected">CEST</option>');
		}else{
			$("#time select").append('<option value="cest">CEST</option>');
		}
		if (myClock != null && myClock == "local"){
			$("#time select").append('<option value="local" selected="selected">Local</option>');
		}else{
			$("#time select").append('<option value="local">Local</option>');
		}
		$("#time form").append('<input id="timebox" type="text" readonly="readonly"></input>');
	}
	
	var current_date = new Date();
	
	/* get the 3 wanted times */
	var cetHours = current_date.getUTCHours() + 1; // CET = UTC +1
	var cestHours = cetHours + 1;
	var hours = new Array(current_date.getHours(), current_date.getUTCHours(), cetHours, cestHours); 
	var minutes = new Array(current_date.getMinutes(), current_date.getUTCMinutes(),  current_date.getUTCMinutes(),  current_date.getUTCMinutes());

    var current_time = new Array('hours', 'minutes', 'final');
    current_time['hours'] = hours ;
    current_time['minutes'] = minutes ;
    current_time['final'] = new Array();
    
    /* add the 0 for 1 number times and format the cetHours to 0 if it is to 24 (UTC+1) */
	for(var i = 0 ; i < 4 ; i++){
		if (current_time['hours'][i] >= 24){current_time['hours'][i] -= 24;}
		if (current_time['hours'][i] < 10){current_time['hours'][i] = '0' + current_time['hours'][i];}
		if (current_time['minutes'][i] < 10){current_time['minutes'][i] = '0' + current_time['minutes'][i];}
		current_time['final'][i] = current_time['hours'][i] + ' : ' + current_time['minutes'][i];
	}

	/* switch the time displayed according to the selected item */
	switch($('#time select :selected').val()){
		case "cet":
			$("#fadetime").fadeOut("normal",function () {
				$("#time form input").val(current_time['final'][2]);
				if (myClock == null || myClock != "cet"){ 
					  setCookie("clock", "cet", "30");
				}
				$("#fadetime").fadeIn("normal");
			});
		break;
		case "cest":
			$("#fadetime").fadeOut("normal",function () {
				$("#time form input").val(current_time['final'][3]);
				if (myClock == null || myClock != "cest"){
					  setCookie("clock", "cest", "30");
				}
				$("#fadetime").fadeIn("normal");
			});
			break;
		case "local":
			$("#fadetime").fadeOut("normal",function () {
				$("#time form input").val(current_time['final'][0]);
				if (myClock == null || myClock != "local"){
					  setCookie("clock", "local", "30");
				}
				$("#fadetime").fadeIn("normal");
			});
			break;
		default :
			$("#fadetime").fadeOut("normal",function () {
				$("#time form input").val(current_time['final'][1]);
				if (myClock == null || myClock != "gmt"){
					  setCookie("clock", "gmt", "30");
				}
				$("#fadetime").fadeIn("normal");
			});
	}

	t = setTimeout("time()", 60000);
}// end time()

/* Reload captcha */
function reload_captcha(){
	var captcha_name = strtok($("#captcha [type='radio']").attr("name"), '[');
	var p_data = 'captcha_id=' + captcha_name; // the datas to post are name="name of the form"
	if (window.location.hostname == "www.elementsofnocturne.info"){
		$.post("http://www.elementsofnocturne.info/captcha/captcha",
				p_data,
				function(data){
					$("#captcha").html($("#captcha_ajax", data).html());
				}
		);
	} else {
		$.post("http://" + window.location.hostname + "/Zend/eoN/captcha/captcha",
				p_data,
				function(data){
					$("#captcha").html($("#captcha_ajax", data).html());
				}
		);
	}
	
	return false;
}

/* NicEditorConfig */
var Nic_iconsPath = JS_URL_ROOT + "public/scripts/nicEditorIcons.gif";



/* when the page is loaded */
$(document).ready(function(){
	
	/* Clock displaying and area managing(gmt-cet-local) */
	time();
	$("#time select").change(function(event){
		clearTimeout(t);
		time();
	});
	
	/* table sorter : allow to sort tables with click on <th> */
	$(document).ready(function(){
		$("#members_table").tablesorter();
	});
	
	/* hide/show sidebar manifest : fancy effect to minimize / maximize the manifest */
	$("#manifest").hide();
    $("#manifest").parent("div").click(function () {
        if ($("#manifest").is(":hidden")) {
        	$("#manifest").slideDown("slow");
        } else {
        	$("#manifest").slideUp("slow");
        }
      });
    
	/* hide/show gathering : fancy effect to minimize gathering*/
    $("#subgathering").parent("div").click(function () {
        if ($("#subgathering").is(":hidden")) {
        	$("#subgathering").slideDown("slow");
        } else {
        	$("#subgathering").slideUp("slow");
        }
      });
    
	/* hide/show links : fancy effect to minimize links*/
    $("#sublinks").parent("div").click(function () {
        if ($("#sublinks").is(":hidden")) {
        	$("#sublinks").slideDown("slow");
        } else {
        	$("#sublinks").slideUp("slow");
        }
      });
    
	/* sho rank_infos*/
    $("div#rank_infos_p").hide();
    $("a.rank_infos_h").click(function () {
        if ($("div#rank_infos_p").is(":hidden")) {
        	$("div#rank_infos_p").slideDown("slow");
        } else {
        	$("div#rank_infos_p").slideUp("slow");
        }
      });
    
	/* switch subscription form */
    if ($("#sub_apply").is(":checked")) {
    	$("#subscription_applicant input").addClass("required");
    	$("#subscription_applicant textarea").addClass("required");
    	$("#subscription_applicant").slideDown("slow");
    	$("#subscription_member").fadeOut("normal");
    }
    $("#sub_apply").livequery('change',function(){
        if ($("#sub_apply").is(":checked")) {
        	$("#subscription_applicant input").addClass("required");
        	$("#subscription_applicant textarea").addClass("required");
        	$("#subscription_applicant").slideDown("slow");
        	$("#subscription_member").fadeOut("normal");
        } else {
        	$("#subscription_applicant input").removeClass("required");
        	$("#subscription_applicant textarea").removeClass("required");
        	$("#subscription_applicant").slideUp("slow");
        	$("#subscription_member").fadeIn("normal");
        }
      });
    
	/* select right rank when changing the role */
    var link_role_rank = [ 
                          	['leader','5'],
                          	['co_leader','5'],
                          	['recruiter','10'],
                          	['cw_arranger','15'],
                          	['praccy_arranger','15'],
                          	['member','20'],
                          	['trial','25'],
                          	['applicant','30'],
                          	['visitor','35']
                     	  ];

    $("select.list_role").change(function(){
		var link_length = link_role_rank.length;
		for(var i = 0; i < link_length; i++){
			if($(this).val() == link_role_rank[i][0]) {
				$(this).parent("td").next().children("select").children("option").each(function(){
					if($(this).attr("selected") && $(this).val() != link_role_rank[i][1]){
						$(this).attr("selected",false);
					}	
		    		if($(this).val() == link_role_rank[i][1]){
		    			$(this).attr("selected","selected");
		    		}
		    	});
			}
		}
    });
    
    $("select.list_rank").change(function(){
		if($(this).val() < 30) {
			var happend = false;
			$(this).parent("td").prev().children("select").children("option").each(function(){
				if($(this).attr("selected") && ($(this).val() == 'visitor' || $(this).val() == 'applicant')){
					happend = true;
					$(this).attr("selected",false);
				}	
	    		if($(this).val() == 'member' && happend){
	    			$(this).attr("selected","selected");
	    		}
	    	});
		}
    });
    
	/* highlight captcha icon */
    $("div#captcha label img").livequery('click',function() {
    	
    	var current_radio = $(this).parent().prev();
    	current_radio.checked = true;
    	current_radio.attr("checked","true");
	
    	var images = $("div#captcha label img");
    	
    	images.each(function(){
    		images.css('border-style','none');
    	});
    	
    	$(this).css('border-style','solid');
    	$(this).css('border-width','1px');
    	$(this).css('border-color','#3B81BE');
      });
	
    /* forms validation */
    $("#contact_form").validate();
    
	// validate signup form on keyup and submit
	$("#subscription_form").validate();
	$("#news_form").validate();
	$("#gathering_form").validate();
    
    /* modification forms */
	$("form#modification_form .m_modif").hide();
	$("#about").hide();
	$("form#modification_form .m_form").click(function(){
		var switched = $(this).next();
		var ta = false;
		if($(this).is("dt")){
			if (switched.find(":last-child").is("textarea")){
				ta = true;
				if(typeof(txt)=='undefined'){ 
					new nicEditor({	iconsPath : Nic_iconsPath, 
													buttonList : [	'fontSize','fontFamily','fontFormat',
																					'bold','italic','underline','strikethrough',
													              	'forecolor','bgcolor',
													              	'subscript','superscript',
													              	'removeformat',
																					'ol','ul','hr',
																					'left','center','right','justify',
																					'link','unlink'
																				]
												}).panelInstance('about');
				}
			} else {
				switched = switched.next(".m_modif");
			}
		}
		
    	if(switched.is(":visible") == false) switched.slideDown("slow");
		else if(! switched.find(":last-child").is("textarea")) switched.slideUp("slow");
	});

	
    /*
    $(".modify_form form").hide();
    $(".modify_form").each(function(){
    	var container = $(this);
    	
    	// Hiding the modification forms
    	$(this).find('a.img').click(function(){
            if( $(this).next().is(":visible") == false) {
            	$(".modify_form form").fadeOut("slow");
    			$(this).next().fadeIn("slow");
            }
            else
            {
            	$(this).next().fadeOut("slow");
            }
    	});
    	    	
        // Ajaxify datas modification
    	
    	$(this).find('form').submit(function(event){ // when form is submit
    		var input = $(this).find('input');
    		// var p_data = input.attr("name") + '=' + input.val(); // old before id in modify_profile
    		var p_data = input.attr("name") + '=' + input.val() + '&id=' + input.next().val(); // the datas to post are name="value of the input field" 
    		$.post("../modify_profile",
    				p_data,
    				function(data){
    					container.find(".data").html($("div#callback", data).html());
		    		}
    		);
    		$(this).fadeOut("slow");
    		return false; // submit effect is canceled 
    	});
    	
    	$(this).find('#ap_checkbox').change(function(event){
    		var p_data = $(this).attr("name") + '=' + $(this).val();
    		$.post("../modify_profile",
    				p_data,
    				function(data){
    					container.find(".data").html($("div#callback", data).html());
    					container.find("form").html($("div#callback_checkbox", data).html());    					
		    		}
    		);
    		$(this).parent().fadeOut("slow");
    		return false;
    	});
    });
    */
});
