var current_block=false;
var script_name=window.location.pathname;
var tinymceFlag=false;

$(document).ready(function(){
	js_initDataset("$(document).ready()");
	$("#cmsDebug").ajaxComplete(function(e,xhr,settings) {
		if ($('#cmsPost').is(":visible")) {
			//this.innerHTML+="<hr/><strong>node:</strong><pre>"+$.dump(e)+"</pre><br/><strong>Sent:</strong><br/>"+settings.url+"<br/><strong>Got:</strong><br/>"+htmlEncode(xhr.responseText);
			this.innerHTML+="<strong>Sent:</strong><br/>"+settings.url+"<br/><strong>Got:</strong><br/>"+htmlEncode(xhr.responseText)+"<br/>";
		}
		js_initDataset("ajaxComplete()");
	});
});

function htmlEncode(value){ 
    if (value) {
        return jQuery('<div/>').text(value).html(); 
    } else {
        return '';
    }
}

function js_postReturn(oldref,newref) {
	if (current_block) {
		if (oldref==-1) {
			// If it's a new entry
			current_block.parents("div.cmsDataset").attr("ref",newref);
			current_block.parents("div.cmsDataset").eq(0).find(".layout-data").load(script_name+"?cmsMode=ajax_l&action=dataset_data&dataset="+current_block.parents(".cmsDataset").attr("name")+"&mode=view&ref="+newref);
			current_block.parents("div.cmsDataset").eq(0).find(".layout-list").load(script_name+"?cmsMode=ajax_l&action=dataset_list&dataset="+current_block.parents(".cmsDataset").attr("name")+"&ref="+newref);
			current_block.parents("div.cmsDataset").eq(0).find(".layout-table").load(script_name+"?cmsMode=ajax_l&action=dataset_table&dataset="+current_block.parents(".cmsDataset").attr("name")+"&ref="+newref);
		} else {
			// If it's an update, reload the block
			current_block.eq(0).load(script_name+"?cmsMode=ajax_l&action=dataset_block&dataset="+current_block.parents(".cmsDataset").attr("name")+"&block="+current_block.attr("name")+"&mode=view&ref="+current_block.parents(".cmsDataset").attr("ref"));
			// Then reload list-table (TO SEE!)
			current_block.parents("div.cmsDataset").eq(0).find(".layout-list").load(script_name+"?cmsMode=ajax_l&action=dataset_list&dataset="+current_block.parents(".cmsDataset").attr("name")+"&ref="+newref);
			current_block.parents("div.cmsDataset").eq(0).find(".layout-table").load(script_name+"?cmsMode=ajax_l&action=dataset_table&dataset="+current_block.parents(".cmsDataset").attr("name")+"&ref="+newref);
		}
	} else alert("Error: no current_block");
}

function js_initDataset(from) {
	if ($('#cmsPost').is(":visible")) $("#cmsDebug")[0].innerHTML+="<strong>Function:</strong> js_initDataset("+from+")<br/>";
	if ($('div.cmsDataset .layout-table table.sortable[data-done!="1"]').length) {
		$('div.cmsDataset .layout-table table.sortable').dataTable( {
			"sPaginationType": "full_numbers",
			"aaSorting": [[ 1, "asc" ]],
			"bStateSave": true,
			"aoColumnDefs": [
				{ "bSortable": false, "aTargets": [ 0 ] }		//Remove first column to be sortable
			],
			"fnDrawCallback": function() {
				js_setDatasetClicks("js_initDataset()->fnDrawCallback");
			}
		} ).attr("data-done","1");		// Set that the table is dataTable ready to avoid to do it once again...
	} else {		// the .dataTable will call js_setDatasetClicks()!
		js_setDatasetClicks("js_initDataset()");
	}
	if (typeof(tinyMCE)!="undefined") tinyMCE.init({
		mode : 'specific_textareas',
		editor_selector : 'tinymce',
			theme : "advanced",
			plugins : "style,table,inlinepopups,media,contextmenu,noneditable,template",
			theme_advanced_buttons1 : "code,|,bold,italic,underline,strikethrough,formatselect,fontsizeselect,|justifyleft,justifycenter,justifyright,justifyfull,bullist,|,undo,redo",
			theme_advanced_buttons2 : "link,unlink,image,cmsBackground,|,forecolor,backcolor|,sub,sup,charmap,pastetext,|,tablecontrols,|,styleprops",
			theme_advanced_buttons3 : "",
			theme_advanced_toolbar_location : "top",
			// fabric
			entity_encoding : "raw",		//convert all special chars to numeric entities (ex: è: &#232;), to be compatible with XML
			theme_advanced_statusbar_location : "bottom",
			file_browser_callback : "tinyBrowser",
			template_external_list_url  : "/uploads/templates/cms_templates.js",
			extended_valid_elements : "div[style|class|cmsReplace|cmsData]",
			relative_urls : false,
			paste_auto_cleanup_on_paste : true,
			paste_remove_spans : true,
			paste_strip_class_attributes : "none",
			paste_text_sticky : true
	});
}

