﻿
String.prototype.count = function( chaine ) {
	return this.split( chaine ).length - 1;
}  

// 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 ) {

	var iZindex = 10000;
	if( $(div).css( "position" ) == "absolute" )
	{
		iZindex = parseInt( $(div).css( "z-index" ) ) + 10000;
	}
	
	$(this).width( $(div).innerWidth() ).height( $(div).innerHeight());
	$(this).css( { left:$(div).offset().left, top:$(div).offset().top } )
	$(this).css( 'z-index', iZindex ).show( );
	return this;
}
/*
	Fonction qui place un div exactement en plein milieu
*/
jQuery.fn.drawCenter = function ( div ) {
	//alert( "drawCenter" );
	var destW = $(div).width();
	var destH = $(div).height(); 
	var destTop = $(div).offset().top;
	var destLeft = $(div).offset().left;
	
	if( destH > $( window ).height() )
	{
		destH = $( window ).height();
		//destTop = $( div ).scrollTop();
	}
	if( destW > $( window ).width() )
	{
		destW = $( window ).width();
		destLeft = $( div ).scrollLeft();
	}
	
	var y = destH/2-$( this ).height()/2 + destTop;
	var x = destW/2-$( this ).width()/2 + destLeft;
	
	// force limits
	if ( x < 0 ) x = 0;
	if ( y < 0 ) y = 0;
	
	$(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 ) {
	var _node = $(this);
	
	var newCallBack = function( html, state, xml_req )
	{
		$(_node).html( html );
			
		// Attach our events...
		$(this).AMCMS_attachEvents( );
		$(this).AMCMS_launchJSGeneratedByControls( html, state, xml_req );
		callback( $(this) );
	}
	$(this).attr('url',url);
	
	//$(this).load( url, newCallBack );
	$.ajax({
		type: "GET",
		url: url,
		dataType: "html",
		error:	function(xhr,err,e){ Error_Report( "Erreur lors de la recuperation des valeurs du &lt;select&gt;", xhr.responseText ); }, 
		success: newCallBack
	});	
	
}



jQuery.fn.inputValue = function(options)
{
	var settings = jQuery.extend({allow:'', disallow:'', numDecimal: 1000000 }, 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);
					var keyCode = (e.which) ? e.which : e.keyCode

					// On laisse passer les flèches / debut / fin /... 
					if ( ( keyCode < 40 || keyCode == 46 ) && code!='.' && code!='\'' && code!='"' && code!='$' && code!='&' && code!='!' && code!='%' && code != ' ' )
					{
						if (e.ctrlKey && code=='v')
							e.preventDefault();	
						// Do Nothing....
					}
					else
					{
						if(code)
						{				
							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();	
						
						var pos = $(this).getSelectionStart();
						var virgule = this.value.indexOf(".");
						
						if ( code == "." && this.value.length - pos > 2 ) 
							e.preventDefault();
						else if ( virgule >= 0  && settings.numDecimal )
						{
							// Récupère la position du curseur
							if ( pos > virgule && this.value.length - this.value.indexOf(".") > settings.numDecimal )
								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(num_decimal)
{
		if ( typeof num_decimal == "undefined" ) num_decimal = 100000; // Unlimited
		return this.each (function()
			{
				jQuery(this).inputValue({allow:'0123456789.', numDecimal: num_decimal});
			}
		);		
};
/**
*	input fields will accept all letters (case insensitive)
*/
jQuery.fn.inputLetter = function()
{
		return this.each (function()
			{
				jQuery(this).inputValue({allow:'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'});
			}
		);		
};


// Calendar en français....
if ( $.datepicker )
{
	$.datepicker.regional['fr'] = {
		closeText: 'Fermer',
		prevText: '&#x3c;Préc',
		nextText: 'Suiv&#x3e;',
		currentText: 'Courant',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
		'Jul','Aoû','Sep','Oct','Nov','Déc'],
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		dateFormat: 'dd/mm/yy', firstDay: 1,
		isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
}


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 = 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.fn.drawAllScreen = function ( params  ) {
	
	$(this).width( $(window).width() + $(window).scrollLeft() );
	$(this).height( $(document).height() + $(window).scrollTop() );
	$(this).css( { left:0, top:0 } )
	
	
	var iIndex = 10000;
	if( typeof params != "undefined" && typeof params.zIndex != "undefined" )
	{
		iIndex = params.zIndex;
	}
	$(this).css( 'z-index', iIndex ).show( );
	return this;
}


jQuery.fn.getSelectionStart = function () 
{
	if (this[0].createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', this[0].value.length)
		if (r.text == '') return this[0].value.length
		return this[0].value.lastIndexOf(r.text)
	} else 	return this[0].selectionStart
}

jQuery.fn.getSelectionEnd = function () 
{
	if (this[0].createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveStart('character', -this[0].value.length)
		return r.text.length
	} else return this[0].selectionEnd
}

jQuery.fn.patchPNG = function( callback, datas ) {


//alert( $(this)[0].src);
	$(this).load( 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 = "";
					try {
						sStyles = jQuery.getStyles($(o)) +";width:"+w+"px;height:"+h+"px;display:inline;"
					}
					catch( e )
					{
						sStyles = "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;
}

		
$.clientCoords = function(){
	if ( document.body.clientHeight )
	{
        return {w:document.body.clientWidth, h:document.body.clientHeight}
	}
    else if(window.innerHeight || window.innerWidth){
        return {w:window.innerWidth, h:window.innerHeight}
    }
    return {
        w:document.documentElement.clientWidth,
        h:document.documentElement.clientHeight
    }
}
