var allways = {
	init: function() {
	
//		$("#fespaceclient").submit(function() {
//			var logs = find("input[type=hidden], input[type=text], input[type=password]").serializeArray();
//			
//			$.post(, logs, function (data, textStatus) {
//		        if (textStatus == "success") {
//		        	if(data)
//		        	{
//		        		data = eval('(' + data + ')');
//		        		$("#fespaceclient")
//		        	}
//		        }
//		    });
//			
//			return false;
//		});
	}
}

var home = {
	    init: function() {
			$("div#mygalone").slideView();
			
			// timer pour slide
			home.timer = window.setInterval("home.slide()", 6000);
			
			  var params = 
				{
				  width: "100%",
				  height: "100%",
				  quality: "best",
				  align: "middle",
				  play: "true",
				  loop: "true",
				  scale: "showall",
				  wmode: "normal",
				  devicefont: "false",
				  bgcolor: "#ffffff",
				  menu: "true",
				  allowFullScreen: "true",
				  allowNetworking: "all"
				};
				
			  var attributes = {};

			  swfobject.embedSWF(this.my_swfobject.swf, "swf", "100%", "100%", "8", this.my_swfobject.express_install, this.flashvars, params, attributes);
			  
			  $("a.thickbox").click(function(){
				  $("#swf").hide();
			  });
		},
		slide: function() {
			if((home.next_slide = $("#stripTransmitter0 li a.current").parent().next().find("a")) && (home.next_slide.text() == "")) home.next_slide = $("#stripTransmitter0 li:eq(1) a");
			home.next_slide.click();
		}
}

