/* Variables globales */
var gSlider; var gSliderPanier; var gIsAdmin;


//Initialisation des actions javascript de la page
window.addEvent('domready', function() {
	
	//$('debug').set('html', 'test')
	
	if(!gIsAdmin){
	
		//Initialisation des actions du menu
		initializeMenu();
		
		//Initialisation des actions du menu de gauche
		initializeMenuLeft();
		
		//Initialisation de la taille des colonnes
		initColsSize();
		
		//Initialisation du scroll
		new SmoothScroll();
		
		//Gestion du panier
		if($('div_panier_contenu') && !gSliderPanier) gSliderPanier = new Fx.Slide('div_panier_contenu', {duration: 500}).hide();
		
		//Liens externes
		vObj = $('ext-links');
		if(vObj) vObj.setStyle('display', 'none');
		
		//login
		var elements = document.getElements('input[id=login_email], input[id=login_password]');
		if(elements) {
			elements.addEvent('keydown', function(event){
			var event = new Event(event);
				if(event.key=='enter'){
					if(login()) document.form_identification.submit()
				}
			})
		}
		
		var elementCodePromo = $('search_code_promo');
		if(elementCodePromo){
			elementCodePromo.addEvent('keydown', function(event){
				var event = new Event(event);
				if(event.key=='enter'){
					searchAboCodePromo();
				}
			})
		}
	}
	
}); 

function focusField(element){
	var value = element.value;
	var initValue = element.get('title');
	if(value==initValue) element.value = '';
}

function blurField(element){
	var value = element.value;
	var initValue = element.get('title');
	if(value=='') element.value = initValue;
}


function searchAboCodePromo(){
	var code_promo = $('search_code_promo').value;
	var request = new Request ({
		url : '/ajax.php',
		data: 'cmd=search_abo_code&code_promo='+code_promo,
		evalScripts	:true,
		onSuccess: function(data){
			var data = JSON.decode(data);
			if(!data || !data.flag) alert('Le code saisi est invalide');
			else{
				var type_code = data.type;
				var off_id = data.off_id;
				var art_id = data.art_id;
				var pri_id = data.pri_id;
				/*return
				if(data.length>1) alert('Le code promotion saisi ne permet pas de bénéficier d\'une remise sur une offre spécifique.');
				else{	
					var pro_id = data[0].pro_id;
					window.location = '/ajax.php?cmd=add_code_promo&id='+pro_id+'&code_promo='+code_promo;
				}*/
				window.location = '/page-code-promo.php?code_promo='+code_promo+'&type_code='+type_code+'&off_id='+off_id+'&art_id='+art_id+'&pri_id='+pri_id;
			}
		}
	});
	request.send();
}

/* Initialisation du menu du gauche */
function initializeMenuLeft(){
	//Menu abonnement
	vObj = $('ul_theme_abo');
	if(vObj){
		var vElements = vObj.getElements('li');
		if(vElements){
			i=0;
			vElements.each(function(pElement){
				pElement.index = i;			
				pElement.addEvent('mouseover', function(e){
					showMenuLeft(pElement.index, this, true, 'div_menu_left_');
				})
				pElement.addEvent('mouseout', function(e){
					showMenuLeft(pElement.index, this, false);
				})
				i++;
			})
		}
	}
	
	//Menu boutique
	vObj = $('ul_theme_boutique');
	if(vObj){
		vElements = vObj.getElements('li');
		if(vElements){
			i=0;
			vElements.each(function(pElement){
				pElement.index = i;			
				pElement.addEvent('mouseover', function(e){
					showMenuLeft(pElement.index, this, true, 'div_menu_left_article_');
				})
				pElement.addEvent('mouseout', function(e){
					showMenuLeft(pElement.index, this, false, 'div_menu_left_article_');
				})
				i++;
			})
		}
	}
	
	//Menu abo/boutique fin de page
	/*vObj = $('div_abo_boutique');
	if(vObj){
		vElements = vObj.getElements('li');
		if(vElements){
			i=0;
			vElements.each(function(pElement){
				vId = pElement.id;
				if(vId.indexOf('a_abo_boutique_')>-1){
					pElement.index = i;			
					pElement.addEvent('mouseenter', function(e){
						showMenuLeft(pElement.index, this, true, 'div_menu_left_abo_boutique_', e.page); 
					})
					pElement.addEvent('mouseleave', function(e){
						showMenuLeft(pElement.index, this, false, 'div_menu_left_abo_boutique_', e.page);
					})
					i++;
				}
			})
		}
	}*/
	
}

