	var CookieManager = {
		
		create : function (name,value,days)
		{
			days = 365;
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";
			document.cookie = name+"="+value+expires+"; path=/";
			//document.cookie = name+"="+value+expires+"; path="+window.location.pathname;
		},
		
		erase : function (name)
		{
			CookieManager.create(name,"",-1);
		},
		
		read : function (name)
		{
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return "";
		}
		
	}





        var Validator = {
            text: function(inputID){
                var regex = /\w/
                if (!regex.test(inputID) ){
			KedemHerbs.loader.hide();
			return false;
                }
                else{			
			return true;
                }
            },
            email: function(what){
                var regex = /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/
                if (!regex.test(what) ){
			KedemHerbs.loader.hide();
			return false;
		}
		else return true;
            },
            defaultValue : function (inputID,what){
                if ($(inputID).attr('value') == what){
                        FormWarning.warn(inputID);
                        $(inputID).addClass('missing');
                        return true;
                }
                else{
                        $(inputID).removeClass('missing');
			KedemHerbs.loader.hide();
                        return false;
                }
            }
        }
        
        
        var ModalWindow = {
        	positionEvent : function(){
        		$('.modal_Event').each(function(){
        			$(this).css({
        				'top': ( $(window).height() - $(this).height() ) / 2 + 'px',
        				'left': ( $(window).width() - $(this).width() ) / 2 + 'px'
        			}); 
        		});
        	},
        	
        	closeEvent : function(){
        		$('.modal_Event, #maskOverlay').remove();
        	},
        	
        	init : function(content){
        		// show the mask
        		content = "<div id='maskOverlay'></div>" + content;
			$('body').append(content);

			// position the content
			ModalWindow.positionEvent();
			$(window).resize(function(){ModalWindow.positionEvent()});
			
			// close the window
			$('.modal_Event .close').click(function(){ModalWindow.closeEvent()});
        	}
        }


