/*///////////////////////////////////////////////////////////////////////////////////////////////////////
///// Code mixing by Molokoloco for Agence Clark... [BETA TESTING FOR EVER] ........... (o_O)  /////////
///////////////////////////////////////////////////////////////////////////////////////////////////////

Functions :

	vd(obj, parent)										: Var dump obj
	db(myvar)											: Debugging
	isset(myVar)										: is Set ?
	die()												: Stop script
	navDetect()											: gecko | msie | netscape
	navVer()
	pcDetect()											: PC / MAC
	isFrame()											: call in a frame ?
	//addLoadEvent(func)								: Depreciated // Check prototype
	fixDialogValue(msg)									: BECAREFUL ! OVERWRITE native fonction alert() !
	parseQuery(query)									: return array from "toto=1&tutut=2"
	getUniqueId()										: return like 14_12_59_53
	iniRoll(evt)										: Init roll over <img src="toto.jpg" roll="toto_hover.jpg"/>
	fixPng(evt)											: IE fixe PNG transparency
	escapeURI(url)										: Encode url
	creatDiv(parentElement,attr,contentHtm)				: var attr = {id:'divId',style:'styleDiv',className:'lassDiv'}
	setImg(imgId,imgSrc)								: setImg image 
	loadImg(imgSrc)
	toggleClass(el,classNor,classSel)					: Switch Class1/Class2
	in_array(myValue,myArray)
	trim(string)
    strRep(string,strSearch,strRep)                        : String replace DEPRECIATED // proto : gsub(pattern, replacement)
	baseName(path)										: baseName
	getExt(string)											: Extension
	affCleanName(imgtitle)								: Clean "12313414654_toto.jpg"
	getPageScroll()										: Returns Array(xScroll,yScroll) 
	getPageSize()										: Returns Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	setFooter()
	SelfResize(Wwide,Whigh)
	resizeIframe(frameid)
	setCookie(name,value,expires,path,domain,secure)	: Cookies manage
	getCookie(name)
	deleteCookie(name)
	getFlashObject(movieName)
    setAutoSizeFlash(flashId)                            : Auto-resize Flash // to check !
	SendDataToFlashMovie(movieName,data)
	checkDate(strDate)									: Validate DATE EXIST : 15/02/78
	checkUrl(strUrl)									: Validate URL
    checkMail(strMail)                                    : Check Mail !
	myPop(url,winName,Wwide,Whigh)						: POP UP URL
	PopImg(imageURL)									: POP UP IMAGE
	removePrintInfo()
	removeFadePrintInfo()
	printInfo(infos,timeOut) 							: Creer une div pour afficher des infos... :)
	removeOverlay()
	startOverlay()
	startDivBox(w,h)
	resizeLightbox(w,h)
	loadUrlInOverlay(url,w,h)							: Div fenetre dialogue modale...
	linkShowHide(linkId,myElement,imgId,imgStart,imgEnd): link change image en display element... 
	showHideBoxes(visibility)							: Cacher les select et les flash pour affichage overlay..
	pause(numberMillis)
	verif(frm_name,arr_control,mep)						: Vérification de formulaire
	openOrCloseDiv(div)									: Frametek
	permuteNodeOpenCloseStatus(ent,div,img,cnx)			: Frametek
	SetDivContent(layer,contenuHtml)					: Depreciated - Frametek
	parseXml()											: Parse en read XML.. To check !
	getXml(xmlPath)
	callTinyMceInit()									: WYSIWYG dyn create TINY MCE
	loadTinyMce(element)

	findIdInClass(el)									: Find ID in class
	findParamInClass(param, el)
	formatTime(seconds)									: Format Time
	setSrc(element, newSrc)								: Set src no Bug
	ajaxCheck(input,valeur,divInfo)						: AJAX check input

/////////////////////////////////////////////////////////////////////////////////////////////////////// */

/* Return the ID of an element */
var ID = function( id ) {
	return $( id );
	// return document.getElementById( id );
}

/* ------------------------- IS ID ? ---------------------------------- */
var isId = function(element) {
	if (!isSet(element)) return false;
	try { 
		if ($(element)) return true;
		else return false;
	}
   	catch(e) { return false; }
};

/* ------------------------- DEBUG VAR ---------------------------------- */
function db(myvar) {
	var varValue = "";
	if (typeof myvar == 'string' || typeof myvar == 'number') varValue = myvar;
	//else if (typeof myvar == 'object') return vd(myvar);
    else { 
		for (var att in myvar) {
			if (typeof myvar[att] != 'function') // (bad prototype noise)
				varValue += '\t'+att + ' <'+typeof myvar[att]+'> ' + myvar[att]+'\n';
		}
	}
	var varValue = 'DB (' + typeof myvar + ') :\n' + varValue;
    if (navigator.userAgent.indexOf('Firefox') >= 0 && console.log) console.log(varValue); // DEV
	else if (document.createEvent) printfire(varValue);
    else nativeAlert(varValue);   
}

/* ------------------------- DEBUG OBJET ---------------------------------- */
function vd(obj, parent) {
    if (typeof obj != 'object') return db(obj);
	for (var attr in obj) {
		if (parent)  console.log(parent + "+" + attr + "\n" + obj[attr]);
		else console.log(attr + "\n" + obj[attr]);
		if (typeof obj[attr] == 'object') {
			if (parent) vd(obj[attr], parent + "+" + attr);
			else vd(obj[attr], attr);
		}
	}
}

/* ------------------------- DEBUG OBJET ---------------------------------- */
function isset(myVar) {
	return ( ( (myVar == '' || myVar == undefined ) && myVar != 0 ) ? false : true );
	
}

/* ------------------------- STOP SCRIPT ---------------------------------- */
function die() {
	throw("MoonWalker is down...");
}

/* ------------------------- NAVIGATOR ---------------------------------- */
var DOM = (document.getElementById ? true : false); // FF / IE / NS...
var IE = (document.all ? true : false);
var NS = (document.layers ? true : false);

function navDetect() {
	var userAgentStr = navigator.userAgent.toLowerCase();
	var isIE = ((userAgentStr.indexOf("msie") != -1) && (userAgentStr.indexOf("opera") == -1) && (userAgentStr.indexOf("webtv") == -1));
	var oldIE = (userAgentStr.indexOf("msie 5.0") != -1) || (userAgentStr.indexOf("msie 4") != -1) || (userAgentStr.indexOf("msie 3") != -1);
	var isGecko = (userAgentStr.indexOf("gecko") != -1);
	var isCamino = (userAgentStr.indexOf("camino") != -1);
	var isKonqueror = (userAgentStr.indexOf("konqueror") != -1);
	var isSafari = (userAgentStr.indexOf("applewebkit") != -1);
	if (isSafari) isGecko = false;
	var isOpera = (window.opera);
	if (isOpera) { isIE = oldIE = isGecko = isSafari = isCamino = isKonqueror = false; }

	if (isGecko) return 'gecko';
    else if (isIE) return 'msie';
    else if (oldIE) return 'msieOld';
    else if (isCamino) return 'camino';
    else if (isSafari) return 'safari';
    else if (isOpera) return 'opera';
    else if (isCamino) return 'camino';
    else return null;
}
function navVer() {
	return parseFloat(navigator.appVersion);
}
function pcDetect() {
	var userAgentStr = navigator.userAgent.toLowerCase();
	if (userAgentStr.indexOf('mac') != -1) return 'mac';
	else return 'pc';
}
function isFrame() {
	return ( window.self == window.parent ? false : true ); /* Checks that page is in iframe. */ 
}

