/**
 * Wizzmedia Store Script
 * @copyright Wizzmedia (c) 2011
 * @class
 */
var wss = {};
wss = {
 	// Identifiant de la page
 	_pageRef: null,
 	// Identifiant du client
 	_clientId: null,
 	// Statut du Client
 	_userStatus: "guest",
 	
 	controller: {
 		objects: {}
 	}, 	
 	// Utilisé par les extensions (s'achitecture autour de wss.path.ajax)
	model: {
		objects: {},
	
		from_map: function(dataMap) {
			wss.log('not implemented');
		},
		to_map: function(model) {
			wss.log('not implemented');
		},
		
		// Fonction de recherche inspiré par Active record
		find: function(model, columns, search) {
			wss.log('not implemented');
		},
		
		// Faire persister localement le model
		persist: function(model, system) {
			wss.log('not implemented');
		},
		
		// Sync
		sync: function(model, with_persist) {
			wss.log('not implemented');
		}
		
	},
	// Template intelligent (utilisation efficace du cache)
	template: {},
	
 	path: {
 		base: null,
 		img: null,
 		ajax: 'ajax/'
 	},
 	browser: {
 		msie: $.browser.msie,
 		webkit: $.browser.webkit,
 		firefox: $.browser.firefox,
 		iphone: null,
 		ipod: null,
 		ipad: null,
 		
 		fetch : function() {
 			if(navigator.userAgent.match(/iPhone/i)) wss.browser.iphone = true;
 			else wss.browser.iphone = false;
 			
 			if(navigator.userAgent.match(/iPod/i)) wss.browser.ipod = true;
 			else wss.browser.ipod = false;
 			
 			if(navigator.userAgent.match(/iPad/i)) wss.browser.ipad = true;
 			else wss.browser.ipad = false;
 		}/*,
 		
 		//support: window.Modernizr*/
 	},
 	get_path : function(scope) {
 		if(wss.path[scope] !== null) return wss.path[scope];
 		else return undefined;
 	},
 	log: function (message, only_error) {
 	    if (wss.logging !== undefined && only_error !== false) {
 	        if (window.Debug && window.Debug.writeln) {
 	            window.Debug.writeln(message);
 	        } else if (window.console) {
 	        	window.console.log(message);
 	        }
 	    }
 	     
 	    //if(wss.Error !== undefined) wss.Error.send(message);
 	},
 	compatibility: function(browser, callback) {
 		// Adaptation du site pour les iPhone
 		if( wss.browser.iphone ) {
 			$('.compatible-tel').each(function() {$(this).wrap('<a href="tel:' + $(this).text() + '">');});			
 		}
 	},
 	
 	init: function(obj) {
 		$.each(obj, function(name, value) { 			
 			wss[name] = value;
 		});
 		
 		if(GLOBAL_img_url) wss.path.img = GLOBAL_img_url;
 		if(GLOBAL_base_url) wss.path.base = GLOBAL_base_url;
 		if(GLOBAL_ajax_dir) wss.path.ajax = GLOBAL_ajax_dir;
 		if(GLOBAL_page_name) wss._pageRef = GLOBAL_page_name;
 	 		
 		wss.browser.fetch();
 		wss.compatibility();
 	},
 	
 	extend: function(type, name, objFn) {
 		$.publish("core.extend");
 		if(type == "controller") {
 			var objCreated = {
 				name : name,
 				map : undefined,
 				attach: function(type, name, obj) {
 					if(type == "extension") {
 						// Validation de l'objet
 						if(typeof(obj) !== "object") throw ('La définition de l\'objet est obligatoire');
 						else {
 							// Objet jQuery auquel est rattaché l'extension
 							if(obj.el === undefined) throw ('obj.el doit être définit avec un objet jQuery');

 							if(obj.follow !== undefined) {
 								$.each(obj.follow, function(idx, v) {
 									//wss.log(obj.el);
 									
 									//if(/$/.test(v[0])) obj.el.v[0].replace('$.', '')(v[1]);
 									//else {
	 									if(/\./.test(v[0]) === false) $.subscribe(objCreated.name + "." + v[0], obj[v[1]]);
	 									else $.subscribe(v[0], v[1]);
	 								//}
 								});
 							}
 							if(obj.model) { // on utilise pas cette méthode pour l'instant mais très utile 
 								wss.model[name] = obj.model,
 								obj.model_ref = obj.model.name
 							}
 							
 							// Devrait être un pseudo template et idéalement transformer de façon invisible un dataMap en Model
 							else if (obj.dataMap) {
 								// TO DO permettre quelques chose comme ça "productData./current.size/.price" par exemple
 								evalued = eval(obj.dataMap);
 								obj.data = evalued;
 								delete(obj.dataMap);
 							}
 							
 							
 							
 							if(obj.publish !== undefined) {
 								// format => jQueryEventName : [topic, customBind]
 								$.each(obj.publish, function(idx) {
 									if(this[1] === undefined) {
 										var parent = this;
 										obj.el.bind(idx, function() {
 											$.publish(objCreated.name + "." + parent[0]);
 										});
 									} else {
 										// TO DO : Créer des évenements.
 									}
 								});
 							}
 							
 							// Méthodes disponible
 							//obj.init <-- doit être définie dans l'objet
 											
 						}
 						this[name] = obj;
 						if(obj.init && typeof(obj.init) == "function") obj.init();
 						
 					} else throw ('Seulement des extensions peuvent être ajouté');
 				}
 			}
 			
 			if(objFn && typeof(objFn) == "function") objFn(objCreated);
 			
 			objCreated.map = "wss." + type + "." + name;
 			wss[type]['objects'][name] = objCreated;
 			return objCreated;
 		}
 	},
 	
 	error: function(message) {
 		var message = this.message;
 		if(wss.error === true) {
	 		return {
	 			send: function() {
	 			},
	 			
	 			display: function() {	
	 			}
	 		}
 		} else {
			return undefined;
		}
 	},
 	helper: {
 		repeat: function(times, data) {
 			var toReturn = "";
 			for(var i=0; i<times; i++) {
 				toReturn += data;
 			}
 			return toReturn;
 		}
 	},
 	
 	
 	// Méthodes associées au PHP
 	hide_after: function(that, time) {
		$(that).delay(time).fadeOut('slow');
	},
	
	flash_message: function(type, message, time, append) {
		if(append == undefined) append = ".flash_message_block";
		this.log($(append).find('.flash_message').length == 0);
		if($(append).find('.flash_message').length == 0) {
			$(append).html('<div class="flash_message flash_message_' + type + '" ' + (time ? 'onload="wss.hide_after(this, ' + time + ') "' : ' ') +'>' + message + '</div>');
			this.log('sho');	
		}
		else {
			$(append).fadeOut();
			$(append).html('<div class="flash_message flash_message_' + type + '" ' + (time ? 'onload="wss.hide_after(this, ' + time + ') "' : ' ') +'>' + message + '</div>').fadeIn();
		}
	}
 	
 	
 }
 
 
 
