/*
 * ---------- Configuration ---------
 */

var chemin = "/extension/cofinoga_shop/design/cofinoga_shop/";
var images_preload=[
    "submenu_bottom_hover.png",
    "submenu_middle_hover.png",
    "submenu_top_hover.png",
    "menu_g_b_h.jpg",
    "menu_g_h_h.jpg",
    "menu_g_m_h.jpg"
];

var onsub=0; onprim=0; // Pr le menu

/** Variables pour Google Analytics **/
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
var pageTracker;

window.addEvent('domready', function() {
	
    // Preload des images hover
    preload_array(images_preload, chemin+"images/");

	init_cp_form();
                              
    /**
     * Script pour le menu horizontal
     */
    if($("showsmenu1") != null) {   
    
    $("showsmenu1").addEvent('mouseover', function() { onsub=0; onprim=1; $("smenu1").setStyle('display', 'block'); });
    $("showsmenu1").addEvent('mouseout', function() { onprim=0; setTimeout("if (onsub==0 && onprim==0) $('smenu1').setStyle('display', 'none');", 500); });
   
    $$("#smenu1 a").each(function(el) {
       el.addEvent('mouseover', function(el) { onsub=1; $("smenu1").setStyle('display', 'block'); });
       el.addEvent('mouseout', function(el) { onsub=0; setTimeout("if (onsub==0 && onprim==0) $('smenu1').setStyle('display', 'none');", 500); });
    });
    
    /**
     * Script pour le sous-menu horizontal
     */  
     $$("li.menuunivers").each(function(el) {
     	
     	if(el.getElement('ul') != null)	//signifie que le menu a au moins un sous-menu
     	{     		
     		var ul = el.getElement('ul');
     		el.addEvent('mouseover', function() { onsub=0; onprim=1; ul.setStyle('display', 'block'); });
    		el.addEvent('mouseout', function() { onprim=0; if (onsub==0 && onprim==0)ul.setStyle('display', 'none'); });
    		
    		ul.getElements('li>a').each(function(sel) {
			    sel.addEvent('mouseover', function(sel) { onsub=1; ul.setStyle('display', 'block'); });
			    sel.addEvent('mouseout', function(sel) { onsub=0; if (onsub==0 && onprim==0)ul.setStyle('display', 'none'); });
			 });
		}
	});
}
    
    /*
    * Tooltips
    */
	
	 var tips = new Tips($$('.tips'), {
		 className: 'tipscustom'
	});
	
    
   /**
	 * Google analytic en lazy-loading
	 */

     /*
    new Asset.javascript(gaJsHost + "google-analytics.com/ga.js", {
        onload: function() {
            pageTracker = _gat._getTracker("UA-10063809-1"); 
            pageTracker._setDomainName("cofinoga.nsylvander.php5.loc");
            pageTracker._initData();
            pageTracker._trackPageview();
        }
    });
    */
   
    
});

/*
 *  ------------------------ Fonctions ---------------------
 */
 
 /*
 * Preload d'une liste d'images
 * @param 	Array  liste_src : liste des images
 */
function preload_array ( liste_src, chemin ) {

	var taille = liste_src.length;
	var preload = new Array(taille);
	
	for (var i=0; i<taille;i++) {
		preload[i] = new Image();
		preload[i].src = chemin+liste_src[i];
	}
}

function get_minimum(table)
{
	var min = table[0];
 	for(i=0; i < table.length; i++){
		if(table[i] < min) min = table[i];
	}
	return min;
}

function get_maximum(table)
{
	var max = table[0];
 	for(i=0; i < table.length; i++){
		if(table[i] > max) max = table[i];
	}
	return max;
}

function submitFormulaire(id,url)
{
	var champs = $(id).getElements("input, select");
	var params = '';
    for(var i = 0; i < champs.length; i++) 
    {
		if(champs[i].value != "")
		{
			params += '/('+champs[i].name+')/'+champs[i].value;
		}
    }

    document.location = 'http://' + document.domain + url + params;
}

function lancerRedirection(url)
{
	setTimeout("document.location.replace('"+url+"')", 2500);
}

/*
 * Fonctions d'utilisation de la carte pour les magasins physiques
 */

//Attache le message un InfoWindow
function attachMessage(map, marker, message, geocodage) {
var infowindow = new google.maps.InfoWindow(
   { 
   	content: message
   });
   
google.maps.event.addListener(marker, 'click', function() {
 infowindow.open(map,marker);
 
google.maps.event.addListener(infowindow, 'domready', function() {
		pager[geocodage] = new Pager ("resultat_" + geocodage , 2);
		pager[geocodage].init();
		pager[geocodage].showPageNav ('pager[\''+geocodage+'\']', "pageNav_" + geocodage );
		pager[geocodage].showPage(1);
	});
});
}

