$(document).ready(function() {
	
	/* ToolBox Client */		
	$('#ToolBoxIdentificationGoMotDePasse').click(function() {
		$('.ToolBoxIdentification').slideUp('fast', function () {
			$('.ToolBoxMotDePassePerdu').slideDown('fast');
		});
	});
	
	$('#ToolBoxIdentificationGoIdentification').click(function() {
		$('.ToolBoxMotDePassePerdu').slideUp('fast', function () {
			$('.ToolBoxIdentification').slideDown('fast');
		});
	});
	
	$('#ToolBoxIdentificationIdentifiant, #ToolBoxIdentificationMotDePasse').focus(function() {
		$('#FormToolBoxIdentificationErr').html('').slideUp('fast');
	});
	
	$('#ToolBoxMotDePassePerduEmail').focus(function() {
		$('#FormToolBoxMotDePassePerduErr').html('').slideUp('fast');
	});
	
	/* Initialisation Panier Header */
	ToolBoxPanierContentProduits();	

	ToolBoxIdentificationInitialize();
	InitializeCufon();
	jScrollFollow();
	jQueryUI();
	jFancy();
	
});

/* ---------------------- */
/* --- IDENTIFICATION --- */
/* ---------------------- */

function ToolBoxIdentificationInitialize() {
	var dataString = "FormAction=Initialisation&";		
		
	// Execution du formulaire
	$.ajax({
		type: "POST",
		url: "./op_identification.php",
		data: dataString,
		dataType : 'html',
		cache: false,
		async: true,
		success: function(data) { eval(data); return(false); }
		//,error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	});
	
	return false;
}

function ToolBoxIdentificationSubmit(gotoPage) {
	
	$.Watermark.HideAll();
	
	var dataString = "FormAction=Identification&"+$("#FormToolBoxIdentification").serialize();

	if((typeof(gotoPage) !== 'undefined') && (gotoPage != "")) { dataString += '&gotoPage='+gotoPage }
		
	// Execution du formulaire
	$.ajax({
		type: "POST",
		url: "./op_identification.php",
		beforeSend: function() { $('.ToolBoxIdentification').hide(0, function() { $('.ToolLoader').show(); }); },
		data: dataString,
		dataType : 'html',
		cache: false,
		async: true,
		success: function(data) { $.Watermark.ShowAll(); eval(data); return(false); },
		error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	});
	
	return false;
}


function ToolBoxMotDePassePerduSubmit() {
	var dataString = "FormAction=MotDePassePerdu&"+$("#FormToolBoxMotDePassePerdu").serialize();		
		
	// Execution du formulaire
	$.ajax({
		type: "POST",
		url: "./op_identification.php",
		data: dataString,
		dataType : 'html',
		cache: false,
		async: true,
		success: function(data) { eval(data); return(false); },
		error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	});
	
	return false;
}

function Deconnexion() {
	var dataString = "FormAction=Deconnexion&";		
		
	// Execution du formulaire
	$.ajax({
		type: "POST",
		url: "./op_deconnexion.php",
		data: dataString,
		dataType : 'html',
		cache: false,
		async: true,
		success: function(data) { eval(data); return(false); }
		//,error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	});
	
	return false;
}

/* -------------- */
/* --- DIVERS --- */
/* -------------- */

function urlencode (str) {
    str = (str + '').toString();
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}


function serverTime() { 
    var time = null; 
    $.ajax({url: './op_time_now.php', 
        async: false, dataType: 'text', 
        success: function(text) { 
            time = new Date(text); 
        }, error: function(http, message, exc) { 
            time = new Date(); 
    }}); 
    return time; 
}

function isDefined(variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function jQueryUI() {
	
	$('.tabs').tabs();		
	
	$('form input[type=text], form input[type=password], form textarea').focus(function() { $('#'+$(this).attr('id')+"_Err").slideUp('fast'); });	
	
	$("button.uiButton").button().mouseout(function() { $(this).removeClass('ui-state-focus'); });	
	
	$("button.qteButton").hover(function() { var src = str_replace('_off','_on', $('img',this).attr('src')); $('img',this).attr('src',src); }, function() { var src = str_replace('_on','_off', $('img',this).attr('src')); $('img',this).attr('src',src); });	
	
	$(".RadioSet").buttonset();
	
	$('.tooltip, .tooltip-s, .tooltip-n, .tooltip-w, .tooltip-e, .tooltip-ne, .tooltip-nw, .tooltip-se, .tooltip-sw').mouseover(function() { $(this).css('cursor', 'help'); });
	$('.FooterPartenairesItemIn a').mouseover(function() { $(this).css('cursor', 'pointer'); });
	
	$('.tooltip').tipsy({title: 'alt', gravity: 's'});
	$('.tooltip-s').tipsy({title: 'alt', gravity: 's'});
	$('.tooltip-n').tipsy({title: 'alt', gravity: 'n'});
	$('.tooltip-w').tipsy({title: 'alt', gravity: 'w'});
	$('.tooltip-e').tipsy({title: 'alt', gravity: 'e'});
	
	$('.tooltip-ne').tipsy({title: 'alt', gravity: 'ne'});
	$('.tooltip-nw').tipsy({title: 'alt', gravity: 'nw'});
	
	$('.tooltip-se').tipsy({title: 'alt', gravity: 'se'});
	$('.tooltip-sw').tipsy({title: 'alt', gravity: 'sw'});
	
	
	$.datepicker.setDefaults($.datepicker.regional['fr']);
	$.datepicker.setDefaults({showWeek: true, dateFormat: 'dd/mm/yy', constrainInput: true});

	$(".datetimepicker").datetimepicker({showOn: "button",buttonImage: "./images/calendrier.png",buttonImageOnly: true, buttonText: 'Sélectionner une date'});	
	$(".datetimepicker").setMask({mask : '39/19/9999 29:69'});
	
	$(".datepicker").datepicker({showOn: "button",buttonImage: "./images/calendrier.png",buttonImageOnly: true, buttonText: 'Sélectionner une date'});	
	$(".datepicker").setMask({mask : '39/19/9999'});
	
	$("img.ui-datepicker-trigger").css('position','relative').css('top','5px').css('padding-left','5px').mouseover(function() { $(this).css('cursor','pointer'); } );
	$("div.ui-datepicker").css('position','relative').css('margin-top','5px');
	
	$(".datepicker, .datetimepicker").dblclick(function() { $(this).select(); });	
	
	//$('input.formatPhone').setMask({mask : '99 99 99 99 99'});	

	$('form.jqTransform').jqTransform();
	
	
}

/* ScrollFollow */
function jScrollFollow() {
	var versionIE = getInternetExplorerVersion();
	if(versionIE > 6 || versionIE == -1)
	{
		$('.ToolBoxFollow').scrollFollow({
			speed: 1000,
			offset: 20,
			easing: 'easeOutBack',
			container: 'ToolBoxContainer'		
		});
	}
}


/* FancyBox */
function jFancy() {
	$('a.fancy').fancybox({ title: $('img',this).attr('alt') ,titlePosition : 'inside', 'zoomOpacity'	: true,	'zoomSpeedIn'	: 500, 'zoomSpeedOut'	: 500 , centerOnScroll : true});
	
	$('a.zoomable').each(function() {
		$(this).prepend('<div class="fancyMagnifier"></div>');
	});
	$('a.zoomable').hover(function() {
		$('.fancyMagnifier', this).show();
	}, function() {
		$('.fancyMagnifier', this).hide();
	});
}

/* SESSIONIZE */
function Sessionize(SessionVar, SessionVal, SessionArray, callBack) {
	var dataString = "FormAction=Sessionize&SessionVar="+SessionVar+"&SessionVal="+SessionVal+"&SessionArray="+SessionArray;		
		
	// Execution du formulaire
	$.ajax({
		type: "POST",
		url: "./includes.php",
		data: dataString,
		dataType : 'html',
		cache: false,
		async: true,
		success: function(data) { if ($.isFunction(callBack)) { callBack(); } else { eval(data); } return(false); },
		error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	});
	
	return false;
}

function UnSessionize(SessionVar, SessionArray, callBack) {
	var dataString = "FormAction=UnSessionize&SessionVar="+SessionVar+"&SessionArray="+SessionArray;		
		
	// Execution du formulaire
	$.ajax({
		type: "POST",
		url: "./includes.php",
		data: dataString,
		dataType : 'html',
		cache: false,
		async: true,
		success: function(data) { if ($.isFunction(callBack)) { callBack(); } else { eval(data); } return(false); },
		error: function() { Boxy.alert('Une erreur est survenue. Veuillez réessayer à nouveau.<br>Si le problème persiste veuillez contacter l\'administrateur du système.', null, {title: 'Information'}); }
	});
	
	return false;
}

/* CUFON */
function InitializeCufon()
{		
	if ((Cufon != "undefined") && (true)) {

		var versionIE = getInternetExplorerVersion();
		if(versionIE > 6 || versionIE == -1)
		{
			Cufon.set('forceHitArea',true);
			
			/* HeaderSub */
			Cufon.replace($('.HeaderSubTitle, .HeaderSubTitleSub'), { fontFamily: 'Cocon', textShadow:'#005C1F 0px 2px' });					
			
			/* NavCatalogue */
			Cufon.replace($('.HeaderSub .NavCatalogue li a'), { fontFamily: 'Cocon', textShadow:'#005C1F 0px 2px', hover: { color: '#FFE000' } });					
			
			/* ToolBox */
			Cufon.replace($('.ToolBoxTitleSml, .ToolBoxTitleMid, .ToolBoxTitleBig'), { fontFamily: 'Cocon', textShadow:'#674E21 0px 2px' });					
			
			/* Content */
			Cufon.replace($('.ContentTitle, .ContentTitleSub'), { fontFamily: 'Cocon', textShadow:'#FFFFFF 0px 1px' });		
			
			/* Coups de coeur */
			Cufon.replace($('.CoupsDeCoeurTitle, .CoupsDeCoeurTitleSub'), { fontFamily: 'Cocon' });					
			Cufon.replace($('.CoupsDeCoeurItemTitre, .CoupsDeCoeurItemPrix,.CoupsDeCoeurItemPrixPromotion'), { fontFamily: 'Cocon', textShadow:'#4F5B20 0px 2px' });

			/* Familles Accueil */
			Cufon.replace($('.BlocFamilleTitre'), { fontFamily: 'Cocon' });					

			/* Produit */
			Cufon.replace($('.DivProduitTitre, .DivProduitHoverTitre, .DivProduitTarif'), { fontFamily: 'Cocon' });		
			Cufon.replace($('.DivProduitAssocTitre, .DivProduitAssocHoverTitre, .DivProduitAssocTarif'), { fontFamily: 'Cocon' });
			
			/* Commandes */
			Cufon.replace($('.CommandeStatut'), { fontFamily: 'Cocon' });
			

			/* Footer */
			Cufon.replace($('.PreFooterAlloBrazilNumTel'), { fontFamily: 'Cocon', textShadow:'#005C1F 0px 2px', color: '-linear-gradient(red, 0.2=#fff, 0.8=#FFE000, rgb(0, 0, 0))' });					
			Cufon.replace($('.PreFooterAlloBrazilTitre, .PreFooterAlloBrazilSubTitre'), { fontFamily: 'Cocon', textShadow:'#005C1F 0px 2px' });					
			Cufon.replace($('.PreFooterBoutiquesCarreVille, .NosMagasinsTitreVille, .NosMagasinsAdresseTitre, .NosMagasinsHorairesTitre'), { fontFamily: 'Cocon' });
			Cufon.replace($('.PreFooterCIAFBTitre'), { fontFamily: 'Cocon', textShadow:'#0E4F11 0px 2px' });
			Cufon.replace($('.FooterTitle, .FooterTitleSub'), { fontFamily: 'Cocon', textShadow:'#F5E59A 0px 2px' });
			Cufon.replace($('.Footer .NavCatalogue li a'), { fontFamily: 'Cocon', textShadow:'#F5E59A 0px 2px', hover: { color: '#725432' } });
		}
	}
}

function str_replace (search, replace, subject, count) {
   
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
