// _____________ [ clientIdent ]_____________
(function($) {
$.fn.clientIdent = function( sUrl ) {

    if(sUrl==undefined) $.fn.clientIdent.sPathUrl = "http://client.numericable.fr/php/json/json_getVille.php"
    else $.fn.clientIdent.sPathUrl = sUrl;

    return this.each(function() {
        var $jForm = $(this);
        if( $jForm.data("clientIdent") !=null) return
        $jForm.data("clientIdent",true);
        

        var $jInput = $("input.ident_field_cp",$jForm);
        var $jChange = $("a.ident_change",$jForm);
        
        var NCcp = $.cookie('NCcp');
        var NCville = $.cookie('NCville');
        if(NCville != null) {while(NCville.match("_")) NCville = NCville.replace("_"," ");}
        
        $jInput.keyup( testCp );
        $jInput.focus( function(){$jInput.val('');} );
        $jChange.click(function(){swap( $jForm , 0 )})
        $jForm.submit(function(event){ event.preventDefault();event.stopPropagation();testCp({currentTarget:$jInput});return false; })
        
        if(NCcp==null || NCcp==''){
            swap( $jForm , 0 )
        }else if(NCville==null || NCville==''){
            swap( $jForm , 1 )
        }else{
            swap( $jForm , 2 )
        }
    })
    
}
    function swap( $jForm , etape )
    {
        var sVilleUrl = $.fn.clientIdent.sPathUrl;
        var sVilleUrl="http://client.numericable.fr/php/json/json_getVille.php";
        var $jInput = $("input.ident_field_cp");
        var $jSelect = $("select.ident_field_ville")
        var $jValid = $("input.ident_valid");
        var $jValue = $("span.ident_field_value");
        var $jChange =$("a.ident_change");
        
        var NCcp = $.cookie('NCcp');
        var NCville =  $.cookie('NCville');
        if(NCville != null) {while(NCville.match("_")) NCville = NCville.replace("_"," ");}
        
        if( etape== 0){
            $jInput.val(NCcp)
            $jInput.css({display:'block'})
            $jSelect.css({display:'none'})
            $jValue.css({display:'none'})
            $jChange.css({display:'none'})
            $jValid.css({display:'block'})
            $.cookie('NCville', null ,{path:'/',domain:'.numericable.fr'});
            $.cookie('NCcp', null ,{path:'/',domain:'.numericable.fr'});
            $jForm.trigger("change",[null,null]);
        }else if(etape== 1){
            $jInput.css({display:'none'})
            $jValid.css({display:'block'})
            $jValue.css({display:'none'})
            $jChange.css({display:'none'})
            $.getJSON(sVilleUrl,{cp:NCcp},function(oVille){ createVilleSelect(oVille,$jForm) })
         }else if(etape== 2){
            $jInput.css({display:'none'})
            $jValid.css({display:'none'})
            $jSelect.css({display:'none'})
            $jValue.css({display:'block'})
            $jValue.html(NCville+"("+NCcp+")")
            $jChange.css({display:'block'})
            $jForm.trigger("change",[NCcp,NCville]);
        }
    }
    function createVilleSelect( oJsonVille, $jForm )
    {
        var $jInput = $("input.ident_field_cp",$jForm);
        
        if( oJsonVille.liste_ville.length==0 ){
            swap($jForm,0)
        }else if( oJsonVille.liste_ville.length==1 ){
            $.cookie('NCville', oJsonVille.liste_ville[0].ville ,{expires: 30, path: '/',domain:'.numericable.fr'});
            swap($jForm,2)
        }else{
            var sSelect ='<select class="ident_field_ville">';
            sSelect = sSelect +'<option value="">Choisissez votre ville</option>';
            for( i in oJsonVille.liste_ville )
                sSelect = sSelect +'<option value="'+oJsonVille.liste_ville[i].ville+'">'+oJsonVille.liste_ville[i].ville+'</option>';
            sSelect = sSelect +'</select>';
            $jInput.css({display:'none'})
            $("select.ident_field_ville",$jForm).remove();
            $jInput.after(sSelect);
            
            $("select.ident_field_ville",$jForm).change(function(event){ 
                $this=$(this);
                if( $this.val()!='' ){
                    $.cookie('NCville', $this.val() ,{expires: 30, path: '/',domain:'.numericable.fr'});
                    swap($jForm,2);
                    event.stopPropagation();
                }
            });
        }
    }
    function testCp(event)
    {
        var sVilleUrl = $.fn.clientIdent.sPathUrl;
        var $jInput = $(event.currentTarget);
        var $jForm = $jInput.parents('form.ident');
        var sVal = $jInput.val();
        var reg =/^[0-9]{5}$/g;
        if(reg.test(sVal) ){
            $.cookie('NCcp', sVal,{expires: 30, path: '/',domain:'.numericable.fr'});
            $.getJSON(sVilleUrl,{cp:sVal},function(oVille){ createVilleSelect(oVille,$jForm) })
        }
    }
    
})(jQuery);

