/**
* bibliotheque javaScript KMT 2
* Created mars 2011
*/

/**
* Navigateur
*/
var myAgent   = navigator.userAgent.toLowerCase();
var myVersion = parseInt(navigator.appVersion);

var is_ie   = ((myAgent.indexOf("msie") != -1)  && (myAgent.indexOf("opera") == -1));
var is_nav  = ((myAgent.indexOf('mozilla')!=-1) && (myAgent.indexOf('spoofer')==-1)
&& (myAgent.indexOf('compatible') == -1) && (myAgent.indexOf('opera')==-1)
&& (myAgent.indexOf('webtv') ==-1)       && (myAgent.indexOf('hotjava')==-1));
var is_opera= (navigator.userAgent.indexOf("Opera" ) != -1);

var is_win   =  ((myAgent.indexOf("win")!=-1) || (myAgent.indexOf("16bit")!=-1));
var is_mac    = (myAgent.indexOf("mac")!=-1);
var is_firefox = (myAgent.indexOf("firefox") != -1);

/**
* Admin access functions
*/
/**

* 
* multiple Onload event function
*/
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}
function showAdminPanel(){
	addLoadEvent(showAdminPanelInit);
}

function showAdminPanelInit(){
	noAdminPanel=LireCookie("noAdminPanel");
	if(noAdminPanel==null || noAdminPanel==0 ) ajaxUpdaterRequest('adminPanelContainer','GET','ajax=1&kmt_login=&view=showAdminPanel&template=showAdminPanel_jquery.tpl','',true);
}


function showAdminControl(){
	µ('#adminPanelContainer').css('height','28px');
	µ('#adminTopBar').css('display','block');
	µ('#adminTopBar').css('margin-top','-24px');
	µ('#adminTopBar').animate({"margin-top": "+=24px"}, "slow");
}


function close_menu_admin(){
	µ('#adminPanelContainer').css("display","none");
}

function setNoAdminCookie(valeur){
	EcrireCookie("noAdminPanel", valeur);
	 location.reload();
}

function loadLocalFic(fic){
	//alert(fic);
	document.location.replace(fic);
	
}


function pushKmtMessage(message,parent){
	if (message!=''){
		v_parent = µ('#'+parent);
		v_div_enfant = document.createElement("div");
		v_div_enfant.setAttribute("id","kmt_message");
		v_parent.append(v_div_enfant);
		document.getElementById("kmt_message").innerHTML = message;
		putOnCenter('#kmt_message','#'+parent,40,0,true);
		string="µ('#kmt_message').fadeOut(500)";
		setTimeout(string,2000);
		string="µ('#kmt_message').remove()";
		setTimeout(string,2500);
	}
}

/**
* Pop up
*/
function openWindow(theURL,winName,features) {
	var fs=window.open(theURL, winName, features);
	fs.focus();
}



/**
 * jQuery anim
 */
var MenuDivOpen = new Array();

function toogle_jQuery(div,effect){

	for (i = 0; i < MenuDivOpen.length; i++) {
		// on ferme les menus ouvert
		if(MenuDivOpen[i]!=div) µ('#'+MenuDivOpen[i]).slideUp("fast");
	}
	MenuDivOpen = new Array();
	
	µ('#'+div).slideToggle("fast");
	MenuDivOpen.push(div);
}

function closeAllMenuDiv(){
	for (i = 0; i < MenuDivOpen.length; i++) {
		// on ferme les menu ouvert
		µ('#'+MenuDivOpen[i]).slideUp("fast");
	}
}
// classe d'interface prototype->jquery
var Effect=function(){
	//objet Effect pour interface vers Jquery
	return;
}

Effect.toggle=function(div,effect){
	µ('#'+div).slideToggle("fast");
}
Effect.Fade=function(div,duration){
	duration= duration==undefined?500:duration;
	µ('#'+div).fadeOut(duration);
}

Effect.Appear=function(div,duration){
	duration= duration==undefined?500:duration;
	µ('#'+div).fadeIn(duration);
}
Effect.Move=function(div,props){
	duration= props.duration==undefined?500:props.duration;
	µ('#'+div).animate({
		left:props.x+=20},
		duration);
}

Effect.SlideDown=function(div){
	µ('#'+div).slideDown("fast");
}

var Form=function(){
	
}

