var Plyce = {};

Plyce.pageType = '';

Plyce.Config = {
	Routes : {
		Alert : '/alertes',
		AlertBrandFilter : '/alert/filter',
		AlertGetSelected: '/alert/getselected',
		AlertSaveBrand : '/alert/savebrand',
		AlertDeleteBrand : '/alert/deletebrand',
		AlertSaveCategory : '/alert/savecategory',
		AlertDeleteCategory : '/alert/deletecategory',
		AlertSubscribe : '/alerte/inscription',
		AlertMultiSubscribe : '/alert/inscription-multiple-alertes',
		BrandIcon : 'http://static.plyce.fr/france/image/enseigne/logo/%picIcon%-50x50.png',
		CitySearch : '/villes/recherche',
		CityUpdate : '/ville/changer',
		GlobalSearch : '/globalSearch',
		MapBrand : '/map/brand/ajax',
		MapBrandIcon : '/map/brand/icon/ajax',
		MapCategory : '/map/category/ajax',
		MapOffer : '/map/offer/ajax',
		MapStoreInfo : '/map/info/store/ajax',
		MapStoresInfo : '/map/info/stores/ajax',
		MapListCategory: '/map/list-category/ajax',
		OfferView : '/bon-plan-details',
		OfferShare : '/share-email',
		OfferSend : '/send-email',
		CouponPrint : '/coupon/print/idOffer',
		StoreGetNearestForOffer: '/store/get-nearest-for-offer',
		StoreView : '/magasins-details',
		WebsiteBundleImages : '/bundles/plycewebsite/images/',
		AuthenticateWithFb : '/mon-compte/authentification',
		Home : '/',
		UserSocial : 'http://www.plyce.fr/mon-compte/mes-reseaux-sociaux',
		UserSignupValidFB : '/mon-compte/inscription-facebook/terminee',
		UserSignupValidAlertFB : '/mon-compte/inscription-alerte-facebook/terminee',
		UserSignupValidAlert : '/mon-compte/inscription-alerte/terminee',
		CheckEmailRegister : '/user/checkEmail',
		UserLogin : '/user/login',
		UserLinkFb : '/mon-compte/linkFb',
		UserUnlinkFb: '/mon-compte/unlinkFb',
		MobileDl: '/application-mobile-email',
		LightboxChangePassword: '/mon-compte/inscription/changer-mes-infos',
		ChangePassword: '/mon-compte/inscription/terminee',
		LightboxTerms: '/form/lightboxTerms',
		AuthenticateAndCreateAccount: '/mon-compte/authentificationCreate',
		AlertSignupAndSubscribe: '/alert/signupAndSubscribe',
		FacebookAuthCallback: 'http://www.plyce.fr/facebook/auth/callback',
		FacebookLinkCallback: 'http://www.plyce.fr/facebook/link/callback',
		AbsoluteHome: 'http://www.plyce.fr/',
		SetOptinNewsletter: 'http://www.plyce.fr/newsletter/optin'
	},
	Apis : {
		facebook : 176560814592,
		facebookAuthDomain : 'http://facebook-auth.plyce.fr'
	},
	Translations : {
		AllCategories : "Toutes les catégories",
		AlertEmpty : "Vous devez sélectionner au moins une marque ou une catégorie.",
		TooMany : "Vous ne pouvez sélectionner que 50 alertes à la fois. Veillez sauvegarder votre sélection actuelle pour en ajouter d'avantage !"
	}
};

Plyce.Block = {};
Plyce.Page = {};
Plyce.Map = {};

Plyce.General = {
	termsAccepted: false,
	optin: false,
	initialize : function(){
		Plyce.General.initPlaceholder();
		if($("#contentLeft").innerHeight() < $("#contentRight").innerHeight()){
			$("#contentLeft").innerHeight($("#contentRight").innerHeight()+80);
		}
		Plyce.General.initFBLikeBt();
		Plyce.General.initGplusBt();
		Plyce.General.showEmailLink();
		
		var subMenuTimer = null;
		var displaySubMenu = function(){
			$("#categorySubMenuBorder").show();
			$(".subMenuHover").addClass('selected');
		}
		var hideSubMenu = function(){
			$("#categorySubMenuBorder").hide();
			$(".subMenuHover").removeClass('selected');
		}
		
		$(".subMenuHover").hover(function(){
			clearTimeout(subMenuTimer);
			displaySubMenu()
		},function(){
			subMenuTimer = setTimeout(hideSubMenu,400);
		});
		$("#categorySubMenuBorder").hover(function(){
			clearTimeout(subMenuTimer);
			displaySubMenu()
		},function(){
			subMenuTimer = setTimeout(hideSubMenu,400);
		});
		$("#categorySubMenuBorder").click(function(){
			clearTimeout(subMenuTimer);
		});
		$("#categorySubMenuBorder *").hover(function(){
			clearTimeout(subMenuTimer);
		});
		
		$("#signupAlertEmailForm").keypress(function(e) {
			if ( e.which == 13 ) {
				e.preventDefault();
			}
			
		});
		
		if($('#searchBarCategoryIndexInput').length != 0){
			$('#searchBarCategoryIndexInput').autocomplete({
				source: function( request, response ) {
					$.ajax(Plyce.Config.Routes.GlobalSearch,{
						data: { search: request.term },
						success: function(data) {
							response( $.map( data, function( item ) {
								return {
									url: item.url,
									label: '› <span class="bold">' + item.name + '</span>',
									value: item.name
								};
							}));
						}
					});
				},
				delay: 300,
				select: function(event, ui ) {
					$("#searchGlobalForm").submit(function() {
						return false;
					});
					location.replace(ui.item.url);
				},
				open: function() {
					$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
				},
				close: function() {
					$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
				}

			}).data( "autocomplete" )._renderItem = function( ul, item ) {
				ul.addClass("selectSearch");
				return $( '<li></li>' ).data( "item.autocomplete", item ).append( "<a>"+item.label+"</a>" ).appendTo( ul );		
			};
		}
		
	},
	initPlaceholder: function() {
		$(".placeholder").each(function(){
			if($(this).val() == ''){
				$(this).val($(this).attr('placeholder'));
				$(this).addClass('placeholderColor');
			}
		});
		$(".placeholder").focus(function(){
			if($(this).val() == $(this).attr('placeholder')){
				$(this).val('');
				$(this).removeClass('placeholderColor');
			}
		});
		$(".placeholder").blur(function(){
			if($(this).val() === ''){
				$(this).val($(this).attr('placeholder'));
				$(this).addClass('placeholderColor');
			}
		});
	},
	loginWithFb: function(next){
		next = next || Plyce.Config.Routes.AbsoluteHome;

		Plyce.General.authFb(Plyce.Config.Routes.FacebookAuthCallback, next);	
	},
	initFBLikeBt: function(){
		window.fbAsyncInit = function() {
		    FB.init({
		      appId      : Plyce.Config.Apis.facebook, // App ID
		      channelUrl : ' <script src="//connect.facebook.net/en_US/all.js"></script>', // Channel File
		      status     : true, // check login status
		      cookie     : true, // enable cookies to allow the server to access the session
		      oauth      : true, // enable OAuth 2.0
		      xfbml      : true  // parse XFBML
		    });

		    // Additional initialization code here
		  };

		  // Load the SDK Asynchronously
		  (function(d){
		     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
		     js = d.createElement('script'); js.id = id; js.async = true;
		     js.src = "//connect.facebook.net/en_US/all.js";
		     d.getElementsByTagName('head')[0].appendChild(js);
		   }(document));
	},
	initGplusBt: function(){
		window.___gcfg = {lang: 'fr'};
		
		  (function() {
		    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
		    po.src = 'https://apis.google.com/js/plusone.js';
		    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
		  })();
	},
	linkFb: function() {	
		Plyce.General.authFb(Plyce.Config.Routes.FacebookLinkCallback, Plyce.Config.Routes.UserSocial);		
	},
	unlinkFb: function() {
		$.ajax(Plyce.Config.Routes.UserUnlinkFb,{
		   	success: function() {
				window.location.replace(Plyce.Config.Routes.UserSocial);
		   	}
		});
		return;
	},
	authFb: function(callback, next){
		window.location.href = 'https://www.facebook.com/dialog/oauth?' + jQuery.param({
			client_id: Plyce.Config.Apis.facebook,
			redirect_uri: Plyce.Config.Apis.facebookAuthDomain + '?' + jQuery.param({
				callback: callback,
				next: next
			}),
			scope: 'email,user_birthday,publish_stream,offline_access',
			response_type: 'token'
		});
	},
	displayLightboxTerms: function(fbSession){
		$.get(Plyce.Config.Routes.LightboxTerms, function(data){
			var html = $(data).html();
			Plyce.General.lightboxInit(html,210,400);
		
			$("#termsLightbox").live('change',function(){
				if($(this).is(':checked')){
					Plyce.General.termsAccepted = true;
				}else{
					Plyce.General.termsAccepted = false;
				}
			});
			$("#optinLightbox").live('change',function(){
				if($(this).is(':checked')){
					Plyce.General.optin = true;
				}else{
					Plyce.General.optin = false;
				}
			});

			$("#termsSubmitLighbox").live('click', function(e){
				if(Plyce.General.termsAccepted){
					$(this).unbind('click');
					Plyce.General.lightboxClose();
					var data = {fbUid: fbSession.uid, fbToken: fbSession.access_token, terms: Plyce.General.termsAccepted, optin: Plyce.General.optin};
					$.ajax(Plyce.Config.Routes.AuthenticateAndCreateAccount,{
						beforeSend: function(){
							$("#loadingBar").slideToggle();		
						},
						complete: function(){
							$("#loadingBar").slideToggle();	
						},
					   	data: data,
					   	success: function(returnData){
							if(returnData.status){
								if(returnData.fbLoginType == 'done'){
									window.location.replace(Plyce.Config.Routes.UserSignupValidFB);
								}
							}
					   	}
					});
				}else{
					$("#labelTerms, #labelTerms a").css('color', '#FF0000');
				}
				e.preventDefault();
				return false;
			});
		});
	},
	lightboxInit: function(content, height, width){
		width = width || $('#lightbox').width();
		$("#lightbox").html(content);
		$("#lightboxContainer").fadeIn('fast');
		$('body').css('overflow', 'hidden');
		$('#lightbox').css('left', ($(window).width() - width)/2);
		$('#lightbox').css('width', width);
		$('#lightbox').css('height', height);
		Plyce.General.initPlaceholder();
	},
	lightboxClose: function(){
		$("#lightbox").empty();
		$("#lightboxContainer").fadeOut('fast');
		$('body').css('overflow', 'visible');
	},
	boxInit: function(content, height, width){
		width = width || $('#lightbox').width();
		$("#lightbox").html(content);
		$("#lightboxContainer").fadeIn('fast');
		$('body').css('overflow', 'hidden');
		$('#lightbox').css('left', ($(window).width() - width)/2);
		$('#lightbox').css('width', width);
		$('#lightbox').css('height', height);
		Plyce.General.initPlaceholder();
	},
	notificationBarInit: function(text, reload){
		if(text !== ''){
			$("#notificationBarText").text(text);
		}
		$("#notificationBar").slideToggle(function(){
			if(reload === true){
				setTimeout(function() { window.location.reload(true); },1500);
			}else{
				setTimeout(Plyce.General.notificationBarClose,1800);
			}
			
		});
	},
	notificationBarClose: function(){
		$("#notificationBar").slideToggle();
	},
	flashBarInit: function(text, color, reload, time) {
		reload = reload || false;
		if (text !== ''){
			$("#flashBarText").text(text);
		}
		$("#flashBar").addClass("flashBar" + color);
		$("#flashBar").slideToggle(function(){
			if (reload === true){
				time = time || 1500;
				setTimeout(function() { window.location.reload(true); }, time);
			} else {
				time = time || 1800;
				setTimeout(Plyce.General.flashBarClose, time);
			}
			
		});
	},
	flashBarClose: function(){
		$("#flashBar").slideToggle();
	},
	showEmailLink: function() {
		if (typeof(emailLink) != 'undefined'){
			if(emailLink !== null){
				for(var e in emailLink){
					if (emailLink[e][2] === "") {
						linkText = emailLink[e][0] + "@" + emailLink[e][1];
				 	}else{
						linkText = emailLink[e][2];
					}
				 	link = "<a href=" + "mail" + "to:" + emailLink[e][0] + "@" + emailLink[e][1] + ">" + linkText + "<\/a>";
					$("#"+emailLink[e][3]).html(link);
				}
			}
		}	
	}
};

