$(function() {
	$(".product div:first-child").addClass("first");
	$("input.input, textarea").placeHolder();
	function filterPath(string) {
	  return string
	    .replace(/^\//,'')
	    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
	    .replace(/\/$/,'');
	  }
	  var locationPath = filterPath(location.pathname);
	  var scrollElem = scrollableElement('html', 'body');
	
	  $('a[href*=#]').each(function() {
	    var thisPath = filterPath(this.pathname) || locationPath;
	    if (  locationPath == thisPath
	    && (location.hostname == this.hostname || !this.hostname)
	    && this.hash.replace(/#/,'') ) {
	      var $target = $(this.hash), target = this.hash;
	      if (target) {
	        var targetOffset = $target.offset().top;
	        $(this).click(function(event) {
	          event.preventDefault();
	          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
	            location.hash = target;
	          });
	        });
	      }
	    }
	  });
	
	  function scrollableElement(els) {
	    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
	      var el = arguments[i],
	          $scrollElement = $(el);
	      if ($scrollElement.scrollTop()> 0) {
	        return el;
	      } else {
	        $scrollElement.scrollTop(1);
	        var isScrollable = $scrollElement.scrollTop()> 0;
	        $scrollElement.scrollTop(0);
	        if (isScrollable) {
	          return el;
	        }
	      }
	    }
	    return [];
	  }
	  
	  modalOpened = false;
	  
	  // kosarba tetel
	$(".product_to_cart").submit(function(e){
		if (!modalOpened) {
			e.preventDefault();
			$(".modal_qty input").val("1");
			var $parent = $(this).parent(), title = $parent.find(".title").text(), priceText = $parent.find(".price").text(), price = cart.priceToInt(priceText), id = $(this).find("input[name='id']").val(), inCart = 1;
			$("#modal_title").text(title);
			$("td.modal_price").text(priceText);
			$("#modal_bg").fadeIn(400);
			$("#continue_shopping").bind("click", function(e) {
				e.preventDefault();
				close_modal(function() {});
			});
			$("#order_product").bind("click", function(e) {
				e.preventDefault();
				close_modal(function() {
					$("a[href='#order']").trigger("click");
				});
			});
			$(".modal_qty input").bind("change", function(e) {
				var $this = $(this), value = parseInt($this.val());
				if (value > 0) {
					$("td.modal_price").text( cart.formatPrice( value * price ) );
				}
				if (value > inCart) {
					cart.addToCart( { title: title, price: price, qty: (value - inCart), id: id } );
					inCart = value;
				}
			});
			
			cart.addToCart( { title: title, price: price, qty: 1, id: id } );
			
			modalOpened = true;
			
		}
		return false;
	});
	
	
	
	function close_modal(callback) {
		$("#continue_shopping").unbind("click");
		$("#order_product").unbind("click");
		$(".modal_qty input").unbind("change");
		modalOpened = false;
		$("#modal_bg").fadeOut(400, callback);
	}
	
	var Cart = function() {
		var products = [];
		var totalItem = 0;
		var totalPrice = 0;
		/*
			@param: item object {title, price, qty, id}
			@return: object { totalPrice, totalItem } 
		*/
		function addToCart (item) {
			if ( !inCart(item.id) ) {
				products.push(item);
				var dataRow = "<tr data-id='" + item.id + "'><td class='product_name'>" + item.title + "</td>";
				dataRow += "<td class='product_qty'>" + item.qty + "</td>";
				dataRow += "<td class='product_price_single'>" + formatPrice(item.price) + "</td>";
				dataRow += "<td class='product_price'>" + formatPrice(item.price * item.qty) + "</td>";
				dataRow += "<td class='product_edit'><a href='#' class='delete'></a></td></tr></table>";
				$("#cart table tr:first-child").after( $(dataRow) );
				updateSummary();
			} else {
				updateProductQty(item.id, item.qty);
				updateSummary();
			}
		}
		
		function deleteFromCart(id) {
			for(var i=0, j=products.length; i<j; i++) {
				var product = products[i];
				if (typeof(product) != "undefined" && product.id == id) {
					products.splice(i, 1);
					$("tr[data-id='" + id + "']").fadeOut(200, function() { $(this).remove(); updateSummary(); });
				}
			}
		}
		
		function emptyCart() {
			for(var i=0, j=products.length; i<j; i++) {
				var product = products[i];
				if (typeof(product) != "undefined") {
					products.splice(i, 1);
					$("tr[data-id='" + product.id + "']").fadeOut(200, function() { $(this).remove(); updateSummary(); });
				}
			}
		}
		
		function getProducts() {
			return products;
		}
		
		/*
			megnezi, hogy az adott elem benne-van-e kosarban
			
			@param: product id
			@return: bool
		*/
		function inCart(id) {
			var incart = false;
			for(var i=0, j=products.length; i<j; i++) {
				if (products[i].id == id) {
					incart = true;
				}
			}
			return incart;
		}
		
		/*
			return object {price, count}
		*/
		function productSummary() {
			var productsCount = 0;
			var priceCount = 0;
			var productsPrice
			for( var i=0, j=products.length; i<j; i++ ) {
				var product = products[i];
				productsCount += product.qty;
				priceCount += ( product.qty * product.price );
			}
			return {
				price: priceCount,
				count: productsCount
			};
		}
		
		function updateProductQty(id, qty) {
			for(var i=0, j=products.length; i<j; i++) {
				if (products[i].id == id) {
					products[i].qty += parseInt(qty);
					var $productRow = $("tr[data-id='" + id + "']");
					$productRow.find(".product_qty").text( products[i].qty );
					$productRow.find(".product_price").text(formatPrice(products[i].price * products[i].qty));
				}
			}
		}
		
		$("a.delete").live("click", function(e) {
			deleteFromCart( $(this).parent().parent().attr("data-id") );
			return false;
		});
		
		function updateSummary() {
			var summary = productSummary();
			$("#summary_count").text(summary.count);
			$("#summary_price").text( formatPrice(summary.price) );
		}
		
		function priceTextToInt(priceText) {
			var parts = priceText.split(" "), priceParts = parts[0].split("."), price = priceParts[0].toString() + priceParts[1].toString();
			return parseInt(price);
		}
		
		function formatPrice (price) {
			var priceString = price.toString(), priceReturn = "", priceLength = priceString.length;
			if (priceLength > 3) {
				priceReturn += priceString.substr(0,(priceLength-3));
				priceReturn += ".";
				priceReturn += priceString.substr((priceLength-3),(priceLength-1));
			}
			return priceReturn + " Ft";
		}
		
		return {
			addToCart: addToCart,
			priceToInt: priceTextToInt,
			formatPrice: formatPrice,
			updateProductQty: updateProductQty,
			getProducts: getProducts,
			emptyCart: emptyCart
		};
		
	};
	
	window.cart = new Cart();
	
	$("form#order_products").submit(function(e) {
		e.preventDefault();
		var name = $("#name").val(), email = $("#email").val(), phone = $("#phone").val(), address = $("#address").val(), city = $("#city").val(), postcode = $("#postcode").val(), comment = $("#comment").val(), products = cart.getProducts();
		if ( name == "Neve" ) {
			alert("Kérem adja meg a nevét!");
			return false;
		} else if (email == "E-mail címe") {
			alert("Kérem adja meg az email címét!");
			return false;
		} else if (phone == "Telefon száma") {
			alert("Kérem adja meg a telefonszámát!");
			return false;
		} else if (address == "Utca, házszám") {
			alert("Kérem adja meg a címét!");
			return false;
		} else if (city == "Város") {
			alert("Kérem töltse ki a város mezőt!");
			return false;
		} else if (postcode == "Irányító szám") {
			alert("Kérem adja meg az irányítószámát!");
			return false;
		}
		$.ajax({
			url: "http://www.pezsegj.hu/order.php",
			type: "post",
			data: { name: name, email: email, phone: phone, address: address, city: city, postcode: postcode, comment: comment, products: products },
			success: function(data) {
				var json = $.parseJSON(data);
				if (json.status == 1) {
					alert("Köszönjük megrendelését, kollégánk hamarosan keresni fogja az átvétel módjáról!");
					cart.emptyCart();
					$("#name").val("");
					$("#email").val("");
					$("#phone").val("");
					$("#address").val("");
					$("#city").val("");
					$("#postcode").val("");
					$("#comment").val("");
				}
			}
		});
		return false;
	});
	  
});
