﻿/*

	STRING FUNCTIONS

*/
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,''); };
String.prototype.replaceAll = function( s1, s2 ) {var o=new RegExp(s1,"gi"); return this.replace(o,s2); }


/*

	JQUERY FUNCTIONS

*/


// JQuery Patchs... ça commence ;)
jQuery.fn.center = function () {
	this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
	this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
	return this;
}
jQuery.fn.centerH = function () {
	this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
	return this;
}
jQuery.fn.centerV = function () {
	this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
	return this;
}

/*
	Fonction qui place un div exactement par dessus un autre
*/
jQuery.fn.drawOver = function ( div ) {
	$(this).width( $(div).innerWidth() ).height( $(div).innerHeight());
	$(this).css( { left:$(div).offset().left, top:$(div).offset().top } )
	$(this).css( 'z-index', 10000 ).show( );
	return this;
}
jQuery.fn.drawAllScreen = function ( ) {
	$(this).width( $(document).width() );
	$(this).height( $(document).height() );
	$(this).css( { left:0, top:0 } )
	$(this).css( 'z-index', 10000 ).show( );
	return this;
}
/*
	Fonction qui place un div exactement en plein milieu
*/
jQuery.fn.drawCenter = function ( div ) {
	var destW = $(div).width();	
	var destH = $(div).height();  
	var y = destH/2-$(this).height()/2 + $(div).offset().top;
	var x = destW/2-$(this).width()/2 + $(div).offset().left;		
	$(this).css({'left':x,'top':y});
	return this;
}

jQuery.fn.AMCMS_attachEvents = function () {
	$(this).find("form").each( function(i,obj){
		AMCMS_AttachFormHandlers( obj );
	});
	return this;
}


jQuery.fn.swapWith = function(to) {
    return this.each(function() {
		var node1 = document.getElementById($(to).attr('id'));
		var node2 = document.getElementById($(this).attr('id'));
		
		var next1 = node1.nextSibling;
		var parent1 = node1.parentNode;
		node2.parentNode.insertBefore( node1, node2 );
		
		if ( next1 )		parent1.insertBefore( node2, next1 );
		else if ( parent1 )	parent1.appendChild( node2 );
    });
};


/*
	Fonction qui execute la function JS nommée JsInit_System<nompage>()
	
	1) Celle ci contient tout le JS de la variable globale this.Context.Items[ "JsInit_System" ]
	2) Chaque composant peut ajouter un bout de script pour son initialisation dedans par la fonction AMCMSWebControl.AddToJSInit(text)  
	3) Dans MyPage.cs, celui crée la fonction JsInit_System<nompage>()
*/
jQuery.fn.AMCMS_launchJSGeneratedByControls = function ( o ) {
	
	var aUrls = $(this).attr('url').split("/");
	var sFileName = aUrls[aUrls.length-1];
	sFileName = sFileName.replace(/\./gi, '_');
	sFileName = sFileName.split("?")[0];
	eval( "JsInit_System" + sFileName + "()");
	return this;
}



jQuery.fn.loadControls = function( url, callback ) {

	function newCallBack( o, state, xml_req )
	{
		// Attach our events...
		$(this).AMCMS_attachEvents( );
		$(this).AMCMS_launchJSGeneratedByControls( o, state, xml_req );
		callback( $(this) );
	}
	$(this).attr('url',url);
	$(this).load( url, newCallBack );
}