function js_setDatasetClicks(from) {
	if ($('#cmsPost').is(":visible")) $("#cmsDebug")[0].innerHTML+="<strong>Function:</strong> js_setDatasetClicks("+from+")<br/>";
	//alert("setClick")
	/*$(".cmsDatasetDataBlock .title").css("cursor","pointer").unbind("click").click(function(){
		$(this).toggleClass("caret_down");
		if ($(this).parents(".cmsDatasetDataBlock").find(".content").find("td").eq(0).html()=="") $(this).next().find("button").click();
		$(this).next().fadeToggle("fast");
		$(this).parents(".cmsDatasetDataBlock").find(".content").eq(0).slideToggle("fast");
		return false;
	});*/
	if (!/firefox/.test(navigator.userAgent.toLowerCase())) {$(".cmsDataset button").css("padding","1px 3px");}
	$("div.cmsDataset .layout-list li span").css("cursor","pointer").unbind("click").click(function(){
		$("div.cmsDataset .layout-list li span").removeClass("selected");
		$(this).addClass("selected");
		$(this).parents(".cmsDataset").attr("ref",$(this).parents("li").attr("ref"));
		$(this).parents(".cmsDataset").find(".layout-data").eq(0).load(script_name+"?cmsMode=ajax_l&action=dataset_data&dataset="+$(this).parents(".cmsDataset").attr("name")+"&mode=view&ref="+$(this).parents("li").attr("ref"));
	}); 
	$("div.cmsDataset .layout-table tbody tr").css("cursor","pointer").unbind("click").click(function(event){
		if (event.target.nodeName!="INPUT") {		// prevent event when clicking on the checkbox
			if (ref=$(this).attr('ref')) {
				$(this).parents(".cmsDataset").attr("ref",ref)
				$(this).parents(".cmsDataset").find(".layout-table").hide();
				$(this).parents(".cmsDataset").find(".layout-back").show();
				$(this).parents(".cmsDataset").find(".layout-data").show();
				$(this).parents(".cmsDataset").find(".layout-data").load(script_name+"?cmsMode=ajax_l&action=dataset_data&dataset="+$(this).parents(".cmsDataset").attr("name")+"&mode=view&ref="+ref);
			} else alert("NO ref!");
		}
	}); 
	$("div.cmsDataset input.grey").each(function() {
		$(this).val($(this).attr("default"));
		$(this).unbind("focus").focus(function(){if ($(this).val()==$(this).attr("default")) {$(this).val("");$(this).removeClass("grey")}});
		$(this).unbind("blur").blur(function(){if ($(this).val()=="") {$(this).val($(this).attr("default"));$(this).addClass("grey")}});
		$(this).unbind("keyup").keyup(function(){
			switch($(this).attr("name")) {
				case "dataset_list_filter":
					keyword=$(this).val().latinise();
					$(this).parents(".layout-list").find("li").each(function(i,obj) {
						if (keyword=='' || $(obj).text().latinise().indexOf(keyword)>-1) obj.style.display=''; else obj.style.display='none';
					});
					break;
				case "dataset_xselect_filter":
					keyword=$(this).val().latinise();
					$(this).parents("ul").find("li").each(function(i,obj) {
						if ($(obj).attr("filter")!="1")
							if (keyword=='' || $(obj).text().latinise().indexOf(keyword)>-1) obj.style.display=''; else obj.style.display='none';
					});
					break;
			}
		});
	});
	$("div.cmsDataset .layout-table table.sortable input[type='checkbox']").unbind("click").click(function(e) {
		c=false;
		$(this).parents("table").find("tbody input[type='checkbox']").each(function(i,obj) {if (obj.checked) c=true;});
		$(this).parents("table").find("tfoot input[type='checkbox']").attr("checked",c);
	} );
	$("div.cmsDataset .layout-list ul input[type='checkbox']").unbind("click").click(function() {
		c=false;
		$(this).parents(".layout-list").find("ul li input[type='checkbox']").each(function(i,obj) {if (obj.checked) c=true;});
		$(this).parents(".layout-list").find("table.options input[type='checkbox']").attr("checked",c);
	} );
	$("div.cmsDataset .layout-table div.columns_select ul li input[type='checkbox']").unbind("click").click(function() {
		c=false;
		$(this).parents(".columns_select").find("ul li input[type='checkbox']").each(function(i,obj) {if (obj.checked) c=true;});
		$(this).parents(".columns_select").find("ul li input[type='radio']").attr("checked",!c);
		$(this).parents("li").find("input[type='radio']").attr("checked",c);
	} );
	if ($("div.cmsDataset .layout-table table.sortable").attr('data-columns_list')) $($("div.cmsDataset .layout-table table.sortable").attr('data-columns_list').split(',')).each(function(i,key){	//key contains the name of the input type='checkbox'
		$("div.cmsDataset .layout-table div.columns_select ul li input[name='"+key+"']").click();
	});
	if ($("div.cmsDataset .layout-table table.sortable").attr('data-columns_index')) {
		$("div.cmsDataset .layout-table div.columns_select ul li input[type='radio']").eq(parseInt($("div.cmsDataset .layout-table table.sortable").attr('data-columns_index'))).click();
	}
	$("div.cmsDataset .simpledialog").simpleDialog();
	$(".cmsDataset button").css("cursor","pointer").unbind("click").click(function() {
		var action=$(this).attr('action')
		switch (action) {
			case "list_new":
				$("div.cmsDataset .layout-list li span").removeClass("selected");
				$(this).parents(".cmsDataset").find(".layout-data").load(script_name+"?cmsMode=ajax_l&action=dataset_data&dataset="+$(this).parents(".cmsDataset").attr("name")+"&mode=new&ref=-1");
				break;
			case "table_new":
				$(this).parents(".cmsDataset").find(".layout-table").hide();
				$(this).parents(".cmsDataset").find(".layout-back").show();
				$(this).parents(".cmsDataset").find(".layout-data").show();
				$(this).parents(".cmsDataset").find(".layout-data").load(script_name+"?cmsMode=ajax_l&action=dataset_data&dataset="+$(this).parents(".cmsDataset").attr("name")+"&mode=new&ref=-1");
				break;
			case "block_data_edit":
			case "block_list_edit":
				//$(this).ajaxStart(function(){$(this).html("<img style='margin:0px 5px' src='/img/dataset/ajax-loader-4.gif'/>")}).ajaxComplete(function(){js_setClicks();});
				//$(this).ajaxComplete(function(){alert(1);js_setClicks();});
				$(this).parents(".layout-block").load(script_name+"?cmsMode=ajax_l&action=dataset_block&dataset="+$(this).parents(".cmsDataset").attr("name")+"&block="+$(this).parents(".layout-block").attr("name")+"&mode=edit&ref="+$(this).parents(".cmsDataset").attr("ref"));
				break;
			case "block_data_cancel":
			case "block_list_cancel":
			case "block_data_load":
				//$(this).ajaxStart(function(){$(this).html("<img style='margin:0px 5px' src='/img/dataset/ajax-loader-4.gif'/>")}).ajaxComplete(function(){js_setClicks();});
				$(this).parents(".layout-block").load(script_name+"?cmsMode=ajax_l&action=dataset_block&dataset="+$(this).parents(".cmsDataset").attr("name")+"&block="+$(this).parents(".layout-block").attr("name")+"&mode=view&ref="+$(this).parents(".cmsDataset").attr("ref"));
				break;
			case "block_data_save":
			case "block_list_save":
				//$(this).html("<img style='margin:0px 5px' src='/img/dataset/ajax-loader-4.gif'/>");
				current_block=$(this).parents(".layout-block");
				$(this).parents(".layout-block").find("form").eq(0).submit();
				break;
			case "block_list_new":
				$(this).parents(".layout-block").load(script_name+"?cmsMode=ajax_l&action=dataset_block&dataset="+$(this).parents(".cmsDataset").attr("name")+"&block="+$(this).parents(".layout-block").attr("name")+"&mode=new&ref="+$(this).parents(".cmsDataset").attr("ref"));
				break;
			case "table-data-back":
				$(this).parents(".cmsDataset").find(".layout-table").show();
				$(this).parents(".cmsDataset").find(".layout-back").hide();
				$(this).parents(".cmsDataset").find(".layout-data").hide();	
				break;
			case "list_options":
			case "table_options":
				var refs=new Array();
				if (action=="table_options")
					$(this).parents("table").eq(0).find("input").each(function(i,obj){if (obj.checked && obj.parentNode.parentNode.getAttribute("ref")) refs.push(obj.parentNode.parentNode.getAttribute("ref"))});
				else
					$(this).parents(".layout-list").eq(0).find("ul input").each(function(i,obj){if (obj.checked && obj.parentNode.getAttribute("ref") && obj.parentNode.style.display!='none') refs.push(obj.parentNode.getAttribute("ref"))});
				var num=refs.length
				node=$(this).parents("tr").find("option:selected").eq(0);
				if (num>0 && node.val()!="") {
					if (confirm("Comfirmation: '"+node.text()+"' "+num+" element(s)")) {
						switch (node.attr("type")) {
							case "javascript":
								eval(node.attr("value"));
								break;
							default:
								form=$(this).parents("tr").find("form").eq(0);
								if (form) {
									form.find("input[name='refs']").val(refs.join(","));
									form.submit();
								} else alert("No form found");
								break;							
						}
					}
				}
				break;
			case "table_columns_select":
				columns_index=0;
				columns_list=new Array();
				$(this).parents("ul").find("input[type='radio']").each(function(i,obj){if (obj.checked) columns_index=i;});
				$(this).parents("ul").find("input[type='checkbox']").each(function(i,obj){if (obj.checked) {columns_list.push(obj.getAttribute("name"))}});
				$(this).parents(".cmsDataset").find(".layout-table").load(script_name+"?cmsMode=ajax_l&action=dataset_table&dataset="+$(this).parents(".cmsDataset").attr("name")+"&columns_index="+columns_index+"&columns_list="+columns_list.join(","));
				break;
		}
	});
}