/* Initialisation du menu du haut */
function initializeMenu(){
	var vObj = $('ul_onglet');
	if(vObj){
		var vElements = vObj.getElements('img');
		if(vElements){
			i=1;
			vElements.each(function(pElement){
				//alert(pElement.id)
				pElement.index = i;			
				pElement.addEvent('mouseover', function(e){
					vFlag = $('flag_selected_'+this.index).value;
					vFlag = (vFlag=='true')?true:false;
					showMenu(pElement.index, this, true, vFlag);
				})
				pElement.addEvent('mouseout', function(e){
					vFlag = $('flag_selected_'+this.index).value;
					vFlag = (vFlag=='true')?true:false;
					showMenu(pElement.index, this, false, vFlag);
				})
				i++;
			})
		}
	}
}

/* Initialisation des actions de la page */
function showPanier(){
	vObj = $('div_panier_content')
	if(vObj) vObj.setStyle('height', 'auto');
	if(gSliderPanier!=null)	gSliderPanier.toggle();
}

/* Redirection */
function goTo(pUrl, pElement){
	value = pElement.value;
	if(value!='choose') window.location = pUrl + pElement.value;
}

//Initialisation de la taille des colonnes
function initColsSize(){
	if($('div_left')){
		var vInfosMiddle = $('div_middle').getCoordinates();
		var vInfosLeft = $('div_left').getCoordinates();
		if($('div_right')){
			var vInfosRight = $('div_right').getCoordinates();
			vHeight = Math.max(vInfosMiddle.height, vInfosLeft.height);
			vHeight = Math.max(vHeight, vInfosRight.height);
		
			$('div_left').setStyle('height', vHeight+'px');
			//$('div_middle').setStyle('height', vHeight+'px');
			$('div_right').setStyle('height', vHeight+'px');
		}
	}
	
}

/* Changement de couleur d'une rubrique */
function changeColor(pElement, pSelected, pSuffixe){
	var vSelected = (pSelected!=null)?pSelected:false;
	var vSuffixe = (pSuffixe!=null)?pSuffixe:'_selected';
	var vValue='';var vRegExp; var vExtension;
	//Type de balise
	switch(pElement.tagName){
		case 'IMG':
			vValue = pElement.src;
			vRegExp = /(.*)\.(.*)/;
		break;
		default :
			vValue = pElement.className;
			vRegExp = new RegExp("(.*)"+vSuffixe)
	}
	//Traitement si l'image n'est pas deja selectionnee
	if(!vSelected){
		var vTab = vRegExp.exec(vValue);
		//IMAGE 
		if(pElement.tagName=='IMG'){
			if(vRegExp.test(vValue)){
				vRegExp = new RegExp("(.*)"+vSuffixe)
				if(!vRegExp.test(vTab[1]))	pElement.src = vTab[1]+vSuffixe+'.'+vTab[2];
				else{
					vExtension = vTab[2]
					vTab = vRegExp.exec(vValue);
					pElement.src = vTab[1]+'.'+vExtension;
				}
			}
		}else{
			vElement = pElement;
			if(vElement){
				vElement.className='';
				if(!vRegExp.test(vValue))  	vElement.toggleClass(vValue+vSuffixe);
				else	vElement.toggleClass(vTab[1]);
			}
			
		}
	}
}

/* Ouverture popup */
function openWindow(theURL,winName,width,height,features) { 
	var w = screen.width;
	var h = screen.height;
	theURL=theURL;
	if(window.screen){
			ratio_x=(width/w)*100;
			ratio_y=(height/width)*100;
			win_x=(screen.width*ratio_x)/100;
			win_y=(win_x*ratio_y)/100;
			x=(screen.width-win_x)/2;
			y=(screen.height-win_y)/2;
	}else{
			x=0;
			y=0;
			win_x=w;
			win_y=y;
	}
	winfeatures=("top="+y+",left="+x+",width="+win_x+",height="+win_y+","+features);
	win = window.open(theURL,winName,winfeatures);
	if(win) win.focus();
}

/* Affichage du menu du haut */
function showMenu(pIndex, pElement, pVisible, pSelected){
	vObj = $('div_menu_'+pIndex);
	//vElement = $(pElement.id);
	vElement = pElement;
	vVisible = pVisible;
	changeColor(pElement, pSelected);
	
	if(vObj && vElement){
		vObj.addEvent('mouseover', eventMenu);
		vObj.addEvent('mouseout', eventMenu);
		if(vVisible){
			//Affichage
			$$('select').setStyle('opacity', 0);
			vCoordonnees = pElement.getCoordinates();
			vObj.setStyle('left', (vCoordonnees.left-1)+'px');
			vObj.setStyle('opacity', 0);
			vObj.setStyle('display', 'block');
			new Fx.Tween(vObj, {duration:300}).start('opacity',0,1);
		}else{
			//Masquage
			$$('select').setStyle('opacity', 1);
			vObj.setStyle('display', 'none');
		}
	}
}

