function Basculer (id) {
    var display = document.getElementById(id).style.display
    if (display == "none" || display == '') {
        document.getElementById(id).style.display = "block"
    }
    else {
        document.getElementById(id).style.display = "none"
    }

}
function isArray (obj) {
	return obj.constructor == Array;
}
function ToggleEnabled (param) {
	if (isArray(param)) { //Fonction custom
		for (i in param) {
			var disabled = 'document.forms.formulaire.'+param[i]+'.disabled';
			if (eval(disabled)) { //On réactive
				var enable = disabled+'=false';
				eval (enable);
			}
			else { //On désactive
				var disable = disabled+'=true';
				eval (disable);
			}
		}
	}
	else {
		console.log ('string');
	}
}
function addFile(count, parent, prefix) {
        var parent = document.getElementById(parent);
        document.getElementById(count).value++;
        var newFile = document.createElement('input');

        newFile.id = prefix + parseInt(document.getElementById(count).value);
        newFile.name = prefix + parseInt(document.getElementById(count).value);
        newFile.type = "file";

        parent.appendChild(newFile);
}
function addSelect(count, parent, prefix, values) {
        var parent = document.getElementById(parent);
        document.getElementById(count).value++;
        var newSelect = document.createElement('select');

        newSelect.id = prefix + parseInt(document.getElementById(count).value);
        newSelect.name = prefix + parseInt(document.getElementById(count).value);

		//Ajout des options
		var tmp = values.split(',');
		for(i=0;i<tmp.length;i++) {
			var valeurs = tmp[i].split('=');
			newSelect.options[newSelect.options.length] = new Option(valeurs[1],valeurs[0]);
		}

        parent.appendChild(newSelect);
}
function addInput(count, parent, prefix, type) {
        var parent = document.getElementById(parent);
        document.getElementById(count).value++;
        var newInput = document.createElement('input');

        newInput.id = prefix + parseInt(document.getElementById(count).value);
        newInput.name = prefix + parseInt(document.getElementById(count).value);
		newInput.type = type;

        parent.appendChild(newInput);
}

function addUnites (count, parent, prefix) {
	var parentSrc = document.getElementById(parent);
	addInput(count, parent, prefix, 'text');
	parentSrc.innerHTML += ' à ';
	addInput(count, parent, prefix, 'text');
}

function groupNames(form){
	var n=0;
	var hashNames={};
	while(document.forms[form].elements[n]){
		if(!hashNames[document.forms[form].elements[n].name]){
			hashNames[document.forms[form].elements[n].name]=1
			}
		else{
			hashNames[document.forms[form].elements[n].name]++
		}
		n++;
	}
	return hashNames;
}

function SendAjaxForm(form){
	var ScanNames=groupNames(form)
	var Params='';
	regEnd=/\[\]jQuery/;
	for (EltName in ScanNames){
		switch (true){
			case(regEnd.test(EltName)):for (i=0;i<ScanNames[EltName];i++){
				Params+="&"+EltName+"="+document.getElementsByName(EltName)[i].value;
			}
			break;
			case(document.getElementsByName(EltName)[0].type=='radio' || document.getElementsByName(EltName)[0].type=='checkbox'):
				for (i=0;i<ScanNames[EltName];i++){
					if (document.getElementsByName(EltName)[i].checked){
						Params+="&"+EltName+"="+document.getElementsByName(EltName)[i].value;
					}
				}
				break;
			case(document.getElementsByName(EltName)[0].tagName.toLowerCase()=='select' && document.getElementsByName(EltName)[0].multiple==true):
				for (i=0;document.getElementsByName(EltName)[0].options[i];i++){
					if(document.getElementsByName(EltName)[0].options[i].selected){
						Params+="&"+EltName+"="+document.getElementsByName(EltName)[0].options[i].value;
					}
				}
				break;
			default:Params+="&"+EltName+"="+document.getElementsByName(EltName)[0].value;

		}
	}
	Params=Params.replace(/^&/,"")
	return Params;
}