$.fn.blink = function(options)
{
	var defaults = { delay:500 };
	var options = $.extend(defaults, options);
	
	return this.each(function()
	{
		var obj = $(this);
		setInterval(function()
		{
			if($(obj).css("visibility") == "visible")
			{
				$(obj).css('visibility','hidden');
			}
			else
			{
				$(obj).css('visibility','visible');
			}
		}, options.delay);
	});
}

 
 
 wss.action = {
 	placeholderReplace : function(that, defaults) {
 		if($(that).attr('value') == defaults) {
 			$(that).css('color', '#777').val('');
 		}
 	},
 	placeholderRestore : function(that, defaults) {
 		if($(that).attr('value') == "") {
 			$(that).css('color', '#BBB').val(defaults);
 		}
 	}
 
 };
 
$(document).ready(function() {

	//Kill des filtres enregistrés en session quand on clique sur le menu
	$('.nav a').click( function(){
		$.post(GLOBAL_ajax_dir + 'unset_filters_session.php', {}, function(){});
	});
	
	// $('.show-fake').css('visibility', 'hidden');
	setTimeout( function(){	
		$('.show-fake').css('visibility','visible');
		$('.coda-slider-wrapper').css('visibility','visible');
	}, 1200);
	
	$('.eval').rating({
		'readOnly' 	:true,
		'half'		:true,
		'starWidth'	: 16
	});

	$('.eval-little').rating({
		'readOnly' 	:true,
		'half'		:true,
		'starWidth'	: 12,
		'little' : true
	});
	
	// Action Dynamique (lié au pub/sub)
	$.subscribe('core.extend', function() {
		wss.log('reload core');
		wss.browser.fetch();
		wss.compatibility();
	});
	
	
	/*/// Affichage du message pour toutes les rechargemen
	$('input[name="view-mode"]').ajaxStart(function() {
	  $.facebox('<h1 style="font: italic 16px Georgia, serif;font-weight: normal;color: #444;margin-bottom: 10px;">Chargement en cours...</h1><p style="color:#999">Veuillez patienter quelques instants.</p>');
	});
	
	$('input[name="view-mode"]').ajaxStop(function(event) {
		$.facebox.close();
	});
	*/
	
	
	

	// $('.add-loader').each( function(){
		// var loader = '<div class="loader" style="height:'+$(this).height()+'px;width:'+$(this).width()+'px"></div>';
		// $(loader).insertBefore(this);
		// $(this).hide();
		// setTimeout( function(){
			// $('.add-loader').fadeIn(500, function(){
				// $('.loader').fadeOut(700);
			// });
		// }, 1500);
	// });

	//Vérification des formulaires en ajax
	$('input').live('blur', function(){
		if(!$(this).hasClass('no-valid-onblur'))
		{
			validInput( $(this) );
		}
	});

	$('.wsslink-account').click(function(){
		if(!$(this).hasClass('open')) $(this).addClass('open').parents('menu').find('.hidden').show('fast');
		else $(this).removeClass('open').parents('menu').find('.hidden').hide('fast');
	});
	
	var mdpo_status = "identification";
	
	$('.resetpwd-access').click(function() {
		mdpo_status == "reset_password";
		$('.login, .subnewsletter').hide();
		$('.resetpwd').show();
	});
	
	$('.login-access').click(function() {
		mdpo_status = "identification";
		$('.resetpwd, .subnewsletter').hide();
		$('.login').show();
	});
	
	//Inscription à la newsletter
	$('.subnewsletter-access').click(function() {
		$('.resetpwd, .login').hide();
		$('.subnewsletter').show();
	});
	
	$('.form-newsletter').submit( function(){
		var newsletter_form = $(this);
		
		if(!validForm(newsletter_form)) return false;
		
		var mail = $('.newsletter-mail', newsletter_form).val();
		$.post(GLOBAL_ajax_dir + 'account/suscribe_newsletter.php', {mail : mail}, function(error){
			if(error) {
				 $('.ERROR', newsletter_form).css('color', 'red').html(error).show();
			}else{
				$('.ERROR', newsletter_form).css('color', 'green').html('Votre inscription à notre newsletter a bien été prise en compte').show();
			}
		});
		return false;
	});
	
	$('.login .valider').click( function(event){
		event.preventDefault();
	        if(mdpo_status == "identification") {
	            var login_form = $(this).parents('form');
	            if( validForm(login_form) )
	            {
	                $('.ERROR', login_form).hide();
	                
	                params = login_form.serialize();
	                $.post(GLOBAL_ajax_dir + 'account/login.php', params, function(error){
	                    if(error){
	                        $('.ERROR', login_form).html(error).show();
	                    }else{
	                        window.location.href = GLOBAL_base_url + 'mon-compte/';
	                    }
	                });
	            }
	        } else if(mdpo_status == "reset_password") {
	            // Reset Password
	            wss.log('Reset du Password');
	        }
			return false;
	    });
	
	$('.resetpwd .valider').click( function(){
		if( validForm( $('.resetpwd') ) )
	    {
			var email = $('#resetpwd_mail').val();
			$.post(GLOBAL_ajax_dir + 'account/reset_password.php', {email : email}, function(error){
				if(error)
				{
					$('.resetpwd .error').html(error).fadeIn();
				}else{
					$('.resetpwd .error').html('Votre nouveau mot passe vous à été envoyé par mail').css('color', 'green').fadeIn();
				}
			});
		}
	});
	
	// Menu V2
	var menu = wss.extend('controller', 'menu', function(that){
		that.el = $('div.nav ul.first.level li'); //nav[role="menu"]
		that.attach('extension', 'submenu', {
			el: $('div.subnav')
		});
	
		that.el.hover(function(event) {
				var proxy_this = $(this);
				event.stopPropagation();
				if(!that.displayed) {
					that.globaltimer = window.setTimeout(function() {
						current = proxy_this.find('.subnav')
						current.show();
						current.find('div.category li:first a').trigger('mouseenter');
						if(current.find('div.category').length == 0) {
							current.find('subsubnav').show();
						}
						that.displayed = true;
					}, 250);
				}
			},
			function(event) {
				event.stopPropagation();
				$(this).find('.subnav').hide();
				that.displayed = false;
				clearTimeout(that.globaltimer);
				delete(that.globaltimer);
		});
		
		$('.subnav > div:not(.subnav-description) li').mouseenter(function() {
			$('.subnav-description ul li div.shown').removeClass('shown').parent("li").hide();
			if($(this).parents('.subnavgroup')) {
				var c = $(this).parents('.subsubnav').index();
				if(c >= 0) $(this).parents('.subnav').find('div.category ul li:eq('+ c +') a ').addClass('selected')
			}
			$('.subnav-description ul li div.nav-ref-' + $(this).attr('class')).addClass('shown').parent("li").show();
		});
	
		
		$('.subnav div.category li').mouseenter(function() {
			$(this).parents('.category').find('a.selected').removeClass('selected');
			$parent = $(this).parents('.subnav');
			if(!$parent.hasClass('always-display')) $('.subsubnav.shown', $parent).removeClass('shown').hide();
			$('.subsubnav', $parent).addClass('shown').eq($(this).index()).show();
		
		});
		
	});
});

$(window).load(function() {
	var size = 0;var count;
	$('.avantages .inner li').each(function() {
		size += $(this).outerWidth();
		count++;
	});
	$('.avantages .inner').width(size);
	
});

function addToCart(id_product, quantity, id_pack)
{
	
	if(jQuery.facebox) $.publish('cart:add');
	$.post(GLOBAL_ajax_dir + 'cart/addProduct.php', {id_product: id_product, quantity: quantity, id_pack : id_pack}, function(){
		document.location.href = GLOBAL_base_url + 'panier.html';
		wss.log('product added to Cart');
	});
}

function updateHTMLCart(id_cart)
{
	$.post( module_ajax_dir + 'updateHTMLCart.php', {id_cart: id_cart}, function(html){
		$('section#cart_products').html( html );
	});
}