/* ------------------------- FIX DIALOGUE BOX ---------------------------------- */
function fixDialogValue(msg) {
    var result = msg+''; // To string..
	result = result.stripScripts();
	result = result.replace(/\0+/g, "");
	result = result.unescapeHTML();
	return result;
}

var nativeAlert = window.alert;
window.alert = function(msg) { nativeAlert(fixDialogValue(msg)); };
var nativePrompt = window.prompt;
window.prompt = function(msg, defaultValue) { return nativePrompt(fixDialogValue(msg), fixDialogValue(defaultValue)); };
var nativeConfirm = window.confirm;
window.confirm = function(msg) { return nativeConfirm(fixDialogValue(msg)); };

/* ------------------------- ADD ONLOAD EVENT ---------------------------------- */
// USE THIS
// function page_loaded(evt) { if (evt) Event.stop(event); /* ... */ }
// Event.observe(window,'load',page_loaded,false);

/* ------------------------- PARSE QUERY ---------------------------------- */
function parseQuery(query) {
	if (!query) return {};
	var params = {};
	var pairs = query.split(/[;&]/);
	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i].split("=");
		if (!pair || pair.length != 2) continue;
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, " ");
	}
	return params;
}
/* ------------------------- STRING UNIQUE ---------------------------------- */
function getUniqueId() {
    var Stamp = new Date();
	var h = Stamp.getHours();
	var m = Stamp.getMinutes();
	var s = Stamp.getSeconds();
    return h+'_'+m+'_'+s+'_'+parseInt(Math.random()*100);
}

/* ------------------------- ADD ROLL OVER IMAGE ---------------------------------- */
var srcBak = {}; // Stock ex Src
var srcLoad = {}; // preLoad hover
function iniRoll(evt) {
	if (evt) Event.stop(evt);
	$$('img[roll]').each( function(picture) { // loop through all images tags with attr "roll"
		if ($(picture).getAttribute("roll") != '') {
			if (getExt($(picture).getAttribute("roll")).toLowerCase()=="png" && navigator.userAgent.toLowerCase().indexOf("msie 6.0")!=-1) { void (0); }
			else {
			var rid = $(picture).getAttribute("id");
			if (!rid) { // generate unik Id
					rid = 'ID_'+getUniqueId();
					picture.setAttribute("id",rid);
			}
			srcBak[rid] = $(picture).getAttribute("src"); // Stock
			loadImg($(picture).getAttribute("roll")); // Preload Hover src
				Event.observe(picture, 'mouseover', function(evt) {
				this.setAttribute('src',this.getAttribute("roll"));
			});
				Event.observe(picture, 'mouseout', function(evt) {
				var rid = this.getAttribute("id");
				this.setAttribute('src',srcBak[rid]);
			});
		}
        }
	});
}
Event.observe(window,'load',iniRoll);

/* ------------------------- FIX PNG ---------------------------------- */
function fixPng(evt) {
	if (evt) Event.stop(evt);
    if (document.body.filters && navVer() < 7) {  // OK pour IE 7 mais par pour IE 5/6
        for(var i=0; i<document.images.length; i++) {
            var img = document.images[i];
            var imgSrc = img.src;
            if (getExt(baseName(imgSrc)).toLowerCase()=="png") {
                img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+imgSrc+"', sizingMethod='scale');";
                img.src = 'images/common/css/pix.gif';
            }
        }
    }
}
// if (navDetect() == 'msie' || navDetect() == 'msieOld') Event.observe(window,'load',fixPng,false);


/* ------------------------- ENCODE URL ---------------------------------- */
function escapeURI(url) {
	if (encodeURIComponent) return encodeURIComponent(url);
	else if (encodeURI) return encodeURI(url);
	else if (escape) return escape(url);
	else return url;
}

/* ------------------------- CREATE DIV (USE BUILDER PROTOTYPE) ---------------------------------- */
function creatDiv(parentElement,attr,contentHtm) { // attr is "id" OR "array" // {id:'divId',style:'styleDiv',className:'lassDiv'}
	if (!attr) return;
	if (attr != '' && typeof attr != 'object') attr = {'id':attr,'name':attr};
    if (!attr['id']) return; // pas d'ID ?
	if ($(attr['id'])) return; // deja construit ?
	// Style par defaut
	if (!attr['style'] && !attr['class'])
        attr['style'] = 'border:1px solid #999999;padding:6px;margin:0;background-color:#FFFFFF;width:100%;';
	var myDiv = Builder.node('div',attr);	
	if (!parentElement && $('divNode')) {
		$('divNode').show();
		parentElement = $('divNode');
	}
    else if (!parentElement) parentElement = $$("body")[0]; // Explorer Can't modificate parent :-/
	parentElement.appendChild(myDiv);
	if (contentHtm) $(attr['id']).update(contentHtm);
}

/* ------------------------- setImg ---------------------------------- */
function setImg(imgId,imgSrc) { // Ex. // onMouseOver="setImg('eff','eff_hover.png');" onMouseOut="setImg('eff','eff.png');"
	if ($(imgId)) $(imgId).setAttribute('src',imgSrc);
}

/* ------------------------- Create loader IMAGE ---------------------------------- */
function loadImg(imgSrc) {
	var imgPreloader = new Image();
	imgPreloader.src = imgSrc;
}

/* ------------------------- TOGGLE CLASS ---------------------------------- */
function toggleClass(el,classNor,classSel) { // Switch Class1/Class2
	var d = $(el);
	if (d.className == classNor) d.className = classSel;
	else d.className = classNor;
}

/* ------------------------- IN_ARRAY ---------------------------------- */
function in_array(myValue,myArray) {
    function equals(a,b) { return (a === b); }
	for (var i in myArray) {
		if (equals(myArray[i],myValue)) return true;
	}
	return false;
}

/* ------------------------- TRIM ---------------------------------- */
function trim(string) {
  return string.replace(/^\s+|\s+$/g, "");
}

/* ------------------------- STRING REPLACE ------------------------------ */
function strRep(string,strSearch,strRep) {
	var regEx = new RegExp(strSearch, 'gi');
	return string.replace(regEx,strRep);
}

/* ------------------------- baseName ---------------------------------- */
function baseName(path) {
	var vb;
	for (i = path.length; i>0; i--) {
		vb = path.substring(i,i+1)
		if (vb == "/") return path.substring(i+1,path.length);
	}
}
/* ------------------------- GetExt ---------------------------------- */
function getExt(string) {
	var vb;
	for(i=string.length;i>0;i--){
		vb=string.substring(i,i+1);
		if (vb==".") return string.substring(i+1,string.length);
	}
}

/* ------------------------- CLEAN FILE NAME ---------------------------------- */
function affCleanName(imgtitle) { // 070305142221_cest_aussi_ca.jpg >>> cest aussi ca
	if (imgtitle.match('/')) imgtitle = baseName(imgtitle);
	myregexp = new RegExp(/_[0-9]{4,}/gi);
	imgtitle = imgtitle.replace(myregexp,'');
	myregexp = new RegExp(/.jpg|.gif|.png/gi);
	imgtitle = imgtitle.replace(myregexp,'');
	myregexp = new RegExp(/_/gi);
	imgtitle = imgtitle.replace(myregexp,' ');
	return imgtitle;
}