Form.serialize=function(form){
	return µ(form).serialize();
}
//classe d'interface pour Validation prototype -> jquery

function Validation(formId,options) {			
	 var defaults = {
	            immediate: "",
	            onSubmit: true,
	            onFormValidate:""
	        };   
	var opts = µ.extend(defaults, options); 
	
	return 	µ("#"+formId).validate({
		errorClass: "validation-advice",
		submitHandler:function(formId){						
			if(this.valid() && opts.onFormValidate!='' ){
				opts.onFormValidate(true,formId);
			}else if (this.valid() && opts.onFormValidate==''){
				formId.submit();
			}
		}
	});
	
}

//interface de remplacement prototype -> jquery
var $=function(id){
	if(typeof id == 'object'){
		return µ(id);
	} else {
		return µ('#'+id);
	}
};


µ.fn.removeClassName=function(className){
		µ(this).removeClass(className);
	};

µ.fn.addClassName=function(className){
		µ(this).addClass(className);
	};


	
/**
* Ajax basic functions
*/


function ajaxSimpleRequest(requestParams,myMethod,HandlerFunc){
	myMethod=myMethod=='' ? 'get' : myMethod;
	µ.ajax({url: ajaxCallURI,global: false,type:myMethod,data:requestParams,success:HandlerFunc});
}

function ajaxUpdaterRequest(target,myMethod,viewParams,completeParam,synchro){
	µ('#'+target).html('<div style="text-align:center;margin:20px"><img src="/icones/common/wait.gif" style="margin-bottom:15px;" alt="Chargement..."/><br/>Chargement...</div>');
	µ.ajax({url: ajaxCallURI,global: false,type:myMethod,data: viewParams,dataType: "html",async:synchro,success: function(html){µ("#"+target).html(html);}});
}


/**
* fckEditor pour retro compatibilité
*/
function createEditor(instance,width,height,toolbar){

	var oTextarea = $(instance) ;
	if ( !oTextarea )	oTextarea = document.getElementsByName(instance)[0] ;
	if ( oTextarea && oTextarea.tagName == 'TEXTAREA' )		{
		Width = !width ? 550 :width ;
		Height =!height ? 250 : height;
		var oFCKeditor = new FCKeditor(instance,Width,Height) ;
		//oFCKeditor.BasePath	= "/js/fckeditor/" ;
		oFCKeditor.ToolbarSet = !toolbar ? 'KMT' :toolbar ;
		oFCKeditor.ReplaceTextarea() ;
		
	}
}
/**
 * Serialization des fomulaires ajax
 */
function serializeForm(form){
	if(typeof form == 'object'){
		return µ(form).serialize();
	} else {
		return µ("#"+form).serialize();
	}
}

/**
* ckEditor  et ckFinder
*/

function createCKEditor(instance,toolbar){
	var editorInstance = CKEDITOR.instances[instance];
    if(editorInstance){ 
    	//editorInstance.remove();
    	CKEDITOR.remove(editorInstance);
    	//editorInstance.destroy();editorInstance = null;
    	
    }
     
	CKFinder.setupCKEditor( null, { basePath : '/js/ckfinder/'} ) ;
	ztoolbar = !toolbar ? 'KMT' :toolbar ;
	µ( '#'+instance ).ckeditor(function(){},{toolbar:ztoolbar});
	
}

function getCKEditorValue(instance,target){
    data = µ( '#'+instance ).val();
    µ("#"+target).val(data);
}


/******** mode inline **/
window.onload = function()
{
	// Listen to the double click event.
	if ( window.addEventListener )
		document.body.addEventListener( 'dblclick', onDoubleClick, false );
	else if ( window.attachEvent )
		document.body.attachEvent( 'ondblclick', onDoubleClick );

};

function onDoubleClick( ev ){
	// Get the element which fired the event. This is not necessarily the
	// element to which the event has been attached.
	var element = ev.target || ev.srcElement;

	
	// Find out the div that holds this element.
	element = element.parentNode;

	if ( element.nodeName.toLowerCase() == 'div' 	 && ( element.className.indexOf( 'editable' ) != -1 ) ){
		replaceDiv( element );
	}
}

var editor;

function replaceDiv( div ){
	if ( editor )
		editor.destroy();
	editor = CKEDITOR.replace( div ,{toolbar:'Inline'});
	
}

