var BE = {
	Layout: {
		toggleForgotPassword: function(){
			$("#forgot_password_form").toggle();
			$("#loginForm").toggle();
		},
		
		attachEvents: function(){
			if ($(".wrapper_filters").length > 0){
				$(".wrapper_filters input").click(function(){
					$(this).next().toggleClass("selected");
					document.location = $(this).next().attr("href");
				})
			}
		},
		
		Banners: {
			nr: 1,
			animate:false,
			attachEvents: function(){
				if ($('#banner_home').length > 0){
					setInterval("BE.Layout.Banners.switchNext()", 5000);
					for(var i = 1; i< $("#banner_home").children().length; i++){
						$("#menu_" + i).click(function(){
							if (!BE.Layout.Banners.animate) {
								BE.Layout.Banners.switchBanner($(this).attr("id").split("_")[1]);
							}
						});
					}
				}
			},
			switchNext: function(){
				var id = parseInt($(".nonHiddenBanner").attr("id").split("_")[1]);
				if(id == $("#banner_home").children().length - 1){ var newId = 1;}
				else{newId = id + 1;}
				$(".nonHiddenBanner").fadeOut("slow", function fade(){
					$(".nonHiddenBanner").addClass("hiddenBanner").removeClass("nonHiddenBanner");
					$("#topBanner_" + newId).addClass("nonHiddenBanner").removeClass("hiddenBanner");
					$("#topBanner_" + newId).fadeIn("slow",function(){BE.Layout.Banners.animate = false;});
					$(".selected_button").removeClass("selected_button");
					$("#menu_" + newId).addClass("selected_button");
					});
				
			},
			switchBanner: function(n){
				BE.Layout.Banners.nr = n;
				BE.Layout.Banners.animate = true;
				$(".nonHiddenBanner").fadeOut("slow", function fade(){
					$(".nonHiddenBanner").addClass("hiddenBanner").removeClass("nonHiddenBanner");
					$("#topBanner_" + n).addClass("nonHiddenBanner").removeClass("hiddenBanner");
					$("#topBanner_" + n).fadeIn("slow",function(){BE.Layout.Banners.animate = false;} );
					$(".selected_button").removeClass("selected_button");
					$("#menu_" + n).addClass("selected_button");
					});
				
			}
		},
		
		StoreHours: {
			attachEvents: function(){
				if ($(".storehours").tooltip){
					$(".storehours").tooltip({ 
					    bodyHandler: function() { 
						
					        return "<h3>Store hours</h3><table class='storehoursTable'>" + 
					 			"<tr><td>Monday:</td><td>9:30am - 9:30pm EST</td></tr>" + 
								"<tr><td>Tuesday:</td><td>9:30am - 9:30pm EST</td></tr>" + 
								"<tr><td>Wednesday:</td><td>9:30am - 9:30pm EST</td></tr>" + 
								"<tr><td>Thursday:</td><td>9:30am - 9:30pm EST</td></tr>" + 
								"<tr><td>Friday:</td><td>9:30am - 9:30pm EST</td></tr>" + 
								"<tr><td>Saturday:</td><td>Closed</td></tr>" + 
								"<tr><td>Sunday:</td><td>19:00am - 8:00pm EST</td></tr></table>";
					    }, 
					    showURL: false 
					});
					
					if ($(".btn_confidence").tooltip){
						$(".btn_confidence").tooltip({ 
						    bodyHandler: function() { 

								return "<h3>Shop With Confidence</h3><ul>" + 
									"<li>No hidden charges</li>" + 
									"<li>Low flat rate shipping</li>" + 
									"<li>Satisfaction guaranteed</li>" + 
									"<li>100% secure shopping</li>" + 
									"<li>Includes USA Manufacturer Warranty</li>" + 
									"<li>All items are brand new</li></ul>";
						    }, 
						    showURL: false 
						});
					}
				}
			}
		},
		
		Product: {
			attachEvents: function(){
				BE.Layout.Product.attachStar();
				BE.Layout.Product.expandDescription();
			},
			
			expandDescription: function(){
				$("#descriptionMore").click(function(){
					if ($("#descriptionMore").html() == "more"){
						$("#longDescription").show();
						$("#descriptionMore").html("less");
					} else {
						$("#longDescription").hide();
						$("#descriptionMore").html("more");
					}
					return false;
				});
			},
			
			attachStar: function(){
				$(".starsrating div").each(function(){
					var star = this;
					
					var elementId = $(star).attr("id");
					var productId = elementId.split("_").pop();
					if (productId){
						var rating = $("#rating_value_" + productId).html();
						
						if (rating){
							var MAX_WIDTH = 85;
							var computedWidth = rating * MAX_WIDTH / 5;
							$(star).width(computedWidth);
						}
					}
				});
			}
		},
		
		Gallery: {
			attachEvents: function(){
				if ($(".image .thumb a").lightBox != undefined){
					$(".image .thumb a").lightBox();
					$("a.btn_gallery").lightBox();
				}
				if ($(".photo .thumb a").lightBox != undefined){
					$(".photo .thumb a").lightBox();
					$("a.btn_zoompic").lightBox();
				}
			}
		},
		
		Quicklook: {
			preloaderDelay: 1000,
			
			attachEvents: function(){
				BE.Layout.Quicklook.preloadImages();
				if (window["quicklookPreloader"]){
					setTimeout('BE.Layout.Quicklook.attachPreloading();', BE.Layout.Quicklook.preloaderDelay);
				}
			},
			
			attachPreloading: function(){
				/*
				for (var index in quicklookPreloader){
					BE.Layout.Quicklook.preload(quicklookPreloader[index]);
				}*/
				BE.Layout.Quicklook.bulkPreload();
			},
			
			bulkPreload: function(){
				var resourceUrl = "/ttest.php";
	            $.get(resourceUrl, {ids: quicklookPreloader.join('|')}, function(json){
					json = json.replace(/\s+/g, ' ');
					var result = eval("data=" + json);
					for (var key in result){
						var productId = key.split("_")[1];
						var link = $("#btn_quicklook_" + productId).get(0);
						$(link).parents(".center:first").before(result[key]);
					}
				});
			},
			
			preload: function(productId){
				var resourceUrl = "/quicklook.php";
				var link = $("#btn_quicklook_" + productId).get(0);
	            $.get(resourceUrl, {id: productId, rand: parseInt(Math.random()*100)}, function(content){
	                $(link).parents(".center:first").before(content);
				});
			},
			
			preloadImages: function(){
				var images = ["/static/images/bgr_quicklook.png",
					"/static/images/bgr_quicklook.png",
					"/static/images/bgr_quickcart_center.gif",
					"/static/images/bgr_quickcart_center.png",
					"/static/images/bgr_quickcart.gif",
					"/static/images/bgr_quickcart.png"];
				for (var i = 0; i < images.length; i++){
					var newImage = new Image();
					newImage.src = images[i];
				}
			}
		}
	},
	
	Logic: {
		VerifyPassword: function(){
			if ($("#signUpPassword").val() != $("#signUpPasswordConfirm").val()) {
				if ($("#errorContainer.invisibleError").length > 0) {
					$("#errorContainer").addClass("visibleError").removeClass("invisibleError");
					$("#errorContainer").html("Your repeated password does not match.");
				}
				return false;
			}
			else {
				$("#errorContainer").removeClass("visibleError").addClass("invisibleError");
				return true;
			}
				
				
			return true;
		},
		setHelpfullReview: function (helpfull, reviewId){
			
				$.post("/setHelpfullReview.php", { helpfull: helpfull, reviewId : reviewId}, function(response){
                     var data = eval("data =" + response);
					 $("#helpfull_" + reviewId).html(data.helpfull);					
 					 $("#totalNr_" + reviewId).html(data.totalNr);
					;});
			},
		Forms: {
			Validations: [],
			
			saveAddress: function(form){
				var fields = {};

				$("#" + form + " .inlineFormField").each(function(){
					var fieldName = $(this).attr("name");
					fields[fieldName] = $(this).val();
				});
		
				$.post("/saveOrderAddress.php", fields, function(response){
                    var data = eval("data=" + response);
					if(data.tax != undefined){
						$('#shippingRightContainer').html("$ " + data.shipping);
						$('#taxRightContainer').html("$ " + data.tax);
						$('#totalRightContainer').html("$ " + data.total);
						$('#subtotalRightContainer').html("$ " + data.subtotal);
						$('#viewMethodName').html(data.methodName);
					} else{
						if(data.response == 'ship'){
							if($('#editCompanyName').val() != ""){
								$('#viewShipName').html($('#editCompanyName').val());
							}else{
								$('#viewShipName').html($('#editShipFirstName').val() + " " + $('#editShipLastName').val());
							}
							$('#viewShipAdd1').html($('#editShipAdd1').val());
							$('#viewShipAdd2').html($('#editShipAdd2').val());
							$('#viewShipCity').html($('#editShipCity').val());
							$('#viewShipState').html($('#shipToAddressState').val());
							$('#viewShipZip').html($('#editShipZip').val());
							$('#viewShipPhone').html($('#editShipPhoneA').val() + " " + $('#editShipPhoneB').val() + " " + $('#editShipPhoneC').val());
							$('#viewShipEmail').html($('#editShipEmail').val());	
							$('#viewBillEmail').html($('#editShipEmail').val());
						}
						if(data.response == 'bill'){
							$('#viewBillName').html($('#billToName').val());
							$('#viewBillAdd1').html($('#editBillAdd1').val());
							$('#viewBillAdd2').html($('#editBillAdd2').val());
							$('#viewBillCity').html($('#editBillCity').val());
							$('#viewBillState').html($('#billToAddressState').val());
							$('#viewBillZip').html($('#editBillZip').val());
							$('#viewBillPhone').html($('#editBillPhoneA').val() + " " + $('#editBillPhoneB').val() + " " + $('#editBillPhoneC').val());
							$('#viewBillEmail').html($('#editShipEmail').val());
						}
						if(data.response == 'card'){
							$('#viewCcType').html($('#ccType').val());
							$('#viewCcNr').html($('#cardNumber').val());
							$('#viewCcName').html($('#cardName').val());
							$('#viewCcMonth').html($('#ccMonth option:selected').html());
							$('#viewCcYear').html($('#ccYear option:selected').html());
						}
						
					}
				});
			},
			
			
			toggleViewEdit: function(trigger, viewForm, editForm, cancel){
				if ($("#" + trigger).html() != "change"){
					if ($("#" + editForm + " .error").length > 0){
						return;
					}
				}

				$("#" + viewForm).toggle();
				$("#" + editForm).toggle();
				
				if ($("#" + trigger).html() == "change"){
					$("#" + trigger).html("save");
					$("#" + cancel).show();
				} else {
					$("#" + trigger).html("change");
					$("#" + cancel).hide();
					BE.Logic.Forms.saveAddress(editForm);
				}
			},
			
			cancelViewEdit: function(trigger, viewForm, editForm, cancel){
				$("#" + viewForm).toggle();
				$("#" + editForm).toggle();
				$("#" + trigger).html("change");
				$("#" + cancel).hide();
			},
			
			mandatory: function(element){
				$(element).val(jQuery.trim($(element).val()));
				return ($(element).val().length > 0);
			},
			verifyPassword: function(){
				if ($("#password").val() != $("#passwordRepeat").val()) {
					$("#password_text").addClass("error");
					$("#passwordRepeat_text").addClass("error");
					return false;
				}
				else {
					$("#password_text").removeClass("error");
					$("#passwordRepeat_text").removeClass("error");
					return true;
				}
			},
			validateEmail: function(element){
				var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
				$(element).val(jQuery.trim($(element).val()));
                return emailPattern.test($(element).val()); 
			},
			validateNumericField: function(element){
				var numericPattern = /^[0-9]+$/;
				$(element).val(jQuery.trim($(element).val()));
                return numericPattern.test($(element).val()); 
			},
			validateZipCode: function(element){
				var zipPattern = /^[0-9]+$/;
				$(element).val(jQuery.trim($(element).val()));
                return zipPattern.test($(element).val()); 
			},
			validatePhone: function(element){
				var phonePattern = /^[0-9]+$/;
				$(element).val(jQuery.trim($(element).val()));
                return phonePattern.test($(element).val()) && ($(element).val().length == 3); 
			},
			validatePhoneB: function(element){
				var phonePattern = /^[0-9]+$/;
				$(element).val(jQuery.trim($(element).val()));
                return phonePattern.test($(element).val()) && ($(element).val().length == 4); 
			},
			validateCardType: function(element){
				return ($("#ccType option").index($("#ccType option:selected")) != 0)
			},
			validateCardExpirationMonth: function(element){
				return ($("#ccMonth option").index($("#ccMonth option:selected")) != 0);
			},
			validateCardExpirationYear: function(element){
				return ($("#ccYear option").index($("#ccYear option:selected")) != 0);
			},
			validateTermsAndCond : function(element){
                return $(element).attr("checked"); 
			},
			attachEvents: function(){
				if ($("#checkOut1").length > 0){
					BE.Logic.Forms.attachCheckoutForm();
				}
				
				if ($("#loginForm").length > 0){
					BE.Logic.Forms.attachLoginForm();
				}
				
				if ($("#editBillingAddress").length > 0){
					BE.Logic.Forms.attachVerifyOrderQuickEdit();
					
				}
			},
			
			attachLoginForm: function(){
				BE.Logic.Forms.attachValidations($("#loginEmail"), $("#loginEmailLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateEmail]);
				BE.Logic.Forms.attachValidations($("#loginPassword"), $("#loginPasswordLabel"), [BE.Logic.Forms.mandatory]);

				BE.Logic.Forms.attachValidations($("#signUpEmail"), $("#signUpEmailLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateEmail]);
				BE.Logic.Forms.attachValidations($("#signUpPassword"), $("#signUpPasswordLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#signUpPasswordConfirm"), $("#signUpPasswordConfirmLabel"), [BE.Logic.Forms.mandatory]);
			},
			
			attachCheckoutForm: function(){
				BE.Logic.Forms.attachDeliveryAndPaymentsEvents();
				$("#why_phone_trigger").tooltip({ bodyHandler: function() { return "We need your phone number in case we have trouble reaching you by email."; }, showUrl: false });
				$("#why_pwd_trigger").tooltip({ bodyHandler: function() { return "You can use your email and this password to check your order status."; }, showUrl: false });
			
            	$("#shipToPhone1a").keyup(function(){BE.Navigation.autocompletePhone("#shipToPhone1a","#shipToPhone1b",3);}); 
				$("#shipToPhone1b").keyup(function(){BE.Navigation.autocompletePhone("#shipToPhone1b","#shipToPhone1c",3);}); 				
				$("#shipToPhone1c").keyup(function(){BE.Navigation.autocompletePhone("#shipToPhone1c","#shipToPhone2a",4);}); 
				$("#shipToPhone2a").keyup(function(){BE.Navigation.autocompletePhone("#shipToPhone2a","#shipToPhone2b",3);}); 								
				$("#shipToPhone2b").keyup(function(){BE.Navigation.autocompletePhone("#shipToPhone2b","#shipToPhone2c",3);}); 		
				$("#shipToPhone2c").keyup(function(){BE.Navigation.autocompletePhone("#shipToPhone2c","#email",4);}); 		
																													
				
				$("#billToPhone1a").keyup(function(){BE.Navigation.autocompletePhone("#billToPhone1a","#billToPhone1b",3);}); 
				$("#billToPhone1b").keyup(function(){BE.Navigation.autocompletePhone("#billToPhone1b","#billToPhone1c",3);}); 				
				$("#shipToPhone1c").keyup(function(){BE.Navigation.autocompletePhone("#billToPhone1c","#ccName",4);}); 	
			},
			
			validate: function(element, label, validators){
				var success = true;
				
				for (var i = 0; i < validators.length; i++){
					if (!validators[i](element)){
						$(label).addClass("error");
						success = false;
					} else {
						$(label).removeClass("error");
					}
				}
				
				return success;
			},
			
			attachValidations: function(element, label, validators){
				var form = $(element).parents("form").attr("id");
				
				if (!BE.Logic.Forms.Validations[form]){
					BE.Logic.Forms.attachConditionalSubmit($(element).parents("form"), form);
					BE.Logic.Forms.Validations[form] = [];
				}
				
				BE.Logic.Forms.Validations[form].push({element: element, label: label, validators: validators});
				$(element).blur( function(){BE.Logic.Forms.validate(element, label, validators);});
			},
			
			attachConditionalSubmit: function(element, form){
				$(element).submit(function(){
					var success = true;
					var form = $(element).attr("id");
					for (var i = 0; i < BE.Logic.Forms.Validations[form].length; i++){
						var field = BE.Logic.Forms.Validations[form][i];
						if (!BE.Logic.Forms.validate(field.element, field.label, field.validators)){
							success = false;
						}
					}
				
					return success;
				});
			},
			
			
			attachVerifyOrderQuickEdit: function(){
				BE.Logic.Forms.attachValidations($("#editShipFirstName"), $("#editShipNameLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#editShipLastName"), $("#editShipNameLabel"), [BE.Logic.Forms.mandatory]);
				
				BE.Logic.Forms.attachValidations($("#editShipAdd1"), $("#editShipAdd1Label"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#editShipCity"), $("#editShipCityLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#editShipZip"), $("#editShipZipLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateZipCode]);
                BE.Logic.Forms.attachValidations($("#editShipPhoneA"), $("#editShipPhoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhone]);
				BE.Logic.Forms.attachValidations($("#editShipPhoneB"), $("#editShipPhoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhone]);
				BE.Logic.Forms.attachValidations($("#editShipPhoneC"), $("#editShipPhoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhoneB]);

				BE.Logic.Forms.attachValidations($("#editShipEmail"), $("#editShipEmailLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateEmail]);
				
				BE.Logic.Forms.attachValidations($("#billToName"), $("#billToNameLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#editBillAdd1"), $("#billToAdd1Label"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#editBillCity"), $("#billToCityLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#editBillZip"), $("#billToZipLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#editBillPhoneA"), $("#billToPhoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhone]);
				BE.Logic.Forms.attachValidations($("#editBillPhoneB"), $("#billToPhoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhone]);
				BE.Logic.Forms.attachValidations($("#editBillPhoneC"), $("#billToPhoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhoneB]);	
			},
					
			attachDeliveryAndPaymentsEvents: function(){
				BE.Logic.Forms.attachValidations($("#first"), $("#firstLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#last"), $("#lastLabel"), [BE.Logic.Forms.mandatory]);
				
				BE.Logic.Forms.attachValidations($("#shipToAddressLine1"), $("#shipToAddressLine1Label"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#shipToAddressCity"), $("#shipToAddressCityLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#shipToAddressState"), $("#shipToAddressStateLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#shipToAddressZip"), $("#shipToAddressZipLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateZipCode]);
                BE.Logic.Forms.attachValidations($("#shipToPhone1a"), $("#phoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhone]);
				BE.Logic.Forms.attachValidations($("#shipToPhone1b"), $("#phoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhone]);
				BE.Logic.Forms.attachValidations($("#shipToPhone1c"), $("#phoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhoneB]);

				BE.Logic.Forms.attachValidations($("#email"), $("#emailLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateEmail]);
				BE.Logic.Forms.attachValidations($("#password"), $("#password_text"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#passwordRepeat"), $("#passwordRepeat_text"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.verifyPassword]);
				
				if($("#billingAddressBox").attr("checked")) {
					BE.Navigation.toggleBillingAddress("#billingAddressBox", false);
					BE.Logic.Forms.attachValidations($("#billToName"), $("#billToNameLabel"), [BE.Logic.Forms.mandatory]);
					BE.Logic.Forms.attachValidations($("#billToAddressLine1"), $("#billToAddressLine1Label"), [BE.Logic.Forms.mandatory]);
					BE.Logic.Forms.attachValidations($("#billToAddressCity"), $("#billToAddressCityLabel"), [BE.Logic.Forms.mandatory]);
					BE.Logic.Forms.attachValidations($("#billToAddressState"), $("#billToAddressStateLabel"), [BE.Logic.Forms.mandatory]);
					BE.Logic.Forms.attachValidations($("#billToAddressZip"), $("#billToAddressZipLabel"), [BE.Logic.Forms.mandatory]);
					BE.Logic.Forms.attachValidations($("#billToPhone1a"), $("#billPhoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhone]);
					BE.Logic.Forms.attachValidations($("#billToPhone1b"), $("#billPhoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhone]);
					BE.Logic.Forms.attachValidations($("#billToPhone1c"), $("#billPhoneLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validatePhoneB]);	
				}
				
				BE.Logic.Forms.attachValidations($("#ccName"), $("#ccNameLabel"), [BE.Logic.Forms.mandatory]);
				BE.Logic.Forms.attachValidations($("#ccType"), $("#ccTypeLabel"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateCardType]);
				BE.Logic.Forms.attachValidations($("#ccYear"), $("#ccDate"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateCardExpirationYear]);
				BE.Logic.Forms.attachValidations($("#ccMonth"), $("#ccDate"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateCardExpirationMonth]);
				BE.Logic.Forms.attachValidations($("#ccNumber"), $("#ccNumber_text"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateNumericField]);
				BE.Logic.Forms.attachValidations($("#cvvCode"), $("#cvv_text"), [BE.Logic.Forms.mandatory, BE.Logic.Forms.validateNumericField]);
				BE.Logic.Forms.attachValidations($("#termsConditions"), $("#terms_text"), [BE.Logic.Forms.validateTermsAndCond]);
					
				$(function() {
        				/*$("#checkOut1").validate({
          					  rules: {
                				 ccNumber: {
                   				 creditcard2: function(){ 
								 		return $('#ccType').val(); 
								}
               				   }	
           					 },
						 	 highlight: function(element, errorClass) {
							 	$(element.form).find("label[for=ccNumber]").removeClass("valid");
             					$(element.form).find("label[for=ccNumber]").addClass("error");
            				 },
  						     unhighlight: function(element, errorClass) {
             					$(element.form).find("label[for=ccNumber]").removeClass("error");
								$(element.form).find("label[for=ccNumber]").addClass("valid");
	            				 }
								 
   						 });


   			 			// helper function to fire validation on field2 when cardType changes
		        		$('#ccNumber').change(function(){
		           		 	$("#checkOut1").validate().element('#ccNumber');
		    			});*/
				});
			}
		},
		
		Review: {
			attachEvents: function(){
				if ($("#submitReview").length > 0){
				   $("#submitReview").click(function(){
				   	var reviewTitle  = jQuery.trim($("#reviewTitle").val());
					var userNickname = jQuery.trim($("#userNickname").val());
					var reviewRating = $("input[name='reviewRating']:checked").val();
					var reviewSummary = jQuery.trim($("#reviewSummary").val());
				    
					var validateMandatoryField = function(field){return (field != undefined) && (field != "");};
					var isValidReviewTitle = function(reviewTitle){return validateMandatoryField(reviewTitle);};	
					var isValidReviewRating = function(reviewRating){return validateMandatoryField(reviewRating);};	
					var isValidReviewSummary = function(reviewSummary){return validateMandatoryField(reviewSummary);};
					
					if(isValidReviewRating(reviewRating) && isValidReviewSummary(reviewSummary) && isValidReviewTitle(reviewTitle)){
						$.post("/reviewActions.php", {action: "saveReview", 
													  reviewRating: reviewRating, 
													  reviewSummary: reviewSummary,
													  reviewTitle: reviewTitle,
													  userNickname: userNickname}, 
													  function(response){
													  	$("#createReview").html(response);
													  },
													  "html");
					}	
				   });
				}
			}
		},
		Cart: {
			attachEvents: function(){
				$(".cart").click(BE.Logic.Cart.refresh);
				if ($(".updateQuantity").length > 0){
					$(".updateQuantity").click(BE.Logic.Cart.updateQuantity);
					$("#deliveryMethods").change(BE.Logic.Cart.updateDeliveryMethods);
				}
			},
			
			updateDeliveryMethods: function(){
				var postData = {action: "methods", method: $("#deliveryMethods").val()};
				
				$.post("/cart.php", postData, function(){ 
					window.location.reload(true); 
				});
			},
			
			updateQuantity: function(){
				var postData = {action: "quantity"};
				$("input[name='qty']").each(function(index, item){
					postData[$(item).attr("id")] = $(item).val();
				});
				
				$.post("/cart.php", postData, function(){ window.location.reload(true); });
//				$.post("/cart.php", postData);
			},
			
			addToCart: function(productId, fastCart){
				if (fastCart){
	            	$.post("/cart.php", {action: "add", productId: productId}, function(){
						document.location = "/yourCart.php";
					});
				} else {
	            	BE.Navigation.closeQuicklook();
	            	$.post("/cart.php", {action: "add", productId: productId}, BE.Logic.Cart.display);
				}
			},
			
			remove: function(productId){
	            BE.Navigation.closeQuicklook();
	            $.post("/cart.php", {action: "remove", productId: productId}, BE.Logic.Cart.display);
			},
			
			removeFromCart: function(productId, orderNr){
	            BE.Navigation.closeQuicklook();
	            $.post("/cart.php", {action: "remove", productId: productId, orderNr: orderNr}, function(response){
					var content = eval("data=" + response);
					$("#cartCount").html(content.count);
					if (content.count == 0){
						window.location.reload(true);
					} else {
						$("#product_" + productId).parents("tr:first").remove();
					}
					
					window.location.reload(true);
				});
			},
			
			refresh: function(){
	            BE.Navigation.closeQuicklook();
	            $.get("/cart.php", {}, BE.Logic.Cart.display);
			},
			
			close: function(){
				$("#cartPopup").fadeOut("slow", function(){ $("#cartPopup").remove(); });
			},
			
			display: function(response){
				var content = eval("data=" + response);
				BE.Logic.Cart.close();
				try {
					$(".cart:first").before(content.html);
					$.scrollTo('.cart', 500);
				} catch(e){
					;
				}
				
				$("#cartPopup").fadeIn("slow");
				$("#cartCount").html(content.count);
//				$("#branding .items").text(content.count == 1? "item": "items");
			}
		}
	},
	
    Navigation: {
		openWarranty: function(productId){
			$('#' + productId + '_warranty').click(); 
			$.scrollTo('#' + productId + '_warranty', 500);
			return false;
		},
		
		toggleFilters: function(link){
			$(link).parent("li").siblings(".hiddenFilter").toggle();
			if ($(link).html() == "more"){
				 $(link).html("less");
			} else {
				 $(link).html("more");
			}
			return false;
		},
		
		Accessories: {
			displayBrandsForCategory: function(element, categoryId){
				$("#accessoryCategory .selected").removeClass("selected");
				$(element).addClass("selected");
				$.get("/getData.php", {content: "brands", categoryId: categoryId}, function(response){
					var data = eval("data=" + response);
					BE.Navigation.Accessories.fillList(data, $("#accessoryBrand"), function(item){
						if (item.manname && item.manid){
							return "<a href='#' onclick='BE.Navigation.Accessories.displayProductsForBrand(this, " + item.manid + ", " + categoryId + "); return false;'>" + item.manname + "</a>";
						} else {
							return "";
						}
					});
					$("#accessoryProduct").html("");
					$("#product").html("");
				});
			},
			
			displayProductsForBrand: function(element, brandId, categoryId){
				$("#accessoryBrand .selected").removeClass("selected");
				$(element).addClass("selected");
				$.get("/getData.php", {content: "products", brandId: brandId, categoryId: categoryId}, function(response){
					var data = eval("data=" + response);
					BE.Navigation.Accessories.fillList(data, $("#accessoryProduct"), function(item){
						if (item.id && item.title){
							return "<a href='#' onclick='BE.Navigation.Accessories.displayProduct(this, " + item.id + "); return false;'>" + item.title + "</a>";
						} else {
							return "";
						}
					});
					$("#product").html("");
				});
			},
			
			displayProduct: function(element, productId){
				$("#accessoryProduct .selected").removeClass("selected");
				$(element).addClass("selected");
				$.get("/getData.php", {content: "product", productId: productId}, function(response){
					$("#product").html(response);
				});
			},
			
			fillList: function(content, container, processor){
				var items = [];
				for (var i = 0; i < content.length; i++){
					items.push(processor(content[i]));
				}
				container.html(items.join(" "));
			}
		},
		
        quicklook: null,
        toggleBillingAddress:  function(selector, replicate){
		   if ($(selector).attr("checked") == true){
			if (replicate){
				$("#billToName").val($("#first").val());
				$("#billToAddressLine1").val($("#shipToAddressLine1").val());
				$("#billToAddressLine2").val($("#shipToAddressLine2").val());
				$("#billToAddressCity").val($("#shipToAddressCity").val());
				$("#billToAddressZip").val($("#shipToAddressZip").val());
				$("#billToPhone1a").val($("#shipToPhone1a").val());
				$("#billToPhone1b").val($("#shipToPhone1b").val());
				$("#billToPhone1c").val($("#shipToPhone1c").val());
				$("#billToAddressState option:selected").removeAttr("selected");
				$("#billToAddressState option[value=" + $("#shipToAddressState").val() + "]").attr("selected", "selected");
			}
			
		   	$(".billInfo").show().addClass("toggledVisible");
		   }
		   else{
		   	$(".billInfo").hide().removeClass("toggledVisible");
		   }
		} ,
		autocompletePhone: function(currentField, nextField, size){
		 if($(currentField).val().length == size){
		 	$(nextField).focus();
		 }
		 /*if(!$(currentField).val().match(/^0-9$/)) {
		 	$(currentField).val("");
		 }	*/
		},
		toggleAccessories: function(selector){
			if ($(selector + " .product_short:hidden").length > 0){
				$(selector + " .product_short:hidden").show().addClass("toggledVisible");
			} else {
				$(selector + " .toggledVisible").hide().removeClass("toggledVisible");
			}
			
			return false;
		},
		
		toggleAccessoriesByCategory: function(catName){
			var className = catName.replace(/ /, "_");
			$(".product_short").hide();
			$("." + className).show();
			
			if ($(".product_short:visible").length > 3){
				$("#viewMorePopular").show();
			} else {
				$("#viewMorePopular").hide();
			}
			
			return false;
		},
		
        attachEvents: function(){
			 $(".smallPopup").click(function(e){
				window.open(e.target.href, "", " location = 1, resizable = yes, status = 1, scrollbars = 1, width = 400, height=400 ");
				return false;
			});

			 $(".bigPopup").click(function(e){
				window.open(e.target.href, "", " location = 1, resizable = yes, status = 1, scrollbars = 1, width = 1000, height=800");
				return false;
			});
			
			$("#sortBy").change(function(){
				if (document.location.search.indexOf("ob=") == -1){
					document.location = document.location + "&ob=" + $("#sortBy").val();
				} else {
					var url = document.location.href;
					url = url.replace("brandaz", $("#sortBy").val());
					url = url.replace("brandza", $("#sortBy").val());
					url = url.replace("priceasc", $("#sortBy").val());
					url = url.replace("pricedesc", $("#sortBy").val());
					document.location =  url;
				}
			});
	
		
			$("#sortByBottom").change(function(){
				if (document.location.search.indexOf("ob=") == -1){
					document.location = document.location + "&ob=" + $("#sortByBottom").val();
				} else {
					var url = document.location.href;
					url = url.replace("brandaz", $("#sortBy").val());
					url = url.replace("brandza", $("#sortBy").val());
					url = url.replace("priceasc", $("#sortBy").val());
					url = url.replace("pricedesc", $("#sortBy").val());
					document.location =  url;
				}
			});
	
	
			var swapHotDeals = function() { BE.Navigation.swapItem("#section_home_deals"); return false; };
            $("#viewMoreHotDeals").click(swapHotDeals);
            $("#viewMoreHotDealsTop").click(swapHotDeals);
			if($(".productRelSelect").length != 0){
				$(".productRelSelect").change(function(){document.location = $("select.productRelSelect option:selected").attr("id")});
			}
            
			var swapMorePopular = function() { 
                if ($("#section_home_popular").length != 0){
                    BE.Navigation.swapItem("#section_home_popular"); return false; 
                } else {
					BE.Navigation.toggleAccessories(".section_product_related");
                }

				return false;
            };

            $("#viewMorePopular").click(swapMorePopular);
            $("#viewMorePopularTop").click(swapMorePopular);
            if($(".search_filters").length != 0){
				BE.Navigation.attachFilterToggle();
			}
            $(".wrapper_tabs").each(BE.Navigation.attachTabToggle);
            $(".wrapper_cart_tabs").each(BE.Navigation.attachTabToggleCart);
            $(".priceRebate").each(BE.Navigation.attachTabToggleRebate);
            $(".pr_snippet_product .prSnippetEngine .prSnippetReadReviews").each(BE.Navigation.attachTabToggleViewReview);
//			$(".wrapper_tabs a:first").click();
            
            BE.Navigation.attachQuicklook();
        },
		
		attachFilterToggle: function(){
			/*$(".search_filters .filterHeader").click(function(){
				$(this).nextAll().toggle();
			});*/
			$(".search_filters .filterTitleTog").click(function(){
				$(this).nextAll().toggle();
			});
		},
        
        getProductQuicklook: function (link, productId){
            var resourceUrl = "/quicklook.php";
            var quicklookId = "product_quicklook_" + productId;
            if (BE.Navigation.quicklook && (BE.Navigation.quicklook == quicklookId)){
                BE.Navigation.closeQuicklook();
                return false;
            }
            
			BE.Logic.Cart.close();
            BE.Navigation.closeQuicklook();

			var displayQuicklook = function(link, quicklookId){
            	$("#" + quicklookId).fadeIn("slow");//.draggable();

					var snippet = "<iframe border='0' src='/reviewSnippet.php?id=" + productId + "' width='120' height='60' frameborder='0' scrolling='no' align ='left'></iframe>";

					$("#" + quicklookId + " .pr_snippet_category").html(snippet);
			
					var index = 0;
					var query = $(link).parents(".center:first").children(".product_short");
					for(var i = 0; i < query.length; i++){
						if ($(link).parents(".product_short").get(0) == query.get(i)){
							break;
						}

						index++;
					}

					var productHeight = 81;

					var top = productHeight * index;
					$("#" + quicklookId).css("top", top);
	                BE.Navigation.quicklook = quicklookId;
					BE.Layout.Product.attachStar();
			};
			
			if ($("#" + quicklookId).length > 0){
				displayQuicklook(link, quicklookId);
			} else {
	            $.get(resourceUrl, {id: productId, rand: parseInt(Math.random()*100)}, function(content){
	                $(link).parents(".center:first").before(content);
					displayQuicklook(link, quicklookId);
	            });
			}
        },

		showTab: function(tab, elementClass){
            $("#" + BE.Navigation.quicklook + " .product_quick .wrapper_tabs a.selected").removeClass("selected");
            $(tab).addClass("selected");

            $("#" + BE.Navigation.quicklook + " .product_quick .wrapper_info").hide();
            $("#" + BE.Navigation.quicklook + " .product_quick ." + elementClass).show();
		},
        
        closeQuicklook: function(){
            if (BE.Navigation.quicklook){
                $("#" + BE.Navigation.quicklook).fadeOut("slow");
                BE.Navigation.quicklook = null;
            }
        },
        
        attachQuicklook: function(){
            $(".product_short").mouseover(function(){
                $(this).children(".quicklook_btn").show();
            });
            $(".product_short").mouseout(function(){
                $(this).children(".quicklook_btn").hide();
            });
			 $(".thumb").mouseover(function(){
                $(this).children(".quicklook_btn").show();
            });
            $(".thumb").mouseout(function(){
                $(this).children(".quicklook_btn").hide();
            });
			
        },
        
        attachTabToggle: function(root){
            $(".wrapper_tabs a").click(function selectTab(newTab){
                $(newTab.target).parents(".wrapper_tabs:first").find("a.selected").removeClass("selected");
                $(this).addClass("selected");
                
				if ($(this).attr("href").indexOf("review") > 0){
					$("#tab_content").html($("#powerReviewsContainer").html());
				} else {
                var	 resourceUrl = $(this).attr("id").split("_");
				
					resourceUrl = "/getProductDetails.php?id=" + resourceUrl[0] + "&tab=" + resourceUrl[1];
	                $.get(resourceUrl, {rand: parseInt(Math.random()*100)}, function(content){
	                    $("#tab_content").html(content);
						BE.Logic.Review.attachEvents();	
	                });
				}
                
                return false;
            });
        },
        attachTabToggleCart: function(root){
            $(".wrapper_cart_tabs a").click(function selectTab(newTab){
               
                var	 resourceUrl = $(this).attr("id").split("_");
				var itemId = resourceUrl[2];
					resourceUrl = "/getProductDetails.php?id=" + resourceUrl[2] + "&cart_tab=" + resourceUrl[1];
				$.get(resourceUrl, {rand: parseInt(Math.random()*100)}, function(content){
	                    $("#tab_cart_content_"+itemId).html(content);
						BE.Logic.Review.attachEvents();	
	                });
//                $("#tab_cart_content_"+itemId).html(resourceUrl);
                return false;
            });
        },
        attachTabToggleRebate: function(root){
             $(".priceRebate a").click(function selectTabNew(newTab){
                 $(".wrapper_tabs").find("a.selected").removeClass("selected");
                 
                 var	 resourceUrl = $(this).attr("id").split("_");
                 $("#"+ resourceUrl[0]+"_rebate").addClass("selected");
                 var pid = resourceUrl[0]+"_rebate";
                 document.getElementById(pid).scrollIntoView();
                 resourceUrl = "/getProductDetails.php?id=" + resourceUrl[0] + "&tab=" + resourceUrl[1];
				
                $.get(resourceUrl, {rand: parseInt(Math.random()*100)}, function(content){
                    $("#tab_content").html(content);
					BE.Logic.Review.attachEvents();	
                });
               
                 return false;
            });
        },
        attachTabToggleViewReview: function(root){
             $(".pr_snippet_product .prSnippetEngine .prSnippetReadReviews a").click(function selectTabNew(newTab){
                $(".wrapper_tabs").find("a.selected").removeClass("selected");
                 
                var res_pid =  $(".pr_snippet_product").attr("id").split("_");
                var pid = res_pid[1];
                 $("#"+pid+"_review").addClass("selected");
                 var pid_tab = pid+"_review";
                 document.getElementById(pid_tab).scrollIntoView();
                $("#tab_content").html($("#powerReviewsContainer").html());
               
                 return false;
            });
        },
        swapItem: function(container){
            var items = $(container + " .product_short");
			if ($(container + " .product_short:hidden").length > 0){
				BE.Navigation.closeQuicklook();
	            var oldItem = items.get(0);
	            var newItem = items.get(3);

	            $(oldItem).animate({"height": "hide"}, "slow", "linear", function(){
	                $(this).parent().append($(oldItem).hide());
	            });
	            $(newItem).show();
			}
            return false;
        },

		toggleSubcategories: function(categoryId){
			if ($("#subcategories_"+categoryId+" .hiddenItem").length != 0){
				$("#subcategories_"+categoryId+" .moreLink").html("less");
				$("#subcategories_"+categoryId+" .hiddenItem").removeClass("hiddenItem").addClass("visibleItem");
				$("#subcategories_"+categoryId+" .btn_expand").removeClass("btn_expand").addClass("btn_collapse");
			} else {
				$("#subcategories_"+categoryId+" .visibleItem").removeClass("visibleItem").addClass("hiddenItem");
				$("#subcategories_"+categoryId+" .moreLink").html("more");
				$("#subcategories_"+categoryId+" .btn_collapse").removeClass("btn_collapse").addClass("btn_expand");
			}
		}
		
    }
};

$(document).ready(function(){
    BE.Navigation.attachEvents();
	BE.Layout.Product.attachEvents();
	BE.Layout.Gallery.attachEvents();
	BE.Layout.Quicklook.attachEvents();
	BE.Layout.StoreHours.attachEvents();
	BE.Layout.attachEvents();
	BE.Logic.Cart.attachEvents();
	BE.Logic.Forms.attachEvents();
	BE.Layout.Banners.attachEvents();
	
	$("#billingAddressBox").click(function(){BE.Navigation.toggleBillingAddress("#billingAddressBox", true);});
	
});