// _____________ [swapImage ]_____________
(function($) {
$.fn.swapImage = function() {
   
    return this.each(function() {
        var $jImage=$(this);
        var src = $jImage.attr('src');
        var bgsrc = $jImage.css('background-image');
        if( src ){
            var oversrc = src.substring(0,src.length-4)+'_over'+src.substring(src.length-4,src.length);
            $jImage.bind('mouseover',function(){ $(this).attr({src:oversrc}) }) 
            $jImage.bind('mouseout',function(){ $(this).attr({src:src}) }) 
        }else if( bgsrc ){
            var iDec = 5;
            if( bgsrc.substring(bgsrc.length-2,bgsrc.length) =='")') iDec=6;
            var oversrc = bgsrc.substring(0,bgsrc.length-iDec)+'_over'+bgsrc.substring(bgsrc.length-iDec,bgsrc.length);
            $jImage.bind('mouseover',function(){ $(this).css({backgroundImage:oversrc}) }) 
            $jImage.bind('mouseout',function(){ $(this).css({backgroundImage:bgsrc}) }) 
        }
    })

}

})(jQuery);

// _____________ [jBounceMenu ]_____________
(function($) {
$.fn.jBounceMenu = function(options) {
    jQuery.extend( jQuery.easing,
    {
        easeInOutElastic:function (x, t, b, c, d) {
            var s=1.70158;var p=0;var a=c;
            if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
            if (a < Math.abs(c)) { a=c; var s=p/4; }
            else var s = p/(2*Math.PI) * Math.asin (c/a);
            return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
        }
    })
    
    var opts = $.extend({}, $.fn.jBounceMenu.defaults, options);
    return this.each(function() {
        var $jMenu=$(this);
        $('li>a',$jMenu).bind('mouseover',function(){ 
            var jLi = $(this).parent();
            $(this).parent().siblings('#rollover').show().stop().animate({left:jLi.offset().left  ,width: jLi.width() + 6},1500,'easeInOutElastic') 
        })
         $jMenu.bind('mouseleave',function(){ 
            var jLi =$('li.selected',this);
            if( jLi.size() >0 ){
                $('#rollover',this).stop().animate({left:jLi.offset().left,width:jLi.width() + 6 },1500,'easeInOutElastic') 
            }else{
                $('#rollover',this).stop().hide();
            }
        })
        
       var jLi =$('.sousmenu li.selected');
       if( jLi.size() >0 ) $('#rollover',$jMenu).stop().css({left:jLi.offset().left,width:jLi.width()+6 }) 
       else  $('#rollover',$jMenu).hide();
    
       $(window).bind('resize',function(){ if( jLi.size() >0 ) {$('#rollover',$jMenu).stop().css({left:jLi.offset().left,width:jLi.width()+6 })}   })
       $('#rollover',$jMenu).show();
    })

  $.fn.jBounceMenu.defaults = {
	fixWidth: 6
  };
}

})(jQuery);