/* ------------------------- WINDOW SCROLL ------------------------------ */
// Core code from - quirksmode.org
function getPageScroll() {
	var yScroll, xScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop) {
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	}
	else if (document.body) {
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;
	}
	return new Array(xScroll,yScroll) 
}

/* ------------------------- WINDOW PAGE SIZE ------------------------------ */
// Core code from - quirksmode.org
// Return Array(pageWidth,pageHeight,windowWidth,windowHeight)
function getPageSize() {
	
	var xScroll, yScroll, pageWidth, pageHeight;
	
    if (window.innerHeight != null && window.scrollMaxY) {   
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
    } else if (document.body != null) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if (yScroll < windowHeight) pageHeight = windowHeight;
	else pageHeight = yScroll;

	// for small pages with total width less then width of the viewport
	if (xScroll < windowWidth) pageWidth = windowWidth;
	else pageWidth = xScroll;

	return new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
}
 
/* ------------------------- TO TEST LATER... ------------------------------ */
function setFooter(evt) {
	if (evt) Event.stop(evt);
	var windowHeight = getWindowHeight();
	if (windowHeight > 0) {
		var contentHeight = $('content').offsetHeight;
		var footerElement = $('footer');
		var footerHeight  = footerElement.offsetHeight;
		if (windowHeight - (contentHeight + footerHeight) >= 0) {
			footerElement.style.position = 'relative';
			footerElement.style.top = (windowHeight - (contentHeight + footerHeight)) + 'px';
		}
		else {
			footerElement.style.position = 'static';
		}
	}
}
//Event.observe(window,'load',setFooter);
//Event.observe(window,'resize',setFooter);

/*
function footerDown() {
    bodyHeight = $('bodyall').offsetHeight;
    winHeight  = window.innerHeight ? window.innerHeight : document.body.clientHeight;
    if (bodyHeight < winHeight)     {
        $('content').style.height = (winHeight - (bodyHeight - $('content').offsetHeight)) + 'px';
    }
}
*/
/* ------------------------- SELF RESIZE WINDOW AND CENTER ---------------------------------- */
function SelfResize(Wwide,Whigh) {
	if (Wwide == '') Wwide = 1024; // Wanted Size
	if (Whigh == '') Whigh = 768;
	
	if (navDetect() == 'msie') Whigh = Whigh + 150; // ToolBar Explorer ???
	var wide = window.screen.availWidth;
	var high = window.screen.availHeight; // Screen size
	var left = 0; var top = 0; // Position
	if (wide > Wwide) left = (wide-Wwide)/2; else Wwide = wide;
	if (high > Whigh) top = (high-Whigh)/2; else Whigh = high; // Max Size
	window.moveTo(left,top);
	window.resizeTo(Wwide,Whigh);
}
/*function SizeWindow(width, height) {
  if (navDetect() == 'msie') {
    window.resizeTo(width, height);
    var dx = width - window.document.body.offsetWidth;
    var dy = height - window.document.body.offsetHeight;
    window.resizeBy(dx, dy);
    window.dialogHeight = (parseInt(window.dialogHeight, 10) + dy) + "px";
    window.dialogWidth = (parseInt(window.dialogWidth, 10) + dx) + "px";
  } else {
    window.innerWidth = width;
    window.innerHeight = height;
  }
}*/

/* ------------------------- resize Iframe // TO CHECK ------------------------------ */
// onload="parent.resizeIframe('popIframe');"
function resizeIframe(frameid) {
    var currentfr = $(frameid);
    if (currentfr && !window.opera) {
        if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) { //ns6 syntax
            if (currentfr.contentDocument.$('media')) { // Si objet Media dans l'iframe
                currentfr.width = currentfr.contentDocument.$('media').width + 30;
                currentfr.height = currentfr.contentDocument.$('media').height + 30;
            }
            else {
                currentfr.height = currentfr.contentDocument.body.offsetHeight;
                currentfr.width = currentfr.contentDocument.body.offsetWidth;
            }
        }
        else if (currentfr.document && currentfr.document.body.scrollHeight) { //ie5+ syntax
            if (currentfr.document.$('media')) { // Si objet Media dans l'iframe
                currentfr.width = currentfr.document.$('media').width + 30;
                currentfr.height = currentfr.document.$('media').height + 30;
            }
            else {
                currentfr.height = currentfr.document.body.scrollHeight;
                currentfr.width = currentfr.document.body.scrollWidth;
            }
        }
    }
}
// Frame resize // To call in the frame...
function frameResize(frameId) {
	var pageSize = getPageSize(); // Returns Array(pageWidth,pageHeight,windowWidth,windowHeight)
	var frameHeight = pageSize[1]; // document.getElementById('fullPageDiv').offsetHeight;
	var iFrame = window.parent.document.getElementById(frameId); // gets frame reference from parent
	iFrame.style.height = frameHeight; //set height of frame
}

/* ------------------------- COOKIES ------------------------------ */

function setCookie(name,value,expires,path,domain,secure) { 
	expires = expires * 60*60*24*1000;
	var today = new Date();
	var expires_date = new Date( today.getTime() + (expires) );
	var cookieString = name + "=" +escape(value) + 
	   ( (expires) ? ";expires=" + expires_date.toGMTString() : "") + 
	   ( (path) ? ";path=" + path : ";path=/ ") + 
	   ( (domain) ? ";domain=" + domain : "") + 
	   ( (secure) ? ";secure" : ""); 
	document.cookie = cookieString; 
}	

function getCookie(name) {
    var nameEQ = name + '=';
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name, '', -1);
}

/* ------------------------- SELF FLASH RESIZE / TO CHECK ---------------------------------- */
// http://www.adobe.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html
function getFlashObject(movieName) {
	if (window.document[movieName]) return window.document[movieName]; // window.document.movie
	else if (document.embeds && document.embeds[movieName]) return document.embeds[movieName]; 
	else if ($(movieName)) return $(movieName);
	else return false;
}

function setAutoSizeFlash(flashId) {
    var myFlash = getFlashObject(flashId);
    if (!myFlash) {
        db('Can\'t find : '+flashId);
        return;
    }
	var Largeur = myFlash.TGetProperty('/', 8);
	var Hauteur = myFlash.TGetProperty('/', 9);
	myFlash.setAttribute('width',Largeur);
	myFlash.setAttribute('height',Hauteur);
}

function SendDataToFlashMovie(movieName,data) { // To test
     var flashMovie = getFlashObject(movieName);
     flashMovie.SetVariable("/:"+data,document.controller.Data.value);
}

/* ------------------------- VALIDATE DATE : 15/02/78 ------------------------------ */
function checkDate(strDate,lang) {
	if (!strDate.match('/')) return false;
	var date_array = strDate.split('/');
	if (lang=='uk') {
    	var day = String(date_array[1]);
    	var month = String(date_array[0]);
    } else {
    	var day = String(date_array[0]);
    	var month = String(date_array[1]);
    }
	var year = String(date_array[2]);
	if (day.length < 2 || month.length < 2 || year.length < 2) return false;
	if (parseInt(year) > 78) year = '19'+year;
	else year = '20'+year;
	month = parseInt(month - 1); // Attention! Javascript range 0 - 11
	var source_date = new Date(year,month,day);
	if (year != source_date.getFullYear() || month != source_date.getMonth() || day != source_date.getDate())
		return false;
	else
		return true;
}