/**
* Position tools
*/

// retourne la taille de la fenï¿½tre
function windowSize(){
	var winWidth, winHeight, d=document;
	if (typeof window.innerWidth!='undefined') {
		winWidth = window.innerWidth;
		winHeight = window.innerHeight;
	} else {
		if (d.documentElement && typeof d.documentElement.clientWidth!='undefined' && d.documentElement.clientWidth!=0) {
			winWidth = d.documentElement.clientWidth;
			winHeight = d.documentElement.clientHeight;
		} else {
			if (d.body && typeof d.body.clientWidth!='undefined') {
				winWidth = d.body.clientWidth;
				winHeight = d.body.clientHeight;
			}
		}
	}
	return [winWidth, winHeight];
}

// retourne la taille du document
function documentSize(){
	var winWidth, winHeight, d=document;
	if (typeof window.innerWidth!='undefined') {
		winWidth = window.innerWidth+window.pageXOffset;
		winHeight = window.innerHeight+window.pageYOffset;
	} else {
		if (d.documentElement && typeof d.documentElement.scrollWidth!='undefined' && d.documentElement.scrollWidth!=0) {

			winWidth = d.documentElement.scrollWidth;
			winHeight = d.documentElement.scrollHeight;
		} else {
			if (d.body && typeof d.body.scrollWidth!='undefined') {
				winWidth = d.body.scrollWidth;
				winHeight = d.body.scrollHeight;
			}
		}
	}
	return [winWidth, winHeight];
}
/**
 * @desc Centre un objet dans son parent
 * @param div a centrer ex :#mydiv
 * @param parentDiv la div parent :#parentDiv
 * @param yRetrait : valeur du retrait Y, si on vet remonter la div de 200px on passe 200 si on veur la descendre -200
 * @param xRetrait : idem en x
 * @param top : si on veut que la div se place en haut de la div parente, passer true (le retrait est pris en comte
 * @return
 */


function putOnCenter(div,parentDiv,yRetrait,xRetrait,top){
	
	if(parentDiv==null){
		myWindowSize=windowSize();
		windowXmiddle=myWindowSize[0]/2;
		windowYmiddle=myWindowSize[1]/2;
	} else {
		windowXmiddle=µ(parentDiv).width()/2;
		windowYmiddle=µ(parentDiv).height()/2;
		µ(parentDiv).css("position",'relative');
	}
	eWidth=µ(div).width();
	eHeight=µ(div).height();

	if(!top){
		x=(windowXmiddle-(eWidth/2))+"px";
		y=(windowYmiddle-((eHeight/2)+yRetrait))+"px";
	}else{
		x=(windowXmiddle-(eWidth/2))+"px";
		y=yRetrait+"px";
	}
 
	µ(div).css("left",x);
	µ(div).css("top",y);
	return true;
}


// centre un objet dans la fenï¿½tre et le fait disparaitre au bout du time out
function putOnCenterAndHide(objName,parentDiv,timeOut,yRetrait){
	putOnCenter($(objName),$(parentDiv),yRetrait);
	$(objName).style.visibility='visible';
	string="Effect.Fade('"+objName+"');";
	setTimeout(string, timeOut);
}



function showBox(box,handler,appear){
	if(appear!='undefined') {µ("#"+box).fadeIn(1000);} else {µ("#"+box).css("display","block");}
	if(handler!='') µ("#"+box).draggable({scroll:true,handle:"#"+handler});
	return;
}

function hideBox(box,fade){
	boxObj=µ("#"+box);
	if (fade!='undefined') {µ("#"+box).fadeOut(1000);} else { µ("#"+box).css("display","none");}
}



/**
* Keyword
*/
function showKeyword(div,keyword_id){
	ajaxUpdaterRequest(div+'_text','get','ajax=1&keywords='+keyword_id+'&view=afficher_keyword_definition&divName='+div);
	µ("#"+div).css("display","block");
	µ("#"+div).css("margin","35px 0 0 120px")
	
}

function showKeywordList(div,kObj_id){
	ajaxUpdaterRequest(div+'_text','get','ajax=1&keywords=0&object_id='+kObj_id+'&view=afficher_keyword_list&divName='+div);
	µ("#"+div).css("display","block");
	µ("#"+div).css("margin","35px 0 0 120px")
}


