var pageUrl="";
var pageModified=false;
var countAjaxCall = 0;
var mouseX = 0;
var mouseY = 0;
var mouseClientX = 0;
var mouseClientY = 0;

$(document).mousemove(function(e) {
	mouseX = e.pageX;
	mouseY = e.pageY;
	mouseClientX = e.clientX;
	mouseClientY = e.clientY;
});



/**
 * Evenement Resize
 * Cette méthode est appelée lors du redimensionnement de la fenêtre pour remettre en forme l'UI
 */
$(window).resize(function() {
	if($("#contentArea")) {
	
		 //il est indispensable de passer par des variables intermediaire pour IE6
		var contentAreaHeight = $(window).height()-79; //max pour IE7
		var mainPanelHeight;
		
		// retaille la partie principale de la fenêtre		
		$("#contentArea").height(contentAreaHeight);

		if (contentAreaHeight>750) {
			if($(document).find("#actionBarContainer2").length>0) {
				$("#actionBarContainer2").css("display","block");
				if($(document).find("#ongletPanel").length>0) {
					contentAreaHeight = contentAreaHeight-38;
				} else {
					contentAreaHeight = contentAreaHeight-34;
				}
			}
		} else {
			$("#actionBarContainer2").css("display","none");
		}	
		// en fonction ou nom de la présence d'un bar d'actino, on réduit plus ou moins la fenetre		
		if ($("#actionBarContainer").is(":visible")) {
			mainPanelHeight = contentAreaHeight-70;
		} else {
			mainPanelHeight = contentAreaHeight-28;
		}
		
		// on met à jour la taille du main Panel
		$("#mainPanel").height(mainPanelHeight);
		
		// s'il y'a un onglet panel, on met à jour sa taille et on active les scrollbar
		if($(document).find("#ongletPanel").length>0) {
			$("#mainPanel").css("overflow","");
			$("#ongletPanel").css("overflow","auto");
			$("#ongletPanel").height(mainPanelHeight-78);
		} else {
			$("#mainPanel").css("overflow","auto");
		}
	}
});

jQuery.extend({
	doAjax : function(url,callbackSuccess,callbackError) {
		callbackSuccess = callbackSuccess || function(html){};
		callbackError = callbackError || function(){};
	   	notifyStartAjaxCall();
		$.ajax({
			type: "POST",
			url: url,
			dataType : "html",
			data: {}, // nécessaire pour passer les proxys sous FF
			success : function(html) {
	           	notifyStopAjaxCall();				
				callbackSuccess(html);
			},
			error : function( httprequest, textStatus, errorThrown){
	           	notifyStopAjaxCall();
	           	callbackError();
				displayAjaxError(httprequest);
			}
		});
	},
	doAjaxSync : function(url,callbackSuccess,callbackError) {
		callbackSuccess = callbackSuccess || function(html){};
		callbackError = callbackError || function(){};
	   	notifyStartAjaxCall();
		$.ajax({
			type: "POST",
			url: url,
			dataType : "html",
			data: {}, // nécessaire pour passer les proxys sous FF
			success : function(html) {
	           	notifyStopAjaxCall();				
				callbackSuccess(html);
			},
			async : false,
			error : function( httprequest, textStatus, errorThrown){
	           	notifyStopAjaxCall();
	           	callbackError();
				displayAjaxError(httprequest);
			}
		});
	}
});

jQuery.fn.applyListenInput = function() {
	$("input",this).change(function() {
		if (!$(this).hasClass("nolisten")) {
			pageModified=true;
		}
	});
	$("textarea",this).change(function() {
		if (!$(this).hasClass("nolisten")) {
			pageModified=true;
		}
	});
	$("select",this).change(function() {
		if (!$(this).hasClass("nolisten")) {
			pageModified=true;
		}
	});
	$("iframe",this).change(function() {
		if (!$(this).hasClass("nolisten")) {
			pageModified=true;
		}
	});
}
/**
 * Rend un élément clickable avec des styles définis pour les rollover
 */