/* ------------------------- VALIDATE URL ------------------------------ */
function checkUrl(strUrl) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	return regexp.test(strUrl);
};

/* ------------------------- VALIDATE URL ------------------------------ */
function checkMail(strMail) {
    var regexp = /^[A-Za-z0-9._-]+@[A-Za-z0-9.\-]{2,}[.][A-Za-z]{2,4}$/;
    return regexp.test(strMail);
};           

/* ------------------------- POP UP URL ---------------------------------- */
function myPop(url,winName,Wwide,Whigh) { // <a href="pop_media.php" onClick="return myPop('pop_media.php','pop','260','120');">
	if (winName=='') winName = '_blank';
	var wide = window.screen.availWidth;
	var high = window.screen.availHeight; // Screen size
	var left = 0; var top = 0; // Position
	if (wide > Wwide) left = (wide-Wwide)/2; else Wwide = wide; if (high > Whigh) top = (high-Whigh)/2; else Whigh = high; // Max Size
	var w = window.open(url,winName,'height='+Whigh+',innerHeight='+Whigh+',width='+Wwide+',innerWidth='+Wwide+',left='+left+',screenX='+left+',top='+top+ ',screenY='+top+',dependent=1,status=1,statusmenubar=1,directories=0,fullscreen=0,toolbar=0,location=0,menubar=0,scrollbars=0,resizable=0');
	w.focus();
	return false; // Don't open href link
}