// input tools
function clearInput(obj){
	obj.value="";
}

function toggleBox(div){
	
	if(µ("#"+div).css("display")=='block') {
		hideBox(div);
	} else {
		showBox(div);
		
	}
}

function hideDelayed(objName,timeOut){
	µ("#"+objName).css("visibility","visible");
	string="µ('#"+objName+"').fadeOut(1000);";
	setTimeout(string, timeOut);
}

// renvoi la position d'un objet
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

// affichage de la date
function afficher_date(){
	navvers = navigator.appVersion.substring(0,1);
	if (navvers > 3)
	navok = true;
	else
	navok = false;

	today = new Date;
	jour = today.getDay();
	numero = today.getDate();
	if (numero<10)
	numero = "0"+numero;
	mois = today.getMonth();
	if (navok)
	annee = today.getFullYear();
	else
	annee = today.getYear();
	TabJour = new Array("Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi");
	TabMois = new Array("janvier","fevrier","mars","avril","mai","juin","juillet","aout","septembre","octobre","novembre","decembre");
	return messageDate = TabJour[jour] + " " + numero + " " + TabMois[mois] + " " + annee;
}


format=function(valeur,decimal,separateur) {
	// formate un chiffre avec 'decimal' chiffres aprï¿½s la virgule et un separateur
	var deci=Math.round( Math.pow(10,decimal)*(Math.abs(valeur)-Math.floor(Math.abs(valeur)))) ;
	var val=Math.floor(Math.abs(valeur));
	if ((decimal==0)||(deci==Math.pow(10,decimal))) {val=Math.floor(Math.abs(valeur)); deci=0;}
	var val_format=val+"";
	var nb=val_format.length;
	for (var i=1;i<4;i++) {
		if (val>=Math.pow(10,(3*i))) {
			val_format=val_format.substring(0,nb-(3*i))+separateur+val_format.substring(nb-(3*i));
		}
	}
	if (decimal>0) {
		var decim="";
		for (var j=0;j<(decimal-deci.toString().length);j++) {decim+="0";}
		deci=decim+deci.toString();
		val_format=val_format+"."+deci;
	}
	if (parseFloat(valeur)<0) {val_format="-"+val_format;}
	return val_format;
}


/***************** Google maps ******************/
function googlemaps_load(latitude,longitude) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(µ("#googlemap"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		map.addControl(new GScaleControl());
		map.setCenter(new GLatLng(latitude,longitude), 14);
	}
}


function checkCookie() {
	setCookie("CookieTest", "OK", 1);
	var v = getCookie("CookieTest");
	setCookie("CookieTest", "");
	return (v == "OK");
}	// checkCookie() end

function getCookie(inName) {
	var search = inName + "="
	if (document.cookie.length > 0) {
		var offset = document.cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			var end = document.cookie.indexOf(";", offset);
			if (end == -1)
			end = document.cookie.length;
			return unescape(document.cookie.substring(offset, end));
		}
	}
}	// getCookie(inName) end

function setCookie(inName, inVal, inTime, inPeriodInSecond) {
	if (!inPeriodInSecond) inPeriodInSecond = 86400;
	if (!inTime && (document.location.href.indexOf("localhost") > -1 ||	document.location.href.indexOf("127.0.0.1") > -1)) {
		inTime = 6;			// on IIS localhost non expiring cookies don't seem to work?
		inPeriodInSecond = 3600;	// so lets have 6 hours instead
	}
	var expire = "";
	if (inTime) {
		var today = new Date();
		today.setTime(today.getTime() + (inTime * inPeriodInSecond * 1000));
		expire = ";expires=" + today.toGMTString();
	}
	//alert(expire);
	document.cookie = inName + "=" + escape(inVal) + expire + ";path=/;";
}	// setCookie(inName, inVal, inDays) end



/************ Lien dynamique  **************/
function goTo(selectObj){

	mySite = selectObj.options[selectObj.selectedIndex].value;
	//alert(mySite);
	document.location.href=mySite;
}
function getUrl(url){
	document.location.href=url;
}

