/**
 * 
 * 
 * NCore default script
 * 	- Configuration
 * 	- Patchs jQuery
 * 	- Fonctions perso
 * 
 */
 
var	CONF = {
	iface: '/js/library/interface/'
};


function	dc(n){return(document.createElement(n))}
function	dt(t){return(document.createTextNode(t))}

if(document.execCommand && document.all && !window.opera) try{document.execCommand("BackgroundImageCache",false,true);}catch(e){}


/** ajoute un texte en grisé quand le champ n'est pas rempli dans
 *	la zone login/pass et newsletter de la toolbar
 */
jQuery(function() {
	jQuery('.TODO,.todo').click(function() {
		jQuery.alert(this.title? this.title: 'Fonctionnalité non implémentée');
		return (false);
	});
	
	jQuery('input.item[@name=login]').focus(function() {
		if (this.value == 'Email')
			jQuery(this).val('').removeClass('helper');
	})
	.blur(function(){
		if (this.value == '')
			jQuery(this).addClass('helper').val('Email');
	}).trigger('blur');
	
	jQuery('input.item[@name=password]').focus(function() {
		if (this.value == '********')
			jQuery(this).val('').removeClass('helper');
	})
	.blur(function(){
		if (this.value == '')
			jQuery(this).addClass('helper').val('********');
	}).trigger('blur');
	
	jQuery('input.item[@name=newsletter]').focus(function() {
		if (this.value == 'Adresse mail')
			jQuery(this).val('').removeClass('helper');
	})
	.blur(function(){
		if (this.value == '')
			jQuery(this).addClass('helper').val('Adresse mail');
	}).trigger('blur');
	
	jQuery('input.item[@name=rechercher]').focus(function() {
		if (this.value == 'Rechercher')
			jQuery(this).val('').removeClass('helper');
	})
	.blur(function(){
		if (this.value == '')
			jQuery(this).addClass('helper').val('Rechercher');
	}).trigger('blur');
	
	jQuery('#go_nl').click(function() {
		jQuery.alert('L\'inscription à la Newsletter n\'est pas disponible');
		return (false);
	});
	
	/** lien dans nouvelle fenetre quand href fini par PDF */
	jQuery('a[@href$=.pdf],blank').each(function(){this.target='_blank'});
});



function	array_search(arry, value) {
	for (var i=0;i<arry.length; i++)
		if (arry[i]===value)
			return (i);
	return (-1);
}
function	MakeInput(obj){
	var input=false;
	if(jQuery.browser.msie){
		var t='';
		for(i in obj)
			if(typeof(obj[i])=='boolean')t+=' '+i+'="'+(obj[i]? 'true': 'false')+'"';
			else if(typeof(obj[i])!='object'&&typeof(obj[i])!='function')
				try{t+=' '+i+'="'+obj[i].replace('\\', '\\\\').replace('"', '\\"')+'"';}catch(e){t+=' '+i+'="undefined"';}
		try {
			input=dc('<input'+t+'>');
			for(i in obj)if(typeof(obj[i])=='object'||typeof(obj[i])=='function')input[i]=obj[i];
		}
		catch(e) {input=false;}
	}
	if (!input) {
		var input=dc('input');
		for(i in obj)
			if(typeof(obj[i])=='object' && typeof(input[i])=='object')
				for(j in obj[i])input[i][j]=obj[i][j];
			else
				input[i]=obj[i];
	}
	with(input.style){borderWidth='1px';fontSize='11px';fontFamily='Verdana';};
	return(input);
}
//jQuery.ajaxUseScriptTag = true;


/******************************************************************************************************************/
/** jQuery AJAX patch
 * 		- throw ne tombe pas dans 'error' quand c'est pas la requete qui foire mais le traitement dans 'success'
 * 		- requete ajax pour récupérer un script ne passe pas par une XHR mais par une balise <script>
 */