function parseXML(contenu){
	var xmlDoc;
	if(jQuery.browser.msie){
		alert ('IE !');
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(contenu);
	}
	else{
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(contenu,"text/xml");
	}
	return xmlDoc;
}
/********* JQUERY *********/
function DesactiverForm () {
	jQuery(':input').attr('disabled', 'disabled')
}
function BasculerDescTechnique () {
	Basculer('desc-technique');
	Basculer('desc-produit');
	if (jQuery('#desc-produit').css('display') == 'none') {
		jQuery('#ensavoirplus').children('a').html('Voir la description du produit');
	}
	else {
		jQuery('#ensavoirplus').children('a').html('Voir la description technique');
	}
}

this.popup_rollover_jsfn = function () {
	/* CONFIG */
		xOffset = 90;
		yOffset = 15;
	/* END CONFIG */
	jQuery(".popinfo").click(function(){return false}); //On empeche le clic
	jQuery(".popinfo").hover(function(e){
		var HTML = '<img src="'+this.href+'" alt=""/>';
		jQuery("body").append("<div id='popup_rollover_img'>"+ HTML +"</div>");
		jQuery("#popup_rollover_img")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function(){
		jQuery("#popup_rollover_img").remove();
    });
	jQuery(".popinfo").mousemove(function(e){
		jQuery("#popup_rollover_img")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
}

//Menu dynamique catégories
this.menuDynamique = function () {
	jQuery(".noeud").hover(function() {
		if (jQuery(this).children("ul").hasClass('categorie')) {
			//Quand la souris entre
			jQuery(this).children("ul").css("display", "block");
			var cur_top = jQuery(this).children("a").position().top;
			if (jQuery(this).children("ul").hasClass('categorie')) {
				//cur_top += 30;
			}
			//jQuery(this).children("ul").css("top", cur_top + "px");
		}
	},
	function () {
		if (jQuery(this).children("ul").hasClass('categorie')) {
			//Quand la souris sort
			jQuery(this).children("ul").css("display", "none");
		}
	});
};

/**
 * Cache les descriptions
 */
function hideProdTabs() {
	$('#fiche-produit #description > div').each(function(){
		$(this).hide();
	});
}
//Gestion des images supplémentaires fiche produit
/*this.changePhoto = function () {
	jQuery("#photos-supplementaires").children("img").click(function () {
		//On change un peu le src
		var src220 = this.src.replace('/140/', '/220/', 'i');
		var srcgrande = this.src.replace('/140/', '/grandes/', 'i');
		jQuery("#photo").attr('src', src220);
		jQuery("#photo_maxi_lien").attr('href', srcgrande);
	});
}*/

// On charge les fonctions quand la page est prête
$(document).ready(function(){
	$('.showCalendar').datepicker({
		changeMonth: true,
		changeYear: true,
		yearRange: '-80:+0'
	});
	popup_rollover_jsfn();
	//menuDynamique();
	//changePhoto();

	//Onglets fiche produit
	$('.action.envoyer-ami').click(function(){
		hideProdTabs();
		$('#tab_fleche').animate({left: '388px'});
		$('.tab.envoyer-ami').show();
	});
	$('.action.questions').click(function(){
		hideProdTabs();
		$('#tab_fleche').animate({left: '354px'});
		$('.tab.questions').show();
	});
	$('#fiche-produit .desc-titre').click(function(){
		var match = $(this).attr('id').match(/desc-titre-([0-9]+)/);
		var id = match[1];

		var pos = $(this).position();
		var width = $(this).width();
		
		var next_x = pos.left + (width / 2);
		
		$('#tab_fleche').animate({left: next_x+'px'});
		hideProdTabs();
		$('#desc-contenu-'+id).show();
	});

	// Plus et moins de la page produit
	$('#commander #produit_plus_panier').click(function() {
		var value = $('#commander #input-qtt').val();
		$('#commander #input-qtt').val(parseInt(value) + 1);
	});
	$('#commander #produit_moins_panier').click(function() {
		var value = $('#commander #input-qtt').val();
		if(value != 1) {
			$('#commander #input-qtt').val(parseInt(value) - 1);
		}
	});

	//Ajout panier
	var $dialog = $('<div></div>')
		.html('The item has been added to your cart')
		.dialog({
			autoOpen: false,
			resizable: false,
			height:80,
			modal: true,
			title: ""
		});
	$('#bouton-commander, .add_to_cart_submit').click(function(){
		var id = $(this).parents('form').find('#id-article').val();
		$.post("/ressources/commande/ajax.php", {
			action: 'cart',
			return_page: $('#current_page').val(),
			form: getForm('formarticle'+id)
		}, function(r){
			if (r['code'] == 1) {
				$('#panier_popup .in').html(r['panier_html']);
				$('#panier-popup-qtte').html(r['nbr_articles']);
				$dialog.dialog( "option", "title", r['produit'] );
				$dialog.dialog('open');
				$('.ui-widget-overlay').remove();
				var timer=setInterval(function(){
					$('.ui-dialog').fadeOut('normal', function(){
						$dialog.dialog('close');
					});
					clearInterval(timer)
				}, 4000)
			}
		}, 'json');
		return false;
	});
        var recherche_is_clicked = false;
        $('input.input_recherche_js').click(function() {
            if(recherche_is_clicked == false) {
                $(this).val('');
            }
            recherche_is_clicked = true;
        });
        $('input.input_recherche_js').blur(function() {
            if($(this).val() == '') {
                $(this).val('Finden');
                recherche_is_clicked = false;
            }
        });
});

// COMMANDE
$(document).ready(function(){
	$('#panier .une_adresse input').change(function(){
		if ($(this).attr('checked') == true) {
			var capture = $(this).attr('id').match(/adrr([0-9]+)/);
			var id = capture[1];
			$.post('../ressources/commande/ajax.php', {
				action: 'getChoixFDP',
				liv_id : id
			}, function(r){
				$('#choix-livraison').html(r);
				$("#choix-liv-date").removeClass('hasDatepicker');
				initCmdDatePicker();
			}, 'html');
		}
	});
	initCmdDatePicker();

	$('.choix-liv label input').live('click', function(){
		var parent = $(this).parents('.choix-liv');
		var options = $('.choix-liv .options');
		var myoption = $(this).parents('.choix-liv').find('.options');
		options.each(function(){
			if ($(this).parents('.choix-liv').attr('id') != parent.attr('id')) {
				options.hide("fast");
			}
		});
		
		if ($(this).is(':checked') == true) {
			if (myoption.is(':visible') == false) myoption.show("fast");
		}
	});
});

function initCmdDatePicker() {
	$("#choix-liv-date").attr("readonly", "readonly");
	$("#choix-liv-date").datepicker({
		minDate : '+1d',
		beforeShowDay: function(date) {
			var day = date.getDay();
			return [(day != 1 && day != 0)];
		}
	});
}
function canProceedShipping() {
	var error=false;
	if ($('#choix-livraison input[name=choix-livraison]:checked').val() == undefined) {
		error = true;
		alert("You have to choose a delivery method");
	}
	if ($('#choix-livraison input[name=choix-livraison]:checked').val() == 2) { //Express
		if ($('#choix-liv-date').val() == undefined || $('#choix-liv-date').val() == "") {
			error = true;
			alert("Please choose when you want your delivery")
		}
		if ($('#choix-liv-horaire').val() == undefined || $('#choix-liv-horaire').val() == "") {
			error = true;
			alert("Please choose the time");
		}
	}
	if (error == true) {
		return false;
	}
	else {
		return true;
	}
}

function getForm(id) {
	var form = new Object();
	var name;
	var i;
	$('#'+ id +' input, textarea, select').each(function(){
		if ($(this).attr('type') == 'radio') {
			if ($(this).attr('checked') == true) {
				form[$(this).attr('name')] = $(this).val();
			}
		}
		else if ($(this).attr('name').match(/\[\]/)) {
			name = $(this).attr('name').replace(/\[\]/, '');
			if (form[name] == undefined) form[name] = new Object();
			i = countProperties(form[name])
			form[name][i] = $(this).val();
		}
		else {
			form[$(this).attr('name')] = $(this).val();
		}

	});
	return JSON.encode(form);
}
/******** //JQUERY ********/