jQuery.log = function(message) {
  if(window.console) {
     console.debug(message);
  } else {
     alert(message);
  }
};

function js_xselectDown(obj,multiple) {
	if (obj.nodeName.toLowerCase()=='ul') {		//we asked to reset the onclick event on the ul (the 'more...' li)
		ulNode=obj;
	} else {
		ulNode=js_getNextNode(obj,'ul','');
		if (typeof(currentNode)=="object" && currentNode!=ulNode) currentNode.style.display="none";
		currentNode=ulNode;
		if (ulNode.style.display=='') ulNode.style.display='none'; else ulNode.style.display='';
	}
	liNodes=ulNode.getElementsByTagName('li');
	for (i=0;i<liNodes.length;i++) {
		if (liNodes[i].getAttribute('filter')!='1' && liNodes[i].getAttribute('noclick')!='1') {
			if (liNodes[i].innerHTML==obj.value) liNodes[i].style.fontWeight='bold'; else liNodes[i].style.fontWeight='normal';
			if (liNodes[i].getAttribute('other')) {
				liNodes[i].onclick=function() {
					js_getPreviousNode(this.parentNode,'input','').focus();
					js_getPreviousNode(this.parentNode,'input','').select();
					this.parentNode.style.display='none';
				}
			
			} else {
				if (!multiple) {
					liNodes[i].onclick=function() {
						//Here, it could be a dselect (only 1 input) or xselect (2 inputs, last one with name='')
						js_getPreviousNode(this.parentNode,'input','').value=this.innerHTML;
						if (js_getPreviousNode(this.parentNode,'input','').name=='') {
							target=js_getParentNode(this,'div','').getElementsByTagName('input')[0]
							target.value=this.getAttribute('value');
							//Simulate an 'onchange' event
							if (document.createEvent) {            // DOM event model -> Firefox
								var e = document.createEvent("Events");
								e.initEvent("change", true, true);
								target.dispatchEvent(e);
							} else if (document.createEventObject) { // IE event model
								var e = document.createEventObject( );
								target.fireEvent("onchange", e); // IE
							}
						}
						this.parentNode.style.display='none';
					}
				} else {
					liNodes[i].onclick=function() {
						//Here, it is a xselect, multiple
						js_getPreviousNode(this.parentNode,'input','').value=this.innerHTML;
						js_getPreviousNode(this.parentNode,'input','').setAttribute('code',this.getAttribute('value'));
						div=js_getParentNode(this,'div','').parentNode;	//the main 'div'
						target=div.getElementsByTagName('input')[0];
						target.value='';
						nodes=div.getElementsByTagName('div');
						//alert('nb divs:'+nodes.length+'\n'+div.innerHTML)
						newnode=nodes[0].cloneNode(true);
						newnode.getElementsByTagName('input')[0].value='';
						newnode.getElementsByTagName('input')[0].setAttribute('code','');
						newnode.getElementsByTagName('ul')[0].style.display='none';
						arr=new Array();
						for (i=nodes.length-1;i>=0;i--) {
							node=nodes[i].getElementsByTagName('input')[0];
							//alert('nb divs:'+nodes.length)
							code=node.getAttribute('code')
							if (code!='') {
								found=false;
								for (key in arr) if (arr[key]==code) found=true
								if (!found) arr.push(code);
							} else {
								nodes[i].parentNode.removeChild(nodes[i])
							}
						}
						if (target.getAttribute("separator")) target.value=arr.reverse().join(target.getAttribute("separator")); else target.value=arr.reverse().join('\n');
						
						//alert('*'+target.value+'*')
						//alert('addind new'+newnode.innerHTML)
						div.appendChild(newnode)
						//alert(div.innerHTML)
						//alert(target.value)
						//Simulate an 'onchange' event
						if (document.createEvent) {            // DOM event model -> Firefox
							var e = document.createEvent("Events");
							e.initEvent("change", true, true);
							target.dispatchEvent(e);
						} else if (document.createEventObject) { // IE event model
							var e = document.createEventObject( );
							target.fireEvent("onchange", e); // IE
						}
						this.parentNode.style.display='none';
					}
				}
			}
		} else {
			//if (liNodes[i].getElementsByTagName('input').length) liNodes[i].getElementsByTagName('input')[0].focus();
		}
	}
}

