//jquery initialization


$(document).ready(function(){
	
 	$(".hiddenbox").hide(0);
	$(".showhiddenbox").toggleClass("title_shown");
	$(".showhiddenbox").click(function(){
		$(this).toggleClass("title_shown");
		$(this).parent().parent().find(".hiddenbox").toggle("slow");
	});
	//$(".showhiddenbox").text($(".showhiddenbox").text().replace("hide","show"));
	//$(".showhiddenbox").toggle();
	
	$.each($(".courriel_address_container"),writeEmails);
	
	createDropDownZones();
});

function parseAllUrl(){
	//parse current url
	//url looks like : http://www......./pages/pagename/#/type:val,val/type:val,val/
	// for example, we want type=tdvs (toggledivs)
	// tdvs:1,2,4 // list of the divs which are shown
	
	var types = [];
	var name,vals;
	var urlanchor = window.location.href.split('#');
	if(1 == urlanchor.length)
		return [];
	urlanchor =urlanchor[1].split('/');
	//console.log("parsing :");
	for(var i=0;i<urlanchor.length;i++){
		name = urlanchor[i].substring(0,urlanchor[i].indexOf(':'));
		vals = urlanchor[i].substring(urlanchor[i].indexOf(':')+1).split(',');
		//console.log(name,vals);
		if(name.length && vals.length){
			types.push([name,vals]);
		} 
	}
	//console.log("parsed result :");
	//console.log(types);
	return types;
}

function unParseAllUrl(types){
	//console.log("Unparse :");
	//console.log(types);
	var href = window.location.href.split('#')[0] + "#";
	for(var i=0;i<types.length;i++){
		//console.log("unparsing ",i," vals  :",types[i][1]);
		types[i][1] = filterArray(types[i][1]); 
		//console.log("unparsing ",i," vals_clean  :",types[i][1]);
		if(types[i][1].length && types[i][0].length)
			href += "/" + types[i][0] + ':' +types[i][1].join(',');
	}
	
	window.location.href = href;
}

function filterArray(arr){
	var arr2 = [];
	var val;
	while(arr.length){
		val = arr.pop();
		//console.log("filter -- val : ",val);
		if( "number" == typeof val  || val != [] ){
			arr2.push(val);
			//console.log("filter -- OKval : ",val);
		}
	}
	//console.log("arr: ",arr," arr2: ",arr2);
	return arr2;
}
	
function parseUrl(type){
	
	types = parseAllUrl();
	for(var i=0;i<types.length;i++)
		if(type == types[i][0])
			return types[i][1];
			
	return false;
}

function addToUrl(type,vals){
	types = parseAllUrl();
	types.push([type,vals]);
	unParseAllUrl(types);
}

function addValToUrl(type,val){
	types = parseAllUrl();

	for(var i=0;i<types.length;i++)
		if(type == types[i][0]){
			types[i][1].push(val);
			//console.log("added my val to types :  ",types);
			unParseAllUrl(types);
			return;
		}	
	types.push([type,[val]]);
	//console.log("created new types :  ",types);
	unParseAllUrl(types);
}

function removeTypeFromUrl(type){
	types = parseAllUrl();
	for(var i=0;i<types.length;i++)
			if(type == types[i][0])
				types[i] = false;
	unParseAllUrl(types);
}

function removeValFromUrl(type,val){
	types = parseAllUrl();
	for(var i=0;i<types.length;i++)
			if(type == types[i][0]){
				nvals = [];
				for(var j=0;j<types[i][1].length;j++)
					if(val != types[i][1][j])
						nvals.push(types[i][1][j]);
				types[i][1] = nvals;
			}
	unParseAllUrl(types);
}

