var ShopMenu = new ShopMenuClass();
var ShopAjax = new ShopAjaxClass();
var ShopProduct = new ShopProductClass();
var ShopPreloader = new ShopPreloaderClass();
var ShopCart = new ShopCartClass();

function ShopMenuClass(){	
	this.init = function (){

	}
	
}

function ShopProductClass(){
	
	this.current_preview = null;
	this.current_back = null;
	
	this.current_thumb = null;
	this.click_avalable = true;
	
	this.currentProduct = new Object();
	this.currentProduct.color = "";
	this.currentImage = null;
	this.currentZoomImage = null;
	
	this.OverPreview = function(elem) {
		$(elem).parent().addClass("mouseOverProduct");
		if (this.current_preview) {
			$(this.current_preview).css({"display":"none"});
			$(this.current_preview).parent().css({"z-index": 1});
			this.current_preview = null;
		}
		this.current_preview = $(elem).next("a.subPreview");
		$(this.current_preview).css({"display":"block"});
		$(elem).parent().css({"z-index": 10});
	}
	
	this.OutPreview = function(elem) {
		$(elem).parent().removeClass("mouseOverProduct");
		$(elem).css({"display":"none"});
		$(elem).parent().css({"z-index": 1});
	}
	
	this.OverPreviewLarge = function(elem) {
		if (this.current_back) {
			$(this.current_back).removeClass("back");
			this.current_back = null;
		}
		this.current_back = $(elem).parent();
		$(this.current_back).addClass("back");
		
	}
	
	this.OutPreviewLarge = function(elem) {
		$(elem).parent().removeClass("back");
	}
	
	this.ClickAddToCart = function(){
		$("#options").submit();
		//alert($("#id_color").get(0).value);
		return false;	
	}
	
	this.ClickThumb = function(elem){
		if ($(elem).hasClass("active") || !this.click_avalable) return false;
		this.click_avalable = false;
		if (this.current_thumb) {
			$(this.current_thumb).removeClass("active");
			var old_image = $("#"+$(this.current_thumb).children(":first").attr("alt"));
		}
		this.current_thumb = elem;
		$(this.current_thumb).addClass("active");
		var new_image = $("#"+$(this.current_thumb).children(":first").attr("alt"));
		$(new_image).addClass("second")
					.css({"opacity":1});
		
		this.currentZoomImage = $("#zoom_"+$(new_image).attr("id"));
		this.currentProduct.color = $(new_image).attr("id").slice($(new_image).attr("id").lastIndexOf("_")+1);
		if ($("#id_color").attr("value") !== this.currentProduct.color)	this.SetCurrentColor();
		
		$(old_image).animate({"opacity":0},500,function(){$(old_image).removeClass("active");$(new_image).addClass("active")
																							   			 .removeClass("second");ShopProduct.click_avalable=true;});
		
		return false;
	}
	
	this.SetCurrentColor = function() {
		$("#id_color").val(this.currentProduct.color);
		$("#id_color").change();
	}
	
	this.SetCurrentThumb = function() {
		//alert("color "+this.current_thumb);
		if (this.currentProduct.color.length > 0) this.current_thumb = $("#thumb_front_"+this.currentProduct.color).parent();
		else this.current_thumb = $("div.productAllImages a.thumb:first");
		$(this.current_thumb).addClass("active");
		this.currentImage = $("#"+$(this.current_thumb).children(":first").attr("alt"));
		$(this.currentImage).addClass("active");
		this.currentZoomImage = $("#zoom_"+$(this.currentImage).attr("id"));
	}
	
	this.ChangeColor = function(elem){
		if ($(this.current_thumb).children(":first").attr("alt").indexOf(elem.value) < 0) 
			this.ClickThumb($("#thumb_front_"+elem.value).parent().get(0));
	}
	
	this.initDialog = function(){
		var dialog = $("#dialog");
		$(dialog).dialog({ autoOpen: false,
							modal: true,
							closeOnEscape: true,
							dialogClass: 'shopDialogBox'});
		$(dialog).bind('dialogclose', function(event, ui) {$("#shopDialogBg").get(0).className = "shopDialogBg"; $("#shopDialogContent").children().remove(); });
	}
	
	this.ShowSizingChart = function(){
		var dialog = $("#dialog");
		$(dialog).dialog("option", "height", 348);
		if ($("#id_size option:first").attr("value") == "XS") {
			$(dialog).dialog("option", "width", 660);
			$("#shopDialogBg").addClass("womensBg");
			this.AddSpanToDialog("womens","womens sizing chart");
			this.AddQuestionEmail();
		}
		else {
			$(dialog).dialog("option", "width", 516);
			$("#shopDialogBg").addClass("mensBg");
			this.AddSpanToDialog("mens","mens sizing chart");
			this.AddQuestionEmail();
		}
		$(dialog).dialog("open");
		return false;
	}
	
	this.AddSpanToDialog = function(elementClass, innerHTML){
		var span = document.createElement("span");
		span.className = elementClass;
		span.innerHTML = innerHTML;
		$("#shopDialogContent").append(span);
	}
	
	this.AddQuestionEmail = function(){
		var a = document.createElement("a");
		a.href = "mailto: info@wearpact.com";
		a.innerHTML = "FOR QUESTIONS, PLEASE EMAIL INFO@WEARPACT.COM";
		a.className = "for_questions";
		$("#shopDialogContent").append(a);
	}
	
	this.ShowZoomImage = function(){
		var dialog = $("#dialog");
		$(dialog).dialog("option", "height", 498);
		$(dialog).dialog("option", "width", 720);
		$("#shopDialogBg").addClass("zoomImageBg");
		var img = document.createElement("img");
		img.className = "zoomImg";
		img.src = $(this.currentZoomImage).attr("src");
		img.alt = "zoom image";
		img.onclick = function (){ $(dialog).dialog("close"); };
		$("#shopDialogContent").append(img);
		$(dialog).dialog("open");
		
		return false;
	}
	
	this.SetActiveFit = function(fit) {
		if (fit) {
			var elem = $("#id_fit_"+fit);
			$(elem).addClass("active");
		}
	}
}