jQuery.extend({ajax: function( s ) {
	// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
	s = jQuery.extend({}, jQuery.ajaxSettings, s);

	// if data available
	if ( s.data ) {
		// convert data if not already a string
		if (s.processData && typeof s.data != "string")
			s.data = jQuery.param(s.data);
		// append data to url for get requests
		if( s.type.toLowerCase() == "get" ) {
			// "?" + data or "&" + data (in case there are already params)
			s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
			// IE likes to send both get and post data, prevent this
			s.data = null;
		}
	}

	// Watch for a new set of requests
	if ( s.global && ! jQuery.active++ )
		jQuery.event.trigger( "ajaxStart" );

	var requestDone = false;

	if (jQuery.ajaxUseScriptTag && s.type.toLowerCase() == 'get' && s.dataType.toLowerCase() == 'script' ) {
		// create a script tag to replace the XHR request
		var tag = document.createElement('script');
		s.type='text/javascript';
		// set its url to the url request
		tag.src = s.url;
		tag._request = s;
		tag.onload = s.onreadystatechange = function() {
			if (typeof(this.readyState)=='string' && this.readyState!='loaded')return ;
			if ( this._request.success )
				this._request.success( null, status );
			this.parentNode.removeChild(this);
		};
		tag.onerror = function() {
			
			jQuery.handleError(this._request, this, null);
			this.parentNode.removeChild(this);
		};
		document.getElementsByTagName('head')[0].appendChild(tag);
		return (tag);
	}

	// Create the request object; Microsoft failed to properly
	// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
	var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

	// Open the socket
	xml.open(s.type, s.url, s.async);

	// Set the correct header, if data is being sent
	if ( s.data )
		xml.setRequestHeader("Content-Type", s.contentType);

	// Set the If-Modified-Since header, if ifModified mode.
	if ( s.ifModified )
		xml.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );

	// Set header so the called script knows that it's an XMLHttpRequest
	xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");

	// Allow custom headers/mimetypes
	if( s.beforeSend )
		s.beforeSend(xml);
		
	if ( s.global )
	    jQuery.event.trigger("ajaxSend", [xml, s]);

	// Wait for a response to come back
	var onreadystatechange = function(isTimeout){
		// The transfer is complete and the data is available, or the request timed out
		if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
			requestDone = true;
			
			// clear poll interval
			if (ival) {
				clearInterval(ival);
				ival = null;
			}
			
			var status;
//			try {
				status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
					s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
				// Make sure that the request was successful or notmodified
				if ( status != "error" ) {
					// Cache Last-Modified header, if ifModified mode.
					var modRes;
					try {
						modRes = xml.getResponseHeader("Last-Modified");
					} catch(e) {} // swallow exception thrown by FF if header is not available

					if ( s.ifModified && modRes )
						jQuery.lastModified[s.url] = modRes;

					// process the data (runs the xml through httpData regardless of callback)
					try {
						
						var data = jQuery.httpData( xml, s.dataType );

					} catch(e) {
//						alert('exception: '+xml.responseText);
						status = "error";
						jQuery.handleError(s, xml, status, e);
						var data = null;
					}

					if (data !== null) {
						// If a local callback was specified, fire it and pass it the data
						if ( s.success )
							s.success( data, status );
	
						// Fire the global callback
						if( s.global )
							jQuery.event.trigger( "ajaxSuccess", [xml, s] );
					}
							
				} else
					jQuery.handleError(s, xml, status);
//			} catch(e) {
//				status = "error";
//				jQuery.handleError(s, xml, status, e);
//			}

			// The request was completed
			if( s.global )
				jQuery.event.trigger( "ajaxComplete", [xml, s] );

			// Handle the global AJAX counter
			if ( s.global && ! --jQuery.active )
				jQuery.event.trigger( "ajaxStop" );

			// Process result
			if ( s.complete )
				s.complete(xml, status);

			// Stop memory leaks
			if(s.async)
				xml = null;
		}
	};
	
	// don't attach the handler to the request, just poll it instead
	var ival = setInterval(onreadystatechange, 13); 

	// Timeout checker
	if ( s.timeout > 0 )
		setTimeout(function(){
			// Check to see if the request is still happening
			if ( xml ) {
				// Cancel the request
				xml.abort();

				if( !requestDone )
					onreadystatechange( "timeout" );
			}
		}, s.timeout);
		
	// Send the data
	try {
		xml.send(s.data);
	} catch(e) {
		jQuery.handleError(s, xml, null, e);
	}
	
	// firefox 1.5 doesn't fire statechange for sync requests
	if ( !s.async )
		onreadystatechange();
	
	// return XMLHttpRequest to allow aborting the request etc.
	return xml;
}});

/******************************************************************************************************************/
/** jQuery COOKIE extension
 */

jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toGMTString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toGMTString(); // use expires attribute, max-age is not supported by IE
		}
		var path = (options.path ? ('; path=' + options.path) : ('; path=' + jQuery.defaultCookiePath));
		var domain = options.domain ? '; domain=' + options.domain : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};
jQuery.defaultCookiePath = '/';


/******************************************************************************************************************/
/** jQuery/interface patch (bug sur les Array) */
delete (Array.prototype.indexOf);
jQuery.prototype.find = function(t) {
	var data = jQuery.map(this, function(a){ return jQuery.find(t,a); });
	return this.pushStack( /[^+>] [^+>]/.test( t ) || array_search(t, '..') > -1 ? jQuery.unique( data ) : data );
};