// _____________ [jSelect ]_____________
(function($) {
$.fn.jSelect = function(options) {
var opts = $.extend({}, $.fn.jSelect.defaults, options);
return this.each(function() {
    var $select=$(this);
    var width = $select.width();
    
    sLabel = $('option:eq(0)',$select).text();
    if(  $('option:selected',$select).size()==1 ) var sLabel = $('option:selected',$select).text();
   
    sStyle = ' style="width:'+(width+60)+'px;display: block;"'
    var sHtml='<ul class="isSelect" style="position:absolute;width:'+(width+60)+'px"><li class="first"><span><span><span class="isSelectLabel">'+sLabel+'</span></span></span><ul style="display:none">';
    sHtml+='<li class="first"><span><span><span></span></span></span></li>'; 
    
    $('option',$select).each(function() {
        var $jOption = $(this);
        sHtml+='<li><a href="javascript:;" class="isSelectOption"><span>'+$jOption.text()+'</span></a></li>';
    })
    sHtml +='<li class="last"><span><span><span></span></span></span></li>';
    sHtml+='</ul><li></ul><br/>';
    $select.css({display:'none'})
    $select.after(sHtml);
    
    $('a.isSelectOption').bind("click",function(){
        var $this = $(this);
        var $select = $(this).parents('.isSelect');
        var position = $this.parent().prevAll().size()-1;
        $('option:eq('+position+')',$select.prev()).attr('selected','selected');
        $('.isSelectLabel',$select).text( $('option:selected',$select.prev()).text() )
        $('ul:first',$select).css({display:'none'})
    })
     $('.isSelect li:first').bind("click",function(){ $('ul:first',this).css({display:'block'}) })
     $('.isSelect').bind("mouseleave",function(){$('ul:first',this).css({display:'none'}) })
})


}

})(jQuery);
// _____________ [jCheckBox ]_____________
(function($) {
    $.fn.jCheckBox = function(options) {
        var opts = $.extend({}, $.fn.jCheckBox.defaults, options);
        return this.each(function() {
            var $this=$(this);
            var jform = $this.parents("form");
            var jInput =$('input',this);
            
            if( $('input',$this).attr("checked") ) $this.css({backgroundPosition:"0 0"})
            
            //neutralise les labels
            if( jInput.attr('id') !=''){
                $("label[@for='"+jInput.attr('id')+"']").bind('click',function(event){ 
                  event.preventDefault();
                  event.stopPropagation();
                  $this.trigger("click");
                })
            }
            $this.bind('click',function(event){ 
                event.stopPropagation();
                var jInput =$('input',this);
                jInput.attr("checked", !jInput.attr("checked") )
               
                if( jInput.attr("type")=="radio"){
                    var jform = jInput.parents("form");
                    $("input[@type='radio'][@name='"+jInput.attr('name')+"']",jform).trigger("change");
                }else{
                    jInput.trigger("change");
                }
            })
            $('input',$this).bind('change',function(){ 
                var jInput =$(this);
                if( jInput.attr("checked") ){
                    jInput.parent().css({backgroundPosition:"0 0"})
                }else{
                     jInput.parent().css({backgroundPosition:"-22px 0"})
                }
            })
        })
    }
    $.fn.jCheckBox.defaults = {w:-22}

})(jQuery);


// _____________ [jMenu ]_____________
 /**
  * Initie un menu horizontal
  **/
(function($) {
    var sMenuOpen;
    $.fn.jMenu = function(options) {
        var opts = $.extend({}, $.fn.jMenu.defaults, options);

        return this.each(function() {
            $this = $(this);
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            sMenuOpen = o.selectedClass;
            var $openMenu = findOpenMenu($this)
            $this.data('openMenu',$openMenu);

            $this.bindIn('mouseleave',onLeave, 400,'jMenuSwap');
            $this.bind('mouseenter',onEnter);
            var dx = 0;
            $openMenu.removeClass(sMenuOpen);
            $this.children('li').each(function() {
                $menu = $(this);
                var mW = $menu.children('ul').width()
                var w = -( mW - $menu.width() ) /2;
                w = Math.max( w, o.xMin - dx );
                w = Math.min( w, o.xMax - dx - mW ) 
                
                $menu.children('ul').css({marginLeft:w})
                $menu.bind('mouseenter',open)
                dx +=  $menu.width();
            })
            $openMenu.addClass(sMenuOpen);
            
            });
    };

    function onEnter() { $(this).unBindIn('jMenuSwap'); }
    function onLeave()
    {
        $this = $(this);
        $this.children('li').removeClass(sMenuOpen);
        $this.data('openMenu').addClass(sMenuOpen)
    }

    // open
    function open()
    {
        $this = $(this);
        getJMenu($this).children('li').removeClass(sMenuOpen);
        $this.addClass(sMenuOpen);
    }
    // close
    function close() { $(this).removeClass(sMenuOpen); }
    // getJMenu
    function getJMenu( $menu ) { return $($menu).parent(); }
    // findOpenMenu
    function findOpenMenu($obj ) {  return $('li.'+sMenuOpen,$obj); };

    // plugin defaults
    $.fn.jMenu.defaults = {
        selectedClass: 'menuselect',
        xMin:0,
        xMax:490
    };
    
})(jQuery);
 // _____________ [bindIn ]_____________
 /**
  * Execute l'action apres x ms
  * 
  * @param options	(Objet) [Optionnel]  {'event','fAction','time','idEvent'}
  * OU
  * @param event	(String)
  * @param fAction	(Function)
  * @param time	(Number)
  * @param idEvent	(String)	[Optionnel]
  **/