var product = {
	    init: function() {
			
		    // init the submit button for cart 
			product.configureImgsubmitformUnclick();
			
			// produit unique avec taille et couleur unique ou actualisation de page firefox
			if(this.quick_post || $("#hidden-id-pdt").val()) this.post();
			else if(this.alert_stock)
			{
				// reconstituer front taille / couleur
				jQuery.each(this.alert_stock, function(index, value){
					if(value.name == "product[couleur]") $("#couleur-product").val(value.value);
					else if(value.name == "product[taille]") $("#taille-product").val(value.value);
				});
				
				this.post();
			}
			
			//gestion paquet cadeau
	        if(!$("#box_cadeau:checked").val()) $("#comment-cadeau").hide(); 
	        
	        $("#box_cadeau").click(function(){
	        	$("#comment-cadeau").toggle();
	        });
			
			// hack swf normal
			$("a.thickbox").click(function(){
			  $("#swf").hide();
			});
			
			this.params = 
			{
			  width: "100%",
			  height: "100%",
			  quality: "best",
			  align: "middle",
			  play: "true",
			  loop: "true",
			  scale: "showall",
			  wmode: (jQuery.browser.msie) ? "transparent":"normal",
			  devicefont: "false",
			  bgcolor: "#ffffff",
			  menu: "true",
			  allowFullScreen: "true",
			  allowNetworking: "all"
			};
			
			this.attributes = {};
			
			// flocage
			if(this.swf_flag){
				$("#couleur-product").val(product.default_flocage_id);
				$(".patch-badge-checkbox :input:checkbox").attr('checked', '');
				this.initFlocage();
			}
			else $(".product-flash").hide();
			
			//gestion change image
			this.configureImageAction(".product-vignette li", ".product-fiche-img img");
			
			// gestion dimensions
			$("#couleur-product").change(function(){
				// gestion flocage joueur reel
				if(product.swf_flag)
				{
			    	// parametrage flocage reel
			    	if($("#couleur-product").val() != product.default_flocage_id)
			    	{
			    		var flocage_nom_num = $("#couleur-product option:selected").text().split('-')
			    		product.flashvars.f_name = flocage_nom_num[0] ? flocage_nom_num[0] : '';
				    	product.flashvars.f_num = flocage_nom_num[1] ? flocage_nom_num[1] : '';
			    	}
			    	else
					{
			    		$(".patch-badge-checkbox :input:checkbox").attr('checked', '');
			    		product.flashvars.f_name = product.flashvars.f_num = '';
					}
			    	
			    	product.initFlocage();
				}
				
				product.dimensionChange();
			});
			
			// gestion du click badge 
			$(".patch-badge-checkbox :input:checkbox").click(function() {
				if(error_badge = product.checkBadge()) { 
					product.errorShow("div#badge-error", error_badge);
					return false;
				}
			});
			
			$("#taille-product").change(function() {

				product.dimensionChange();
				
		    	// Gestion hack badge
		    	if(product.error_badge_exception && (error_badge = product.checkBadge())) { 
					$(".patch-badge-checkbox :input:checkbox").attr('checked', '');
		    	}
			});
	
            // select + input quantite
            $('#i_quantite').focus(function() {
                $(this).val('');
            });
            $('#i_quantite').blur(function() {
                if ($(this).val() == '') {
                	product.initQuantity();
                }
            });
            $('#i_quantite').keypress(function(evt) {
                return evt.which != 13;
            });
            
            $('#product_qty').change(function() {
            	if(!parseInt($(this).val())) {
            		$('#i_quantite').show();
            		$('#i_quantite').focus();
            	} 
            	else {
            		$('#i_quantite').hide();
            	}
            });
             // init qty process
            this.initQuantity();
            
            // limitation à la saisie sur l input message cadeau
            $('textarea#pochette-cadeau').keypress(function(evt) {
            	if($(this).val().length >= product.cadeau_max_length) return evt.which == 8 || evt.which == 0;
            });
            
            // guide des tailles
            $("#guide-des-tailles, .guidetailles-table div").css('width', '700px');
            $(".guidetailles-table table").css('width', '699px');
            $(".guide-des-tailles-button").click(function() {
            	$("#guide-des-tailles").animate({ height: 'toggle', opacity: 'toggle' }, "slow");
            	return false;
            });
            
            // button alert stock
            $('#alert-stock-email a').click(function(){
            	postdata = product.getPostData();
            	postdata.push({ name:'product[url]', value: window.location.href});
            	product.alertStock(postdata);
            	return false;
            });
	    },
	    alertStock: function(postdata)
	    {
	    	$.post(product.posturl_alertstock, postdata, function (data, status) {
                if (status == "success") {
                  if(data)
            	  {
                	  product.errorShow("div#cart-error", data.statusmessage);
                	  
                	  // redirect si log necessaire
      				  if(data.status == 1) window.location = data.redirect;
            	  }
                }
            });
	    },
	    configureImgsubmitformUnclick: function() {
	    	$("img#submit_form").unbind('click', product.imgsubmitformClick);
	    	$("img#submit_form").bind('click', function() { return false; });
	    	$("img#submit_form").show();
	    	$("img#submit_form").css('cursor', 'default');
	    	if($("img#submit_form").css('opacity') != 0.2) $("img#submit_form").animate({opacity: '0.2'}, 500);
	    },
	    configureImgsubmitformClick: function() {
	    	$("img#submit_form").bind('click', product.imgsubmitformClick);
	    	
	    	$("img#submit_form").css('cursor', 'pointer');
	    	if($("img#submit_form").css('opacity') != 1) $("img#submit_form").animate({opacity: '1'}, 500);
	    },
	    imgsubmitformClick: function() {
	    	product.configureImgsubmitformUnclick();
        	product.errorHide();
        	
        	// determine la regle de selection du champs qty
        	if(!parseInt($("#product_qty").val())) var qty_id = "#i_quantite"; // $("#product_qty").attr("disabled")
        	else var qty_id = "#product_qty";
        	
        	// gestion erreur sur (int)qty  + id_unique undefined 
        	if(!$("#hidden-id-pdt").val() || !parseInt($(qty_id).val())) { product.errorShow("div#cart-error", product.error); product.init(); return false; }
        	
            // get the for input hidden and select values
            var postdata = $(document).find("#product-form :input[type=hidden], #product-form "+ qty_id).serializeArray(); // , #couleur-product, #taille-product

            //cadeau
            if($("#product-form input#box_cadeau").attr('checked'))
            {
            	if($("textarea#pochette-cadeau").val().length >= product.cadeau_max_length) { product.errorShow("div#cadeau-error", product.cadeau_max_length +' '+product.cadeau_error); return false; }
            	postdata.push($("textarea#pochette-cadeau").serializeArray()[0]); //postdata.push({ name:var_name, value :  var_val });
            }
            
        	//badge
           	if($(".patch-badge-checkbox :input:checkbox").attr('checked')) postdata.push({ name:'product[badge]', value :  1 });
            
            // post the data via AJAX post
            $.post(product.posturl_cart, postdata, function (data, textStatus) {
                if (textStatus == "success") {
                    if (data)
                    {
                    	// gestion no qty
                    	if(data['cart-error']) { 
                    		product.errorShow("div#cart-error", data['cart-error']);
                    		product.init();
                    		return false;
                    	}
                    	
                    	$("#panier-article-count").text(parseInt(data['qty']));
                    	$("#panier-article-cart-price").text(data['cart_price']);
                    	
                    	$("#swf").hide();
                    	
                    	// launch thickbox
                    	var t = product.lightbox_addcart_title +" !";
                    	var a = product.lightbox_addcart +"/cartline/"+ data['cartline'] +"/?height=155&width=380";
                    	var g = false;
                    	
                    	tb_show(t,a,g);
                    	
                    	product.configureImgsubmitformClick();
                    }
                    
                    return false;
                }
            });
            
            return false;
        },
		configureImageAction: function(button, image) {
	    	// disable link
	    	$(button).click(function() { return false; });

	    	$(button).mouseover(function(){
				if($(this).hasClass('noselected'))
				{
					var img_src = product.media_slide[$(this).find("a").attr('href')].src;
					
					$(image).stop(true).fadeTo(0, 0.5).attr('src', img_src).fadeTo(500, 1);
					$(this).siblings().removeClass("selected").addClass("noselected");
					$(this).removeClass("noselected").addClass("selected");
				}
				
				return false;
			});
		},
	    initQuantity: function() {
	    	$('#product_qty').val('1');
            $('#product_qty').change();
	    },
	    initFlocage: function() {
	    	$("input#hidden-name-flocage").val(product.flashvars.f_name);
			$("input#hidden-num-flocage").val(product.flashvars.f_num);
			
			swfobject.embedSWF(product.my_swfobject.swf, "swf", "100%", "100%", "8", product.my_swfobject.express_install, product.flashvars, product.params, product.attributes);
	    },
	    dimensionChange: function() {
	    	product.configureImgsubmitformUnclick();
	    	product.errorHide();
	    	
	    	// controle sur les attributs avant post
			if(($("#taille-product").length && !$("#taille-product").val()) || ($("#couleur-product").length && !$("#couleur-product").val()))
			{
				$("#hidden-id-pdt").val('');
				return;
			}
			
	    	product.post();
	    },
	    getPostData : function() {
	    	postdata = $(document).find("#hidden-product_id, #taille-product, #couleur-product").serializeArray();
	    	if(product.unique_color_id != '') postdata.push({ name:'product[couleur]', value:product.unique_color_id});
	    	return postdata;
	    },
		post: function()
		{	    	
			var postdata = product.getPostData();

			$.post(product.posturl_control, postdata, function (data, textStatus) {
	            if (textStatus == "success") {
	            	if(data)
	            	{
	            		if(data["id"])
	            		{
	            			$("div#product-dispo-state").hide().text(data["dispo_view"]).fadeIn(1000);
	            			$("#big-price").text(data["big_price"]);
	            			$("#small-price").text(','+data["small_price"]);
	            			
	            			if(data["dispo_state"] >= 0)
	            			{
	            				// toggle css dispo
	            				$("div#product-dispo-state").removeClass('redweight_dispo').addClass('greenweight_dispo');
	            				$('div#alert-stock-email').hide();
	            				
		            			$("#hidden-id-pdt").val(data["id"]);
		            			$("#hidden-price-pdt").val(data["big_price"]+'.'+data["small_price"]);
		            			$("#hidden-fees-pdt").val(data["fees"]);
		            			
		            			product.configureImgsubmitformClick();
	            			}
	            			else 
	            			{
	            				// toggle css dispo
	            				$("div#product-dispo-state").removeClass('greenweight_dispo').addClass('redweight_dispo');
	            			}
	            		}
	            		// si pas d id no stock
	            		else {
	            			$("div#product-dispo-state").removeClass('greenweight_dispo').addClass('redweight_dispo');
	            			$("div#product-dispo-state").hide().text(data["dispo_view"]).fadeIn(1000);
	            		}

	            		// alert stock system on no available product
	            		if(data["dispo_state"] < 0)
            			{
	        				if(!product.alert_stock) $('div#alert-stock-email').fadeIn(1000);
	        				else
	    					{	// auto launch
	        					// for just one call
	        					postdata = product.alert_stock;
	        					delete product.alert_stock;
	        					product.alertStock(postdata);
	    					}
            			}
	            	}
	            }
	        });

	    },
	    // appel flash: popule les hidden
	    valid: function(nom, numero) {
	    	product.errorHide();

			product.flashvars.f_name = product.flashvars.f_num = '';
	    	// with persistant system
	    	if(nom) product.flashvars.f_name = nom; 
	    	if(numero != undefined) product.flashvars.f_num = numero;
	    	
	    	$("input#hidden-name-flocage").val(product.flashvars.f_name);
	    	$("input#hidden-num-flocage").val(product.flashvars.f_num);
	    	product.initFlocage();
	    	
	    	// init dimension flocage joueur
	    	$("#couleur-product").val(product.default_flocage_id);
	    	if(product.checkBadge()) $(".patch-badge-checkbox :input:checkbox").attr('checked', '');
	    	
	    	product.dimensionChange();
	    },
	    // gestion retour message erreur en fonction du type d erreur
	    checkBadge: function () {
	    	// hack pour filtrer les tailles sur les maillots enfants flocable (badgeable)
	    	
	    	if($("input#hidden-name-flocage").val() == '' && $("input#hidden-num-flocage").val() == '') { 
	    		if(product.error_badge_exception && $("#taille-product").val() != 'L' && $("#taille-product").val() != 'XL') {
		    		return product.error_badge_exception[0];
		    	}
	    		
	    		return product.error_badge;
			} 
	    	else if(product.error_badge_exception && $("#taille-product").val() != 'L' && $("#taille-product").val() != 'XL') {
	    		return product.error_badge_exception[1];
	    	}
	    	
	    	return false;
	    },
	    errorShow: function(jmarker, msg) {
	    	product.errorHide();
	    	$(jmarker).text(msg).fadeIn(1000);
	    },
	    errorHide: function() {
	    	$("div#cart-error, div#cadeau-error, div#badge-error,").hide();
	    }
}