/* ------------------------- POP UP IMAGE ---------------------------------- */
function PopImg(imageURL) {
    var PositionX = 0;
    var PositionY = 0;
    var defaultWidth = 60;
    var defaultHeight = 60;
	var imgWin = window.open('about:blank','','resizabe=no,scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
    if (!imgWin) return true; // Open HREF
	with (imgWin.document) {
        writeln('<html><head><title>Chargement...</title><style type="text/css"> body { margin:0; overflow:hidden; } </style><scr'+'ipt> var NS = (navigator.appName=="Netscape")?true:false; function doTitle() { document.title="'+affCleanName(imageURL)+'"; } function waiting() { document.getElementById(\'wait\').innerHTML += \'.\'; } var tt = null; function fitPic() { difW = (NS)?window.innerWidth:document.body.clientWidth; difH = (NS)?window.innerHeight:document.body.clientHeight; difW = document.images[0].width - difW;  difH = document.images[0].height - difH; window.resizeBy(difW,difH); wide = screen.availWidth; high = screen.availHeight; difW = (NS)?window.innerWidth:document.body.clientWidth; difH = (NS)?window.innerHeight:document.body.clientHeight; var left = 0; var top = 0; if (wide > difW) left = (wide-difW)/2; else difW = wide;  if (high > difH) top = (high-difH)/2; else difH = high; window.moveTo(left,top); document.getElementById(\'wait\').style.display=\'none\'; document.getElementById(\'George\').style.display=\'block\'; if(tt) {clearInterval(tt); tt = null; } self.focus(); doTitle(); } </scr'+'ipt></head><body bgcolor="#000000" scroll="no" onLoad="fitPic();" onclick="self.close();"><img name="George" id="George" src="'+imageURL+'" style="cursor:pointer;"><div id="wait" style="color:#FFFFFF; padding-left:10px; padding-top:30px;" width="'+defaultWidth+'" height="'+defaultHeight+'"></div><script>tt = setInterval("waiting();", 500); </script></body></html>');
		close();
	}
	return false; // Don't open href
}
function popImg(imageURL) {
	return PopImg(imageURL);
}

/* ------------------------- Creer une DIV pour afficher des infos DYN ------------------------------ */
var myTimer = null;

function startOverlay() {
	showHideBoxes('hidden');
    if (!$('divNode')) return alert('Il manque l\'élément "divNode"');
	$('divNode').show();
    if (!$('dyn_overlay')) {
		//var objBody = document.getElementsByTagName("body").item(0);
		var objOverlay = document.createElement("div");
        objOverlay.setAttribute('id','dyn_overlay');
         objOverlay.setAttribute('style','display:none;');
		$('divNode').appendChild(objOverlay);
	}
	var arrayPageSize = getPageSize();
    Element.setHeight('dyn_overlay', arrayPageSize[1]);
    new Effect.Appear('dyn_overlay', {duration: 0.2, from: 0.0, to: 0.7, queue: 'front'});
}

function removeOverlay() {
    new Effect.Fade('dyn_lightbox', {duration: 0.2, from: 0.7, to: 0.0, queue: 'front'});
    new Effect.Fade('dyn_overlay', {duration: 0.2, from: 0.7, to: 0.0, queue: 'end'});
    $('dyn_lightbox').hide();
    $('dyn_overlay').hide();
    $('divNode').hide();
    showHideBoxes('visible');
}

function removePrintInfo() {
	if (myTimer) {
		clearTimeout(myTimer);
		myTimer = null;
	}
    if ($('dyn_infos')) $('dyn_infos').remove();
    if ($('dyn_overlay')) $('dyn_overlay').hide();
	$('divNode').hide();
	showHideBoxes('visible');
}

function removeFadePrintInfo() {
    new Effect.Fade('dyn_infos', {duration: 0.2, from: 0.7, to: 0.0, queue: 'front'});
    new Effect.Fade('dyn_overlay', {duration: 0.2, from: 0.7, to: 0.0, queue: 'end', onfinish:removePrintInfo()});
}

function printInfo(infosHtml) {
    if (infosHtml == '') return false;
    infosHtml = infosHtml.stripScripts();
    //infosHtml = infosHtml.escapeHTML();
	removePrintInfo();
	startOverlay();
	var marge = 10; // Marge fenetre
	var infosWidth = 300; // Largeur de la fenetre "infos", en Pix
    var timeOut = (parseInt(infosHtml.length) * 80);
	if (timeOut < 1600) timeOut = 2000;
	
    $('dyn_overlay').onclick = function() { removeFadePrintInfo(); return false; }
    if (infosHtml.indexOf('<br>') == 0 || infosHtml.indexOf('<br />') == 0) infosHtml += '<br>&nbsp;';
	var arr_Scroll = getPageScroll();		  
	var pageSize = getPageSize(); // (pageWidth,pageHeight,windowWidth,windowHeight) 
	offsetX = arr_Scroll[0] + ((pageSize[2] - infosWidth - (marge*2)) / 2);
	offsetY = arr_Scroll[1] + (pageSize[3] / 15)  + marge;
	if (offsetY < marge) offsetY = marge;
	var attrDivInfo = {};
    attrDivInfo['id'] = 'dyn_infos';
	attrDivInfo['style'] = 'display:inline;position:absolute;left:'+offsetX+'px;top:'+offsetY+'px;width:'+infosWidth+'px;z-index:900;margin:0;padding:'+marge+'px;background:#FFFFFF;border : 1px solid #E6E6E6';
	creatDiv('',attrDivInfo,'');	
    if (!$('dyn_infos')) alert('error create info');
	var attrDivPrint = {};
	attrDivPrint['id'] = 'infos_print';
	attrDivPrint['style'] = 'position:relative;left:0;top:0;margin:0;padding:'+marge+'px;border:1px dashed #CC0000;background:#F3F3F3;z-index:909;font-size : 12px;font-weight : bold; color : #CC0000;text-align:left;';
    creatDiv($('dyn_infos'),attrDivPrint,infosHtml);
    // $('dyn_infos').onclick = function() { removeFadePrintInfo(); return false; }
	myTimer = setTimeout("removeFadePrintInfo();", timeOut);
}

/* ------------------------- Modal dialogue box from Url ------------------------------ */

function startDivBox(w,h) {
	if (w < 1) w = 620;
	if (h < 1) h = 520;
    if (!$('dyn_lightbox')) {
		var objLightbox = document.createElement("div");
        objLightbox.setAttribute('id','dyn_lightbox');
		objLightbox.style.display = 'none';
		objLightbox.style.width = w+'px';
		objLightbox.style.height = h+'px';
		$('divNode').appendChild(objLightbox);
	}
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var offsetX = arrayPageScroll[0] + ((arrayPageSize[2] - w) / 2);
	var offsetY = arrayPageScroll[1] + (arrayPageSize[3] / 15);
    Element.setTop('dyn_lightbox', offsetY);
    Element.setLeft('dyn_lightbox', offsetX);
}

/*function resizeLightbox(w,h) {
	if (w < 1) w = 620;
	if (h < 1) h = 520;
    var wCur = Element.getWidth('dyn_lightbox');
    var hCur = Element.getHeight('dyn_lightbox');
	var xScale = (w / wCur) * 100;
	var yScale = (h / hCur) * 100;
	var wDiff = wCur - w;
	var hDiff = hCur - h;
    new Effect.Appear('dyn_lightbox', { duration: 0.3, queue: 'front' });
    if (wDiff != 0) new Effect.Scale('dyn_lightbox', xScale, {scaleY: false, duration: 0.3, scaleContent:false });
    if (hDiff != 0) new Effect.Scale('dyn_lightbox', yScale, {scaleX: false, duration: 0.3, scaleContent:false });
	//afterFinish: function() { 
}*/

function loadUrlInOverlay(url,w,h) {
	startOverlay();
    $('dyn_overlay').onclick = function() { removeOverlay(); return false; }
	startDivBox(w,h);
	if (!$('lightboxUrl')) {
		var objlightboxUrl = document.createElement("div");
		objlightboxUrl.setAttribute('id','lightboxUrl');
        $('dyn_lightbox').appendChild(objlightboxUrl);
		var objDivClose = document.createElement("div");
		objDivClose.setAttribute('align','right');
		objDivClose.setAttribute('style','clear:both;');
		var objClose = document.createElement("input");
		objClose.setAttribute('id','closeBt');
		objClose.setAttribute('name','closeBt');
		objClose.setAttribute('type','button');
		objClose.setAttribute('value','Fermer');
		objClose.onclick = function() { removeOverlay(); return false; }
		objDivClose.appendChild(objClose);
        $('dyn_lightbox').appendChild(objDivClose);
	}
	else $('lightboxUrl').update('');
    $('dyn_lightbox').show();
	// Ajax
	var specs = url.split('?');
	var contentUrl = specs[0]
	var parameters = specs[1];
	var laRequete = new Ajax.Updater(
		{success:'lightboxUrl'},
		contentUrl, {
			method: 'get',
			evalScripts: true,
			parameters: parameters,
			insertion: Insertion.Top
		}
	);
	return false; // Don't open href
}

/* ------------------------- linkShowHide ------------------------------ */
/* <a id="linkOption" href="javascript:void(0);" onclick="linkShowHide('linkOption','otpions','showOpt1','images/nav/flech_down.png','images/nav/flech_up.png');"  onmouseover="lshwOnMouseOver('otpions','showOpt1','images/nav/flech_down_over.png','images/nav/flech_up_over.png');"
onmouseout="lshwOnMouseOut('otpions','showOpt1','images/nav/flech_down.png','images/nav/flech_up.png');" title="Afficher/Masquer les options"><img src="../scripts/images/nav/flech_down.png" id="showOpt1" border="0"></a><div id="otpions" style="display:none;">TEST</div> */
var pos = new Array();
function linkShowHide(linkId,myElement,imgId,imgStart,imgEnd) {
	if (!pos[myElement]) pos[myElement] = 'open'; // Store init pos..
	ElinkId = $(linkId);
	EmyElement = $(myElement);
	EimgId = $(imgId);
	if (pos[myElement] == 'open') { 
		EmyElement.style.display = 'block';
		if (document.images[imgId]) document.images[imgId].src = imgEnd;
		else EimgId.src = imgEnd;
		pos[myElement] = 'close';
	}
	else {
		EmyElement.style.display = 'none';
		if (document.images[imgId]) document.images[imgId].src = imgStart;
		else EimgId.src = imgStart;
		pos[myElement] = 'open';
	}
}

function lshwOnMouseOver(myElement,imgId,imgStart_over,imgEnd_over) {
	if (!pos[myElement]) pos[myElement] = 'open'; // Store init pos..
	if (pos[myElement] == 'open') setImg(imgId,imgStart_over);
	else setImg(imgId,imgEnd_over);
}

function lshwOnMouseOut(myElement,imgId,imgStart,imgEnd) {
	if (pos[myElement] == 'open') setImg(imgId,imgStart);
	else setImg(imgId,imgEnd);
}

/* ------------------------- Hide input for OVERLAY ------------------------------ */
function showHideBoxes(visibility) { // visibility = hidden|visible
    var selects = $$('select');
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = visibility;
	}
    var objects = $$('object');
	for (i = 0; i != objects.length; i++) {
		objects[i].style.visibility = visibility;
	}
    var embeds = $$('embed');
	for (i = 0; i != embeds.length; i++) {
		embeds[i].style.visibility = visibility;
	}
    var iframes = $$('iframe');
	for (i = 0; i != iframes.length; i++) {
		iframes[i].style.visibility = visibility;
	}
}

/* ------------------------- PAUSE// Brute style ------------------------------ */
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime) return;
	}
}

/* ------------------------- VERIF Formulaire ---------------------------------- */
/*
	EXEMPLE :
		// Class pour les inputs avec erreur
		form input.input_error, form textarea.area_error, form select.select_error{
			border: 1px solid #FF0000;
		}
		// Class pour la div des messages d'erreur
		.divError{
			clear:both;
			display:block;
			font-size:11px;
			color:#00A7DC;
			font-weight:normal;
			padding:0 0 0 262px;
			background:#EBEBEB;
		}

		<scr + ipt language="javascript" type="text/javascript">
		var param_inscription = { mep: 'message', autoScroll: true, action: 'submit' };
       
		var champs_inscription = {
			civilite: 	{type:'',		alerte:'La civilité est obligatoire'},
			annif:	 	{type:'date',	alerte:'La date est obligatoire et doit etre valide'},
			ins_mel: 	{type:'mel',	alerte:'Le mel est obligatoire et doit etre valide'}, // Vas chercher si "ins_mel_2" existe et si identique
			adresse: 	{type:'',		alerte:'L\'adresse est obligatoire'},
			tel: 		{type:'tel_fr',	alerte:'Le télephone est obligatoire et doit etre valide'}
		};
		</scr + ipt>
		<a href="javascript:verif('frm_inscription',champs_inscription,param_inscription);" class="valider">Valider</a>

        // --------------- //
       
        // Extension de la function (avant submit)
        var checkCheck = function() {
            var myForm = document.frm_participer;
            var info = '';
            if (myForm.doc.value == '' && myForm.lien.value == '') {
                 info += '<br>- Veuillez choisir une photo ou un lien Youtube';
            }
            if (info != '') {
                printInfo(info);
                return false;
            }
            else myForm.submit();
        }
        var param_participer = { mep: 'alerte', autoScroll: true, action: checkCheck };

Par defaut...
 - mep (Mise en Page) = 'message' (apres input) | 'alerte' (utilise l'alerte "google like")
 - autoScroll = true : Si erreur scroll formulaire jusqu'a input | false : pas de scroll !
 - action = 'submit' | action a définir...
En mode "message", il est possible de créer et placer une DIV "infos alerte" pour chaque champs (Cf. cas particulier radio) : 
<div id="div_error_MONCHAMPS" style="display:none;"></div>  (remplacez "MONCHAMPS" par le nom du champs)
Types de contraintes : tel_fr, tel, chiffre, mel, url, date et "extensions" (Ex : jpg|jpeg|gif|png)
*/