jQuery.fn.makeClickable = function() {
	$(this).hoverIntent({
		sensitivity: 10, // number = sensitivity threshold (must be 1 or higher)
		interval: 30, // number = milliseconds for onMouseOver polling interval
		over: function() { 
			$(this).addClass("clickableover");
		} ,
		timeout: 0, // number = milliseconds delay before onMouseOut
		out: function() { 
			$(this).removeClass("clickableover"); 
			$(this).removeClass("clickableclicked"); 
		}
	});
	$(this).bind("mousedown", function() {
		$(this).addClass("clickableclicked");
	});
	$(this).bind("mouseup", function() {
		$(this).removeClass("clickableclicked");
	});
}

jQuery.fn.makeMenu = function () {
	$(this).superfish({
		hoverClass	: "sfHover",
		currentClass	: "none", /*new to Superfish v1.2a*/
		delay		: 0,
		animation	: {opacity:'show'},
		speed		: "0"
	})
	.find(">li:has(ul)")
		/* fix IE6 z-index dropdowns */
		.mouseover(function(){
			$("ul", this).bgIframe({opacity:true});
		})
		/* fix IE6 hover */
		.find(">ul>li")
			.hover(
				function(){	$(this).addClass("sfHover"); }, 
				function(){	$(this).removeClass("sfHover"); }
			);
}

jQuery.fn.makeTab = function() {
	$(this).hoverIntent({
		sensitivity: 10, // number = sensitivity threshold (must be 1 or higher)
		interval: 30, // number = milliseconds for onMouseOver polling interval
		over: function() { $(this).addClass("tabhover");} ,
		timeout: 0, // number = milliseconds delay before onMouseOut
		out: function() { $(this).removeClass("tabhover"); $(this).removeClass("tabclicked");}
	});
	$(this).bind("mousedown", function() { 
		$(this).addClass("tabclicked");
	});
	$(this).bind("mouseup", function() { 
		$(this).removeClass("tabclicked");
	});
}

jQuery.fn.makeTooltip = function() {
	var tooltipTimeout;
	$(this).hoverIntent({
		sensitivity: 10, // number = sensitivity threshold (must be 1 or higher)
		interval: 30, // number = milliseconds for onMouseOver polling interval
		over: function() {

			$("#tooltip").find("p").eq(0).html($(this).attr("tooltip"));

			// détermination de la position top du tooltip (au dessus, en dessous)
			tooltipHeight = $("#tooltip").height();
			tooltipWidth = $("#tooltip").width();			
			windowHeight = $(window).height();
			windowWidth = $(window).width();
			
			if (mouseY+tooltipHeight+20>windowHeight) {
				$("#tooltip").css("top",""+(mouseY-tooltipHeight-20)+"px");
			} else {
				$("#tooltip").css("top",""+(mouseY+20)+"px");
			}
			if (mouseX+tooltipWidth>windowWidth) {
				$("#tooltip").css("left",""+(mouseX-tooltipWidth)+"px");
			} else {			
				$("#tooltip").css("left",""+mouseX+"px");
			}
			$("#tooltip").show();
			tooltipTimeout = setTimeout(function() {
				$("#tooltip").hide();
			},4000);
		} ,
		timeout: 0, // number = milliseconds delay before onMouseOut
		out: function() {
			clearTimeout(tooltipTimeout);
			$("#tooltip").hide();
		}
	});
}

jQuery.fn.displayResult = function(srcdiv) {
	var target = $(this);
	target.show();
	target.html($("#"+srcdiv).html());
	$("#"+srcdiv).remove(); //on supprime la div temporaire apres avoir recupere son contenu, pour eviter tout doublon	
	target.css("top",$(window).height()-$(this).height()-26);
	target.fadeTo("slow","1");
	setTimeout(function() {
		clearTimeout();
		target.fadeTo("slow","0", function() {
			target.hide();
		});
		
	},3000);
}