Plyce.Block.Header = {
	initialize : function(){}
};Plyce.Block.Alert = {
	termsAccepted: false,
	optin: false,
	initialize : function() {
	},
	subscribeNewsletter: function(){
		var email = $("#newsletterSubscribeField").val();
		if(email !== '' && email !== $("#newsletterSubscribeField").attr('placeholder')){
			$.ajax(Plyce.Config.Routes.CheckEmailRegister,{
				data: {'email': email},
				success: function(returnData) {
					if(returnData.valid){
						if(returnData.result){
							Plyce.General.lightboxInit(returnData.html, 300);
							$("#lightboxPasswordForm").submit(function(e) {
								e.preventDefault();
								Plyce.Block.Alert.loginAndSubscribe();
							});
						}else{
							$.get(Plyce.Config.Routes.LightboxTerms, function(data){
								var html = $(data).html();
								Plyce.General.lightboxInit(html,210,400);
							});
							$("#termsLightbox").live('change',function(){
								if($(this).is(':checked')){
									Plyce.Block.Alert.termsAccepted = true;
									$("#terms").val(1);
								}else{
									Plyce.Block.Alert.termsAccepted = false;
									$("#terms").val(0);
								}
							});
							$("#optinLightbox").live('change',function(){
								if($(this).is(':checked')){
									$("#optin").val(1);
								}else{
									$("#optin").val(0);
								}
							});
							$("#termsSubmitLighbox").live('click', function(){
								if(Plyce.Block.Alert.termsAccepted){
									$(this).unbind('click');
									//$("#alertSubscribeField").val(email);
									$("#signupNewsletterEmailForm").submit();
								}else{
									$("#labelTerms, #labelTerms a").css('color', '#FF0000');
								}
							});
							
						}
					}else{
						Plyce.General.notificationBarInit(returnData.error);
					}
				}
			});
		}
	},
	subscribe: function(type, idCity, idBrand, idCategory, email){
		console.log('sur');
		var data = {};
		data.type = type;
		data.idCity = idCity;
		data.idBrand = idBrand;
		data.idCategory = idCategory;
		
		if(type == 'email'){
			data.email = email;
			if(email !== '' && email !== $("#alertSubscribeField").attr('placeholder')){
				$.ajax(Plyce.Config.Routes.CheckEmailRegister,{
					data: data,
					success: function(returnData) {
						if(returnData.valid){
							if(returnData.result){
								Plyce.General.lightboxInit(returnData.html, 300);
								$("#lightboxPasswordForm").submit(function(e) {
									e.preventDefault();
									Plyce.Block.Alert.loginAndSubscribe();
								});
							}else{
								$.get(Plyce.Config.Routes.LightboxTerms, function(data){
									var html = $(data).html();
									Plyce.General.lightboxInit(html,210,400);
								});
								$("#termsLightbox").live('change',function(){
									if($(this).is(':checked')){
										Plyce.Block.Alert.termsAccepted = true;
										$("#terms").val(1);
									}else{
										Plyce.Block.Alert.termsAccepted = false;
										$("#terms").val(0);
									}
								});
								$("#optinLightbox").live('change',function(){
									if($(this).is(':checked')){
										$("#optin").val(1);
									}else{
										$("#optin").val(0);
									}
								});
								$("#termsSubmitLighbox").live('click', function(){
									if(Plyce.Block.Alert.termsAccepted){
										$(this).unbind('click');
										//$("#alertSubscribeField").val(email);
										$("#signupAlertEmailForm").submit();
									}else{
										$("#labelTerms, #labelTerms a").css('color', '#FF0000');
									}
								});
								
							}
						}else{
							Plyce.General.notificationBarInit(returnData.error);
						}
					}
				});
			}
		}else if(type == 'facebook'){
			FB.login(function(response) {
				return function(response){
					if (response.session) {
						data.fbUid = response.session.uid;
						data.fbToken = response.session.access_token;
						Plyce.Block.Alert.subscribeProceed(data);
					} else {
				    	return;
				  	}
				};
			}(),{perms:'email,user_birthday,publish_stream,offline_access'});
		}else{
			Plyce.Block.Alert.subscribeProceed(data);
		}
	},
	subscribeBlock: function(type, idCity, idBrand, idCategory){
		var email = $("#alertSubscribeField").val();
		Plyce.Block.Alert.subscribe(type, idCity, idBrand, idCategory, email);
	},
	subscribeNoOffer: function(type, idCity, idBrand, idCategory){
		var email = $("#noOfferAlertSubscribeField").val();
		Plyce.Block.Alert.subscribe(type, idCity, idBrand, idCategory, email);
	},
	subscribeProceed: function(data){
		$.ajax(Plyce.Config.Routes.AlertSubscribe,{
			data: data,
			success: function(returnData) {
				if(returnData.status === true){
					if(data.type == 'facebook'){
						if(returnData.fbLoginType == 'signup'){
							$.get(Plyce.Config.Routes.LightboxTerms, function(data){
								var html = $(data).html();
								Plyce.General.lightboxInit(html,210,400);
							});
							$("#termsLightbox").live('change',function(){
								if($(this).is(':checked')){
									Plyce.Block.Alert.termsAccepted = true;
									$("#terms").val(1);
								}else{
									Plyce.Block.Alert.termsAccepted = false;
									$("#terms").val(0);
								}
							});
							$("#optinLightbox").live('change',function(){
								if($(this).is(':checked')){
									Plyce.Block.Alert.optin = true;
									$("#optin").val(1);
								}else{
								Plyce.Block.Alert.optin = false;
									$("#optin").val(0);
								}
							});
							$("#termsSubmitLighbox").live('click', function(){
								if(Plyce.Block.Alert.termsAccepted){
									$(this).unbind('click');
									data.terms = true;
									data.optin = Plyce.Block.Alert.optin;
									Plyce.General.lightboxClose();
									$.ajax(Plyce.Config.Routes.AlertSignupAndSubscribe,{
										beforeSend: function(){
											$("#loadingBar").slideToggle();		
										},
										complete: function(){
											$("#loadingBar").slideToggle();	
										},
										data: data,
										success: function(returnData) {
											if(returnData.status === true){
												window.location.replace(Plyce.Config.Routes.UserSignupValidAlertFB);
											}else{
												Plyce.General.notificationBarInit(returnData.error);
												window.location.replace(Plyce.Config.Routes.Home);
											}			
										}
									});
								}else{
									$("#labelTerms, #labelTerms a").css('color', '#FF0000');
								}
							});
							
							
						}else{
							Plyce.General.notificationBarInit(returnData.message);
							window.location.replace(Plyce.Config.Routes.Home);
						}
					}else if(data.type == 'user'){
						Plyce.General.notificationBarInit(returnData.message, true);
					}
				}else{
					Plyce.General.notificationBarInit(returnData.error);
					if(data.type == 'facebook'){	
						window.location.replace(Plyce.Config.Routes.Home);
					}
				}			
			}
		});
	},
	loginAndSubscribe: function(){
		var data = {};
		data.email = $("#lightboxEmail").val();
		data.password = $("#lightboxPasswordInputField").val();
		data.rememberMe = $("#lightboxCheckboxRemember").val();

		$.ajax(Plyce.Config.Routes.UserLogin,{
			data: data,
			success: function(returnData) {
				if(returnData.status === true){
					var alertData = {};
					alertData.type = 'user';
					alertData.idCity = $("#idCity").val();
					alertData.idBrand = $("#idBrand").val();
					alertData.idCategory = $("#idCategory").val();
					Plyce.General.lightboxClose();
					Plyce.Block.Alert.subscribeProceed(alertData);
				}else{
					Plyce.General.notificationBarInit(returnData.error);
				}			
			}
		});
	},
	setOptinNewsletter: function(){
		$.ajax(Plyce.Config.Routes.SetOptinNewsletter,{
			success: function(returnData) {
				location.reload();			
			}
		});
	}
};Plyce.Page.Offer = {
	initialize : function(idOffer) {
		$.ajax(Plyce.Config.Routes.OfferView,{
			data: {
				idOffer: idOffer
			}
		});
	},
	view : function(idOffer) {
		$.ajax(Plyce.Config.Routes.OfferView,{
			data: {
				idOffer: idOffer
			}
		});
		$("#storeOfferContentText" + idOffer).hide();
		$("#storeOfferContentTextHidden" + idOffer).show();
	},
	printCoupon: function(idOffer) {
		window.open(Plyce.Config.Routes.CouponPrint.replace("idOffer", idOffer));
	},
	shareEmail: function(idOffer, brandName, brandImgUrl, email) {
		$.ajax(Plyce.Config.Routes.OfferShare,{
			type: 'POST',
			data: {
				idOffer: idOffer, 
				brandName: brandName, 
				brandImgUrl: brandImgUrl, 
				email: email
			},
			success: function(returnData) {
				Plyce.General.lightboxInit(returnData.html, 425, 600);
			},
			complete: function() {
				Plyce.Page.User.initialize();
				$("#formShareEmailLightbox").submit(function(e) {
					e.preventDefault();
					var data = $(this).serializeArray();
					Plyce.Page.Offer.sendEmail(data);
				});
			}
		});
	},
	sendEmail: function(data) {
		$.ajax(Plyce.Config.Routes.OfferSend,{
			data : data,
			success: function(returnData) {
				if (returnData.status === false) {
					for(var key in returnData.errors) {
						var div = $("#" + key + "Input");
						var message = div.find(".accountFormInputFieldError");
						message.html(returnData.errors[key]);
						message.show();
						div.children(".accountFormInputFieldContainer").addClass("red");
					}
				} else {
					Plyce.General.lightboxClose();
				}
			}
		});
	}
};Plyce.Page.Category = {
	idCity: 0,
	idCategory: 0,
	initialize : function(idCity, idCategory) {
		Plyce.Page.Category.idCity = idCity;
		Plyce.Page.Category.idCategory = idCategory;
		
		$(".subCatMenuEl").hide();
		$("#childrenCategoryMenu").hover(function(){
			$(".subCatMenuEl").show();
		}, function(){
			$(".subCatMenuEl").hide();
		});
		$(".categoryOfferInfo").each(function(){
			var url = $(this).find("a").attr('href');
			var link = '<a href="'+url+'" class="clickBox" />';
			$(this).wrapInner(link);
		});
		
		$("#searchCityFieldCategory").autocomplete({
			autoFocus: true,
			source: function( request, response ) {
				$.ajax(Plyce.Config.Routes.CitySearch,{
					data: { search: request.term },
					success: function(data) {
						response( $.map( data, function( item ) {
							return {
								hiddenValue: item.id,
								label: '› <span class="bold">' + item.name + '</span> <span class="lighter">' + item.zipcode + '</span>',
								value: item.name + ', ' + item.zipcode
							};
						}));
					}
				});
			},
			delay: 300,
			select: function(event, ui ) {
				$.ajax({
					url: Plyce.Config.Routes.CityUpdate,
					data: { idCity: ui.item.hiddenValue,
							from: 'category',
							idCategory: Plyce.Page.Category.idCategory},
					success: function(data) {
						if(data.status){
							window.location.replace(data.url);
						}
					}
					
				});
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			}
			
		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			ul.addClass("selectCity");
			return $( '<li></li>' ).data( "item.autocomplete", item ).append( "<a>"+item.label+"</a>" ).appendTo( ul );		
		};
		
		$("#searchCityForm").submit(function() {
			return false;
		});
		
		$("#searchCityFieldCategory").focus(function(){
			$("#searchCityFieldCategory").attr('placeholder', $("#searchCityFieldCategory").val());
			$("#searchCityFieldCategory").val('');
		});
		$("#searchCityFieldCategory").blur(function(){
			$("#searchCityFieldCategory").val($("#searchCityFieldCategory").attr('placeholder'));
			$("#searchCityFieldCategory").attr('placeholder', '');
		});
	}

	
};Plyce.Map = function(options) {
	
	/* options = {
		mode : 'offer' / 'store' / 'brand' / 'categoryStore / categoryOffer'
		param : { idOffer : ID_OFFER, idBrand : ID_BRAND, latitude : 48.4, longitude : 2.3} if offer mode OR
				{ idStore : ID_STORE, idBrand : ID_BRAND, latitude : 48.4, longitude : 2.3} if store mode OR
				{ idBrand : ID_BRAND, latitude : 48.4, longitude : 2.3} if brand mode OR
				{ idCategory : ID_CATEGORY, latitude : 48.4, longitude : 2.3} if categoryStore mode
				{ idCategory : ID_CATEGORY, latitude : 48.4, longitude : 2.3} if categoryOffer mode
		brandIcons : [[123, 'http://path.to.icon']],
		zoomLevel : 11,
		scrollwheel: true,
		pois : 200,
		mapType : google.maps.MapTypeId.ROADMAP,
		mapContainer : "divContainer"
	} */
	
	this.mode = options.mode;
	this.idOffer = options.param.idOffer;
	this.idStore = options.param.idStore;
	this.idBrand = options.param.idBrand;
	this.idCategory = options.param.idCategory;
	this.brandIcons = options.brandIcons;
	this.latitude = options.param.latitude;
	this.longitude = options.param.longitude;
	this.latlng = new google.maps.LatLng(options.param.latitude + (this.mode === 'store' ? 0.001 : 0), options.param.longitude);
	this.zoomLevel = options.zoomLevel !== undefined ? options.zoomLevel : 11;
	this.scrollwheel = options.scrollwheel === false ? false : true;
	this.nbPois = options.pois !== undefined ? options.pois : 200;
	this.mapType = options.mapType !== undefined ? options.mapType : google.maps.MapTypeId.ROADMAP;
	this.mapTypeControl = false;

	this.pois = [];
	this.infoWindow = undefined;
	this.timerUpdateRegion = undefined;
	
	var myOptions = { zoom: this.zoomLevel, center: this.latlng, mapTypeId: this.mapType, scrollwheel : this.scrollwheel,
		 mapTypeControl: this.mapTypeControl};
	this.map = new google.maps.Map(document.getElementById(options.mapContainer), myOptions);
	this.markerManager = new Plyce.Map.MarkerManager(this.map, this.mode);
	
	Plyce.Map.MarkerManager.loadBrandIcons(this.brandIcons);
	
	var me = this;
	
	google.maps.event.addListener(this.map, 'click', function(event) {
		return function(event) {
			me.triggerEventClick();
		};
	}());
	
	google.maps.event.addListener(this.map, 'idle', function(event) {
		return function(event) {
			me.triggerEventIdle();
		};
	}());
	
};

Plyce.Map.instance = function(options) {
	
	if(this.plyceMap === undefined) {
		this.plyceMap = new Plyce.Map(options);
	}
	
	return this.plyceMap;
};

Plyce.Map.prototype.triggerEventClick = function(){
	this.markerManager.closeInfoWindow();
};

Plyce.Map.prototype.triggerEventIdle = function() {
	if(this.timerUpdateRegion !== undefined) {
		clearTimeout(this.timerUpdateRegion);
		this.timerUpdateRegion = undefined;
	}
	
	var me = this;
	
    this.timerUpdateRegion = setTimeout(function(event) {
		return function(event) {
			me.updateRegion();
		};
	}(), 50);
	
};

Plyce.Map.prototype.updateRegion = function() {
	
	if(this.timerUpdateRegion !== undefined) {
		clearTimeout(this.timerUpdateRegion);
		this.timerUpdateRegion = undefined;
	}
	
	var ne = this.map.getBounds().getNorthEast();
	var sw = this.map.getBounds().getSouthWest();
	
	var data = {
		latMin : sw.lat(),
		latMax : ne.lat(),
		lonMin : sw.lng(),
		lonMax : ne.lng(),
		maxNbResults : this.nbPois
	};

	var me = this;
	
	//Store update
	if(this.mode === 'store') {
		this.displayResults([[this.latitude, this.longitude, 1, this.idStore, this.idBrand]]);
	
	//Brand update
	} else if(this.mode === 'brand') {
		
		data.brand = this.idBrand;
		
		$.ajax(Plyce.Config.Routes.MapBrand, { data : data,	success: function(data) {
			return function(data) {
				for(var i in data) {
					data[i].push(me.idBrand);
				}
				me.displayResults(data);
			};
		}() });
	
	//Offer update
	}else if(this.mode === 'offer') {
		
		data.offer = this.idOffer;
		
		$.ajax(Plyce.Config.Routes.MapOffer, { data : data, success: function(data) {
			return function(data) {
				for(var i in data) {
					data[i].push(me.idBrand);
				}
				me.displayResults(data);
			};
		}() });
	
	//Category update
	} else if(this.mode === 'categoryStore' || this.mode === 'categoryOffer') {
		
		data.category = this.idCategory;
		data.hasOffer = (this.mode === 'categoryOffer')?1:0;
		
		$.ajax(Plyce.Config.Routes.MapCategory, { data : data,	success: function(data) {
			return function(data) {
				me.displayResults(data);
			};
		}() });
	}
	
};

Plyce.Map.prototype.displayResults = function(results) {
	
	// Construct Pois
	var allPois = Plyce.Map.Poi.instantiatePoisFromResults(results);

	// Regroup Pois that are to close from each others
	var clusteredPois = Plyce.Map.Poi.clusterPois(allPois, this.map.getZoom());
	
	// Replace previous markers by new ones
	this.markerManager.loadPois(clusteredPois);

};


// Constructor
Plyce.Map.Poi = function(result) {
	this.latlng = new google.maps.LatLng(result[0], result[1]);
	this.latitude = result[0];
	this.longitude = result[1];
	this.nbStores = result[2];
	this.idStore = result[3];
	this.idBrand = result[4];
	this.clusterStores = [];
	if(this.idStore > 0) {
		this.clusterStores.push(this.idStore);
	}
};



// Static function
// Instantiate results to Pois
Plyce.Map.Poi.instantiatePoisFromResults = function(results) {
	// Create Poi objects
	var pois = [];
	for(var i in results) {
		pois.push(new Plyce.Map.Poi(results[i]));
	}
	return pois;
};

// Static function
// Merge Pois that are too close from each others
Plyce.Map.Poi.clusterPois = function(pois, mapZoom) {
	
	pois.sort(function(a, b){
	 return a.nbStores - b.nbStores;
	});
	
	var clusteredPois = [];
	
	for(var i = 0; i < pois.length; i++) {
		
		var nearestPoi = pois[i].getNearestPoi(clusteredPois);
		
		if(nearestPoi === null) {
			clusteredPois.push(pois[i]);
			
		} else {
			if(pois[i].isTooClose(nearestPoi, mapZoom)) {
				nearestPoi.mergeWithPoi(pois[i]);
			} else {
				clusteredPois.push(pois[i]);
			}
		}
	}
	
	return clusteredPois;
};

// Instance function
// Return the nearest Poi from an array of Pois
Plyce.Map.Poi.prototype.getNearestPoi = function(pois) {
	
	if(pois.length === 0) {
		return null;
	}
	
	var nearestPoi;
	var nearestDistance = 999999999;
	var i = 0;
	
	while(i < pois.length) {
		var distance = google.maps.geometry.spherical.computeDistanceBetween(this.latlng, pois[i].latlng);
		if(distance < nearestDistance) {
			nearestPoi = pois[i];
			nearestDistance = distance;
		}
		i++;
	}
	
	return nearestPoi;
};

// Instance function
// Return true if the 2 pois should be clustered
Plyce.Map.Poi.prototype.isTooClose = function(poi, zoomLevel) {
	if(zoomLevel >= 20) {
		return false;
	}
	var distance = google.maps.geometry.spherical.computeDistanceBetween(this.latlng, poi.latlng);
	var relativeDistance = Math.pow(2, zoomLevel) * distance;
	
	if(relativeDistance < 5000000 && poi.nbStores > 1 && this.nbStores > 1) {
		return true;
	}
	
	if(relativeDistance < 5000000 && (poi.nbStores == 1 || this.nbStores == 1)) {
		return true;
	}
	
	return false;
};

// Instance function
// Merge a Poi with another
Plyce.Map.Poi.prototype.mergeWithPoi = function(poi) {
	this.latitude = (this.latitude * this.nbStores + poi.latitude * poi.nbStores) / (this.nbStores + poi.nbStores);
	this.longitude = (this.longitude * this.nbStores + poi.longitude * poi.nbStores) / (this.nbStores + poi.nbStores);
	this.nbStores += poi.nbStores;
	this.idStore = 0;
	this.latlng = new google.maps.LatLng(this.latitude, this.longitude);
	if(this.clusterStores.length > 0 && poi.clusterStores.length > 0) {
		this.clusterStores = this.clusterStores.concat(poi.clusterStores);
	} else {
		this.clusterStores = [];
	}
	
};
Plyce.Map.MarkerManager = function(map, mapMode) {	
	//Instance
	this.map = map;
	this.mapMode = mapMode;
	this.markers = [];
	this.infoWindow = undefined;
	
	if(Plyce.Map.MarkerManager.markerImages.brandIcon === undefined) {
		Plyce.Map.MarkerManager.markerImages.brandIcon = new google.maps.MarkerImage(Plyce.Config.Routes.WebsiteBundleImages + "default-store-or-brand.png",
															new google.maps.Size(29,29),
															new google.maps.Point(0,0),
															new google.maps.Point(15,39),
															new google.maps.Size(29,29));
	}
	
	if(Plyce.Map.MarkerManager.markerImages.brandShadow === undefined) {
		Plyce.Map.MarkerManager.markerImages.brandShadow = new google.maps.MarkerImage(Plyce.Config.Routes.WebsiteBundleImages + "marker.png",
																	new google.maps.Size(45,51),
																	new google.maps.Point(0,0),
																	new google.maps.Point(23,43));
	}
	
	if(Plyce.Map.MarkerManager.markerImages.clusterIcon === undefined) {
		Plyce.Map.MarkerManager.markerImages.clusterIcon = new google.maps.MarkerImage(Plyce.Config.Routes.WebsiteBundleImages + "markerMapClusterClickable.png",
																	new google.maps.Size(40,40),
																	new google.maps.Point(0, 0),
																	new google.maps.Point(24,24));
	}
};

//Statics
Plyce.Map.MarkerManager.missingBrandIcons = [];
Plyce.Map.MarkerManager.markerImages = {
	brand : [],
	cluster : []
};

Plyce.Map.MarkerManager.loadBrandIcons = function(brands) {
	for(var i in brands) {
		var idBrand = brands[i][0];
		if(brands[i][1] !== null && brands[i][1].length > 0) {
			
			this.markerImages.brand[idBrand] = new google.maps.MarkerImage(Plyce.Config.Routes.BrandIcon.replace('%picIcon%', brands[i][1]),
																new google.maps.Size(29,29),
																new google.maps.Point(0,0),
																new google.maps.Point(15,39),
																new google.maps.Size(29,29));
		} else {
			this.markerImages.brand[idBrand] = Plyce.Map.MarkerManager.markerImages.brandIcon;
		}
	}
};

Plyce.Map.MarkerManager.queueMissingBrandIcons = function(id) {
	if($.inArray(id, this.missingBrandIcons) === -1) {
		this.missingBrandIcons.push(id);
	}
};

Plyce.Map.MarkerManager.retrieveMissingBrandIcons = function(callback) {
	
	var brands = this.missingBrandIcons.join(',');

	var data = {
		brands : brands
	};

	$.ajax(Plyce.Config.Routes.MapBrandIcon, { data : data,	success: function(data) {
		return function(data) {
			Plyce.Map.MarkerManager.loadBrandIcons(data);
			Plyce.Map.MarkerManager.missingBrandIcons.length = 0;
			callback();
		};
	}() });
};


Plyce.Map.MarkerManager.imagesForMarker = function(marker) {
	//BRAND IMAGES
	if(marker.poi.nbStores === 1) {
		
		if(this.markerImages.brand[marker.poi.idBrand] !== undefined) {
			return {
				icon : this.markerImages.brand[marker.poi.idBrand],
				shadow : this.markerImages.brandShadow,
				shouldReload : false
			};
		} else {
			this.queueMissingBrandIcons(marker.poi.idBrand);
			return {
				icon : this.markerImages.brandIcon,
				shadow : this.markerImages.brandShadow,
				shouldReload : true
			};
		}
	}
	
	//CLUSTER IMAGES
	if(this.markerImages.cluster[marker.poi.nbStores] === undefined) {
		var offset = {
			x : marker.poi.nbStores > 99 ? 360 : (marker.poi.nbStores % 10) * 40,
			y : marker.poi.nbStores > 99 ? 360 : Math.floor(marker.poi.nbStores / 10) * 40
		};
		var url = Plyce.Config.Routes.WebsiteBundleImages + "markerMapCluster.png";
		this.markerImages.cluster[marker.poi.nbStores] = new google.maps.MarkerImage(url, new google.maps.Size(40,40),
																					new google.maps.Point(offset.x, offset.y),
																					new google.maps.Point(24,24));
	}
	
	return {
		icon : this.markerImages.clusterIcon,
		shadow : this.markerImages.cluster[marker.poi.nbStores],
		shouldReload : false
	};

};

Plyce.Map.MarkerManager.prototype.loadPois = function(newPois) {
	
	// Reuse Markers for Pois that haven't changed between the previous and current results
	// and save available markers for other pois to reuse later
	
	var newMarkers = [];
	for(var i in newPois) {
		
		for(var j in this.markers) {
			if(newPois[i].latitude == this.markers[j].poi.latitude && 
			   newPois[i].longitude == this.markers[j].poi.longitude &&
			   newPois[i].nbStores == this.markers[j].poi.nbStores &&
			   newPois[i].idStore == this.markers[j].poi.idStore) {
				
				newMarkers.push(this.markers[j]);
				delete this.markers[j];
				newPois[i] = null;
				break;
				
			}
		}
		
	}
	
	// Reuse available markers or create new ones for other Pois
	for(var i in newPois) {
		if(newPois[i] !== null) {
			var marker = this.markers.pop();
			
			//if we don't have any available marker, create one
			if(marker === undefined) {
				    var marker = new google.maps.Marker({
						map: this.map,
						clickable : true
				});
			}
			
			//Set the new marker
			marker.poi = newPois[i];			
			marker.setPosition(newPois[i].latlng);
			marker.setZIndex(newPois[i].nbStores);
			
			var images = Plyce.Map.MarkerManager.imagesForMarker(marker);
			marker.setIcon(images.icon);
			marker.setShadow(images.shadow);
			marker.shouldReload = images.shouldReload;
			
			//Add a click event on this marker
			var me = this;
			google.maps.event.clearListeners(marker, 'click');
			google.maps.event.addListener(marker, 'click', function(event) {
				return function(event) {
					if(this.poi.clusterStores.length > 1 && (me.mapMode === 'categoryStore' || me.mapMode === 'categoryOffer' || this.map.getZoom() > 16) && this.map.getZoom() > 15) {
						me.openInfoWindow(this);
					}
					//If it's a cluster Poi (nbStores > 1), zoom in
					else if(this.poi.nbStores > 1) {
						this.map.setOptions({zoom: this.map.getZoom() + 2, center: this.poi.latlng});
					
					}
					//Otherwise open the info window
					else if(this.poi.idStore > 0) {
						me.openInfoWindow(this);
					}
				}
			}());
			
			newMarkers.push(marker);
			
		}
	}
	
	//If missing brand icons get them and reload markers
	if(Plyce.Map.MarkerManager.missingBrandIcons.length > 0) {
		var me = this;
		Plyce.Map.MarkerManager.retrieveMissingBrandIcons(function(){
			return function() {
				me.reloadMissingMarkerIcons();
			}
		}());
	}
	
	//Destroy old and unused other markers
	for(var i in this.markers) {
		this.markers[i].setMap(null);
	}
	this.markers = newMarkers;
}

Plyce.Map.MarkerManager.prototype.reloadMissingMarkerIcons = function() {
	for(var i in this.markers) {
		var marker = this.markers[i];
		if(marker.shouldReload == true) {
			var images = Plyce.Map.MarkerManager.imagesForMarker(marker);
			marker.setIcon(images.icon);
			marker.setShadow(images.shadow);
			marker.shouldReload = images.shouldReload;
		}
	}
}

Plyce.Map.MarkerManager.prototype.openInfoWindow = function(marker) {
	
	var me = this;
	if(marker.poi.clusterStores.length > 1) {
		
		$.ajax(Plyce.Config.Routes.MapStoresInfo, {
			data : { stores : marker.poi.clusterStores },
			success: function(data) {
				return function(data) {

					if(me.infoWindow === undefined) {
						me.infoWindow = new google.maps.InfoWindow();
					}

					me.infoWindow.setOptions({content : data, maxWidth : 310});
					me.infoWindow.open(me.map, marker);
				}
			}()
		});
	} else {
		
		$.ajax(Plyce.Config.Routes.MapStoreInfo, {
			data : { store : marker.poi.idStore },
			success: function(data) {
				return function(data) {

					if(me.infoWindow === undefined) {
						me.infoWindow = new google.maps.InfoWindow();
					}

					me.infoWindow.setOptions({content : data, maxWidth : 600});
					me.infoWindow.open(me.map, marker);
				}
			}()
		});
	}
	
};

Plyce.Map.MarkerManager.prototype.closeInfoWindow = function() {
	if(this.infoWindow !== undefined) {
		this.infoWindow.close();
	}
};
Plyce.Page.Alert = {
	idCity: 0,
	currentPage: 1,
	currentCategory: 0,
	currentName: '',
	currentLocation: $("#currentLocation").val(),
	brandSelected: [],
	categorySelected : [],
	timerFilter: null,
	termsAccepted: false,
	initialize : function(idCity) {
		Plyce.Page.Alert.idCity = idCity;
		Plyce.Page.Alert.initializeSelected();
		Plyce.Page.Alert.initializeSelection();
		
		$("#searchCityFieldAlert").autocomplete({
			autoFocus: true,
			source: function( request, response ) {
				$.ajax(Plyce.Config.Routes.CitySearch,{
					data: { search: request.term },
					success: function(data) {
						response( $.map( data, function( item ) {
							return {
								hiddenValue: item.id,
								label: '› <span class="bold">' + item.name + '</span> <span class="lighter">' + item.zipcode + '</span>',
								value: item.name + ', ' + item.zipcode
							};
						}));
					}
				});
			},
			delay: 300,
			select: function(event, ui ) {
				$.ajax({
					url: Plyce.Config.Routes.CityUpdate,
					data: { idCity: ui.item.hiddenValue,
							from: 'alert'},
					success: function(data) {
						if(data.status){
							if(data.url == Plyce.Config.Routes.Alert) {
								window.location.reload();
							} else {
								window.location.replace(data.url);
							}
							
						}
					}
					
				});
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			}
			
		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			ul.addClass("selectCity");
			return $( '<li></li>' ).data( "item.autocomplete", item ).append( "<a>"+item.label+"</a>" ).appendTo( ul );		
		};
		
		$("#searchCityForm").submit(function() {
			return false;
		});
		
		$("#searchCityFieldAlert").focus(function(){
			$("#searchCityFieldAlert").attr('placeholder', $("#searchCityFieldAlert").val());
			$("#searchCityFieldAlert").val('');
		});
		$("#searchCityFieldAlert").blur(function(){
			$("#searchCityFieldAlert").val($("#searchCityFieldAlert").attr('placeholder'));
			$("#searchCityFieldAlert").attr('placeholder', '');
		});
		
		if ($('#alertEmailForm').length > 0) {
			$('#alertEmailForm').submit(function(e) {
				e.preventDefault();
				Plyce.Page.Alert.subscribe('email');
			});
		}
		
		$('#alertFilterInputField').keyup(function(event){
			clearTimeout(Plyce.Page.Alert.timerFilter);
			var name = $(this).val();
			var currentCat = Plyce.Page.Alert.currentCategory;
			var delay = function() {
				Plyce.Page.Alert.getBrandForCategoryAndName(currentCat, name);
			};
			Plyce.Page.Alert.timerFilter = setTimeout(delay,400);
			
		});
		$(".alertSelectBrandMenuEl").hide();
		$("#alertSelectBrandCategory").hover(function(){
			$(".alertSelectBrandMenuEl").show();
		}, function(){
			$(".alertSelectBrandMenuEl").hide();
		});
	},
	initializeSelection : function() {
		var idCity = Plyce.Page.Alert.idCity;
		$(".alertSelectElement").unbind();
		$(".alertSelectElement").click(function(){
			var id = $(this).attr('id');
			if ($(this).hasClass('selected')) {
				Plyce.Page.Alert.unselectBrand(id, idCity);
			} else {
				Plyce.Page.Alert.selectBrand(id);
			}
			
		});
	},
	initializeSelected : function() {
		$.ajax(Plyce.Config.Routes.AlertGetSelected, {
			success: function(data) {
				if (data.length === 0) {
					$("#alertValidationLoad").hide();
					$("#alertValidationEmpty").show();
				} else { 
					for (var i in data) {
						var id = data[i].id;
						$("#alertValidationLoad").hide();
						$("#alertValidationEmpty").hide();
						$("#alertValidationElementContainer").append(data[i].html);
						if (data[i].type == 'b') {
							Plyce.Page.Alert.brandSelected.push({
								id: id, 
								idCity: data[i].idCity
							});
							if (data[i].idCity == Plyce.Page.Alert.idCity) {
								$("#alertSelectElementContainer").find("#" + data[i].id).addClass('selected');
							}
						} else if (data[i].type == 'c') {
							Plyce.Page.Alert.categorySelected.push({
								id: id, 
								idCity: data[i].idCity
							});
						}
					}
				}
			}
		});
	},
	selectBrand: function(id) {
		var cookieSize = 0;
		if ((Plyce.Page.Alert.brandSelected.length + Plyce.Page.Alert.categorySelected.length) > 49) {
			var cookie = Plyce.Page.Alert.getCookie('selectedAlerts');
			if (cookie !== null) {
				cookieSize = JSON.parse(cookie);
				cookieSize = cookieSize.length;
			}
		} 
		if (cookieSize > 50) {
			Plyce.General.notificationBarInit(Plyce.Config.Translations.TooMany);
		} else {
			var idCity = Plyce.Page.Alert.idCity;
			if (Plyce.Page.Alert.indexOf(Plyce.Page.Alert.brandSelected, id, idCity) === -1) {
				$.ajax(Plyce.Config.Routes.AlertSaveBrand, {
					data: {
						idBrand: id,
						idCity: Plyce.Page.Alert.idCity
					},
					async: false,
					success: function(returnData) {
						if (returnData.status === true) {
							Plyce.Page.Alert.brandSelected.push({
								id: id, 
								idCity: idCity
							});
							Plyce.Page.Alert.blockSelectBrand(id, returnData.html);
						} else {
							if (typeof(returnData.error) !== 'undefined') {
								Plyce.General.notificationBarInit(returnData.error, false);
							}
						}
					}
				});
			}
		}
	},
	blockSelectBrand: function(id, html) {
		$("#alertValidationEmpty").hide();
		$("#alertValidationElementContainer").append(html);
		$("#alertSelectElementContainer").find("#" + id).addClass('selected');
	},
	unselectBrand: function(id, idCity){
		$.ajax(Plyce.Config.Routes.AlertDeleteBrand, {
			data: {
				id: id,
				idCity: idCity
			},
			success: function(returnData) {
				if (returnData.status === true) {
					Plyce.Page.Alert.brandSelected.splice(Plyce.Page.Alert.indexOf(Plyce.Page.Alert.brandSelected, id, idCity), 1);
					if (idCity == Plyce.Page.Alert.idCity) {
						$("#alertSelectElementContainer").find("#" + id).removeClass('selected');
					}
					$("#alertValidationElementContainer").find("#brand" + id + "-" + idCity).remove();
					if($("#alertValidationElementContainer").children().length == 0){
						$("#alertValidationEmpty").show();
					}
				}
			}
		});
	},	
	focusBrand: function() {
		for (var i in Plyce.Page.Alert.brandSelected) {
			var element = $("#alertSelectElementContainer").find("#" + Plyce.Page.Alert.brandSelected[i].id)
			if (!element.hasClass('selected')) {
				element.addClass('selected');
			}
		}
	},
	selectAlertCategory: function(id) {
		var idCity = Plyce.Page.Alert.idCity;
		if (typeof(id) === 'undefined') {
			id = Plyce.Page.Alert.currentCategory;
		}
		if(Plyce.Page.Alert.indexOf(Plyce.Page.Alert.brandSelected, id, idCity) === -1) {
			
			$.ajax(Plyce.Config.Routes.AlertSaveCategory, {
				data: {
					idCategory: id,
					idCity: Plyce.Page.Alert.idCity
				},
				async: false,
				success: function(returnData) {
					if (returnData.status === true) {
						Plyce.Page.Alert.categorySelected.push({
							id: id, 
							idCity: idCity
						});
						Plyce.Page.Alert.blockSelectCategory(id, returnData.html);
					} else {
						if (typeof(returnData.error) !== 'undefined') {
							Plyce.General.notificationBarInit(returnData.error, false);
						}
					}
					
				}
			});
		}
	},
	blockSelectCategory: function(id, html) {
		$("#alertValidationEmpty").hide();
		$("#alertValidationElementContainer").append(html);
	},
	unselectAlertCategory: function(id, idCity){
		$.ajax(Plyce.Config.Routes.AlertDeleteCategory, {
			data: {
				idCategory: id,
				idCity: idCity
			},
			success: function(returnData) {
				if (returnData.status === true) {
					Plyce.Page.Alert.categorySelected.splice(Plyce.Page.Alert.indexOf(Plyce.Page.Alert.categorySelected, id, idCity), 1);
					$("#alertValidationElementContainer").find("#cat" + id + "-" + idCity).remove();
					if($("#alertValidationElementContainer").children().length == 0){
						$("#alertValidationEmpty").show();
					}
				}
			}
		});
	},
	selectCategory: function(idCategory){
		$(".alertSelectBrandMenuEl.hover").removeClass('hover');
		$("#menuEl" + idCategory).addClass("hover");
		$("#menuFirstEl").text($("#menuEl" + idCategory).text());
		$(".alertSelectBrandMenuEl").hide();
		Plyce.Page.Alert.getBrandForCategoryAndName(idCategory, '', 1);
		$('#alertFilterInputField').val('');
	},
	getBrandForCategoryAndName: function(idCategory, name){	
		$.ajax(Plyce.Config.Routes.AlertBrandFilter,{
			data: {
				idCategory: idCategory, 
				name: name
			},
			success: function(data) {
				if(!data.displayButton){
					$("#alertSelectMoreResult").hide();
				}else{
					$("#alertSelectMoreResult").show();
				}
				$("#alertSelectElementContainer").empty();
				$("#alertSelectElementContainer").append(data.content);
				Plyce.Page.Alert.initializeSelection();
				Plyce.Page.Alert.currentCategory = idCategory;
				Plyce.Page.Alert.currentPage = 1;
				Plyce.Page.Alert.currentName = name;
				Plyce.Page.Alert.focusBrand();
			}
		});
	},
	getNextPage: function(){
		var page = Plyce.Page.Alert.currentPage + 1;
		Plyce.Page.Alert.currentPage = page;
		var currentName = Plyce.Page.Alert.currentName ;
		var currentCat = Plyce.Page.Alert.currentCategory;	
		$.ajax(Plyce.Config.Routes.AlertBrandFilter,{
			data: {
				idCategory: currentCat, 
				name: currentName, 
				page: page
			},
			success: function(data) {
				if(!data.displayButton){
					$("#alertSelectMoreResult").hide();
				}else{
					$("#alertSelectMoreResult").show();
				}
				$("#alertSelectElementContainer").append(data.content);
				
				Plyce.Page.Alert.focusBrand();
				Plyce.Page.Alert.initializeSelection();
			}
		});
	},
	subscribe: function(type) {
		if (Plyce.Page.Alert.brandSelected.length > 0 || Plyce.Page.Alert.categorySelected.length > 0) {
			var data = {};
			data.type = type;
			data.selectionType = 'multi';
			if (type == 'email') {
				data.email = $("#alertValidationEmailInputField").val();
				$.ajax(Plyce.Config.Routes.CheckEmailRegister, {
					data: data,
					success: function(returnData) {
						if(returnData.valid){
							if(returnData.result){
								Plyce.General.lightboxInit(returnData.html, 300);
								$("#lightboxPasswordForm").submit(function(e) {
									e.preventDefault();
									Plyce.Page.Alert.loginAndSubscribe();
								});
								$("#lightboxPasswordInputField").focus();
							} else {
								Plyce.Page.Alert.postToUrl(Plyce.Config.Routes.AlertMultiSubscribe, data, 'post')
							}
						} else {
							Plyce.General.notificationBarInit(returnData.error);
						}
					}
				});
			}
		} else {
			Plyce.General.notificationBarInit(Plyce.Config.Translations.AlertEmpty);
		}
	},
	subscribeMultiProceed: function(data){
		$.ajax(Plyce.Config.Routes.AlertMultiSubscribe, {
			data: data,
			success: function(returnData) {
				if (returnData.status === true){
					if (data.type == 'user'){
						Plyce.General.notificationBarInit(returnData.message, true);					
					}
				} else {
					Plyce.General.notificationBarInit(returnData.error);
				}			
			}
		});
	},
	loginAndSubscribe: function() {
		var data = {};
		data.email = $("#lightboxEmail").val();
		data.password = $("#lightboxPasswordInputField").val();
		data.rememberMe = $("#lightboxCheckboxRemember").val();

		$.ajax(Plyce.Config.Routes.UserLogin,{
			data: data,
			success: function(returnData) {
				if(returnData.status === true){
					var alertData = {};
					alertData.type = 'user';
					alertData.from = 'email';
					Plyce.General.lightboxClose();
					Plyce.Page.Alert.subscribeMultiProceed(alertData);
				}else{
					Plyce.General.notificationBarInit(returnData.error);
				}			
			}
		});
	},
	getCookie: function(c_name) {
		var i, x, y, ARRcookies = document.cookie.split(";");
		for (i = 0; i < ARRcookies.length; i++) {
			x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
			y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
			x = x.replace(/^\s+|\s+$/g, "");
			if (x == c_name) {
				return unescape(y);
			}
		}
		return null;
	},
	indexOf: function(arr, id, idCity) {
		if (typeof(arr) === 'undefined') return -1;
		for (var i in arr) {
			if (arr[i].id == id && arr[i].idCity == idCity) return i;
		}
		return -1;
	},
	postToUrl : function(path, params, method) {
		
		$.get(Plyce.Config.Routes.LightboxTerms, function(data){
			var html = $(data).html();
			Plyce.General.lightboxInit(html,210,400);
		});
		
		$("#termsLightbox").live('change',function(){
			if($(this).is(':checked')){
				Plyce.Page.Alert.termsAccepted = true;
				params.terms = 1;
			}else{
				Plyce.Page.Alert.termsAccepted = false;
				params.terms = 0;
			}
		});
		$("#optinLightbox").live('change',function(){
			if($(this).is(':checked')){
				params.optin = 1;
			}else{
				params.optin = 0;
			}
		});
		
		
		$("#termsSubmitLighbox").live('click', function(){
			if(Plyce.Page.Alert.termsAccepted){
				$(this).unbind('click');
				method = method || "post"; 

				var form = document.createElement("form");
				form.setAttribute("method", method);
				form.setAttribute("action", path);

				for(var key in params) {
					var hiddenField = document.createElement("input");
					hiddenField.setAttribute("type", "hidden");
					hiddenField.setAttribute("name", key);
					hiddenField.setAttribute("value", typeof(params[key]) === 'object' ? JSON.stringify(params[key]) : params[key]);

					form.appendChild(hiddenField);
				}

				document.body.appendChild(form);
				
				form.submit();
			}else{
				$("#labelTerms, #labelTerms a").css('color', '#FF0000');
			}
		});
		
		
	}
};Plyce.Page.User = {
	initialize : function() {
		$('.accountFormInput, .accountFormInputBirthdate').focus(function(){
			var container = $(this).parents('.accountFormInputFieldContainer');
			if(container.hasClass('red')){
				container.removeClass('red');
			}
			container.addClass('blue');
			container.find('.accountFormInputFieldMessage').fadeIn('fast');
			container.find('.accountFormInputFieldError').hide();
		});
		$('.accountFormInput, .accountFormInputBirthdate').blur(function(){
			$(".accountFormInputFieldContainer.blue").removeClass('blue');
			var container = $(this).parents('.accountFormInputFieldContainer');
			container.find('.accountFormInputFieldMessage').hide();
		});
		var selectFrequency = $("#alertFrequency");
		var selectDeliveryMethod = $("#alertDeliveryMethod");
		if (selectDeliveryMethod.val() == 'none') {
			selectFrequency.attr("disabled", true);
			selectFrequency.addClass("disabled");
		}
		selectDeliveryMethod.change(function() {
			if ($(this).val() == 'none') {
				selectFrequency.attr("disabled", true);
				selectFrequency.addClass("disabled");
			} else {
				selectFrequency.attr("disabled", false);
				selectFrequency.removeClass("disabled");
			}
		});
	},
	changeGender : function(value) {		
		$('.accountFormInputRadioSelected').removeClass('accountFormInputRadioSelected');
		if(value == 'female'){
			$('#accountFormRadioFemale').addClass('accountFormInputRadioSelected');
			$('#accountFormRadioMale').addClass('accountFormInputRadio');
		}else if(value == 'male'){
			$('#accountFormRadioFemale').addClass('accountFormInputRadio');
			$('#accountFormRadioMale').addClass('accountFormInputRadioSelected');
		}
		$("#genderChoice").val(value);
	},
	flashMessage : function(message) {
		if (message !== '') {
			Plyce.General.flashBarInit(message, "Blue");
		}
	}
};Plyce.Page.Brand = {
	initialize : function() {
		$("#brandStoreFinderField").autocomplete({
			source: function( request, response ) {
				$.ajax(Plyce.Config.Routes.CitySearch,{
					data: { search: request.term },
					success: function(data) {
						response( $.map( data, function( item ) {
							return {
								hiddenValue: item.id,
								label: '› <span class="bold">' + item.name + '</span> <span class="lighter">' + item.zipcode + '</span>',
								value: item.name + ', ' + item.zipcode
							};
						}));
					}
				});
			},
			delay: 300,
			select: function(event, ui ) {
				var placeholder = $("#brandStoreFinderField").attr('placeholder');
				$("#brandStoreFinderField").val(placeholder);
				$("#idCity").val(ui.item.hiddenValue);
				$("#brandStoreFinderForm").unbind();
				$("#brandStoreFinderForm").submit();
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			}
			
		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			ul.addClass("selectCity");
			return $( '<li></li>' ).data( "item.autocomplete", item ).append( "<a>"+item.label+"</a>" ).appendTo( ul );		
		};
		
		$("#brandStoreFinderForm").submit(function() {
			return false;
		});
		
		$("#brandStoreFinderField").focus(function(){
			$(this).attr('placeholder', $(this).val());
			$(this).val('');
		});
		$("#brandStoreFinderField").blur(function(){
			$(this).val($("#brandStoreFinderField").attr('placeholder'));
			$(this).attr('placeholder', '');
		});
	}
};Plyce.Page.SignupValid = {
	changePassword: function(password){
		var data = {};
		data.password = password;
		$.ajax(Plyce.Config.Routes.LightboxChangePassword,{
			data: data,
			success: function(returnData) {
				Plyce.General.lightboxInit(returnData, 565, 600);
			},
			complete: function() {
				Plyce.Page.User.initialize();
				$("#formPasswordLightbox").submit(function(e) {
					e.preventDefault();
					var data = $(this).serializeArray();
					Plyce.Page.SignupValid.changePasswordProcess(data);
				});
			}
		})
	},
	changePasswordProcess: function(data) {
		$.ajax(Plyce.Config.Routes.ChangePassword,{
			type: 'POST',
			data: data,
			success: function(returnData) {
				if (returnData.status === false) {
					for(var key in returnData.errors) {
						var div = $("#" + key + "Input");
						var message = div.find(".accountFormInputFieldError");
						message.html(returnData.errors[key]);
						message.show();
						div.children(".accountFormInputFieldContainer").addClass("red");
					}
				} else {
					location.replace(Plyce.Config.Routes.Home);
				}
			}
		})
	}
};Plyce.Block.NearestStoreForOffer = {
	initialize : function() {
		$("#offerStoreFinderField").autocomplete({
			autoFocus: true,
			source: function( request, response ) {
				$.ajax(Plyce.Config.Routes.CitySearch,{
					data: { search: request.term },
					success: function(data) {
						response( $.map( data, function( item ) {
							return {
								hiddenValue: item.id,
								label: '› <span class="bold">' + item.name + '</span> <span class="lighter">' + item.zipcode + '</span>',
								value: item.name + ', ' + item.zipcode
							};
						}));
					}
				});
			},
			delay: 300,
			select: function(event, ui ) {
				$("#idCity").val(ui.item.hiddenValue);
				$("#offerStoreFinderForm").submit();
				$("#offerStoreFinderField").attr({
					'placeholder': ui.item.value,
					'value': ui.item.value
				});
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			}
			
		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			ul.addClass("offerStoreFinderSelectCity");
			return $( '<li></li>' ).data( "item.autocomplete", item ).append( "<a>"+item.label+"</a>" ).appendTo( ul );		
		};
		
		$("#offerStoreFinderForm").submit(function() {
			var idOffer = $("#idOffer").val();
			var idCity = $("#idCity").val();
			var page = 1;
			if( idCity !== '' && idOffer !== ''){
				Plyce.Block.NearestStoreForOffer.get(idOffer, idCity, page);
			}
			return false;
		});
		
		Plyce.Block.NearestStoreForOffer.initializePagination();
		
	},
	get : function(idOffer, idCity, page) {
		$.ajax(Plyce.Config.Routes.StoreGetNearestForOffer,{
			data: { idOffer: idOffer, idCity: idCity, page: page },
			success: function(data){
				$("#storeList").empty();
				$("#storeList").append(data);
				Plyce.Block.NearestStoreForOffer.initializePagination(page);
			}
		});
		
	},
	submit: function(){
		$("#offerStoreFinderForm").submit();
	},
	getPage: function(page){
		var idOffer = $("#idOffer").val();
		var idCity = $("#idCity").val();
		Plyce.Block.NearestStoreForOffer.get(idOffer, idCity, page);
	},
	initializePagination: function(){
		var page = parseInt($(".paginationLink.active").text());
		$(".paginationLink").click(function(){
			Plyce.Block.NearestStoreForOffer.getPage(parseInt($(this).text()));
			return false;
		});
		$(".paginationFirstPage").click(function(){
			Plyce.Block.NearestStoreForOffer.getPage(1);
			return false;
		});
		$(".paginationPrevPage").click(function(){
			Plyce.Block.NearestStoreForOffer.getPage(page - 1);
			return false;
		});
		$(".paginationNextPage").click(function(){
			Plyce.Block.NearestStoreForOffer.getPage(page + 1);
			return false;
		});
	}
};Plyce.Page.NearestStoreForBrand = {
	initialize : function() {
		$("#brandStoreListFinderField").autocomplete({
			source: function( request, response ) {
				$.ajax(Plyce.Config.Routes.CitySearch,{
					data: { search: request.term },
					success: function(data) {
						response( $.map( data, function( item ) {
							return {
								hiddenValue: item.id,
								label: '› <span class="bold">' + item.name + '</span> <span class="lighter">' + item.zipcode + '</span>',
								value: item.name + ', ' + item.zipcode
							};
						}));
					}
				});
			},
			delay: 300,
			select: function(event, ui ) {
				$("#idCity").val(ui.item.hiddenValue);
				$("#brandStoreListFinderForm").submit();
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			}
			
		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			ul.addClass("brandStoreListFinderSelectCity");
			return $( '<li></li>' ).data( "item.autocomplete", item ).append( "<a>"+item.label+"</a>" ).appendTo( ul );		
		};
		
		$("#brandStoreFinderForm").submit(function() {
			var idCity = $("#idCity").val();
			if( idCity !== ''){
				$("#brandStoreListFinderForm").submit();
			}else{
				return false;
			}
		});
	},
	submit: function(){
		$("#brandStoreListFinderForm").submit();
	}
};Plyce.Page.MapCategory = {
	initialize : function(map, currentCategory) {
		// Display root Category //
		$.ajax({
			type: "GET",
			dataType: "json",
			url: Plyce.Config.Routes.MapListCategory,
			data: {
				idCategory : currentCategory, root : true
			},
			success : function(data) {
				for (var i in data.parents) {
					$("div#mapFilters").append(Plyce.Page.MapCategory.htmlCombobox(data.parents[i].idParent, data.parents[i].name, 'mapFilterButtonDarkGreen', data.parents[i].children, data.parents[i].idParent));
				}
				$("div#mapFilters").append(Plyce.Page.MapCategory.htmlCombobox(currentCategory, Plyce.Config.Translations.AllCategories, 'mapFilterButtonGreen', data.children));

			}
		});
		//

		$("div#mapFilters a").live('click', function(event) {
			event.preventDefault();
			var combobox = $(this).next("div[name='combobox']");
			combobox.slideToggle();

		});

		$("div[name='combobox'] li").live('click', function(event) {
			event.preventDefault();
			var li = $(this);
			var combobox = $(this).parent();
			var firstLi = combobox.children().first();
			
			if (li.attr("name") === 'default') {
				map.idCategory = li.attr("id");
				map.updateRegion();
				
				var a = $("a#linkCategory-" + li.attr("id"));
				
				combobox.hide();
				a.next().nextAll().remove();
				$("span#nameCategory-" + li.attr("id")).text(Plyce.Config.Translations.AllCategories);
				firstLi.remove();
				
				if (li.attr("id") != 0) {
					$("h1#mapTitle strong").html(combobox.prev().prev().prev().find("span.mapFilterButtonText").html());
					a.removeClass("mapFilterButtonDarkGreen");
					a.addClass("mapFilterButtonGreen");
				} else {
					$("h1#mapTitle strong").html("");
				}
			} else {
				$("h1#mapTitle strong").html(li.html());
				
				var idParent = li.attr("name").split("-")[1];
				var parent = $("a#linkCategory-" + idParent);
				var children = $("a#linkCategory-" + idParent).nextAll("a");

				if (children.length > 0) {
					$("a#linkCategory-" + idParent).next().nextAll().remove();
				}

				var id = $(this).attr("id");
				var name = $(this).text();
				
				$.ajax({
					type: "GET",
					dataType: "json",
					url: Plyce.Config.Routes.MapListCategory,
					data: {
						idCategory : id
					},
					success : function(data) {
						map.idCategory = id;
						map.updateRegion();

						$("span#nameCategory-" + idParent).text(name);

						parent.removeClass("mapFilterButtonGreen");
						parent.addClass("mapFilterButtonDarkGreen");

						combobox.hide();
						if (firstLi.attr("name") !== 'default') {
							combobox.prepend(Plyce.Page.MapCategory.htmlLiAllCategories(idParent));
						}

						if(data.children.length > 0) {
							$("div#mapFilters").append(Plyce.Page.MapCategory.htmlCombobox(id, Plyce.Config.Translations.AllCategories, 'mapFilterButtonGreen', data.children));
						}
					}
				});
			}
		});
	},

	htmlCombobox : function(id, name, classCSS, data, idParent) {
		var html = '<a id="linkCategory-' + id + '" class="' + classCSS + '"><span id="nameCategory-' + id + '" class="mapFilterButtonText">' + name + '</span><span class="mapFilterButtonSeparator"></span><span class="mapFilterButtonArrow"></span></a>';
		html += '<div name="combobox" class="mapFilterCombobox">';
		if (typeof(idParent) !== 'undefined') {
			html += '<li id="' + idParent +'" name="default">' + Plyce.Config.Translations.AllCategories + '</li>';
		}
		for (var i in data) {
			html += '<li id="' + data[i].id + '" name="subFilter-' + id + '">' + data[i].name + '</li>';
		}
		html += '</div>';

		return html;
	},

	htmlLiAllCategories : function(id) {
		return '<li id="' + id +'" name="default">' + Plyce.Config.Translations.AllCategories + '</li>';
	}
};Plyce.Page.Intro = {
	termsAccepted: false,
	initialize : function() {
		$("#introLightboxButton").click(function(){
			$("#introLightbox").fadeIn();
			
		});		
		$("#btClose").click(function(){
			$("#introLightbox").fadeOut();
		});
		$("#introLightboxBg").click(function(){
			$("#introLightbox").fadeOut();
		});
		$("#introCityInput").autocomplete({
			source: function( request, response ) {
				$.ajax(Plyce.Config.Routes.CitySearch,{
					data: { search: request.term },
					success: function(data) {
						response( $.map( data, function( item ) {
							return {
								hiddenValue: item.urlId,
								label: '› <span class="bold">' + item.name + '</span> <span class="lighter">' + item.zipcode + '</span>',
								value: item.name + ', ' + item.zipcode
							};
						}));
					}
				});
			},
			delay: 300,
			select: function(event, ui ) {
				$("#urlIdCity").val(ui.item.hiddenValue);				
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			}
			
		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			ul.addClass("introSelectCity");
			return $( '<li></li>' ).data( "item.autocomplete", item ).append( "<a>"+item.label+"</a>" ).appendTo( ul );		
		};
		
		$("#introBottomBar").click(function(){
			var position = $("#introBottomBar").position();
			$(window).unbind('scroll');
			$(window).unbind('resize');
			$('#introTop').height(position.top+10);
			
			var introBottomBar = $("#introBottomBar");
			introBottomBar.css('position', 'absolute');
			introBottomBar.css('top', position.top);
			
			var whyRegisterContainer = $("#whyRegisterContainer");
			whyRegisterContainer.css('position', 'absolute');
			whyRegisterContainer.css('top', position.top + 90);
			whyRegisterContainer.css('left', (($(window).width()-$("#whyRegisterContainer").width())/2));
			$('html,body').animate({'scrollTop': (position.top-10)}, 1000, 'swing');
		});
		$("#introForm").submit(function(){
			var email = $("#introEmailInput").val();
			if(email == "" || email == $("#introEmailInput").attr('placeholder') || Plyce.Page.Intro.termsAccepted){
				return true;
			}
			else{
				$.get(Plyce.Config.Routes.LightboxTerms, function(data){
					var html = $(data).html();
					Plyce.General.lightboxInit(html,210,400);
				});
				return false;
			}
		});
		$("#termsLightbox").live('change',function(){
			if($(this).is(':checked')){
				Plyce.Page.Intro.termsAccepted = true;
				$("#terms").val(1);
			}else{
				$("#terms").val(0);
			}
		});
		$("#optinLightbox").live('change',function(){
			if($(this).is(':checked')){
				$("#optin").val(1);
			}else{
				$("#optin").val(0);
			}
		});
		$("#termsSubmitLighbox").live('click', function(){
			if(Plyce.Page.Intro.termsAccepted){
				$(this).unbind('click');
				Plyce.General.lightboxClose();
				$("#introForm").submit();
			}else{
				$("#labelTerms, #labelTerms a").css('color', '#FF0000');
			}
		});
	}

};Plyce.Page.Mobile = {
	initialize: function(){
		$("#mobileForm").submit(function(){
			var email = $("#mobileEmail").val();
			if(email !== '' && email !== $("#mobileEmail").attr('placeholder')){
				$.ajax(Plyce.Config.Routes.MobileDl,{
					data : {email: email },
					success: function(msg) {
						Plyce.Page.Mobile.flashMessage(msg);
					}
				});
			}
			return false;
		});
	},
	flashMessage : function(message) {
		if (message !== '') {
			Plyce.General.flashBarInit(message, "Blue");
		}
	}
};Plyce.Page.Brands = {
	initialize : function() {
		$(".brandListBrand").each(function(){
			var url = $(this).find("a").attr('href');
			var link = '<a href="'+url+'" class="clickBox" />';
			$(this).wrapInner(link);
		});
		
		
	}
};Plyce.Page.Store = {
	initialize : function(idStore) {
		$.ajax(Plyce.Config.Routes.StoreView,{
			data: {
				idStore: idStore
			}
		});
	}
};Plyce.Page.Signup = {
	termsAccepted: false,
	initialize : function() {
		$("#signupForm").submit(function(e){
			var email = $("#registerEmailInputField").val();
			if(email == "" || email == $("#registerEmailInputField").attr('placeholder') || Plyce.Page.Signup.termsAccepted){
				return true;
			}
			else{
				$.ajax(Plyce.Config.Routes.CheckEmailRegister,{
					data: {email : email},
					success: function(returnData) {
						if(returnData.valid){
							if(returnData.result){
								$("#signupForm").submit();
							}else{
								$.get(Plyce.Config.Routes.LightboxTerms, function(data){
									var html = $(data).html();
									Plyce.General.lightboxInit(html,210,400);
								});
							}
						}
					}
				});
			}
			e.preventDefault();
			return false;
		});
		$("#termsLightbox").live('change',function(){
			if($(this).is(':checked')){
				Plyce.Page.Signup.termsAccepted = true;
				$("#termsSignup").val(1);
			}else{
				Plyce.Page.Signup.termsAccepted = false;
				$("#termsSignup").val(0);
			}
		});
		$("#optinLightbox").live('change',function(){
			if($(this).is(':checked')){
				$("#optinSignup").val(1);
			}else{
				$("#optinSignup").val(0);
			}
		});
		$("#termsSubmitLighbox").live('click', function(){
			if(Plyce.Page.Signup.termsAccepted){
				$(this).unbind('click');
				Plyce.General.lightboxClose();
				$("#signupForm").submit();
			}else{
				$("#labelTerms, #labelTerms a").css('color', '#FF0000');
			}
		});
	},
	flashMessage : function(message) {
		if (message !== '') {
			Plyce.General.flashBarInit(message, "Blue");
		}
	}
};Plyce.Page.Index = {
	initialize : function() {
		$(".nearestOfferContent").each(function(){
			var url = $(this).find("a").attr('href');
			var link = '<a href="'+url+'" class="clickBox" />';
			$(this).wrapInner(link);
		});
		$('.carousel').carousel();
		
		$('#searchBarIndexInput').autocomplete({
			source: function( request, response ) {
				$.ajax(Plyce.Config.Routes.GlobalSearch,{
					data: { search: request.term },
					success: function(data) {
						response( $.map( data, function( item ) {
							return {
								url: item.url,
								label: '› <span class="bold">' + item.name + '</span>',
								value: item.name
							};
						}));
					}
				});
			},
			delay: 300,
			select: function(event, ui ) {
				$("#searchGlobalForm").submit(function() {
					return false;
				});
				location.replace(ui.item.url);
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			}

		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			ul.addClass("selectSearch");
			return $( '<li></li>' ).data( "item.autocomplete", item ).append( "<a>"+item.label+"</a>" ).appendTo( ul );		
		};
	}
};