(function($) {
  $.fn.bindIn = function(options) {
	// Verifie si l'argument unique est un Object
	if( arguments.length ==1 && typeof(options)!='Object' ){
		debug( arguments[0] ,' Nombre d\'arguments invalide.'  );
		return;
	}
	// Crée un objet d'options, si les arguments sont multuples
	var aArgumentOrder = ['event','fAction','time','idEvent'];
	var ArgOptions = {};
	if( arguments.length > 1 ){
		for (var i = 0; i < arguments.length; i++){
			ArgOptions[ aArgumentOrder[i] ] = arguments[i]
		}
		options = ArgOptions
	}

	// Applique les arguments par défault
	var opts = $.extend({}, $.fn.bindIn.defaults, options);
	
	// parcours les éléments, et les renvoie
	return this.each(function() {
	$this = $(this);
	// Applique les options metas de chacun
	var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
	// bind l'action
	$this.bind( o.event ,
		function(){
			var $scope=$(this);
			var options = o;
            var sEvent = options.idEvent+':'+options.event
            
			if( $scope.data( sEvent ) ) {
				clearInterval( $scope.data(sEvent) );
			}
			$scope.removeData(sEvent);
			$scope.data(sEvent,
				setInterval(function(){
					clearInterval( $scope.data( sEvent ) );
					$scope.removeData( sEvent );
					
					$scope.__fAction = options.fAction;
					$scope.__fAction() ;
					
				}, options.time )
			)
		}
	);
	});
  };
  //
  // private function for debugging
  //
  function debug($obj, msg) {
	if (window.console && window.console.log)
	  window.console.log('bindIn Error on[ ' + $obj +'] :'+msg);
  };
  //
  // plugin defaults
  //
  $.fn.bindIn.defaults = {
	event: 'click',
	fAction:function( ){},
	time:1000,
	idEvent:'delayId'
	
  };
//
// end of closure
//
})(jQuery);


 // _____________ [unBindIn ]_____________
  /**
  * Annule l'éxecution de l'action bindIn 
  * 
  * @param _idEvent	(String) [Optionnel] Identifiant de l'action
  * @param _sTrigger	(String) [Optionnel] event, si non spécifié annulera tous les events standards jquery
  **/
(function($) {
    var aE=['mouseenter','mouseleave','mousedown','mousemove','mouseout','mouseover','mouseup','blur','change','click','dblclick','error','focus','keydown','keypress','keyup','load','resize','scroll','select','submit','unload'];
    $.fn.unBindIn = function(_idEvent,_sTrigger) {
        var options = {idEvent:_idEvent, sTrigger:_sTrigger}
    	var opts = $.extend({}, $.fn.unBindIn.defaults, options);
        return this.each(function() {
            $this = $(this);
        	var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            if( o.sTrigger!=null ){
                var sEvent = o.idEvent+':'+o.sTrigger
                clearInterval( $this.data( sEvent ) );
            }else{
                for( i in  aE){
                  var sEvent = o.idEvent+':'+ aE[i];
                  clearInterval( $this.data( sEvent ) );
                }
            }
        })
    }
    
  // plugin defaults
  $.fn.unBindIn.defaults = {
	idEvent:'delayId',
    sTrigger:null
  };
})(jQuery);

// _____________ [ getMeta ]_____________
 /**
  * Retoune la valeur d'un champ passé en metadata dans l'attribut de classe ex:
  * <a href="#" class="{ key:value } etc.."/>
  * @param sName	(String) Nom de la clef 
 **/
(function($) {
    var regexp = /\{(\w+ ?: ?'[a-z0-9#\-_\.]*',?)+\}/gi;
    $.fn.getMeta = function(sName) {
        $this= $(this);
        var sC = $this.attr('class');
        var aR = sC.match(regexp);
        if( aR==null ) return '';
        for(var i=0;i<aR.length;i++){
            eval('var oM = '+aR[i]+';');
            if( oM[sName] ) return oM[sName];
        }
    }
})(jQuery);


// _____________ [ Cookie ]_____________
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
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;
    }
};