jQuery.fn.applyUI = function (url) {

	if (url) {
		pageUrl = url.substring(0,url.lastIndexOf("/"));
	}

	var target = $(this);

	$(".boite",this).each( function() {
		if ($(".boxtabs",this).css("display")=="block") {
			$("div.boxActionBarContainer",this).show();
			$(".contenu",this).css("border-top","0px");
		}
	});
	
	var mythis = this;
	
	$("div.hiddenboxbutton",mythis).each(function() {
		var id = $("button",$(this)).attr("id");
		var box = $(this).parents("div.boite").get(0);
		$("div.boxActionBarContainer",box).show();			
		$("div.boxActionBar",box).append($(this).html());
		$("div.contenu",box).css("border-top","0px");
		$(this).empty();
		$(this).append("<button id=\"src"+id+"\" type=\"hidden\"/>");
	});

	// réalisation des clickable
	$(".clickable",this).makeClickable();
	$(".tooltip",this).each(function() { $(this).makeTooltip() });;
	$(".menudd",this).makeMenu();
	$(".menudd",this).css("display","block");
	$(".draggable",this).draggable({
		helper: function() {
			return "<div class='treehelper'>"+$(this).html()+"</div>";
		},
		scroll:true,
		revert:true,
		opacity:0.6,
		delay:300,
		cursor:"move"
	});

	$(".tab",this).makeTab();
	$("#tooltip").hide();
	$("input[@type='checkbox']",this).css("border","0px");
	$("input[@type='radio']",this).css("border","0px");


	if ($.browser.msie==true&&$.browser.version!="7.0") {
		$(this).fixIE();
	}
	target.applyListenInput();
}

jQuery.fn.disableInput = function() {
	$("input[@type='text']",this).attr("disabled",true);
	$("input[@type='password']",this).attr("disabled",true);
	$("input[@type='radio']",this).attr("disabled",true);
	$("input[@type='checkbox']",this).attr("disabled",true);
	$("input[@type='select-one']",this).attr("disabled",true);
	$("input[@type='select-multiple']",this).attr("disabled",true);
	$("input[@type='select']",this).attr("disabled",true);
	$("textarea",this).attr("disabled",true);
	$("select",this).attr("disabled",true);
}

jQuery.fn.applyRights = function () {
	$.each($(this).find(".rights"), function() {
		$.each($(this).find(":hidden"), function() {
			if ($(this).attr("value")=="0") {
				$(this).parent().addClass("rightoff");
			}
			else if ($(this).attr("value")=="1") {
				$(this).parent().addClass("righton");
			}
		});
	});
}

jQuery.fn.changeRight = function (userId, code, viewCode) {
	var input = $(this).find(":hidden");
	var target = $(this);
	
	// en cas de clic sur le droit voir pour le désactiver, on vérifie d'abord que d'autres droits 
	// ne sont pas cochés autrement on ne le désactivera pas
	var viewAndOneOtherRight = new Boolean(false);
	if (code==viewCode && input.attr("value")=="1") {
		$.each($(this).parent().children(), function() {
			if ($(this).attr("id")!=target.attr("id")) {
				var nextInput = $(this).find(":hidden");
				if (nextInput.attr("value")=="1") {
					viewAndOneOtherRight=Boolean(true);
				}
			}
		});
	}
	
	if (input.attr("value")=="0") {
		input.attr("value","1");
		$(this).removeClass("rightoff");
		$(this).addClass("righton");
		
		// En cas de clic sur un droit autre que voir, on l'active le droit voir s'il ne l'est pas
		if (code!=viewCode) {
			var viewTarget =  $(this).parent().children(":eq(1)");
			var viewInput = viewTarget.find(":hidden");
			if (viewInput.attr("value")=="0") {
				viewInput.attr("value","1");
				viewTarget.removeClass("rightoff");
				viewTarget.addClass("righton");
			}
		}
	}
	else if (viewAndOneOtherRight!=true && input.attr("value")=="1") {
		input.attr("value","0");
		$(this).removeClass("righton");
		$(this).addClass("rightoff");
	}	
}