function js_xselectFilter(obj) {
	// the user tries to filter the list (ul) of proposition
	var node=js_getParentNode(obj,"div","");
	liNodes=node.getElementsByTagName('li');
	if (obj.value=="") {
		for (i=0;i<liNodes.length;i++) 
			if (liNodes[i].getAttribute('filter')!='1') liNodes[i].style.display='';
	} else {
		for (i=0;i<liNodes.length;i++) 
			if (liNodes[i].getAttribute('filter')!='1') {
				if (liNodes[i].innerHTML.indexOf(obj.value)>-1) liNodes[i].style.display=''; else liNodes[i].style.display='none';
			}
	}
}
function ICdown(obj,flag){
	//Fonction pour les calendar
	//spanNode=js_getParentNode(obj,'span','');
	//divNode=spanNode.getElementsByTagName("div")[0];
	divNode=js_getNextNode(obj,"div","");
	if (typeof(currentNode)=="object" && currentNode!=divNode) currentNode.style.display="none";
	currentNode=divNode;
	if (divNode.style.display=='') divNode.style.display='none'; else divNode.style.display='';
	//dateT=spanNode.getElementsByTagName('input')[0].value;
	dateT=obj.value;
	if (dateT=='') dateT=ICdateT(new Date());
	//extrasNodes=js_getNextNode(divNode,"div","");
	divNode.innerHTML=ICbuild(dateT,1,flag);
}
function ICbuild(dateT,hightlight,flag){
	//hightlight: permet de dire si la 'dateT' doit etre highlightée ou pas (par ex, pas de hightlight quand on change de mois)
	dateN=ICdateN(dateT,1);
	tmp="<table class='tableCalendar'>"
	tmp+="<tr>"
	//alert("new ICbuild("+dateT+")")
	lastYear=new Date(dateN.getFullYear()-1,dateN.getMonth(),1);
	tmp+="<td><a href='#' dateT='"+ICdateT(lastYear)+"' onClick='this.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML=ICbuild(this.getAttribute(\"dateT\"),0,"+flag+");return(false)'>&#171;</a></td>"
	lastMonth=new Date(dateN.getFullYear(),dateN.getMonth()-1,1);
	tmp+="<td><a href='#' dateT='"+ICdateT(lastMonth)+"' onClick='this.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML=ICbuild(this.getAttribute(\"dateT\"),0,"+flag+");return(false)'>&lt;</a></td>"
	tmp+="<td colspan='3'><strong>"+ICdateT(dateN,2)+"</strong></td>"
	nextMonth=new Date(dateN.getFullYear(),dateN.getMonth()+1,1);
	tmp+="<td><a href='#' dateT='"+ICdateT(nextMonth)+"' onClick='this.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML=ICbuild(this.getAttribute(\"dateT\"),0,"+flag+");return(false)'>&gt;</a></td>"
	nextYear=new Date(dateN.getFullYear()+1,dateN.getMonth(),1);
	tmp+="<td><a href='#' dateT='"+ICdateT(nextYear)+"' onClick='this.parentNode.parentNode.parentNode.parentNode.parentNode.innerHTML=ICbuild(this.getAttribute(\"dateT\"),0,"+flag+");return(false)'>&#187;</a></td>"
	tmp+="</tr>"
	
	tmp+="<tr><td>Lu</td><td>Ma</td><td>Me</td><td>Je</td><td>Ve</td><td>Sa</td><td>Di</td></tr>"
	//alert(-(dateN.getDay()+2)%6)
	//On fait partir le jour de -(le nombre de jour avant le 1er du mois) jusqu'a 32
	firstDay=new Date(dateN.getFullYear(),dateN.getMonth(),1);
	offset=firstDay.getDay()-1		//premier jour semain=lundi -> -1
	if (offset<0) offset=6			//si dimanche -> 6
	//alert(firstDay.getDay())
	for (d=-offset;d<32;d+=7) {
		tmp+="<tr>"
		for (d2=1;d2<8;d2++) {
			date2=new Date(dateN.getFullYear(),dateN.getMonth(),d+d2);
			if (date2.getMonth()!=dateN.getMonth()) {
				tmp+="<td></td>"
			} else {
				if (hightlight && ICdateT(date2)==dateT) tmpClass=" class='selected'"; else tmpClass="";
				//if (flag && date2>new Date())
				//	tmp+="<td"+tmpClass+">"+zeroPad(date2.getDate(),2)+"</td>"
				//else
					tmp+="<td"+tmpClass+"><a href='#' dateN='"+date2+"' dateT='"+ICdateT(date2)+"' onClick='this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName(\"input\")[0].value=this.getAttribute(\"dateT\");this.parentNode.parentNode.parentNode.parentNode.parentNode.style.display=\"none\";return(false);'>"+zeroPad(date2.getDate(),2)+"</a></td>"
			}
		}
		tmp+="</tr>"
		date3=new Date(dateN.getFullYear(),dateN.getMonth(),d+d2);
		if (date3.getMonth()!=dateN.getMonth()) d=40;			//On quitte la boucle des semaines
			
	}
	if (node=js_getNextNode(currentNode,"div","")) {
		nodes=node.getElementsByTagName('extra');
		for (i=0;i<nodes.length;i++) {
			//nodes[i].getAttribute('value') instead of nodes[i].innerHTML because of IE does not support the 2nd form...
			tmp+="<tr><td colspan='7'><a href='#' dateT='"+nodes[i].getAttribute('value')+"' onclick='this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName(\"input\")[0].value=this.getAttribute(\"dateT\");this.parentNode.parentNode.parentNode.parentNode.parentNode.style.display=\"none\";return(false);'>"+nodes[i].getAttribute('display')+"</a></td></tr>";
		}
	}
	tmp+="</table>"
	return tmp;
}
function ICdateT(dateN,format){
	//renvoie la date au format text (JJ.MM.AAAA par defaut, MM.AAAA si format=2) d'une date javascript
	if (format==2) return zeroPad(dateN.getMonth()+1,2)+'.'+zeroPad(dateN.getFullYear(),4);
	return zeroPad(dateN.getDate(),2)+'.'+zeroPad(dateN.getMonth()+1,2)+'.'+zeroPad(dateN.getFullYear(),4);
}
function ICdateN(dateT){
	//renvoie la date javascript d'une date au format text (JJ.MM.AAAA)
	var arr=dateT.split(".");
	var dateN=new Date(arr[2],arr[1]-1,arr[0]);
	return dateN;
}
function zeroPad(num,count) { 
	var numZeropad = num + '';
	while(numZeropad.length < count) {
		numZeropad = "0" + numZeropad; 
	}
	return numZeropad;
}
String.prototype.latinise = function() {
	return latiniseIt(this);
};
latiniseIt = function(s) {
	var r=s.toLowerCase();
	r = r.replace(new RegExp("\\s", 'g'),"");
	r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
	r = r.replace(new RegExp("æ", 'g'),"ae");
	r = r.replace(new RegExp("ç", 'g'),"c");
	r = r.replace(new RegExp("[èéêë]", 'g'),"e");
	r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
	r = r.replace(new RegExp("ñ", 'g'),"n");                            
	r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
	r = r.replace(new RegExp("œ", 'g'),"oe");
	r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
	r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
	r = r.replace(new RegExp("\\W", 'g'),"");
	return r;
};