function initializeMagasinPhysique( marques ) {
	if ( typeof(marques)!='undefined' )
	{
		bounds = new Array(marques[0],marques[0],marques[1],marques[1]);	
		for(var j = 0; j < marques.length; j=j+5)
		{
			bounds[0] = Math.min(bounds[0],marques[j]);
			bounds[1] = Math.max(bounds[1],marques[j]);
			bounds[2] = Math.min(bounds[2],marques[j+1]);
			bounds[3] = Math.max(bounds[3],marques[j+1]);
		}
	
		// Create a new map with some default settings
		if ( marques.length == 5 )
		{
	    	var myLatlng = new google.maps.LatLng(marques[0],marques[1]);
	    	var zooom = 14;
	    }
	    else
	    {
	    	var myLatlng = new google.maps.LatLng(46,2);
	    	var zooom = 5;
	    }
	    var myOptions = {
	      zoom: zooom,
	      center: myLatlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    }
    
	    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		
		// Initialize Fluster and give it a existing map
		var fluster = new Fluster2(map);
		
		for(var i = 0; i < marques.length; i=i+5)
		{
			// Create a new marker
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(marques[i], marques[i+1]),
				title: marques[i+2]
			});
			
			// On attache le message à la InfoWindow
			attachMessage(map, marker, marques[i+3], marques[i+4]);
			
			// Add the marker to the Fluster
			fluster.addMarker(marker);
		}
		
		// Set styles
		fluster.styles = {
			// This style will be used for clusters with more than 0 markers
			0: {
				image: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m1.png',
				textColor: '#FFFFFF',
				width: 53,
				height: 52,
				showText: false,
				infoDebut: "",
				infoFin: " magasins"
			},
			// This style will be used for clusters with more than 10 markers
			10: {
				image: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m2.png',
				textColor: '#FFFFFF',
				width: 56,
				height: 55,
				showText: false,
				infoDebut: "",
				infoFin: " magasins"
			},
			20: {
				image: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m3.png',
				textColor: '#FFFFFF',
				width: 66,
				height: 65,
				showText: false,
				infoDebut: "",
				infoFin: " magasins"
			}
		};
		fluster.gridSize = 40;
		
		// Initialize Fluster
		// This will set event handlers on the map and calculate clusters the first time.
		fluster.initialize();
		
		var myBounds = new google.maps.LatLngBounds(new google.maps.LatLng(bounds[0],bounds[2]),new google.maps.LatLng(bounds[1],bounds[3]));
	
		if ( marques.length != 5 )
		{
			map.fitBounds(myBounds);
		}
	}
	else
	{
		document.getElementById("map_canvas").innerHTML = "<p>Votre recherche ne contient aucun r&eacute;sultat</p>";
		document.getElementById("map_canvas").style.height = "30px";
	}
}


function initialize() {

    var myLatlng = new google.maps.LatLng(46,2);
    var zooom = 5;
    
    var myOptions = {
      zoom: zooom,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);		
}

function nouveauFluster ( marques )
{
	// Initialize Fluster and give it a existing map
	if ( idFlu != 0 )
	{
		fluster[idFlu-1].removeClusters();
	}
	
	fluster[idFlu] = new Fluster2(map);
	
	bounds = new Array(marques[1],marques[1],marques[2],marques[2]);	
	for(var j = 1; j < marques.length; j=j+5)
	{
		bounds[0] = Math.min(bounds[0],marques[j]);
		bounds[1] = Math.max(bounds[1],marques[j]);
		bounds[2] = Math.min(bounds[2],marques[j+1]);
		bounds[3] = Math.max(bounds[3],marques[j+1]);
	}
	
	
	for(var i = 1; i < marques.length; i=i+5)
	{
		// Create a new marker
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(marques[i], marques[i+1]),
			title: marques[i+2]
		});
		
		// On attache le message à la InfoWindow
		attachMessage(map, marker, marques[i+3], marques[i+4]);
		
		// Add the marker to the Fluster
		fluster[idFlu].addMarker(marker);
	}
	
	// Set styles
	fluster[idFlu].styles = {
		// This style will be used for clusters with more than 0 markers
		0: {
			image: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m1.png',
			textColor: '#FFFFFF',
			width: 53,
			height: 52,
			showText: false,
			infoDebut: "",
			infoFin: " magasins"
		},
		// This style will be used for clusters with more than 10 markers
		10: {
			image: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m2.png',
			textColor: '#FFFFFF',
			width: 56,
			height: 55,
			showText: false,
			infoDebut: "",
			infoFin: " magasins"
		},
		20: {
			image: 'http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/1.0/images/m3.png',
			textColor: '#FFFFFF',
			width: 66,
			height: 65,
			showText: false,
			infoDebut: "",
			infoFin: " magasins"
		}
	};
	fluster[idFlu].gridSize = 40;
	
	// Initialize Fluster
	// This will set event handlers on the map and calculate clusters the first time.
	fluster[idFlu].initialize();
	
	if ( marques[0] == 1 )
	{
		$('GMTitre').innerHTML = "<h3>" + marques[0] + " point de vente trouv&eacute;<h3>";
		var myBounds = new google.maps.LatLngBounds(new google.maps.LatLng(bounds[0],bounds[2]),new google.maps.LatLng(bounds[1],bounds[3]));
	}
	else
	{
		$('GMTitre').innerHTML = "<h3>" + marques[0] + " points de vente trouv&eacute;s<h3>";
		var myBounds = new google.maps.LatLngBounds(new google.maps.LatLng(bounds[0],bounds[2]),new google.maps.LatLng(bounds[1],bounds[3]));
	}
	
	map.fitBounds(myBounds);

	idFlu = idFlu+1;
}