var KedemHerbs = {
	
	validateForm : function(){
			//event.preventDefault();
			var shouldSubmitForm = true;
			
			$('.mandatory').each(function(){
				$parent = $(this).parents('li');
				if (!Validator.text($(this).attr('value'))) {
					$parent.addClass('missing');
					shouldSubmitForm = false;
				}
				else $parent.removeClass('missing');
			});
			$('input[type="email"].mandatory').each(function(){
				$parent = $(this).parents('li');
				if (!Validator.email($(this).attr('value'))) {
					$parent.addClass('missing');
					shouldSubmitForm = false;
				}
				else $parent.removeClass('missing');
			});
			
			
			// remove the error as completed
			$('.mandatory').blur(function(){
				$parent = $(this).parents('li');
				$parent.removeClass('missing');
			});
			
			return shouldSubmitForm;
			
	},
	
	updateCartStatus : function(){
		
		$.ajax({ 
			type: 'POST',
			url: '/_Assets/Ajax/cart_status.php',

			success : function(theXML){
				$(theXML).find("status").each(function(){
					var status = $(this).text();
					status = status.replace(/{/g,"<");
					status = status.replace(/}/g,">");
					$('#shoppingCartStatus').html(status);
				});
				$(theXML).find("products").each(function(){
					var products = $(this).text();
					if (products == 1) _gaq.push(['_trackPageview', '/en/cart/addToCart/']);
				});
			}
		});		
	},
	
	addToCart : {
		animate : function(id){
	
			// animate image
			var newContent = "<img id='tempImage' src='" + $('.'+id).attr('src') + "'>";
			$('#productShowcase aside').append(newContent);
			$('#tempImage').animate({
				top:'-180px',
				left:'900px',
				width: '0',
				height: '0',
				opacity : '0'
			},1200, function(){$(this).remove()});

			KedemHerbs.updateCartStatus();
		},
		
		
		init : function (id){
		// add to cart section
			// read the existing cookie
			var content = CookieManager.read('cartContent');
			var products = [];
			var cookie = "";
			var found = false; // product not in the cart

			if (content) { // there are products in cart
				// read all the products and put them in an array
				content = content.split(",");
				for (i=0, j=content.length; i<j; i++){
					var position = content[i].split("#");
					products.push([position[0],position[1]]);
				}
				
				// check if the selected is on the list
				for (i=0, j=products.length; i<j; i++){
					if (id == products[i][0]) {
						products[i][1]++; // the products is in cart, so increment the quantity
						found = true;
					}
				}

			}
			
			if (!found) products.push([id,"1"]); // the product is not on cart, so add it
			
			// convert all the array elements in a string
			for (i=0, j=products.length; i<j; i++){
				cookie += products[i][0] + "#" + products[i][1];
				cookie +=",";

			}		
		
			// write cart content
			CookieManager.create('cartContent',cookie.slice(0,cookie.length-1));		
			KedemHerbs.addToCart.animate(id);
		
		}
		
	},
	
	removeFromCart : {
		
		
		animate : function(id){
			$('#list_'+id).slideUp(500,function(){$(this).remove()});
		},
		
		init : function(id){
			var content = CookieManager.read('cartContent');
			var products = [];
			var cookie = "";
			if (content) { // there are products in cart
				// read all the products and put them in an array
				content = content.split(",");
				for (i=0, j=content.length; i<j; i++){
					var position = content[i].split("#");
					products.push([position[0],position[1]]);
				}
				
				// check if the selected is on the list
				for (i=0, j=products.length; i<j; i++){
					if (id == products[i][0]) {
						products[i][1]--; // the products is in cart, so decrement the quantity
					}
				}
			}
			
			for (i=0, j=products.length; i<j; i++){
				if (products[i][1] >0 ){ 
					cookie += products[i][0] + "#" + products[i][1];
					cookie +=",";

				}
				
				else KedemHerbs.removeFromCart.animate(id);
			}		
		
			// write cart content
			if (cookie != "") CookieManager.create('cartContent',cookie.slice(0,cookie.length-1));
			else CookieManager.erase('cartContent');
		}
	
	},
	
	updateQuantity : function (id,quantity){
			var content = CookieManager.read('cartContent');
			var products = [];
			var cookie = "";
			if (content) { // there are products in cart
				// read all the products and put them in an array
				content = content.split(",");
				for (i=0, j=content.length; i<j; i++){
					var position = content[i].split("#");
					products.push([position[0],position[1]]);
				}
				
				// check if the selected is on the list
				for (i=0, j=products.length; i<j; i++){
					if (id == products[i][0]) {
						products[i][1] = quantity; // the products is in cart, so decrement the quantity
					}
				}
			}
			
			for (i=0, j=products.length; i<j; i++){
				if (products[i][1] === "0")  {
					KedemHerbs.removeFromCart.animate(id);
				}
				else{
					cookie += products[i][0] + "#" + products[i][1];
					cookie +=",";

				}
			}		
		
			// write cart content
			if (cookie != "") CookieManager.create('cartContent',cookie.slice(0,cookie.length-1));
			else CookieManager.erase('cartContent');
	},
	
	
	cartValue : {
		
		countryName : "",
		
		display : function (){
			$.ajax({ 
				type: 'POST',
				url: '/_Assets/Ajax/cart_elements.php',
				data: {},
				success : function(theXML){
//					console.log(theXML);
					
					var country;
					var province;
					var idCountry;
					$(theXML).find("product").each(function(){
						$('#'+$(this).find("quantity").attr('id')).attr('value',$(this).find("quantity").text());
						$('#paypal_'+$(this).find("quantity").attr('id')).attr('value',$(this).find("quantity").text());
						$('#'+$(this).find("price").attr('id')).html( KedemHerbs.formatValue($(this).find("price").text()) + "/each");
						$('#'+$(this).find("value").attr('id')).html( KedemHerbs.formatValue($(this).find("value").text()) );
					});
					
					$(theXML).find("shipping").each(function(){
						$('#shipping_options option').attr('selected',''); // reset previous selected
						$('#shipping_'+$(this).find("id").text()).attr('selected','selected') ;// show selected one
						$('#shipping_value').html( KedemHerbs.formatValue($(this).find("value").text()) ); // display the value
						if ($(this).find("name").text() == "Canada") $('#taxes_content').slideDown(200,function(){KedemHerbs.loader.hide();});// show the taxes field
						
						idCountry = $(this).find("id").text();
						country = $(this).find("name").text();
					});
					
					$(theXML).find("taxes").each(function(){
						$('#taxes_options option').attr('selected',''); // reset previous selected
						$('#taxes_'+$(this).find("id").text()).attr('selected','selected') ;// show selected one
						$('#taxes_value').html( KedemHerbs.formatValue($(this).find("value").text()) ); // display the value
						var content = "<span>"+$(this).find("name").text()+"</span>";
						$('#taxes_content hgroup span').remove();
						$('#taxes_content hgroup').append(content);
						//province = $('#taxes_'+$(this).find("id").text()).text();
						province = $(this).find("id").text();
						

					});
					
					
					$(theXML).find("promotionalCode").each(function(){
						var value = $(this).find("value").text();
							if (value > 0) value = "-$"+value;
							else value = "$"+value;
						var error = $(this).find("error").text();
							if (error == "false") $('#coupon_note').html($(this).find("name").text());
						
						$('#coupon_code').attr('value',$(this).find("promoCode").text());
						$('#discount_value').html(value);
				
					});
					
					
					$(theXML).find("total").each(function(){
						$('#grand_total').html( KedemHerbs.formatValue($(this).text()) ); // display the value
					});
						

				}
			});			
		},
		
		
		processState : function(idCountry){
			if (!idCountry) idCountry = CookieManager.read('shipping');
			
			$.ajax({ 
				type: 'POST',
				url: '/_Assets/Ajax/shipping_states.php',
				data: {idCountry:idCountry},
				success : function(theXML){
					
					// remove all the option list from the states dropdown - reset	
						$('#province_form option, #taxes_options option').remove();
					// create the new drop down
						var newDropDownTaxes = '<option value="">-- Select --</option>';
						var newDropDownStates = '<option value="">-- Select --</option>';

						
						$(theXML).find("state").each(function(){
							var id = $(this).find("id").text();
							var name = $(this).find("name").text();
							var value = $(this).find("value").text();
							
							newDropDownTaxes += '<option id="taxes_'+id+'" value="'+id+'">'+name+'</option>';
							newDropDownStates += '<option id="states_'+id+'" value="'+id+'">'+name+'</option>';
						});
					// append the new list to select tag
						$('#province_form').append(newDropDownStates);
						$('#taxes_options').append(newDropDownTaxes);
						
					// format the drop down visual
					if (KedemHerbs.cartValue.countryName == "Canada") $('#taxes_content').slideDown(200,function(){KedemHerbs.loader.hide();});
					else $('#taxes_content').slideUp(200, function(){KedemHerbs.loader.hide();});
					
					var idState = CookieManager.read('taxes');
					KedemHerbs.cartValue.processStateForm(idState); //adjust the state display in all form elements

		
				}
			});
			
		},
					
		formatPromoCode : function (theXML){
			var name = $(theXML).find("name").text();
			var value = $(theXML).find("value").text();
			var error = $(theXML).find("error").text();
			var promoCode = $(theXML).find("promoCode").text();
			
			
			$('#coupon_note').text(name).removeClass('error');
			if (error == "true"){
				$('#coupon_note').addClass('error');
				CookieManager.erase("promoCode");
			}
			else CookieManager.create("promoCode", promoCode);
			
			if (value > 0) $('#discount_value').text('-$'+value);
			else $('#discount_value').text('$'+value);
			
			KedemHerbs.cartValue.display();
			KedemHerbs.loader.hide();
			
		},

		processCountry : function(idCountry){
			$('#shipping_options option, #country_form option').attr('selected','');
			
			$.ajax({ 
				type: 'POST',
				url: '/_Assets/Ajax/shipping_country.php',
				data: {id:idCountry},
				success : function(name){
					KedemHerbs.cartValue.countryName = name;
					if (name == "International"){
						$('#shipping_eccbc87e4b5ce2fe28308fd9f2a7baf3').attr('selected','selected');
					// switch the dropdown over a regular input
						$('#province_form').removeClass('mandatory').hide();
						$('#province_form_manual').addClass('mandatory').show();
					}
					else{
						$('#shipping_'+idCountry).attr('selected','selected');
					// switch regular input over a dropdown
						$('#province_form_manual').removeClass('mandatory').hide();
						$('#province_form').addClass('mandatory').show();
					}
					$('#country_'+idCountry).attr('selected','selected');
				}
			});
			
			// write the value for the selected country
			CookieManager.create('shipping',idCountry);
			
		},
		
		processStateForm : function(idState){
			$('#taxes_options option, #province_form option').attr('selected',''); // reset all the previous states
			$('#taxes_'+idState).attr('selected','selected'); // mark the selected ones
			$('#states_'+idState).attr('selected','selected'); // mark the selected ones
		},
		


		init : function (){
				var idCountry = CookieManager.read('shipping');

				KedemHerbs.cartValue.processCountry(idCountry); //adjust the country display in all form elements
				KedemHerbs.cartValue.processState(idCountry); // adjust the state display list based on the selected country
			
			KedemHerbs.cartValue.display();
			
			$('.setQuantity .up').click(function(){
				var id = $(this).attr('id').split("_")[1];
				KedemHerbs.addToCart.init(id);
				KedemHerbs.cartValue.display();
			});
			
			$('.setQuantity .down').click(function(){
				var id = $(this).attr('id').split("_")[1];
				KedemHerbs.removeFromCart.init(id);
				KedemHerbs.cartValue.display();
			});
			
			$('#shipping_options, #country_form').change(function(){
				KedemHerbs.loader.show();
				var idCountry = $(this).attr('value');
				$('#province_form_manual').attr('value','')// reset the manual field
				CookieManager.create('shipping',idCountry); // create the cookie
				KedemHerbs.cartValue.processCountry(idCountry); //adjust the country display in all form elements
				KedemHerbs.cartValue.processState(idCountry); // adjust the state display list based on the selected country
				KedemHerbs.cartValue.display();	// process the form based on the newly created cookie
			});
			

			$('#taxes_options, #province_form').change(function(){
				KedemHerbs.loader.show();
				var idState = $(this).attr('value');
				CookieManager.create('taxes',idState); // create the cookie
				KedemHerbs.cartValue.processStateForm(idState); //adjust the state display in all form elements
				KedemHerbs.cartValue.display();	// process the form based on the newly created cookie
				KedemHerbs.loader.hide();
			});
			
	
			$('#validate_coupon').click(function(){
				KedemHerbs.loader.show();
				var code = $('#coupon_code').attr('value');
				$.ajax({ 
					type: 'POST',
					url: '/_Assets/Ajax/promo_code.php',
					data: {code:code},
					success : function(theXML){KedemHerbs.cartValue.formatPromoCode(theXML);}
				});
			});
		}
		
	},
	

	
	multipleProductVariations : function(){
		// init images
		$('#productShowcase img').hide();
		$('#productShowcase img:first').show();
		
		$('#productShowcase section.action').mouseover(function(){
			var selected = $(this).find('button').attr('id'); // determine the selected variation
			$('#productShowcase img').hide(); // hide all
			$('#productShowcase img.'+selected).show(); // show the selected
		});
		
		
	},
	
	formatValue : function(value){
		var temp = value.split(".");	
		return "$" + value;
	},
	
	
	loader : {
		show : function(cssclass){
			var loader = "<div id='mask'><div class="+cssclass+"><span></span></div></div>";
			$('body').append(loader);
			var $loader = $('#mask div');
			//var top = ($(window).height() - $loader.height() ) / 2;
			//var left = ($(window).width() - $loader.width() ) / 2;
				var top = ($(window).height() - 200 ) / 2;
				var left = ($(window).width() - 200 ) / 2;
			$loader.css({'top':top+'px', 'left':left+'px'});
			$('#mask').show();
			
		},
		hide : function(){
			$('#mask').remove();			
		}
	},

	init : function(){
		
		// init loader
		// KedemHerbs.loader.show();
		
		
		// Validate Forms
		$('#submit, #checkout, #checkoutWithPaypal, #paynow').click(function(event){
			if ($('#payment_method').attr('value') == "Credit Card") {KedemHerbs.loader.show('CreditCard');}
			else if ($('#payment_method').attr('value') == "PayPal"){KedemHerbs.loader.show('PayPal');}
			else KedemHerbs.loader.show();
			
			
			KedemHerbs.loader.show();
			if (KedemHerbs.validateForm() ){
				
				if ($(this).hasClass('ConfirmationSubmit')){
					
					$.ajax({ 
						type: 'POST',
						url: '/_Assets/Ajax/confirmation_survey.php',
						data: {
							answer: $('#ConfirmationAnswer').attr('value')
						},
						success : function(data){
							$('#ConfirmationQuestion').fadeOut(200,function(){$('#ConfirmationThankyou').fadeIn(200)});
							KedemHerbs.loader.hide();
						}
					});
					
				}
				
			
				if ($(this).attr('id') == "checkout"){
					
					// THIS IS A WORK IN PROGRESS
					
					//$.ajax({ 
					//	type: 'POST',
					//	url: '/_Assets/Ajax/record_preorder.php',
					//	data: {
					//		shipping_FirstName : $('#shipping_FirstName').attr('value'),
					//		shipping_LastName : $('#shipping_LastName').attr('value'),
					//		shipping_Email : $('#shipping_Email').attr('value')
					//	},
					//	success : function(data){
					//		console.log(data);
					//		$('#goToChekcout').submit();
					//	}
					//});
					
					
					$('#goToChekcout').submit();

				}
				
				if ($(this).attr('id') == "paynow" || $(this).attr('id') == "checkoutWithPaypal"){

					_gaq.push(['_trackPageview', '/en/cart/checkoutWithPaypal/']);
					
					$.ajax({ 
						type: 'POST',
						url: '/_Assets/Ajax/record_order.php',
						data: {
							shipping_FirstName : $('#shipping_FirstName').attr('value'),
							shipping_LastName : $('#shipping_LastName').attr('value'),
							shipping_Email : $('#shipping_Email').attr('value'),
							shipping_Address1 : $('#shipping_Address1').attr('value'),
							shipping_Address2 : $('#shipping_Address2').attr('value'),
							shipping_City : $('#shipping_City').attr('value'),
							shipping_PostalCode : $('#shipping_PostalCode').attr('value'),
							shipping_State : $('#shipping_State').attr('value'),
							shipping_Country : $('#shipping_Country').attr('value'),
							
							billing_FirstName : $('#billing_FirstName').attr('value'),
							billing_LastName : $('#billing_LastName').attr('value'),
							billing_Email : $('#billing_Email').attr('value'),
							billing_Address1 : $('#billing_Address1').attr('value'),
							billing_Address2 : $('#billing_Address2').attr('value'),
							billing_City : $('#billing_City').attr('value'),
							billing_PostalCode : $('#billing_PostalCode').attr('value'),
							billing_State : $('#billing_State').attr('value'),
							billing_Country : $('#billing_Country').attr('value'),
							
							PaymentMethod : $('#payment_method').attr('value')
		
						},
						success : function(data) {
							if ($('#payment_method').attr('value') == "Credit Card"){ // Credit card payment
								
								$.ajax({ 
									type: 'POST',
									url: '/_Assets/Ajax/process_creditcard_payment.php',
									data: {
										billing_FirstName : $('#billing_FirstName').attr('value'),
										billing_LastName : $('#billing_LastName').attr('value'),
										creditCardType : $('#creditCardType').attr('value'),
										card_num : $('#card_num').attr('value'),
										exp_month : $('#exp_month').attr('value'),
										exp_year : $('#exp_year').attr('value'),
										card_code : $('#card_code').attr('value'),
										billing_Address1 : $('#billing_Address1').attr('value'),
										billing_City : $('#billing_City').attr('value'),
										billing_State : $('#billing_State').attr('value'),
										billing_Country : $('#billing_Country').attr('value'),
										billing_PostalCode : $('#billing_PostalCode').attr('value'),
										amount : $('#totalCart').attr('value'),
										currency_code : $('#currency_code').attr('value')
									},
									success :  function(theXML) {
										var status = $(theXML).find('status').text();
										var shortMessage = $(theXML).find('shortMessage').text();
										var longMessage = $(theXML).find('longMessage').text();
										var orderID = $(theXML).find('orderID').text();
										var transactionID = $(theXML).find('transactionID').text();
										var response = status + ". " + shortMessage + ". " + longMessage;
										//var response = status + ". " + orderID + ". " + transactionID;
										
										if (status=="Success") {
											$(location).attr('href','/en'+'/cart/confirmation/?orderID='+orderID);
										}
										else {
											$('#CreditCardPaymentInfo li').addClass('missing');
											$('#ccError').text(response);
											KedemHerbs.loader.hide();
										}
									}
								});
							}
							
							if ($('#payment_method').attr('value') == "PayPal"){ // Paypal payment
								$('#custom').val(data);
								
								$('#first_name').attr('value',$('#billing_FirstName').attr('value'));
								$('#last_name').attr('value',$('#billing_LastName').attr('value'));
								$('#payer_email').attr('value',$('#billing_Email').attr('value'));
								$('#address_street').attr('value',$('#billing_Address1').attr('value'));
								$('#address_city').attr('value',$('#billing_City').attr('value'));
								$('#address_zip').attr('value',$('#billing_PostalCode').attr('value'));
								$('#address_state').attr('value',$('#billing_State').attr('value'));
								$('#address_country').attr('value',$('#billing_Country').attr('value'));

								$('#payment').submit();
							}
							
							
						}
					});

				}
				
				return true;
				
			}
			else return false;
		});
		
		// process multiple images for the product showcase
		KedemHerbs.multipleProductVariations();
	
		
		// add to cart
		$('button').click(function(){
			KedemHerbs.addToCart.init($(this).attr('id'));
		});
			
		// treat the search box
		$('#search_value').focus(function(){
			if ($(this).attr('value')=="Search") $(this).val('');
		}).blur(function(){
			if ($(this).attr('value')=="") $(this).val('Search');
		});
		
		$('#submit_search').click(function(){
			if($('#search_value').attr('value') != "Search") $('#search_form').submit();
		});
		
		
		// payment options
		$('#checkoutWithPaypal').click(function(){
			//$('#business').attr('value','seller_1254424795_biz@chiru.ca');
			//$('#business').attr('value','contact@simple-design.ca');
			$('#business').attr('value','herbsofkedem@gmail.com');
		});

		$('#payWithPaypal').click(function(){
			$('#CreditCardPaymentInfo, #ccError').slideUp(200);
			$('#paynow').addClass('payWithPaypal').removeClass('paynow');
			$('.legendCreditCard').fadeOut(300);
			$('#payment_method').val('PayPal');
			$('#creditCardType, #card_num, #exp_month, #exp_year, #card_code').removeClass('mandatory');
				//$('#business').attr('value','seller_1254424795_biz@chiru.ca');
				//$('#business').attr('value','contact@simple-design.ca');
				$('#business').attr('value','herbsofkedem@gmail.com');

		});
		$('#payWithCreditCard').click(function(){
			$('#CreditCardPaymentInfo, #ccError').slideDown(200);
			$('#paynow').removeClass('payWithPaypal').addClass('paynow');
			$('.legendCreditCard').fadeIn(300);
			$('#payment_method').val('Credit Card');
		
			$('#creditCardType, #card_num, #exp_month, #exp_year, #card_code').addClass('mandatory');	
		

			$('#business').val('');
		});
		
		
		// CVV2 details
		$('#whatIsCVV').mouseover(function(){$('#cvv').fadeIn(200)}).mouseout(function(){$('#cvv').fadeOut(200)});
		
		// Modal window
			// youtube popup		
			$('#youtubeFrameSmall .modal_Trigger, #youtubeFrameSmall-modal_Trigger').click(function(){
				var content = "<div id='youtubeFrameBig' class='modal_Event'><div class='close'></div><iframe width='592' height='444' src='https://www.youtube.com/embed/0oHwt-se9dk?rel=0&autoplay=1' ></iframe></div>";
				ModalWindow.init(content);
			});
			
			// Subscriber popup
			$(".subscribeToOurEmailList").click(function(){
				KedemHerbs.Subscribers.init(override=true);
			});
	
	},
	
	recordOrder : function(){

	},
	
	Subscribers : {
		popup_en : "<div class='modal_Event'><div id='newsletterSubscribeBig' class='cols8 box'><div class='top'></div><div class='content'><h1>Be The First To Know!</h1><h2>Fantastic Monthly Promotions For 100% Herbal Products</h2><fieldset><input type='text' id='subscriberName' class='mandatory short empty' title='Name' value='Name'> <input type='email' id='subscriberEmail' class='mandatory short empty' title='Email address' value='Email address'> <input type='submit' id='subscribe' value=''><div class='disclaimer'><input type='checkbox' id='privacyPolicyAccepted' > <span id='acceptance'>I have read and accepted</span> the <span id='loadPrivacyPolicy'>Herbs of Kedem Inc's Privacy Policy</span></div></fieldset><div class='section'></div></div><div class='bottom'></div></div><div class='close'></div></div>",
		
		
		privacyPolicy : function(){
			// hide the current background
			$('#newsletterSubscribeBig div.section').css('backgroundImage','url(/_Assets/Images/Misc/spinner.gif)');

			$.ajax({ 
				type: 'POST',
				url: '/en/privacy-policy/privacy-policy.html',
				success : function(data){
					$('#newsletterSubscribeBig div.section').css('backgroundImage','none').html(data);
				}
			});			
			
		},
		
		record : function(){
			var subscriberName = $('#subscriberName').attr('value');
			var subscriberEmail = $('#subscriberEmail').attr('value');
			
			$('#newsletterSubscribeBig fieldset').addClass('loading').html('');
			
			
			$.ajax({ 
				type: 'POST',
				data: {email : subscriberEmail, name: subscriberName},
				url: '/_Assets/Ajax/record_email_subscriber.php',				
				success : function(data){					
					if (data == "success" ) $('#newsletterSubscribeBig fieldset').removeClass('loading').append("<blockquote>Thank you! You've been subscribed.</blockquote>");
					else $('#newsletterSubscribeBig fieldset').removeClass('loading').append("<blockquote>Error! Try again.</blockquote>");
					_gaq.push(['_trackPageview', '/en/newsletterSubscriber/']);
				}
			});	
			
			
		},
		validate : function(){
		
			var pass = true;

			$('#newsletterSubscribeBig .mandatory').each(function(){
				if ($(this).attr('value') == $(this).attr('title') || !Validator.text($(this).attr('value'))){ $(this).addClass('missing'); pass = false; }
				else  {$(this).removeClass('missing empty');}
			});
			$('#newsletterSubscribeBig .mandatory[type=email]').each(function(){
				if (!Validator.email($(this).attr('value'))) { $(this).addClass('missing'); pass = false;}
				else  {$(this).removeClass('missing empty');}
			});
			$('#newsletterSubscribeBig #privacyPolicyAccepted').each(function(){
				if ($(this).attr('checked') == "" ) {$('#acceptance').addClass('missing'); pass = false;}
				else {$('#acceptance').removeClass('missing');}
			});
				
			return pass;

		},
		
		init : function(override){		
			var displayed = CookieManager.read('popupNewsletterShownCount');
			if (!displayed) displayed=1;
			else displayed = parseInt(displayed) + 1;
			CookieManager.create('popupNewsletterShownCount',displayed);
				
			
			if (displayed ==2 || displayed ==4 || override){
				// show popup
				ModalWindow.init(KedemHerbs.Subscribers.popup_en);
				if (override) CookieManager.create('popupNewsletterShownCount','10');
				
				
				$('#newsletterSubscribeBig input[type=text], #newsletterSubscribeBig input[type=email]').focus(function(){
					if ( $(this).attr('title') == $(this).attr('value') ) $(this).attr('value','');
				}).blur(function(){
					if ( $(this).attr('value') == $(this).attr('title') || $(this).attr('value') == "" ) $(this).attr('value',$(this).attr('title'));
					else $(this).removeClass('empty');
				});

				
				$('#subscribe').click(function(){
					if (KedemHerbs.Subscribers.validate()) KedemHerbs.Subscribers.record();
				});
			}
			
			$('#loadPrivacyPolicy').click(function(){
				KedemHerbs.Subscribers.privacyPolicy();
			});
			
		}
	},
	
	Stores : {
		eraseData : function(){
			$('table.store-list tbody tr, table.store-list thead td').remove();
		},		
		display : function (province){
			$.ajax({ 
				type: 'POST',
				url: '/_Assets/Ajax/stores.php',
				data: {province:province},
				success : function(theXML){
					var Row = "";
					// determine table header upon the country
					
					
					if (province == "international"){ // international
						tableHeader = '<td class="store">Store name</td><td class="address">Address</td><td class="city">Country</td><td class="phone">Phone</td>';
						$(theXML).find("partners").each(function(){
							$(this).find("store").each(function(){
								var store = $(this).find("Store").text();
								var address = $(this).find("Address").text();
								var city = $(this).find("Country").text();
								var phone = $(this).find("Phone").text();
								
								Row += "<tr><td class='store'>"+store+"</td><td class='address'>"+address+"</td><td class='city'>"+city+"</td><td class='phone'>"+phone+"</td></tr>";					
							});
						}); 
					}
					else if (province == "unitedstates"){// united states
						tableHeader = '<td class="store">Store name</td><td class="addressShort">Address</td><td class="city">City</td><td class="state">State</td><td class="phone">Phone</td>'; 
						$(theXML).find("partners").each(function(){
							$(this).find("store").each(function(){
								var store = $(this).find("Store").text();
								var address = $(this).find("Address").text();
								var city = $(this).find("City").text();
								var state = $(this).find("State").text();								
								var phone = $(this).find("Phone").text();
								
								Row += "<tr><td class='store'>"+store+"</td><td class='addressShort'>"+address+"</td><td class='city'>"+city+"</td><td class='state'>"+state+"</td><td class='phone'>"+phone+"</td></tr>";					
							});
						}); 					
					}
					else {
						var tableHeader = '<td class="store">Store name</td><td class="address">Address</td><td class="city">City</td><td class="phone">Phone</td>'; // canada				
						$(theXML).find("partners").each(function(){
							$(this).find("store").each(function(){
								var store = $(this).find("Store").text();
								var address = $(this).find("Address").text();
								var city = $(this).find("City").text();
								var phone = $(this).find("Phone").text();
								
								Row += "<tr><td class='store'>"+store+"</td><td class='address'>"+address+"</td><td class='city'>"+city+"</td><td class='phone'>"+phone+"</td></tr>";					
							});
						});
					}
					
					$('table.store-list thead').append(tableHeader);
					$('table.store-list tbody').append(Row);
					$('table.store-list tbody tr:odd').addClass('zebra');
					KedemHerbs.loader.hide();					

				}
			});				
		},	
			
		process : function(province){
			KedemHerbs.Stores.eraseData(); // remove the old content		
			KedemHerbs.loader.show();
			KedemHerbs.Stores.display(province);
		},
			
		init : function (province){						
			$("nav.storeCountries li").click(function(){
				$('nav.storeCountries li, nav.storeStates li').removeClass('selected'); // reset the displayed
				$(this).addClass('selected'); // assign the selected display
				var region = $(this).attr("name"); // get the new trigger
				if (region == "canada") {
					$("nav.storeStates").slideDown(200);
					province = "ab";
					$('nav.storeStates li:first').addClass('selected');
				}
				else {
					$("nav.storeStates").slideUp(200);
					province = region;
				}
				KedemHerbs.Stores.process(province);
				
			});			
			
			$("nav.storeStates li").click(function(){
				province = $(this).attr("name"); // get the new trigger
				$('nav.storeStates li').removeClass('selected'); // reset the displayed
				$(this).addClass('selected'); // assign the selected display
				KedemHerbs.Stores.process(province);
			});
			
			KedemHerbs.Stores.process(province);
		
		}
	}
}

$(document).ready(function(){
	KedemHerbs.init();
	KedemHerbs.Subscribers.init(override=false);
});