//TODO: remove with jQuery fct...

function js_getParentNode(obj,name,className){
	//return the first parent node with nodeName 'name' and className 
	var node=obj
	while (node) {
		if (node.nodeName.toUpperCase()==name.toUpperCase() && (className=='' || className==node.className)) return node;
		node=node.parentNode;
	}
	return false;
}
function js_getNextNode(obj,name,className){
	//return the next sibling node with nodeName 'name' and className 
	var node=obj.nextSibling;
	while (node) {
		if (node.nodeName.toUpperCase()==name.toUpperCase() && (className=='' || className==node.className)) return node;
		node=node.nextSibling;
	}
	return false;
}
function js_getPreviousNode(obj,name,className){
	//return the previous sibling node with nodeName 'name' and className 
	var node=obj.previousSibling;
	while (node) {
		if (node.nodeName.toUpperCase()==name.toUpperCase() && (className=='' || className==node.className)) return node;
		node=node.previousSibling;
	}
	return false;
}
function js_isChild(child,parent){
	//Return true if 'child' is a child node of 'parent'
	//PAS POSSIBLE?? A VOIR
	var node=child;
	while(node) {
		if(node===parent) {alert(true);return true;}
		node=node.parentNode;
	}
	alert(false);
	return false;
}


//jQuery Extensions