/* Affichage du menu de gauche*/
function showMenuLeft(pIndex, pElement, pVisible, pName, pCoordonnees){
	vName = (pName!=null)?pName:'div_menu_left_';
	vObj = $(vName+pIndex);
	vElement = $(pElement.id);
	vVisible = pVisible;
	changeColor(vElement);
	if(vObj && vElement){

		vObj.addEvent('mouseover', eventMenu);
		vObj.addEvent('mouseout', eventMenu);	
		if(vVisible){
			vCoordonnees = vElement.getCoordinates();
			if(pCoordonnees){
				vObj.setStyle('top', pCoordonnees.y);
				vObj.setStyle('left', pCoordonnees.x+10);
			}else{
				vObj.setStyle('top', (vCoordonnees.top-1)+'px');
				vObj.setStyle('left', (vCoordonnees.left+120)+'px');
			}
			vObj.setStyle('opacity', 0);
			vObj.setStyle('display', 'block');
			new Fx.Tween(vObj, {duration:200}).start('opacity',0,1);
		}else{
			//Masquage
			vObj.setStyle('display', 'none');
		}
	}
}
/* Evenement sur le menu */
function eventMenu(pEvent){
	//event = new Event(pEvent);
	vDisplay = (vObj.getStyle('display')=='none')?'block':'none';
	vObj.setStyle('display', vDisplay);
	changeColor(vElement);
}
/* Identification */
function login(){
	var form = document.form_identification;
	var myform = new Form('document.form_identification');
	myform.addField('email', form.js_email.value, 'text');
	//myform.addField('email', form.js_email_nok.value, 'email');
	myform.addField('pass', form.js_pass.value, 'text');
	return myform.verifForm();
}
/* Deconnexion */
function deconnexion(){
	document.form_identification.submit();
}
/* Suppression d'un article */
function deleteProduct(pIndex, pId, pIdPrime, pIdPays, pIdUnite, pIdExpedition, pType, pArchive, pArchiveNum){
	var flag = confirm('Etes vous sûr de vouloir supprimer cet article ?');
	if(flag){
		//Menu de droite
		vObjDroite = $('ul_article_'+pIndex);
		if(vObjDroite){
			new Fx.Tween(vObjDroite, {duration:500}).start('opacity',1,0);
		}
		//Tableau
		vObjLigne = $('ul_article_ligne_'+pIndex);
		if(vObjLigne){
			new Fx.Tween(vObjLigne, {duration:500}).start('opacity',1,0);
		}
		vRequest = new Request ({
			url : '/ajax.php',
			data: 'id='+pId+'&prime='+pIdPrime+'&pays='+pIdPays+'&type='+pType+'&code_unite_1='+pIdUnite+'&expedition='+pIdExpedition+'&archive='+pArchive+'&archive_num='+pArchiveNum+'&cmd=product_delete',
			evalScripts	:true,
			onSuccess: completeDeleteProduct
		});
		vRequest.send();
	}
	
}
/* Fin de la suppression d'un article */
function completeDeleteProduct(pRequest){
	if(vObjDroite) vObjDroite.setStyle('display', 'none');
	if(vObjLigne) vObjLigne.setStyle('display', 'none');
	refreshInfosCommande();
	refreshInfosPanier();
}

/**Rafrachaissement des infos du panier**/
function refreshInfosPanier(){
	vRequest = new Request ({
		url : '/ajax.php',
		data: 'cmd=resfreh_panier_infos',
		evalScripts	:true,
		onSuccess: completeRefreshInfosCommande
	});
	vRequest.send();
}


/*Affichage des infos de la commande */
function refreshInfosCommande(){
	vRequest = new Request ({
		url : '/ajax.php',
		data: 'cmd=commande_infos',
		evalScripts	:true,
		onSuccess: completeRefreshInfosCommande
	});
	vRequest.send();
}