function succesPdv(result){
	if ( result[0] > 0 )
	{
		nouveauFluster ( result );
	}
	else if ( result[0] < 0 )
	{
		$('GMTitre').innerHTML = "<h3>Trop de points de vente trouv&eacute;s<h3>";
	}
	else
	{
		$('GMTitre').innerHTML = "<h3>Aucun point de vente trouv&eacute;<h3>";
	}
}

function init_cp_form()
{
	if($('pvcp'))
	{
		$('pvcp').addEvent('submit', function(e){

			e = new Event(e).stop();
			cp = $('pvcp').code_postal.value;
			url_send = $('pvcp').action+'/(CodePostal)/'+cp;
			new Request.JSON({
				url:url_send,
				method:'post',
				onComplete:function(){
				},				
				onSuccess:function(){
					result= JSON.decode(this.response.text);
					succesPdv(result);
				}
			}).send();
		});
	}
}

function FAISelect(){
	
	var A=document.getElementById("FAI_select");

	if(A.selectedIndex==A.options.length-1){document.getElementById("FAI_select").style.display="none";

	document.getElementById("FAI_autre").style.display="inline";

	document.getElementById("FAI_autre").style.height="100%";

	document.getElementById("FAI_autre").focus()
	}
}

function concatDateNaiss(){
	document.getElementById("datenaiss").value = document.getElementById("jourNaissance").value+"/"+document.getElementById("moisNaissance").value+"/"+document.getElementById("anneeNaissance").value;
}

function concatMail(){
	if(document.getElementById("FAI_select").style.display!="none"){
		document.getElementById("email").value=document.getElementById("prefix").value+"@"+document.getElementById("FAI_select").value;
	}
	else {
		document.getElementById("email").value=document.getElementById("prefix").value+"@"+document.getElementById("FAI_autre").value;
	}
}

function verifieForm(id)
{
	var champs = $(id).getElements("input, select");
	var valide = true;
	var isCheck = false;
    for(var i = 0; i < champs.length; i++)
    {
    	if(champs[i].get('name') == 'nom' || champs[i].get('name') == 'prenom' || champs[i].get('name') == 'deptNaissance' || champs[i].get('name') == 'villeNaissance' || champs[i].get('name') == 'adresse1' || champs[i].get('name') == 'codePostal' || champs[i].get('name') == 'ville')
    	{
    		$('erreur'+champs[i].get('name')).setStyle('display','none');
    		if(champs[i].get('value') == '')
    		{
    			valide = false;
    			$('erreur'+champs[i].get('name')).setStyle('display','inline');
			}
		}
		else if(champs[i].get('name') == 'datenaissance')
		{
			$('erreur'+champs[i].get('name')).setStyle('display','none');
			if(!verifierDateNaissance(champs[i].get('value')))
			{
    			valide = false;
    			$('erreur'+champs[i].get('name')).setStyle('display','inline');
			}
		}
		else if(champs[i].get('name') == 'email')
		{
			$('erreur'+champs[i].get('name')).setStyle('display','none');
			if(!verifierAdresseMail(champs[i].get('value')))
			{
				valide = false;
				$('erreur'+champs[i].get('name')).setStyle('display','inline');
			}
		}
		else if(champs[i].get('name') == 'cu')
		{
			//$('erreur'+champs[i].get('name')).setStyle('display','none');
			//if(champs[i].checked)
				isCheck = true;	
		}
	}

	if(isCheck == false)
	{
		$('erreurcu').setStyle('display','inline');
		valide = false;
	}
	
	return valide;
}