function createDropDownZones(){
	var div_prefix = 'ddz-';
	var url_type = "tdvs";
	
	$(".drop-down-zone").each(function(index){
		$(this).attr('id',div_prefix+index);
	});
	
	// type=tdvs (toggledivs)
	// tdvs:1,2,4 // list of the divs which are shown

	var divs_to_show = parseUrl(url_type);
	//console.log("divs_to_show : ",divs_to_show);
	
	if(divs_to_show.length)
		for(var i=0;i<divs_to_show.length;i++)	
			$("#"+div_prefix+divs_to_show[i]+".drop-down-zone").addClass('nohide');
	
	$(".drop-down-zone:not(.nohide)").hide();


	$(".drop-down-zone")
		.prev("h4")
		.addClass('drop-down-zone-prepend');
	$(".drop-down-zone")
		.prev("*:not(h4)")
		.after('<div class="drop-down-zone-prepend"><a href="#" class="toggle">show</a></div>');
	
	
	$(".drop-down-zone").prev("div.drop-down-zone-prepend").children("a.toggle").click(
					function(){		
						var id = parseInt($(this).parent()
									.next(".drop-down-zone")
									.attr('id').substring(div_prefix.length));
						if("none" == $(this).parent().next(".drop-down-zone").css('display')){
							$(this).html("hide");
							$(this).parent().next(".drop-down-zone").slideDown('slow');
							addValToUrl(url_type,id);
						}else{
							$(this).html("show");
							$(this).parent().next(".drop-down-zone").slideUp('slow');
							removeValFromUrl(url_type,id);
						}
						return false;
					});
	
	$(".drop-down-zone").prev("h4.drop-down-zone-prepend")
	.css('cursor','pointer')
	.append('<a href="#" class="toggle">show</a>')
	.click(function(){
				var id = parseInt($(this).next(".drop-down-zone")
					.attr('id').substring(div_prefix.length));				
				if("none" == $(this).next(".drop-down-zone").css('display')){
					$(this).children("a.toggle").html("hide");
					$(this).next(".drop-down-zone").slideDown('slow');
					addValToUrl(url_type,id);
				}else{
					$(this).children("a.toggle").html("show");
					$(this).next(".drop-down-zone").slideUp('slow');
					removeValFromUrl(url_type,id);
				}
				return false;
			});
	
	// if it's shown, the link should read "hide"
	$(".drop-down-zone:visible").prev(".drop-down-zone-prepend").children("a.toggle").text("hide");

}

function writeEmails(index,span_name){
	$($(span_name).find("span")[0]).append("@");
	$($(span_name).find("span")[1]).append(".");
	var add = $(span_name).find("span").text();
	$(span_name).text(add);
	$(span_name).html(	'<a href="&#109;&#97;&#105&#108;&#116;&#111;&#58;'+add+'">'+add+'</a>'	);
}


function email(login,domaine,show) 
{ 
	 if(!show)
		show=login + ' (a) ' + domaine;
	 document.write('<a href="mailto:' + login + '@' + domaine + '">' + show + '</a>'); 
 }
 
 
function sfHover() {
	var sfEls = $("#Menu li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}


if (window.attachEvent) window.attachEvent("onload", sfHover);
shown_elem = null;


function switch_elems(elem)
{
	$("#" + 'div_'+elem).css('display','block');
	$("#" + 'a_'+elem).text('(-) less');
	if(shown_elem != null )
	{
		$("#" + 'div_'+shown_elem).css('display','none');
		$("#" + 'a_'+shown_elem).text( '(+) more');
	}
	
	if(shown_elem  == elem)
		shown_elem = null;
	else
		shown_elem  = elem;
}


/*** JS fake popups ***/
function switch_show_hide(div)
{
	obj = $("#" + div);
	ln = $("#" + 'show_hide_' +div);
	if( obj.css('display') == 'none' )
	{
		obj.css('display','block');
		ln.text( 'hide');
	}
	else
	{
		obj.css('display','none');
		ln.text('show');
	
	}
}


function SwitchShow(id)
{
	obj = $("#" + id);
	if( obj.css('display') == 'none' )
		obj.css('display','block');
	else
		obj.css('display','none');
}


//function GeBi(id)
//{
//	return document.getElementById(id);
//}




var Base64 = {
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = Base64._utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },
    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = Base64._utf8_decode(output);
        return output;
    },
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}
//*/