function verif(frm_name,arr_control,arr_param) {

	// Array parametres (extensibles!...)
	var mep = arr_param['mep'] == 'alerte' ? 'alerte' : 'message';
	
	var autoScroll = arr_param['autoScroll'] == true ? true : false;
	var action = arr_param['action'] ? arr_param['action'] : 'submit';
	
	// Class error applicable aux champs
	var inputCss = {
		input:		'input_error',
		textarea:	'area_error',
		select:		'select_error'
	}
	
	// Class error applicable a la div affichant l'alerte
	var divErrorCss = 'divError';
	var oneError = false;
	var focusinput = false;
	var errorMessage = '';

	if (!document.forms[frm_name]) {
		alert('Vérifiez l\'ID du formulaire');
		return true;
	}

    var myForm = document.forms[frm_name];
	for (var property in arr_control) {
		var nom_champ = property;
		var type = arr_control[property]['type'];
		var alerte = arr_control[property]['alerte'].stripScripts();
		var reg_expression;
		var matched = false;
		var alerte_sup = ''; // Alerte spécifique pour 2nd email
        if (!myForm[nom_champ]) {
            alert('Champ HTML absent : "'+nom_champ+'"');
            return false;
        }
        var input_element = myForm[nom_champ];
		var input_element_p = "";
		var input_element_d = "";
		if (input_element[0] && input_element[0].nodeName.toLowerCase() != 'option') {// Si input type radio|check > array
			input_element_p = input_element[0]; // Premier element
			input_element_d = input_element[(input_element.length-1)]; // Dernier element
		}
		else {
			input_element_p = input_element;
			input_element_d = input_element;
		}
			
		var input_element_tag = "";
		input_element_tag = input_element_p.nodeName.toLowerCase(); // 'textarea' | 'input' | ...

		var input_type_area = '';
			switch(input_element_tag) {
            case 'textarea': input_type_area = 'text'; // Astuce > fait passer textarea pour input "text"
				case 'input':
              var input_type = (input_type_area ? input_type_area : input_element_p.getAttribute('type'));
				  input_type = input_type.toLowerCase();
				  switch(input_type) {
					  case 'password':
						if (input_element.value != '') matched = true;
						if (matched && myForm[nom_champ+'_2']) {
							if (myForm[nom_champ+'_2'].value != input_element.value) {
								alerte_sup = 'second_pass_erreur';
							} else alerte_sup = 'second_pass_ok';
						}
						break;
					  case 'text':
					  case 'hidden':
                          
							if (input_element.value == '') break;
							switch(type) {
								case 'tel_fr' : 	reg_expression = /^0([1-6]|8|9)([. -\/]?)\d{2}(\2\d{2}){3}$/; break;
								case 'tel' : 		reg_expression = /^[0-9]{10}$/; break;
								case 'chiffre' : 	reg_expression = /^[0-9]{1,}$/; break;
								case 'mel' : 		reg_expression = /^[A-Za-z0-9._-]+@[A-Za-z0-9.\-]{2,}[.][A-Za-z]{2,4}$/; break;
								case 'url' : 		reg_expression = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; break;
								case 'date':
								case 'dateuk': 		reg_expression = ''; break;
                            default :            reg_expression = /^(.+)[\r\n]|$/; break; // 0-9a-zA-Z&éèàùâêîûôùëïöüç'\-_" // Valide text non vide
							}
							if (type == 'date') { // Valide jj/mm/aa(aa)
								if (checkDate(input_element.value)) matched = true;
							}
							else if (type == 'dateuk') { // Valide jj/mm/aa(aa)
								if (checkDate(input_element.value, 'uk')) matched = true;
							}
							else if (input_element.value.match(reg_expression)) matched = true;
							else if (type == 'mel') alerte = 'Cet e-mail ne semble pas correct';

							// Si type "mel" check if "mel_2" exist et si identique
                        if (matched && type == 'mel' && myForm[nom_champ+'_2']) {
                            if (myForm[nom_champ+'_2'].value != myForm[nom_champ].value) alerte_sup = 'second_email_erreur';
								else alerte_sup = 'second_email_ok';
							}
							break;
					  case 'file':
							if (input_element.value!='') {
								var fichier = baseName(input_element.value);
								if (type != '') {
									exts = type.split('|');
									for (i=0; i<exts.length; i++) if (fichier.match(exts[i])) matched = true;
								} 
								else if (fichier) matched = true;
							}
							break;
					  case 'checkbox':
					  case 'radio':
						 input_element_tag = 'radio';
						 if (input_element.length) {
							 for(var j=0; j<input_element.length; j++) { if (input_element[j].checked) matched = true; }
						 }
						 else if (input_element.checked) matched = true;
					  break;
				  }
			  break;
			  case 'select':	  
				  if (input_element.options[input_element.selectedIndex].value != '') matched = true;
			  break;
			}
			if (!matched) {
				oneError = true;
				if (mep == 'message') {
					if ($('div_error_'+nom_champ)){
						$('div_error_'+nom_champ).update(alerte);
						$('div_error_'+nom_champ).addClassName('divError');
						$('div_error_'+nom_champ).show();
					}
					else {
						if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').show();
						else new Insertion.After(input_element_d,'<div class="'+divErrorCss+'" id="'+nom_champ+'_erreur">'+alerte+'</div>');
					}
				}
				else errorMessage += '<br>- '+alerte;

				if (input_type != 'checkbox' && input_type != 'radio') {
					Element.removeClassName(input_element_p, inputCss[input_element_tag]);
					Element.addClassName(input_element_p, inputCss[input_element_tag]);
				}
				if (!focusinput) { // Focus la première erreur
					focusinput = true;
					input_element_p.focus();
				}
			}
			else {
            if (input_type != 'checkbox' && input_type != 'radio') Element.removeClassName(input_element_p, inputCss[input_element_tag])
				if ($('div_error_'+nom_champ)) $('div_error_'+nom_champ).hide();
				else if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').hide();
			}
			if (alerte_sup != '') {
				switch(alerte_sup) {
					case 'second_pass_erreur' :
						oneError = true;
						alerte = js_msg_14;
						nom_champ = nom_champ+'_2';
						if (mep == 'message') {
						if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').show();
						else new Insertion.After($(nom_champ),'<div class="'+divErrorCss+'" id="'+nom_champ+'_erreur">'+alerte+'</div>');
							Element.removeClassName($(nom_champ), inputCss[input_element_tag]);
							Element.addClassName($(nom_champ), inputCss[input_element_tag]);
						}
                    else errorMessage += '<br>- '+alerte;
                   
						if (!focusinput) { // Focus la première erreur
							focusinput = true;
                        $(nom_champ).focus();
						}
					break;
					case 'second_pass_ok' :
						nom_champ = nom_champ+'_2'; // Envois alert input "mel" sur "mel_2"
                    if (mep == 'message') {
							Element.removeClassName($(nom_champ), inputCss[input_element_tag])
						if ($('div_error_'+nom_champ)) $('div_error_'+nom_champ).hide();
						else if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').hide();
				}
					break;
					case 'second_email_erreur' :
						oneError = true;
                    alerte = 'Les deux e-mails ne sont pas identiques';
						nom_champ = nom_champ+'_2'; // Envois alert input "mel" sur "mel_2"
                    if (mep == 'message') {
						if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').show();
						else new Insertion.After($(nom_champ),'<div class="'+divErrorCss+'" id="'+nom_champ+'_erreur">'+alerte+'</div>');
							Element.removeClassName($(nom_champ), inputCss[input_element_tag]);
							Element.addClassName($(nom_champ), inputCss[input_element_tag]);
						}
                    else errorMessage += '<br>- '+alerte;
                   
						if (!focusinput) { // Focus la première erreur
							focusinput = true;
                        $(nom_champ).focus();
						}
					break;
					case 'second_email_ok' :
						nom_champ = nom_champ+'_2'; // Envois alert input "mel" sur "mel_2"
                    if (mep == 'message') {
							Element.removeClassName($(nom_champ), inputCss[input_element_tag])
						if ($('div_error_'+nom_champ)) $('div_error_'+nom_champ).hide();
						else if ($(nom_champ+'_erreur')) $(nom_champ+'_erreur').hide();
				}
					break;
				}
			}
		}
	// SUBMIT

	if (frm_name == 'add_tip') {
		document.getElementById('list_of_city').style.display = 'none';
	}
	
	//////////////MAJ 20090528
	if (frm_name == 'add_tip') {
		if (myForm['ville'].value != '') {
			var url = "_ajax_get_soundex_city.php?ville="+myForm['ville'].value+"&";
			
			var params = "";
			new Ajax.Request(url, {
			  method: 'get',
			  asynchronous: false,
			  onComplete: function(transport) {
				if (transport.status == 200) {
					strResponseText = transport.responseText;
					if( strResponseText != "" ) {
						oneError = true;
						document.getElementById('list_of_city').innerHTML = strResponseText;
						document.getElementById('list_of_city').style.display = 'block';
					}
				}
			  }
			});
		}
	}
	//////////////////////////

	
	if (!oneError) {
        if (action == 'submit') myForm.submit();
        else if (typeof action == 'function') action();
        else if (typeof action == 'string') {
            var actionFunction = eval(action);
            actionFunction; // To test
        }
        else alert('Ajoutez des actions dans le JS ;)');
	}
	else {
        if (autoScroll) new Effect.ScrollTo(myForm, {offset: -16});
        if (autoScroll && mep != 'message') setTimeout("printInfo('"+strRep(errorMessage,'\'','\\\'')+"');",1000); // Wait scroll
        else if (mep != 'message') printInfo(strRep(errorMessage,'\'','\\\''));
	}
}