/********** cookies **************/
function getCookieVal(offset){
	var endstr=document.cookie.indexOf (';', offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function LireCookie(nom){
	var arg=nom+'=';
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen)
	{
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
		i=document.cookie.indexOf(' ',i)+1;
		if (i==0) break;

	}
	return null;
}

function EcrireCookie(nom, valeur){
	var argv=EcrireCookie.arguments;
	var argc=EcrireCookie.arguments.length;

	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=nom+'='+escape(valeur)+
	((expires==null) ? '' : ('; expires='+expires.toGMTString()))+
	((path==null) ? '' : ('; path='+path))+
	((domain==null) ? '' : ('; domain='+domain))+
	((secure==true) ? '; secure' : '');
}

// mise a jour de la derniï¿½re date de visite
function setlastVisit(){
	today = new Date();
	expire = new Date();
	expire.setTime(expire.getTime() + ( 180*24*60*60*1000));
	EcrireCookie('lastVisit',today.getTime(),expire,'/');
	return;
}
setlastVisit();

/**************** Pub **********/

var pubArray=new Array();

// commandes de rechargement des bandeaux pub
function changeAdds(){
	for(i=0;i<pubArray.length;i++){
		ajaxUpdaterRequest('adds_'+pubArray[i],'get','ajax=1&adds='+pubArray[i]+'&view=get_afficher_adds_code');
	}
}

// commandes de modification du premier bandeaux pub de la page en fonction de la video
function specialAdds(NewAddId){
	if(NewAddId!=''){
		ajaxUpdaterRequest('adds_'+pubArray[0],'get','ajax=1&adds='+NewAddId+'&view=get_afficher_adds_code');
	}
}

/**************** Taille de police ************/
function updateFontSize(A,div) {
	B=µ('#'+div);
	 var currentFontSize = B.css('font-size');
	    var currentFontSizeNum = parseFloat(currentFontSize, 10);
	    factor=1+(A/100);
	    var newFontSize = currentFontSizeNum*factor;
	   B.css('font-size', newFontSize);
	    return false;
}

/***************** Move object ***************/
function moveObject( obj, e ) {

	var tempX = 0;
	var tempY = 0;
	var offset = 5;
	var objHolder = obj;

	// step 2
	obj = $( obj );
	if (obj==null) return;

	// step 3
	if (document.all) {

		tempX = event.clientX + document.documentElement.scrollLeft;
		tempY = event.clientY + document.documentElement.scrollTop;
	} else {
		tempX = e.pageX;
		tempY = e.pageY;
	}

	// step 4
	if (tempX < 0){tempX = 0}
	if (tempY < 0){tempY = 0}

	// step 4
	if (tempX < 0){tempX = 0}
	if (tempY < 0){tempY = 0}

	// step 5
	obj.css('top',(tempY + offset) + 'px');
	obj.css('left',(tempX + offset) + 'px');
	return;

}



/*********** défilant HTML ****/


// Dï¿½filement 4 directions multiple
function Defilant(id, pos_init, pos_min, pos_max, delta, direction) {
	this.id          = id;
	this.element     = document.getElementById(id);
	this.pos_init    = pos_init;
	this.pos_min     = pos_min;
	this.pos_max     = pos_max;
	this.pos_current = pos_init;
	this.delta       = delta;
	this.direction   = direction;
}


Defilant.prototype.defile = function() {
	if (!this.element) {
		this.element = document.getElementById(this.id);
	}
	if (this.element) {
		if(this.direction == 'vertical'){
			if(this.pos_current < (this.pos_min - this.element.offsetHeight) ){
				this.pos_current = this.pos_init;
			} else if (this.pos_current > this.pos_max ) {
				this.pos_current = this.pos_init - this.element.offsetHeight;
			} else {
				this.pos_current += this.delta;
			}
			this.element.style.top = this.pos_current+"px";
		} else if(this.direction == 'horizontal') {
			if(this.pos_current < (this.pos_min - this.element.offsetWidth) ){
				this.pos_current = this.pos_init;
			} else if (this.pos_current > this.pos_max ) {
				this.pos_current = this.pos_init - this.element.offsetWidth;
			} else {
				this.pos_current += this.delta;
			}
			this.element.style.left = this.pos_current+"px";
		}
	}
}

function switch_image(id,newimage){
	µ('#'+id).src=newimage;
}


sfHover = function(divName) {
	if (document.all&&document.getElementById) {
		navRoot = document.getElementById(divName);
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" sfhover";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" sfhover", "");
				}
			}
		}
	}
}