jQuery.fn.inputValue = function(options)
{
	var settings = jQuery.extend({allow:'', disallow:''}, options);
	return jQuery(this).keypress
		(
			function (e)
				{					
					if (!e.charCode)
						var code = String.fromCharCode(e.which);
					else
						var code = String.fromCharCode(e.charCode);							
					
					var keyCode = (e.keyCode ? e.keyCode : e.which);
					if ( keyCode < 46 )
					{
						if (e.ctrlKey && code=='v')
							e.preventDefault();	
						// Do Nothing....
					}
					else
					{
						if(code && (typeof(e.keyCode) == 'undefined' || (e.keyCode != 8 && e.keyCode != 46)))
						{										
							if(settings.allow.length != 0 && settings.disallow.length != 0)
							{
								if(settings.allow.indexOf(code) == -1)
								{
									e.preventDefault();
								}else if(settings.disallow.indexOf(code) != -1)
								{
									e.preventDefault();
								}
							}else if(settings.allow.length != 0)
							{
								if(settings.allow.indexOf(code) == -1)
								{
									e.preventDefault();
								}						
							}else if(settings.disallow.length != 0)
							{
								if(settings.disallow.indexOf(code) != -1)
								{
									e.preventDefault();
								}
							}						
						}
						if (e.ctrlKey && code=='v')
							e.preventDefault();	
					}
					$(this).bind('contextmenu',function () {return false});					
				}				
		);		
		
};
/**
*	input fields will accept valid email address
*/
jQuery.fn.inputEmail = function()
{
		return this.each (function()
			{
				jQuery(this).inputValue({allow:'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@.0123456789'});
			}
		);		
};
/**
*	input fields will accept digits only
*/
jQuery.fn.inputInteger = function()
{
		return this.each (function()
			{
				jQuery(this).inputValue({allow:'9876543210'});
			}
		);	
};
/**
*	input fields will accept digits and dots.
*/
jQuery.fn.inputFloat = function()
{
		return this.each (function()
			{
				jQuery(this).inputValue({allow:'0123456789.'});
			}
		);		
};
/**
*	input fields will accept all letters (case insensitive)
*/
jQuery.fn.inputLetter = function()
{
		return this.each (function()
			{
				jQuery(this).inputValue({allow:'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'});
			}
		);		
};
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            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.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        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 = "";
        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;
    }
};

/*
	On prend un objet { toto=1,toto2=2} 
	et on renovie toto=1&toto=2
*/
jQuery.objetToQuery = function( o )
{
	var s = ""
	for (var key in o) {
		if( typeof key == "string" );
		{
			if ( s != '' ) s+='&';
			s += key + "=" + eval('o.'+key)
		}
	}
	return s;
}

jQuery.getStyles = function( o )
{
	var s = ""
	for (var key in o) {
		if( typeof key == "string" );
		{
			var cssvalue = $(o).css(key);
			if ( cssvalue )	s += key + "=" + cssvalue +";"
		}
	}
	return s;
}


/*
	<form>.serialize( ) permet de renvoyer la querystring de tous ses elements
	// FORMAT : [ { 'fieldname1' : 'value1', 'fieldname2' : 'value2' }
*/
jQuery.fn.serialize = function( format ) 
{
	var sQuery = "";
	// now data is a hash. insert each parameter into the form
	$( 'input,select,textarea', this ).each(function() {
		var p = this.name;
		var v = [];
		if ( typeof this.name == "undefined" )	p = this.id;

		if ( (''+$(this).attr('serialize')).toUpperCase() == "FALSE" ) return;

		var disable=false;
		// Additional parameter overwrite
		switch(this.type || this.tagName.toLowerCase()) {
			case "radio":							if ( this.checked == true )	v[v.length] = this.value;
													else disable=true;	// Si jamais la case n'est pas cochée, alors le champ n'est meme pas pris en compte
													break;
			case "checkbox":						if ( this.checked == true )	v[v.length] = "1";
													else						v[v.length] = "0";
													break;
			case "select-multiple" || "select":		for( i=0;i<this.options.length;i++) {
														this.options[i].selected=false;
														for(var j=0;j<v.length;j++) {
															this.options[i].selected|=(this.options[i].value!='' && this.options[i].value==v[j]);
														}
													}
													break;
			case "button":
			case "submit":							break;
			default:								v[v.length] = this.value;
		}
		if ( ! disable ) {
			if ( sQuery != "" ) sQuery += "&";
			sQuery += p + "="
			sQuery += v.join(",");
		}
	 });
	if ( sQuery == "" ) return "{}";
	return '{ '+sQuery.replace(/=/gi,':\'').replace(/&/gi,'\',\n') + '\'}';		// format [ { fieldname1 : 'value1', fieldname2 : 'value2' }
}