/******************************************************************************************************************/
/**	Number formatting function (same as in PHP) */
function number_format(n, d, dp, tsep) {
var e='';var nstr=''+n;var ei=nstr.indexOf("e");if(ei>-1){e=nstr.substr(ei);n=parseFloat(nstr.substr(0, ei));}if(d!=null){var temp=Math.pow(10,d);
n=Math.round(n*temp)/temp;}var sign=n<0?'-':'';var ig=(n>0?Math.floor(n):Math.abs(Math.ceil(n))).toString();var fc=(''+n).substr(ig.length+sign.length);
dp=dp!=null?dp:'.';fc=d!=null&&d>0||fc.length>1?(dp+fc.substr(1)):"";if(d!=null&&d>0){for(var i=fc.length-1,z=d;i<z;++i)fc+='0';}
tsep=(tsep!=dp||fc.length==0)?tsep:null;if(tsep!=null&&tsep!=""){for(var i=ig.length-3;i>0;i-=3)ig=ig.substr(0,i)+tsep+ig.substr(i);}
return sign+ig+fc+e;}


/******************************************************************************************************************/
/**	Equivalent PHP print_r();
 *	fonction pour printer récursivement un objet
 */
function	str_repeat(input, mult) {
	var t = '';
	for (var i=0; i<mult; i++)
		t += input;
	return (t);
}
function	print_r(obj, level, done) {
	if (typeof(level) != 'number')
		level = 0;
	if (typeof(done) != 'object')
		done = [];
//	else
//		window.console.info('done: '+done.length);
	
	var t = '';
	if (typeof(obj)=='object') {
		t += 'object';
		if (array_search(done, obj) === -1) {
			done.push(obj);
			t += "\n"+(level? str_repeat('    ', level+1):'')+"(\n";
			for (var i in obj)
				t += str_repeat('    ', level+2)+'['+i+'] => '+print_r(obj[i], level+1, done)+"\n";
			t += (level? str_repeat('    ', level+1):'')+")";
		}
//		else
//			t += "\n*RECURSION*";
	}
	else
		t += obj;
	if (!level)
		alert(t);
	else
		return (t);
}
function	empty(obj) {
	for (var i in obj)
		return (false);
	return (true);
}
/******************************************************************************************************************/
/**	Definition of the object's toString method (automatically called when printing object) */
//function toString () {
//	var res = '';
//	for ( var i in this ) {
//		res += i + ' : ' + this[i] + ', \n';
//	}
//	return res;
//}
//Object.prototype.toString = toString;

/******************************************************************************************************************/
function	print_error(request, xml) {
	
	return (dt(xml.responseText));
}
jQuery(document).ajaxError(function(request, xml){
//	print_r(data);
	var div = dc('div');
	//div.className = 'debugzone'; // Class de base modifier pour la popup d'erreur
	div.className = 'data';
	div.innerHTML = 'Une erreur est survenue lors de la communication avec le serveur.<br />' +
		'Veuillez nous excuser pour le désagrément occasioné.<br />';
	
	
	if (typeof(_debug) != 'undefined') {
		div.appendChild(dc('hr'));

		var debug = dc('div');
		debug.style.overflow = 'auto';
		debug.style.height = '150px';
		debug.style.border = 'inset 2px #000';
		var text = debug.appendChild(dc('div'));
		text.className = 'TEXT';
		var html = debug.appendChild(dc('div'));
		html.className = 'HTML';
		
		var pre = text.appendChild(dc('pre'));
		pre.appendChild(dt(xml.responseText));
		text.style.display = 'none';
		html.innerHTML = xml.responseText;
		
		var buttons = div.appendChild(dc('div'));
		buttons.style.textAlign = 'right';
		buttons.appendChild(MakeInput({type: 'button', value:'TEXT', onclick: function() {
			if (this.value == 'HTML') {
				this.value = 'TEXT';
	//			alert(jQuery(this).parents('.debugzone')[0]);
				jQuery('.TEXT', jQuery(this).parents('.debugzone')).hide();
				jQuery('.HTML', jQuery(this).parents('.debugzone')).show();
			}
			else {
				this.value = 'HTML';
				jQuery('.HTML', jQuery(this).parents('.debugzone')).hide();
				jQuery('.TEXT', jQuery(this).parents('.debugzone')).show();
			}
		}}));
		div.appendChild(debug);
	}
//		 +
//		(typeof(_debug)!='undefined'? '<h'+'r />'+print_error(request, xml): '')
//	'</div>';
	jQuery(div).alert();
//	if (window.console && window.console.error) {
//		console.error(arguments);
//	}
});

try {
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}
}catch(e) {}