/* Fin de l'affichage des infos de la commande */
function completeRefreshInfosCommande(pRequest){
	
	//Mise a jour de la hauteur du panier
	vObj = $('div_panier');
	if(vObj){
		vObjDivs = vObj.getElements('div');
		vObjDivs.each(function(element){
			if(element.id=='' && element.className=='') {
				element.setStyle('height', 'auto');
			}
		});
	}

	vObj = $('div_panier_content_ope');
	if(vObj){
		vObjDivs = vObj.getElements('div');
		vObjDivs.each(function(element){
			if(element.id=='' && element.className=='') {
				element.setStyle('height', 'auto');
			}
		});
	}
}

/* Affichage de la prime */
function enSavoirPlusPrime(pIdPrime, pId, pType){
	vObjOverlay = $('div_overlay');
	if(vObjOverlay){
		//EFFETS
		vHeight = window.getScrollHeight()+'px';
		vObjOverlay.setStyle('width', '100%')
		vObjOverlay.setStyle('height', vHeight);
		vObjOverlay.setStyle('visibility', 'visible');
		vObjOverlay.setStyle('opacity', 0);
		new Fx.Tween(vObjOverlay, {duration:500}).start('opacity',0,0.8);
		$$('select').setStyle('opacity', 0);
		vObjCouv = $('div_couv');
		if(vObjCouv)	{
			vCoordonnees = vObjCouv.getCoordinates();
			vLeft = vCoordonnees.left;
		}
		vObjEtapes = $('ul_etapes');
		if(vObjEtapes)	{
			vCoordonnees = vObjEtapes.getCoordinates();
			vLeft = vCoordonnees.left+13;
		}
		vObjPrime = $('div_prime');
		 $('div_prime_content').innerHTML = '<div class="loading"><img src="/img/site/loading.gif" alt=""/> </div>';
		vObjPrime.setStyle('left', vLeft+'px');
		vObjPrime.setStyle('top', (window.getScrollTop()+5)+'px');
		vObjPrime.setStyle('display', 'block');		
		//Chargement du contenu
		vRequest = new Request ({
			url : '/prime.php',
			data: 'pri_id='+pIdPrime+'&id='+pId+'&type='+pType,
			evalScripts	:true,
			onSuccess: function(pData){
				$('div_prime_content').set('html', pData);
			}
		});
		vRequest.send();
	}
}

/* Fermeture de la fenetre de la prime */
function closePrime(){
	vObjOverlay = $('div_overlay');
	if(vObjOverlay){
		//EFFETS
		vObjPrime = $('div_prime');
		vObjPrime.setStyle('display', 'none');	
		new Fx.Tween(vObjOverlay, {duration:500}).start('opacity',0.8,0);
		$$('select').setStyle('opacity', 1);
	}
}

//Affichage de l'image de la prime
function showImagePrime(pElement, pImageId){
	vObj = $('image_prime');
	if(vObj){
		//Deselection
		i=1;
		vObjSelect = $('div_vignette_'+i);
		while(vObjSelect){
			vObjSelect.className = "vignette";
			vObjSelect.onmouseover = function(){changeColor(this, false)}
			vObjSelect.onmouseout = function(){changeColor(this, false)}
			vObjSelect = $('div_vignette_'+i);
			i++;
		}
		//Selection
		pElement.className = "vignette_selected";
		pElement.onmouseover = function(){changeColor(this, true)}
		pElement.onmouseout = function(){changeColor(this, true)}
		$('div_image_prime').setStyle('display', 'none');
		$('div_loading_prime').setStyle('display', 'block');
		vObj.src = "/image.php?id="+pImageId+"&path=big";
		vObj.onload = completeImagePrime;
	}
}

/* Fin du chargement de l'image de la prime */
function completeImagePrime(){
	$('div_loading_prime').setStyle('display', 'none');
	$('div_image_prime').setStyle('display', 'block');
}