var cart = {
	clickvalid: 1,
	init: function() {
		$(".select").change(function(){
			
			var a_line = $(this).attr('id').split('_');
			var postdata = "line="+a_line[1]+"&qty="+$(this).val();
			$.post(cart.posturl_addqty, postdata, function (data, textStatus) {
	            if (textStatus == "success") {
	            	window.location = cart.url;
	            }
	        });
		});
		
		$("a.valider").click(function() {
			if(!$(".condition-panier-checkbox input:checkbox:checked").val()){
				$(".condition-panier").fadeOut(50).fadeIn(500);
				cart.clickvalid = 1;
				
				return false;
			}
			// check only one valid click
			if(--cart.clickvalid < 0) return false;
		});
		
		$('a.view-cartline-attribute').click(this.toggleAttribute);
	},
	toggleAttribute: function() {
		var text = $(this).text(); 
		$(this).next().animate({ height: 'toggle', opacity: 'toggle' }, "slow");
		$(this).find('b').text(((text[0] == '+') ? '-' : '+') + text.substr(1));
		
		return false;
	}
}

var sendToFriend = {
    submit: function() {
        var formdata = $('.sendtofriend-form-field').serializeArray();
	    // post the data via AJAX post
	    $.post($('#sendToFriendForm').attr('action'), formdata, function (data, textStatus) {
            if (data == 'error') {
                $('#error-bloc').show(); 
            } else {
                $('#lightbox-form').hide();
                $('#lightbox-success').show();
            }
	    });
    }
}