(function( $ ) {
	$.fn.exportXls = function( options ) {
		// Default settings
		var settings = {
			'post_url'		:	'/jqueryXls.php',
			'selector_tr'	:	'tr',					// default table selector (default: "tr", example: not the tfoot part: "thead tr, tbody tr")
			'matching_tr'	:	'',						// Filter for tr (default: "": no filter, example; only tr with 'th' or 'input checked' in a column: "th, input:checked")
			'selector_td'	:	'th,td'					// default tr childs selector (default: "th,td", example: not the first column: "th:not(:nth-child(1)),td:not(:nth-child(1))")
		};

		//Creation of the main node (we use true XML document to keep case sensitive tags and attributes)
		if (window.ActiveXObject) {
			var e=new ActiveXObject("Microsoft.XMLDOM");
			e.async="false";
		} else if (document.implementation && document.implementation.createDocument) {
			var e = document.implementation.createDocument ('', '', null);
		}
		//Then we use jQuery or normal DOM to populate the xml
		e.appendChild(e.createElement("Workbook"));
		//$('Workbook',e).attr("xmlns","urn:schemas-microsoft-com:office:spreadsheet");		//This can't be done! do it after by 'replace'
		$('Workbook',e).attr("xmlns:o","urn:schemas-microsoft-com:office:office");
		$('Workbook',e).attr("xmlns:x","urn:schemas-microsoft-com:office:excel");
		$('Workbook',e).attr("xmlns:ss","urn:schemas-microsoft-com:office:spreadsheet");
		$('Workbook',e).attr("xmlns:html","http://www.w3.org/TR/REC-html40");

		$('Workbook',e).append(e.createElement("DocumentProperties"));
			$('DocumentProperties',e).attr("xmlns","urn:schemas-microsoft-com:office:office");
			$('DocumentProperties',e).append($(e.createElement("Author")).text("Stephane Carion"));
			$('DocumentProperties',e).append($(e.createElement("Version")).text("1.0"));
					
		$('Workbook',e).append(e.createElement("ExcelWorkbook"));
			$('ExcelWorkbook',e).attr("xmlns","urn:schemas-microsoft-com:office:office");
			$('ExcelWorkbook',e).append($(e.createElement("WindowHeight")).text("6795"));
			$('ExcelWorkbook',e).append($(e.createElement("WindowWidth")).text("8460"));
			$('ExcelWorkbook',e).append($(e.createElement("WindowTopX")).text("120"));
			$('ExcelWorkbook',e).append($(e.createElement("WindowTopY")).text("15"));
			$('ExcelWorkbook',e).append($(e.createElement("ProtectStructure")).text("False"));
			$('ExcelWorkbook',e).append($(e.createElement("ProtectWindows")).text("False"));

		$('Workbook',e).append(e.createElement("Styles"));
			$('Styles',e).append($(e.createElement("Style")).attr("ss:ID","Default").attr("ss:Name","Normal"));
			$('Styles',e).append($(e.createElement("Style")).attr("ss:ID","s21").append($(e.createElement("Font")).attr("x:Family","Swiss").attr("ss:Bold","1")));
			
		return this.each(function(i,node) {        
			// merge with our default settings
			if ( options ) { 
				$.extend( settings, options );
			}
			rowCount=0;
			cellCountMax=0;
			table=$(e.createElement("Table"));
			$(node).find(settings['selector_tr']).each(function(j,tr) {
				if (settings['matching_tr']=="") {
					match=true;
				} else {
					match=($(tr).find(settings['matching_tr']).length!=0);
				}
				//alert(match)
				if (match) {
					row=$(e.createElement("Row"));
					rowCount++;
					cellCount=0;
					//$.log("Found tr "+tr.innerHTML)
					$(tr).find(settings['selector_td']).each(function(k,td) {
						//$.log("Found td "+td.innerHTML)
						cellCount++;
						cell=$(e.createElement("Cell")).append($(e.createElement("Data")).attr("ss:Type","String").text($(td).text()));
						if (td.nodeName.toLowerCase()=="th") cell.attr("ss:StyleID","s21")
						row.append(cell);
					});
					table.append(row);
					if (cellCount>cellCountMax) cellCountMax=cellCount;
				}
			});
			table.attr("ss:ExpandedColumnCount",cellCountMax).attr("ss:ExpandedRowCount",rowCount).attr("x:FullColumns","1").attr("x:FullRows","1")
			$('Workbook',e).append($(e.createElement("Worksheet")).attr("ss:Name","Sheet1").append(table));
			
			if (window.ActiveXObject) {
				content=e.xml;
			} else {
				content=(new XMLSerializer()).serializeToString(e);
			}
			content=content.replace('<Workbook ','<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" ');
			content=content.replace('</Workbook>','<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"><Print><ValidPrinterInfo /><HorizontalResolution>600</HorizontalResolution><VerticalResolution>600</VerticalResolution></Print><Selected /><Panes><Pane><Number>3</Number><ActiveRow>1</ActiveRow><ActiveCol>1</ActiveCol></Pane></Panes><ProtectObjects>False</ProtectObjects><ProtectScenarios>False</ProtectScenarios></WorksheetOptions></Workbook>');

			content='<'+'?xml version="1.0"?><'+'?mso-application progid="Excel.Sheet"?>'+content;
			
			form=$("<form method='post' style='display:none'/>")
			form.attr('action',settings['post_url']);
			form.append($("<textarea name='export'>").text('xls'));
			form.append($("<textarea name='name'>").text('test.xls'));
			form.append($("<textarea name='content'>").text(content));
			document.body.appendChild(form[0]).submit();
		});
	};
})( jQuery );