/* Affichage de la prime */
function showArticle(pIdArticle){
	
	//Chargement du contenu
	var request = new Request ({
		url : '/ajax.php',
		data: 'id='+pIdArticle+'&cmd=article_infos',
		evalScripts	:true,
		onSuccess: function(data){
			var data = JSON.decode(data);
			if(data.art_type=='archive_num'){
				var url_mag_archives = data.mag_url_archives_num;
				if(url_mag_archives!='') window.location = url_mag_archives;
			}else{
				vObjOverlay = $('div_overlay');
				if(vObjOverlay){
					//EFFETS
					vHeight = window.getScrollHeight()+'px';
					vObjOverlay.setStyle('width', '100%')
					vObjOverlay.setStyle('height', vHeight);
					vObjOverlay.setStyle('visibility', 'visible');
					vObjOverlay.setStyle('opacity', 0);
					new Fx.Tween(vObjOverlay, {duration:500}).start('opacity',0,0.8);
					$$('select').setStyle('opacity', 0);
					vLeft = 0;
					vObj = $('div_middle');
					if(vObj)	{
						vCoordonnees = vObj.getCoordinates();
						vLeft = vCoordonnees.left;
					}
					vObjPrime = $('div_prime');
					
					 $('div_prime_content').innerHTML = '<div class="loading"><img src="/img/site/loading.gif" alt=""/> </div>';
					vObjPrime.setStyle('left', vLeft+'px');
					vObjPrime.setStyle('top', (window.getScrollTop()+5)+'px');
					vObjPrime.setStyle('display', 'block');		
					//Chargement du contenu
					vRequest = new Request ({
						url : '/article.php',
						data: 'id='+pIdArticle,
						evalScripts	:true,
						onSuccess: function(pData){
							completeShowArticle(pData);
							$('div_prime_content').set('html', pData);
						}
					});
					vRequest.send();
				}
				
			}
		}
	});
	request.send();
	
	
	
	
}
//Fin du chargement de l'article
function completeShowArticle(){
	vObjOverlay = $('div_overlay');
	if(vObjOverlay){
		vHeight = window.getScrollHeight()+'px';
		vObjOverlay.setStyle('height', vHeight);
	}
}
/* Ajouter au panier un article */
function addArticle(){
	vForm = $('form_article');
	vQueryString = vForm.toQueryString();
	vRequest = new Request ({
		url : '/ajax.php',
		data: vQueryString+'&cmd=commander_article',
		evalScripts	:true,
		onSuccess: completeAddArticle
	});
	vRequest.send();
	
}

/*Fin de l'ajout de l'article */
function completeAddArticle(){
	closePrime();
	window.location = "/mon-panier";
}

/* Ajouter au panier d'une offre */
function addOffre(){
	vForm = $('form_offre');
	vQueryString = vForm.toQueryString();
	vRequest = new Request ({
		url : '/ajax.php',
		data: vQueryString+'&cmd=commander_offre',
		evalScripts	:true,
		onSuccess: completeAddOffre
	});
	vRequest.send();
}

/*Fin de l'ajout de l'article */
function completeAddOffre(){
	window.location = "/mon-panier";
}

/*Vide le champ */
function clearInput(pElement, pDefaultValue){
	vValue = pElement.value
	if(vValue==pDefaultValue)	pElement.value = '';
}

function setOptionValue(element, value){
	if(element.options){
		for(i=0;i<element.options.length;i++){
			option = element.options[i];
			if(option.value==value) option.selected = true;
		}
	}
}

function getRadioValue(element){
	value = '';
	if(element.length && element.length>0){
		for(var i=0;i<element.length;i++){
			if(element[i].checked) value=element[i].value; 
		}
	}else {
		if(element.checked) value = element.value;
	}
	return value;
}

function initMenuBoutique(){
	//Menu boutique
	var vNav = $$('.navigation .boutique');
	var vMenu = $('nav_menu_boutique');
	
	if(vNav){
		var vAnchor = vNav.getElement('a');
		var flagBoutique = vAnchor.hasClass('on');
		vNav.addEvent('mouseenter', function(e){
			$('picto_triangle').set('src', 'http://www.kiosquemag.com/img/site/picto_triangle_roll.png');
			vAnchor.set('class', 'on');
			if(vMenu) vMenu.setStyle('display', 'block');
			$$('select').setStyle('opacity', 0);
		})
		vNav.addEvent('mouseleave', function(e){
			if(flagBoutique=='false' || !flagBoutique){
				vAnchor.removeClass('on');
				//this.setStyle('backgroundImage', '/img/site/bg_boutique.png');
				$('picto_triangle').set('src', 'http://www.kiosquemag.com/img/site/picto_triangle.png');
			}
			if(vMenu)  vMenu.setStyle('display', 'none');
			$$('select').setStyle('opacity', 1);
		})
	}
}

/* Archive numérique */
function archivesNumMag(pUrl){
	if(pUrl!='')	openWindow(pUrl, 'Archive', 950, 650);
}

function scrollToElement(pElement){
	var vScroll = new Fx.Scroll(window, {
		wait: false,
		duration: 500,
		offset: {'y': -20},
		transition: Fx.Transitions.Quad.easeInOut
	});
	vScroll.toElement(pElement);
}

function savePanier(page){
	var request = new Request ({
		url : '/ajax.php',
		data: 'cmd=save_panier&page='+page
	});
	request.send();
}