jQuery.fn.makeAjaxCall= function(url,callback) {
	var target=$(this);
	
	if (target.attr("id")=="mainPanel"||target.attr("id")=="ongletPanel") {
		if(pageModified==true&&$(document.body).hasClass("alertonexit")) {
			var idConfirmPageChange = $.openDialog({
				title : constants.labels.modifiedTitle,
				content : constants.labels.modifiedContent,
				icon : constants.images.questionMark,
				type : "modal",
				buttons : {
					ok : {
						img: constants.images.accept,
						label: "Poursuivre",
						js: function() {
							$("#"+idConfirmPageChange).closeDialog();
							jQuery.ignoreAjaxErrors = true;
							document.location.href=url;
							return;
						}
					},
					nok : {
						img: constants.images.cancel,
						label: "Annuler",
						js : function() { 
							$("#"+idConfirmPageChange).closeDialog();
							return;
						}
					}
				},
				position:"center",
				draggable:true,
				width:400,
				height:180
			});
		} else {
			jQuery.ignoreAjaxErrors = true;
			document.location.href=url;
			return;
		}
	} else {
		callback = callback || function(){};
	   	notifyStartAjaxCall();
		$.ajax({
			type: "POST",
			url: url,
			dataType : "html",
			data: {}, // nécessaire pour passer les proxys sous FF
			success : function(html) {
				// supprime les draggable/droppable existant avant dans le cadre
				target.find(".ui-draggable").draggable("destroy");
				target.find(".ui-draggable-disabled").draggable("destroy");
				target.find(".ui-droppable").droppable("destroy");
				target.find(".ui-droppable-disabled").droppable("destroy");
				target.html(html);
	           	notifyStopAjaxCall();
				callback();
			},
			error : function( httprequest, textStatus, errorThrown){
	           	notifyStopAjaxCall();
				displayAjaxError(httprequest);
			}
		});
	}
}

// fonction a appeler pour fixer les differents bugs sous IE lorsque le contenu change (apres chargements ajax)
jQuery.fn.fixIE = function() {
	
	//PNGs transparents	
	var domTarget = this.get(0); //nécessaire pour récupérer le target dans le timeout
	setTimeout(function() { //un timeout est necessaire pour IE6, sinon bug dans certains cas...
		pngfix.loadPngs(domTarget); //on applique le pngfix uniquement au target
	},50);
	
	//rollovers tableaux
	var hoverClass = "sfHover";
	$("tr.even").hover( 
		function(){	$(this).addClass(hoverClass); }, 
		function(){	$(this).removeClass(hoverClass); }
	);
	$("tr.odd").hover( 
		function(){	$(this).addClass(hoverClass); }, 
		function(){	$(this).removeClass(hoverClass); }
	);
}

// attention la mÃ©thode goHref permet de faire un appel ajax sur le div appelant.
// mï¿½fiance, il y a des réécriture de liens...!
jQuery.fn.goHref = function(href,callback) {
	var target = $(this);
	var needConfirm = false;
	callback = callback || function(){};
	if (href.indexOf('/')==-1) {
		href = pageUrl+"/"+href;
	}
	if (href.indexOf(constants.contextPath)==-1) {
		href = constants.contextPath+href;
	}
	if(target.attr("id")=="ongletPanel") {
		$("#mainPanel").block("", { backgroundColor: '#aaa', color: '#aaa', fadeOut:0} );
	} else {
		target.block("", { backgroundColor: '#aaa', color: '#aaa', fadeOut:0} );
	}

	target.makeAjaxCall(href, function() {
		target.applyUI(href);
		callback();
		if (target.attr("id")=="ongletPanel") {
			$("#mainPanel").unblock();
		} else {
			target.unblock();
		}

   	});
}

jQuery.fn.goSubmit = function (targetId) {

	if (targetId!=undefined&&(targetId=="mainPanel"||targetId=="ongletPanel")) {
		$(this).submit();
		return;
	}

	// find the target id = the div up including the $form
	if (targetId==undefined) {
		var target = $($(this).parents("div").get(0));
		//alert('target undefined = '+$(target).attr("id"));
	}
	else {
		var target = $("#"+targetId);
		//alert('target = '+$(target).attr("id"));
	}
	target.block("", { backgroundColor: '#aaa', color: '#aaa', fadeOut:0} );
	action = $(this).attr("action");

	notifyStartAjaxCall();

	$(this).ajaxForm();
	
	// patch pour update les fck s'il existent
	for ( i = 0; i < parent.frames.length; ++i )
		if ( parent.frames[i].FCK )
			parent.frames[i].FCK.UpdateLinkedField();
			
	$(this).ajaxSubmit({ 
		target: target,
		beforeSubmit: function(formArray) {
/*			formArray.push({ 
				//name:"submit", 
				//value: $(input).attr("value") 
			});*/ 
		},
		success: function() {
           	target.unblock();
           	notifyStopAjaxCall();
  			target.applyUI(action);
  			pageModified=false;
	    },
		error : function( httprequest, textStatus, errorThrown){
			target.unblock();
           	notifyStopAjaxCall();
			displayAjaxError(httprequest);
		}	    
    });
    return false; 
}