/* ------------------------- Frametek - Open Close Div ------------------------------ */
function openOrCloseDiv(div) {
	if( $(div).style.display != "none" ) {
		$(div).style.display = 'none';
		return 0;
	} else {
		$(div).style.display = 'inline';
		return 1;
	}
}

/* ------------------------- Frametek - Node Open/Close ------------------------------ */
function permuteNodeOpenCloseStatus(ent,div,img,cnx) {
	var sts = openOrCloseDiv(div);
	var img_id = $(img);
	var tmp = div.split( '_' );
	var nod_idt = tmp[2];
	if (sts == 1) img_id.src = './images/less.gif';
	else img_id.src = './images/more.gif';
	var paramUrl = "entity=" + ent + "&node=" + nod_idt + "&status=" + sts + "&needlogin=" + cnx;
	var laRequete = new Ajax.Request('store_node_status.php', {
		method: 'get',
		asynchronous:true,
		parameters: paramUrl
	});
}

/* ------------------------- Frametek - SetDivContent DEPRECIATED ------------------------------ */
function SetDivContent(layer,contenuHtml ) {
   $(layer).update(contenuHtml);
}

/* ------------------------- Parse XML ------------------------------ */
var xmlDoc = null;
var xmlArray = {};
function parseXml() {
	if (xmlDoc) {
		var nodes = $A(xmlDoc.getElementsByTagName('galerie'));
		nodes.each( function(e) {
			xmlArray.push({
				'id':			e.getElementsByTagName('id')[0].childNodes[0].nodeValue,
				'titre':		e.getElementsByTagName('titre')[0].childNodes[0].nodeValue,
				'legende':		e.getElementsByTagName('legende')[0].childNodes[0].nodeValue.stripTags(),
				'miniature':	e.getElementsByTagName('miniature')[0].childNodes[0].nodeValue
			});	
		});
	}
	else printInfo('Probl&egrave;me de lecture du fichier XML.');
	return xmlArray;
}

/* ------------------------- Get XML ------------------------------ */
function getXml(xmlPath) {
	if (document.implementation && document.implementation.createDocument) {
		xmlDoc = document.implementation.createDocument("", "", null);	
		xmlDoc.onload = parseXml;
	}
	else if (window.ActiveXObject) {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4) parseXml();
		};
	}
	else {
		printInfo('Votre navigateur ne supporte pas le XML.');
		return;
	}
	xmlDoc.load(xmlPath);
}

/* ------------------------- TINY MCE ------------------------------ */
function showResponse(originalRequest) {
    alert(originalRequest.responseText);
    //var reply = originalRequest.responseText.split("||my tinyMCE id||");
    //tinyMCE.execInstanceCommand(reply[0], "mceFocus");
    //tinyMCE.setContent(reply[1]);
}

function postForm(inst){
    var content = tinyMCE.getContent().replace(/\+/g, "&#43");
    content = content.replace(/\\/g, "&#92");
    content = escape(content);
    var elementId = inst.formTargetElementId;
    var url = 'index.php';
    var pars = elementId+'='+content;
    var myAjax = new Ajax.Request(url, {
            method: 'post',
            postBody: pars,
            onLoading: tinyMCE.setContent('<div style="text-align: center;padding-top:10px;">SAVING...</div>'),
            onComplete: showResponse
        }
    );
}
       