function verifierAdresseMail(adresse)
{
	var place = adresse.indexOf("@",1);
	var point = adresse.indexOf(".",place+1);
	return ((place > -1)&&(adresse.length >2)&&(point > 1)) && adresse == $('confirmationEmail').value;
}

function verifierDateNaissance(date)
{
   var d = new RegExp('^[0-9]{2}/[0-9]{2}/[0-9]{4}$');
   return d.test(date);  
   	
}

function concatCentreInt(id)
{
	var champs = $(id).getElements("input");
	var preferences = '';
    for(var i = 0; i < champs.length; i++)
    {
    	if(champs[i].get('name') == 'preference' && champs[i].checked)
    	{
    		if(preferences != '')
    		{
    			preferences += ',';
    		}
    		preferences += champs[i].get('value');
    	}
    	
	}
	$("preferences").value=preferences;
	
}

function submitForm(id)
{
	var champs = $$('#'+id+' input');
	var data = '';
    for(var i = 0; i < champs.length; i++)
    {
    	if(i!=0 && champs[i].get('name') != 'preference') data += '&';
    	if(champs[i].get('name') != 'preference')
    		data += champs[i].get('name') + '=' + champs[i].get('value');
	}

	var url = 'http://' + document.location.hostname + '/ajaxProxy.php?url=http://www.cofinoga.fr/newsletter/inscriptionSave.do';
	var options = { method:'post', url: url, async: false };
	var ajax= new Request(options).send(data);
	$(id).submit();
}

function checkFormNewsletter(idForm){
	if(verifieForm(idForm)){
		document.getElementById("formNewsletter").submit();
	}
}

function openHighslide()
{
	var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
	hs.htmlExpand(null, { contentId: 'highslide-html' } );
	if(isIE6)
		setTimeout("hs.htmlExpand(null, { contentId: 'highslide-html' } )", 1000);
	 
}

var timer;
var myEffect;

function openOffre(element)
{
	timer = openOffreGo.delay(300, element, element);
}

var openOffreGo = function (element)
{
	var lien = $(element);	
	var offre = lien.getNext();
	
	if(offre != null)
	{
		offre.setStyle('visibility','visible');

		myEffect = new Fx.Morph(offre, {duration: 500, transition: Fx.Transitions.Sine.easeOut});

		myEffect.set({
			'opacity': 0
		});

		myEffect.start({
			'opacity': 1 
		});
	}
	
}

function closeOffre(element)
{
	$clear(timer);
		
	var lien = $(element);
	var offre = lien.getNext();
	
	if(offre != null)
		if(offre.getStyle('opacity') > 0 && myEffect != null)
		{
			myEffect.cancel();
			myEffect.start({
				'opacity': 0 
			});
		}
	
}

var maxCookie = 9;	//correspond à 8 produits dans l'historique, car on exclut le produit en cours de visualisation

function ajoutProduitCookie(id)
{
	var cookie = Cookie.read('parcoursProduit');
	if(cookie != null)
	{
		var tabId = cookie.split(';');
		if(!tabId.contains(id))	//le node id n'existe pas encore, on l'ajoute
		{
			tabId.push(id);
			
			if(tabId.length > maxCookie+1)
			{
				var tmpId = tabId[0];
				tabId.erase(tmpId);
			}
				
			var newCookie = '';
			tabId.each(function(item, index){
				if(item!= '') 
					newCookie += item+';';
			});
			
			Cookie.write('parcoursProduit', newCookie, {duration: 365, domain: document.location.hostname , path: '/'});
		}
		else
		{
			tabId.erase(id);
			tabId.push(id);
			
			var newCookie = '';
			tabId.each(function(item, index){
				if(item!= '') 
					newCookie += item+';';
			});
			
			Cookie.write('parcoursProduit', newCookie, {duration: 1, domain: document.location.hostname , path: '/'});
		}
		
	}
	else
		Cookie.write('parcoursProduit', id+';', {duration: 1, domain: document.location.hostname ,path: '/'});

}

function afficheHistorique(id,node_id)
{	
	var cookie = Cookie.read('parcoursProduit');
	if(cookie != null)
	{	
		var tabId = cookie.split(';');
		if(tabId.length > 2) // on a au moins 2 produits en historique, donc on peut afficher l'historique
		{
			$("historique").setStyle('display','block');
			var url = 'http://' + document.location.hostname + '/historique/affiche_historique/' + cookie +'/'+node_id;
			var myHTMLRequest = new Request.HTML({evalScripts:true, update:id}).get(url);
		}
	}	
}