function displayAjaxError(httprequest) {
	if (jQuery.ignoreAjaxErrors) {
		// on vient de changer de page alors que certaines boites ajax n'étaient pas totalement chargées. On ignore donc l'erreur...
	}
	else {
		var report = $("#messageajax");
		frames['frameerror'].document.body.innerHTML=httprequest.responseText;
		report.css("top",$("#page").height()/2-report.height()/2);
		report.css("left",$("#page").width()/2-report.width()/2);
		report.showElement();	
		blockPage();
	}
}

function closeAjaxError() {
	var report = $("#messageajax");
	report.hideElement();
	unblockPage();
}

function blockPage() {
	$("#userBar").block("", { backgroundColor: '#aaa', color: '#aaa',fadeOut : 0 });
	$("#adminBar").block("", { backgroundColor: '#aaa', color: '#aaa',fadeOut : 0 });
	$("#menuBar").block("", { backgroundColor: '#aaa', color: '#aaa',fadeOut : 0 });
	$("#contentArea").block("", { backgroundColor: '#aaa', color: '#aaa',fadeOut : 0 });
	$(".dialog").block("", { backgroundColor: '#aaa', color: '#aaa',fadeOut : 0 });
}

function unblockPage() {
	$("#userBar").unblock();
	$("#adminBar").unblock();
	$("#menuBar").unblock();
	$("#contentArea").unblock();
	$(".dialog").unblock();
}

function getDocument(target) {
	if (target == undefined)
		return document;
	else if (target.contentDocument)
		return target.contentDocument;
	else if (target.contentWindow)
		return target.contentWindow.document;
	else if (target.document)
		return target.document;
	else
		throw 'unable to get document object';
}

function notifyStartAjaxCall() {
	if (countAjaxCall==0) {
		$("#ajaxload").showElement();
		//$("#messageload").showElement();
	}
	countAjaxCall++;
}

function notifyStopAjaxCall() {
	countAjaxCall--;
	if (countAjaxCall==0) {
		$("#ajaxload").hideElement();
	}
}

jQuery.fn.boxRefresh = function(callback) {
	callback = callback || function(){};
	var target = $(this);
	var url = target.attr("refreshUrl");
	// desactivation des draggable et droppable
	target.find(".boxActionBar").empty();
	target.find(".contenu").eq(0).goHref(url,function() {
		callback();
		$(target).applyUI();
	});
}

/**
 * Fonctions pour gï¿½rer l'apparation et la disparition d'un message en bas de la fenï¿½tre.
 * Il y a plusieurs div de message dans la page
 */
jQuery.fn.showElement = function () {
	$(this).show();
	$(this).fadeTo("slow","1");
}

jQuery.fn.hideElement = function() {
	$(this).fadeTo("slow","0",function() { 
		$(this).hide();
	});

}

jQuery.fn.changeState = function () {
	var input = $(this).find(":hidden");
	var target = $(this);
	var ok=Boolean(true);
	
	
	//On coche une case
	if (input.attr("value")=="0") {
		input.attr("value", "1");
		target.removeClass("rightoff");
		target.addClass("righton");
	} else { //On décoche une case
		input.attr("value", "0");
		target.removeClass("righton");
		target.addClass("rightoff");
	}
}


jQuery.fn.applyStates = function () {
	$.each($(this).find(".rights"), function() {
		$.each($(this).find(":hidden"), function() {
			if ($(this).attr("value")=="0") {
				$(this).parent().addClass("rightoff");
			}
			else if ($(this).attr("value")=="1") {
				$(this).parent().addClass("righton");
			}
		});
	});
}

jQuery.fn.getMassIds = function() {
	id = $(this).attr("id");
	idsArray = new Array();
	$(".check"+id).each(function() {
		if($(this).attr("checked")==true) {
			idsArray.push($(this).attr("value"));
		}
	});
	return idsArray;
}

jQuery.fn.getMassIdsQuery = function() {
	id = $(this).attr("id");
	ids="";
	idsArray = $(this).getMassIds();
	for(var i=0;i<idsArray.length;i++) {
		ids+="&idObjectList="+idsArray[i];
	}
	return ids;
}