function ShopAjaxClass( ){
	this.url = "/shop/ajax/";
	this.request = "";
	
	this.loaderBox = null;
	this.loaderBoxInfo = null;
	this.loader = null;
	
	this.getProductsByCause = function(slug){
		this.getJson("getProductsByCause",slug);
	}
	
	this.getProductsByFit = function(slug) {
		this.getJson("getProductsByFit",slug);	
	}
	
	this.getProductDetailsByCategories = function(cause_slug,fit_slug){
		this.getJson("getProductDetailsByCategories",cause_slug,fit_slug);
	}
	
	this.getStateList = function(countryId, select_id){
		var data_txt = '{"action": "getStateList", "countryId": "'+countryId+'"}';
		if (String(document.location).indexOf("https") > -1) var url = "/shop/ssl/ajax/";
		else var url = "/shop/ajax/";
		$.ajax({
			type: "POST",
			url: url,
			data: data_txt,
			dataType: "json",
			processData: false,
			success: function (json, status) {
				if (json.result) {
					create_state_list(json.stateList, select_id);
				} else {
					ShopAjax.showJsonError(json);
				}
		  		
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				ShopAjax.showServerError(textStatus, errorThrown);
			}
		});
	}
	
	this.setNewQuantity = function(cartitem){
		if (!$("#btn-quantity-"+cartitem).hasClass("active")) return false;
		var quantity = $("#quantity-"+cartitem).val();
		if (quantity < 1) 
			if (!confirm("Do you really want to delete "+$("#description-"+cartitem).html()+" from cart?")) return false;
		if (quantity > 0) {
			ShopCart.showCartAjaxProcess();	
			var data_txt = "cartitem="+cartitem+"&quantity="+quantity;
			var url = "/shop/cart/qty/ajax/";
			$.ajax({
				type: "POST",
				url: url,
				data: data_txt,
				dataType: "json",
				processData: false,
				success: function (json, status) {
					if (json.errors == ""){
						if (json.results) ShopCart.setNewQuantity(json);
					} else {
						$("#quantity-"+json.item_id).val($("#init-quantity-"+json.item_id).val());
						alert(json.errors);
						ShopCart.hideCartAjaxProcess(cartitem);
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					$("#quantity-"+cartitem).val($("#init-quantity-"+cartitem).val());
					ShopAjax.showServerError(textStatus, errorThrown);
					ShopCart.hideCartAjaxProcess(cartitem);
				}
			});
		}
		else {
			alert("There is impossible value!");
			$("#quantity-"+cartitem).val($("#init-quantity-"+cartitem).val());
		}
	}
	
	this.getJson = function(action,slug1,slug2){
		this.showLoader();
		if (slug2) var data_txt = '{"action": "'+action+'", "causeSlug": "'+slug1+'", "fitSlug": "'+slug2+'"}';
		else var data_txt = '{"action": "'+action+'", "slug": "'+slug1+'"}';
		$.ajax({
			type: "POST",
			url: "/shop/ajax/",
			data: data_txt,
			dataType: "json",
			processData: false,
			success: function (json, status) {
				if (json.result) {
					switch (action){
						case "getProductDetailsByCategories":
							ShopInfoBoxes.FillRightFinalBox(json);
							break;
						case "getProductsByCause":
							ShopInfoBoxes.FillFitBox(slug1,json);
							break;
					}
				} else {
					ShopAjax.showJsonError(json);
					ShopAjax.hideLoader();
				}
		  		
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				ShopAjax.showServerError(textStatus, errorThrown);
				ShopAjax.hideLoader();
			}
		});
	}
	
	this.addToCart = function(slug,color,size,kolvo){
		this.showLoader();
		var color_key = $("#color_id").get(0).value;
		var size_key = $("#size_id").get(0).value;
		var data_txt = color_key+"="+color+"&"+size_key+"="+size+"&productname="+slug+"&quantity="+kolvo;
		$.ajax({
			type: "POST",
			url: "/cart/add/ajax/",
			data: data_txt,
			dataType: "json",
			success: function (json, status) {
				if (json.results == "Success") {
					if (!ShopInfoBoxes.goToCart) {
						ShopAjax.getCartStatus();
						ShopInfoBoxes.DecProductQuantity(kolvo);
						ShopCart.addedItems = kolvo;
					}
					else self.location = "/cart/";
					sendTrackToGa(slug,"addedToCart");
				} else {
					ShopAjax.showJsonError(json);
				}
				ShopAjax.hideLoader();
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				ShopAjax.showServerError(textStatus, errorThrown);
				ShopAjax.hideLoader();
			}
		});
	}
	
	this.getCartStatus = function(){
		$.ajax({
			type: "POST",
			url: "/shop/ajax/",
			data: '{"action": "getCartStatus"}',
			dataType: "json",
			processData: false,
			success: function (json, status) {
				ShopCart.setCart(json);
			},
			error: function (){
				ShopAjax.hideLoader();
			}
		});
		return false;
	}
	
	this.showLoader = function() {
		if (!this.loader) this.addLoader();
		
		if (this.loaderBox) {
			
			var top = getY(this.loaderBox);
			var left = getX(this.loaderBox);
			var width = this.loaderBox.offsetWidth;
			var height = this.loaderBox.offsetHeight;
			
			this.loader.style.top = top+"px";
			this.loader.style.left = left+"px";
			this.loader.style.width = width+"px";
			this.loader.style.height = height+"px";
			
			this.loader.style.display = "block";
		} else {
			//this.loader.style.top = "0px";
			//this.loader.style.left = "0px";
			//this.loader.style.width = "100%";
			//this.loader.style.height = "100%";
			
			window.scroll(0,0);
			document.body.style.overflow = "hidden";			
			this.loader.style.display = "block";
			
		}
	}
	
	this.hideLoader = function() {
		if(!this.loaderBox) {
			document.body.style.overflow = "visible";			
		}
		this.loaderBox = null;
		if (this.loader) this.loader.style.display = "none";
	}
	
	this.addLoader = function() {
		if(this.loader == null) {
			var loaderElem = document.createElement("div");
			loaderElem.className = "pactLoader"
			this.loader = document.body.appendChild(loaderElem);
		}
	}
	
	this.showJsonError = function(json) {
		if (json.result === false)
		if (json.reasonMap)
		if (json.reasonMap.error)
			alert("Server error appears: " + json.reasonMap.error + ".\nPlease, try again later.");
			
		if (json.results == "Error")
		if (json.errors) {
			var errorMessage = "Server error appears:";
			for (var i = 0; i<json.errors.length; i++) {
				errorMessage += "\n" + json.errors[i][1];
			}
			errorMessage += ".\nPlease, try again later.";
			alert(errorMessage);
		}
	}
	
	this.showServerError = function(textStatus, errorThrown) {
		var textMessage = (errorThrown) ? "Server error appears: " + errorThrown + ".\nPlease, try again later." : "Server error appears.\nPlease, try again later.";
		alert(textMessage);
	}
}



function ShopPreloaderClass(){
	this.imagesOrder = new Array();
	this.downloadCounter = 0;
	this.windowDownloaded = false;
	this.timeoutPointer = null;
	this.timeoutDelay = 30000; //30 sec
	this.canceled = false;
		
	this.AddImgToOrder = function(img_src,slug){
		var image = new Object();
		image.src = img_src;
		if (slug) image.slug = slug;
		else image.slug = "";
		this.imagesOrder.push(image);
	}
	
	this.LoadImagesOrder = function(){
		var img = null;
		for (var i=0;i<this.imagesOrder.length;i++){
			img = new Image();
			img.onload = function(){ ShopPreloader.CheckCounter(); };
			img.src = this.imagesOrder[i].src;
			this.imagesOrder[i].img = img;
		}
	}
	
	this.GetSrcBySlug = function(slug){
		for (var i=0;i<this.imagesOrder.length;i++)
			if (this.imagesOrder[i].slug == slug) return this.imagesOrder[i].src;
		return null;
	}
	
	this.startTimeOut = function() {
		this.timeoutPointer = window.setTimeout("ShopPreloader.cancelPreloading()", this.timeoutDelay)
	}
	
	this.clearTimeOut = function() {
		window.clearTimeout(this.timeoutPointer);
	}
	
	this.cancelPreloading = function() {
		this.canceled = true;
		ShopAjax.hideLoader();
		ShopAjax.loader = $("#shopLoader").get(0);
	}
	
	this.CheckCounter = function(only_check){
		if(!this.canceled) {
			if (only_check) {
				this.windowDownloaded = true;
				if(this.downloadCounter < this.imagesOrder.length) {
					this.startTimeOut();
				}
			} else this.downloadCounter++;
			
			if ((this.downloadCounter >= this.imagesOrder.length) && this.windowDownloaded == true) {
				this.clearTimeOut();
				this.cancelPreloading();
			}
		}
	}
}

function ShopCartClass() {
	this.firstTimeLoad = false;
	this.buttonShown = false;
	this.collapsed = true;
	
	this.addedItems = 0;
	
	this.expandHeight = 66;
	this.collapseHeight = 25;
	this.duration = 600;
	
	this.timeoutDuration = 3000;
	this.timeoutPointer = null;
	
	this.quantityBefore = 0;
	
	this.setCart = function(json) {
		if(json.result) this.setCartInfo(json.count, json.total);
		else this.setCartInfo(0, 0);
		this.firstTimeLoad = true;
	}
	
	this.setCartInfo = function(count, total) {
		if (count > 1) var countSign = " items";
		else var countSign = " item";
		
		if (this.addedItems > 1) var msgSign = " items have ";
		else var msgSign = " item has ";
		
		$("#cartQuantity").attr("innerHTML"," (" + count + ")");
		if (count > 0) $("#cartQuantity").parent().parent().addClass("few");
		else $("#cartQuantity").parent().parent().removeClass("few");
		//$("#cartQuantitySign").get(0).innerHTML = this.addedItems + msgSign;
		this.items = count;
		
		//$("#cartMoney").get(0).innerHTML = "$"+total;
		
		if(this.firstTimeLoad) {
			$("#cartStatus").slideDown(300);
			//$("#cartStatus").slideDown(300, ShopCart.openCartButton());
		} else {
			$("#cartStatus").slideDown(300);
		}
	}
	
	//open cart button
	this.openCartButton = function(){
		var $cartBg = $("#cartStatusBg");
		var $cartDetails = $("#cartStatusDetails");
		
		if (this.collapsed){
			$cartBg.animate({height: (this.expandHeight-7)+"px"}, this.duration, "swing");
			$cartDetails.animate({height: this.expandHeight+"px"}, this.duration, "swing", function(){ShopCart.setCloseTimeout()});
			this.collapsed = false;
		}
	}
	
	this.setCloseTimeout = function() {
		this.timeoutPointer = window.setTimeout("ShopCart.closeCartButton()", this.timeoutDuration);
	}
	
	//close cart button
	this.closeCartButton = function(boxClass){
		var $cartBg = $("#cartStatusBg");
		var $cartDetails = $("#cartStatusDetails");
		
		if(this.timeoutPointer) {
			window.clearTimeout(this.timeoutPointer);
			this.timeoutPointer = null;
		}
		
		if (!this.collapsed){
			$cartBg.animate({height: (this.collapseHeight-7)+"px"}, this.duration, "swing");
			$cartDetails.animate({height: this.collapseHeight+"px"}, this.duration, "swing");
			this.collapsed = true;
		}
	}
	
	this.setNewQuantity = function(json){
		if (json.errors == ""){
			$("#quantity-"+json.item_id).val(json.item_qty);
			$("#init-quantity-"+json.item_id).val(json.item_qty)
			if (parseInt(json.item_qty) > 0) $("#itemsum-"+json.item_id).html("$"+parseFloat(json.discount_item_price).toFixed(2));
			else $("#itemsum-"+json.item_id).parent().parent().remove();
			$("#cartsum").html("$"+parseFloat(json.discount_cart_total).toFixed(2));
			var edit_href = $("#edit-"+json.item_id).attr("href");
			edit_href = edit_href.slice(0,edit_href.lastIndexOf("/")+1)+json.item_qty;
			$("#edit-"+json.item_id).attr("href",edit_href);
		}
		else {
			$("#quantity-"+json.item_id).val($("#init-quantity-"+json.item_id).val());
			alert(json.errors);
		}
		this.hideCartAjaxProcess(json.item_id);
	}
	
	this.showCartAjaxProcess = function(){
		$("#cartAjaxProcess").css({"width":$("#cartContent").attr("offsetWidth")})
							.css({"height":$("#cartContent").attr("offsetHeight")-$("#cartContent tr.cartButtons").eq(0).attr("offsetHeight")*2-$("#cartContent tr").eq(1).attr("offsetHeight")-45-28})
							.css({"margin-top":"45px"})
							.css({"display":"block"});
	}
	
	this.hideCartAjaxProcess = function(cartitem){
		$("#cartAjaxProcess").css({"display":"none"});
		$("#btn-quantity-"+cartitem).removeClass("active");
	}
	
	this.keydownQuantity = function(e,cartitem){
		if (e.keyCode == 13) {
			ShopAjax.setNewQuantity(cartitem);
			return false;
		}
		else {
			switch(e.keyCode){
				case(8):
				case(46):
				case(96):
				case(97):
				case(98):
				case(99):
				case(100):
				case(101):
				case(102):
				case(103):
				case(104):
				case(105):
					$("#btn-quantity-"+cartitem).addClass("active");
				case(37):
				case(39):	
				case(9):
					return true;
					break;
			}
			if ((e.keyCode >= 48) && (e.keyCode <= 57)) {
				$("#btn-quantity-"+cartitem).addClass("active");
				return true;
			}
			else return false;
			return false;
		}
	}
}