jQuery.fn.deserialize = function(d,config) {
	if (!d.length) return this;
	d = eval( "data=" + d );
	var data= d;
	me = this;

	if (d === undefined) return me;

	config = $.extend( { isPHPnaming	: false, overwrite	: true}, config );
	
	// check if data is an array, and convert to hash, converting multiple entries of 
	// same name to an array
	if (d.constructor == Array)	{
		data={};
		for(var i=0; i<d.length; i++) {
			if (typeof data[d[i].name] != 'undefined') {
				if (data[d[i].name].constructor!= Array) {
					data[d[i].name]=[data[d[i].name],d[i].value];
				} else {
					data[d[i].name].push(d[i].value);
				}
			} else {
				data[d[i].name]=d[i].value;
			}
		}
	}

	// now data is a hash. insert each parameter into the form
	$( 'input,select,textarea', me ).each(function() {
		var p = this.name;
		var v = [];
		if ( typeof this.name == "undefined" )	p = this.id;
		
		if ( (''+$(this).attr('serialize')).toUpperCase() == "FALSE" ) return;

		// handle wierd PHP names if required
		if (config.isPHPnaming) {
			p=p.replace(/\[\]$/,'');
		}
		if(p && data[p] != undefined) {
			v = data[p].constructor == Array ? data[p] : [data[p]];
		}
		// Additional parameter overwrite
		if (config.overwrite === true || data[p]) {
			switch(this.type || this.tagName.toLowerCase()) {
				case "radio":
				case "checkbox":
					this.checked=false;
					for(var i=0;i<v.length;i++)	this.checked|=(this.value!='' && v[i]==this.value);
					break;
				case "select-multiple" || "select":
					for( i=0;i<this.options.length;i++) {
						this.options[i].selected=false;
						for(var j=0;j<v.length;j++)	this.options[i].selected|=(this.options[i].value!='' && this.options[i].value==v[j]);
					}
					break;
				case "button":
				case "submit":
					this.value=v.length>0?v.join(','):this.value;
					break;
				default:
					this.value=v.join(',');
			}
		}
	 });
	return me;
};

/*
	Permet de faire une alerte contextuelle dans une chaine Jquery
	Ex:
		Si this.alert('.html()') --> Fait une alert du résultat de this.html()
		Si this.alert('html()') --> Fait une alert du text html()

*/
jQuery.fn.alert = function( test ) {
	this.each( function() {
		if (test.length && test.substring(0,1) == '.')		alert( eval("this"+test) );
		else												alert( test );
		return true;
	});
	return this;
}

jQuery.fn.onComplete = function( callback ) {
	$(this).each( function() {
		if ( this.complete ) callback.call( this );
		else {
			$(this).load( callback );
		}
	});
	return this;
}



jQuery.fn.patchPNG = function( callback, datas ) {

	$(this).onComplete( function( ) {
	
		if ( $.browser.msie && $.browser.version < 7 )
		{
			for ( var i = 0 ; i < $(this).length ; i++ )
			{
				var o = $(this)[i];
				if ( $(o).attr('src').toLowerCase().indexOf( '.png' ) > 0 ) {
					var w = $(o).width();
					var h = $(o).height();
					var sStyles = jQuery.getStyles($(o)) +";width:"+w+"px;height:"+h+"px;display:inline;"
					var span = document.createElement("SPAN")
					if (o.className!='')	span.className = o.className
					$(span).attr('style',sStyles+"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + $(o).attr('src') + "\', sizingMethod='scale');\"" )
					$(span).insertAfter($(o))
					$(o).remove( );
					
					$(this)[i]=span;
				}
			}
		}
		if ( typeof callback != "undefined" ) callback.call( this, datas );
		return this;
	})
	
	
	return this;
}

				
					