/**
 * jquery.dump.js
 * @author Torkild Dyvik Olsen
 * @version 1.0
 * 
 * A simple debug function to gather information about an object.
 * Returns a nested tree with information.
 * 
 */
(function($) {

	$.fn.dump = function() {
	   return $.dump(this);
	}

	$.dump = function(object) {
	   var recursion = function(obj, level) {
		  if(!level) level = 0;
		  var dump = '', p = '';
		  for(i = 0; i < level; i++) p += "\t";
		  
		  t = type(obj);
		  switch(t) {
			 case "string":
				return '"' + obj + '"';
				break;
			 case "number":
				return obj.toString();
				break;
			 case "boolean":
				return obj ? 'true' : 'false';
			 case "date":
				return "Date: " + obj.toLocaleString();
			 case "array":
				dump += 'Array ( \n';
				$.each(obj, function(k,v) {
				   dump += p +'\t' + k + ' => ' + recursion(v, level + 1) + '\n';
				});
				dump += p + ')';
				break;
			 case "object":
				dump += 'Object { \n';
				$.each(obj, function(k,v) {
				   dump += p + '\t' + k + ': ' + recursion(v, level + 1) + '\n';
				});
				dump += p + '}';
				break;
			 case "jquery":
				dump += 'jQuery Object { \n';
				$.each(obj, function(k,v) {
				   dump += p + '\t' + k + ' = ' + recursion(v, level + 1) + '\n';
				});
				dump += p + '}';
				break;
			 case "regexp":
				return "RegExp: " + obj.toString();
			 case "error":
				return obj.toString();
			 case "document":
			 case "domelement":
				dump += 'DOMElement [ \n'
					  + p + '\tnodeName: ' + obj.nodeName + '\n'
					  + p + '\tnodeValue: ' + obj.nodeValue + '\n'
					  + p + '\tinnerHTML: [ \n';
				$.each(obj.childNodes, function(k,v) {
				   if(k < 1) var r = 0;
				   if(type(v) == "string") {
					  if(v.textContent.match(/[^\s]/)) {
						 dump += p + '\t\t' + (k - (r||0)) + ' = String: ' + trim(v.textContent) + '\n';
					  } else {
						 r--;
					  }
				   } else {
					  dump += p + '\t\t' + (k - (r||0)) + ' = ' + recursion(v, level + 2) + '\n';
				   }
				});
				dump += p + '\t]\n'
					  + p + ']';
				break;
			 case "function":
				var match = obj.toString().match(/^(.*)\(([^\)]*)\)/im);
				match[1] = trim(match[1].replace(new RegExp("[\\s]+", "g"), " "));
				match[2] = trim(match[2].replace(new RegExp("[\\s]+", "g"), " "));
				return match[1] + "(" + match[2] + ")";
			 case "window":
			 default:
				dump += 'N/A: ' + t;
				break;
		  }
		  
		  return dump;
	   }
	   
	   var type = function(obj) {
		  var type = typeof(obj);
		  
		  if(type != "object") {
			 return type;
		  }
		  
		  switch(obj) {
			 case null:
				return 'null';
			 case window:
				return 'window';
			 case document:
				return 'document';
			 case window.event:
				return 'event';
			 default:
				break;
		  }
		  
		  if(obj.jquery) {
			 return 'jquery';
		  }
		  
		  switch(obj.constructor) {
			 case Array:
				return 'array';
			 case Boolean:
				return 'boolean';
			 case Date:
				return 'date';
			 case Object:
				return 'object';
			 case RegExp:
				return 'regexp';
			 case ReferenceError:
			 case Error:
				return 'error';
			 case null:
			 default:
				break;
		  }
		  
		  switch(obj.nodeType) {
			 case 1:
				return 'domelement';
			 case 3:
				return 'string';
			 case null:
			 default:
				break;
		  }
		  
		  return 'Unknown';
	   }
	   
	   return recursion(object);
	}

	function trim(str) {
	   return ltrim(rtrim(str));
	}

	function ltrim(str) {
	   return str.replace(new RegExp("^[\\s]+", "g"), "");
	}

	function rtrim(str) {
	   return str.replace(new RegExp("[\\s]+$", "g"), "");
	}

})(jQuery);

/*jslint browser: true */ /*global jQuery: true */

/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Get the value of a cookie with the given key.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String key The key of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (key, value, options) {
    
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        
        value = String(value);
        
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