function callTinyMceInit(toolsbar_set) { //( $name, $value, toolsbar_set="Default", $max_length="16384", $width="500", $height="300", $arrayStyles, &$javascript )
       
    // Default CONFIG
    var toolbar = 'preview,separator,';
    var toolbar2;
    var toolbar3;
    var plugg = 'preview';
    var config_supp = {plugin_preview_width:'460' ,plugin_preview_height:'600',plugin_preview_pageurl:'../../plugins/preview/tiny_mce_preview.html', popups_css_add: 'css/admin.css', content_css:'css/admin.css'};
       
    // Switch TOOLBAR
    switch(toolsbar_set) { // Default, Basic, BasicImg, BasicStyle, BasicTab
        case 'Basic' :
            toolbar += 'bold,italic,separator,link,unlink,separator,bullist,numlist,indent,outdent,justifyleft,justifycenter,justifyright,justifyfull,separator,pasteword,cleanup,removeformat';
        break;
        case 'BasicTab' :
            toolbar += 'bold,italic,separator,link,unlink,separator,bullist,numlist,indent,outdent,justifyleft,justifycenter,justifyright,justifyfull,separator,pasteword,cleanup,removeformat,code';
            toolbar2 = 'tablecontrols';
            plugg += ',table';
            config_supp.push({table_cell_limit : 100, table_row_limit : 6, table_col_limit : 6, theme_advanced_toolbar_location : 'top', theme_advanced_statusbar_location : 'bottom'});
        break;
        case 'BasicImg' :
            toolbar += 'image,separator,bold,italic,separator,link,unlink,separator,bullist,numlist,indent,outdent,justifyleft,justifycenter,justifyright,justifyfull,separator,pasteword,cleanup,removeformat,code';
        break;
        case 'BasicStyle' :
            toolbar += 'bold,italic,separator,styleselect,separator,link,unlink,separator,bullist,numlist,indent,outdent,justifyleft,justifycenter,justifyright,justifyfull,separator,pasteword,cleanup,removeformat,code';
            config_supp.push({ theme_advanced_styles : '$arrayStyles', theme_advanced_toolbar_location : 'top', theme_advanced_statusbar_location : 'bottom'});
        break;
        case 'Default' :
        default :
            toolbar += ',separator,bold,italic,separator,link,unlink,separator,separator,pasteword,cleanup,removeformat';
        break;
    }
   
    var config = {
        mode : 'exact',
        theme : 'advanced',
        elements : '',
        language : 'fr',
        plugins : plugg,
        theme_advanced_buttons1 : toolbar,
        theme_advanced_buttons2 : toolbar2,
        theme_advanced_buttons3 : '',
        button_tile_map : true,
        auto_reset_designmode : true,
        dialog_type : 'modal',
        cleanup_on_startup : true,
        cleanup: true,
        object_resizing : false,
        //execcommand_callback : "myCustomExecCommandHandler",
        //hide_selects_on_submit : true,
        //strict_loading_mode : false,
        //theme_advanced_text_colors : "FF00FF,FFFF00,000000"
        //theme_advanced_fonts : "Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace"
        //theme_advanced_background_colors : "FF00FF,FFFF00,000000"
        debug : false
    }
    config.push(config_supp);         
    tinyMCE.init(config);
}

function loadTinyMce(element) {
   
    // DOC : http://tinymce.moxiecode.com/tinymce/docs/tinymce_api/ ||| http://wiki.moxiecode.com/index.php/
    // TEMPLATE : http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/template
    // BOUTTONS : http://wiki.moxiecode.com/index.php/TinyMCE:Control_reference
    // AJAX : http://wiki.moxiecode.com/index.php/TinyMCE:Turn_tinyMCE_into_an_Ajax_editor || http://www.crossedconnections.org/w/?p=88
    // EX. : <div id="testArera"></div><a href="javascript:void(0);" onClick="loadTinyMce('testArera');">TinyMce ?</a>
   
    if (!$('area_'+element)) {
        var objForm = document.createElement("form");
        objForm.setAttribute('id','form_'+element);
        objForm.setAttribute('name','form_'+element);
        objForm.setAttribute('action','');
        objForm.setAttribute('method','POST');
        objForm.setAttribute('enctype','multipart/form-data');
        $(element).appendChild(objForm);
       
        var objArea = document.createElement("div");
        objArea.setAttribute('id','area_'+element);
        objArea.setAttribute('name','area_'+element);
        objArea.setAttribute('width','260px');
        objArea.setAttribute('height','110px');
        // tabindex="1"
        objForm.appendChild(objArea);
    }
    else {
        tinyMCE.idCounter = 0;
        tinyMCE.removeMCEControl('area_'+element,false, 'area_'+element);
    }

    tinyMCE.execCommand("mceAddControl", false, 'area_'+element);
    //var instance1 = tinyMCE.getInstanceById(idBlocs + '_bloc_texte_1_' + lngList[i]);
   
    return false;
}

// -------------------- PROMPT YOUTUBE -------------------- //
// <object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/HxNiOK_-hrs"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/HxNiOK_-hrs" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>
// http://www.youtube.com/watch?v=8mnt5_BI1qY
function promptVideo(myInput) {
    var saisie = prompt('Coller ici le lien de votre vidéo sur YouTube :', '');
	if (!saisie) {
		alert('Désolé nous n\'avons pas réussi à identifier un lien Youtube ni à en extraire l\'ID');
		$(myInput).value = '';
		$(myInput).blur();
		return;
	}
	var reg = /youtube\.com\/v\/([^\"]+)\">/; // <obj..
    var test = reg.exec(saisie);
    if (test && test[1] != '') $(myInput).value = test[1];
    else {
		var reg = /watch\?v=(.*)$/; // <href
        var test = reg.exec(saisie);
        if (test && test[1] != '') $(myInput).value = test[1];
        else {
            alert('Désolé nous n\'avons pas réussi à identifier un lien Youtube ni à en extraire l\'ID');
            $(myInput).value = '';
			promptVideo(myInput); // Re ?
		}
	}
}
// -------------------- FIND ID IN CLASS -------------------- //
function findIdInClass(el) {
    var regexp = /id_([0-9a-z_-]+)/;
    var mymatch = regexp.exec(el.className);
    return mymatch[1];
}
// -------------------- FIND PARAM IN CLASS -------------------- //
function findParamInClass(param, el) {
    var regexp = new RegExp(param + '_([A-Za-z0-9/:?&\-\._]+)');
    var mymatch = regexp.exec(el.className);
    if(mymatch)
    {
        return mymatch[1];
    }
    return false;
}
// -------------------- Format Time -------------------- //
function formatTime(seconds) {
    seconds = parseInt(seconds);
    hours = 0;
    minutes = 0;
    var str = '';
    if ((seconds / 3600) >= 1)     {
        hours = Math.floor((seconds / 3600));
        seconds = seconds - (hours * 3600);
        str += hours + 'h ';
    }
    if ((seconds / 60) >=1)     {
        minutes = Math.floor((seconds / 60));
        seconds = seconds - (minutes * 60);
        str += minutes + 'm ';
    }
    if (seconds > 0)     {
        if (seconds < 10) str += '0' + seconds + 's';
        else str += seconds + 's';
    }
    return str;
        }
// -------------------- SET SOURCE -------------------- //
function setSrc(element, newSrc) {
    setTimeout(function(){$(element).src = newSrc; }, 100);
    }

// -------------------- AJAX VALID INPUT -------------------- //
var isWorking = false;
var ajaxReq;
function ajaxCheck(input,valeur,divInfo) {
	//if (!isWorking) {
		ajaxReq = new Ajax.Request('_ajax_valid_input.php', {
			method: 'get',
			parameters: 'input='+input+'&valeur='+escapeURI(valeur),
			onSuccess: function(requete) {
				isWorking = false;
				$(divInfo).update(requete.responseText);
			}
		});
		isWorking = true;
	//}
}
