$(function() {
        $(".hideIt").hide();
	var ie6 = ($.browser.msie && $.browser.version === "6.0");
	var headerCls = ["skyblue", "lightgreen", "orange", "pink", "lightpurple", "darkred", "darkpurple" ];
	var navigationHeaders = $("td#headerNavigation a");
	navigationHeaders.each(function(i, el) {
		$(el).addClass(headerCls[i]);
	});
	$("#slide_show_container").width($("#contactDetailsTopBox").width() - 20);

	$("div#headerNavigationDiv").width(navigationHeaders.size() * 120);
	if (window.slide_show_products && window.slide_show_products.length > 0) {
		var html = "",
			img = "",
			imageObj = new Image();
		$.each(window.slide_show_products, function(i, product) {
			img = image_dir + product.products_image;
			imageObj.src = img;
			html += "<li product_id='" + product.products_id + "'>" +
					"<img src='" + img + "' title='" + product.products_model + "' />" +
					"</li>";
		});
		$("#slideShow")
			.html(html)
			.galleryView({
				panel_width: 800,
				panel_height: 300,
				frame_width: 100,
				frame_height: 100,
				pointer_size: $.browser.msie ? 0 : 8
			});
		$(window).resize(function() {
			$("#slide_show_container").width("auto");
			$(window).unbind("resize");
		});
	}
	if (!ie6) {
		$("a.wide_button").each(function(i, el) {
			$(el).width($(el).width()+20);
		});
		$("div#headerNavigationDiv a").corner("bottom");
		$("div.roundBox, a.button, a.wide_button, a.topBox, div#slide_show_container, div.panel_table_div").corner();
	}
	// category box
	if (window.categories_box_obj) {
		var root_arr = categories_box_obj['0'];
		var child_arr = [];
		var html = "";
		// loop through the root directories
		$(root_arr).each(function(i, root) {
			var root_id = root['categories_id'];
			html += "<a href='index.php?cPath=" + root_id + "'";
			if (selected_category_id == root_id) {
				html += " class='selectedCategory'";
			}
			html += ">";
			html +=   root['categories_name'] + " -> ";
			html +=   " (" + root['noOfProducts'] + ")";
			html += "</a>";
			html += "<br/>";
			if (selected_category_id == root_id && selected_category_id != '-1') {
				// loop through all the child directories
				child_arr = categories_box_obj[root_id];
				$(child_arr).each(function(n, child) {
					if (child['categories_id']) {
						var child_category_id = child['categories_id'];
						html += "<a href='index.php?cPath=" + root_id + "_" + child_category_id + "' class='child_categories";
						if (selected_child_category_id == child_category_id) {
							html += " selectedCategory";
						}
						html += "'>";
						html +=  "- " + child['categories_name'];
						html +=  " (" + child['noOfProducts'] + ")";
						html += "</a>";
						html += "<br/>";
					}
				});
			}
		});
	    $("#categoriesBoxDetails").html(html);
	}
	Event = {
		isNumberKey: function(key) {
			return (key>=48 && key<=57);
		},
		isMovementKey: function(key) {
			return (key === 0);
		},
		isDeleteKey: function(key) {
			return (key === 8);
		},
		isDotKey: function(key) {
			return (key === 46);
		},
		isCommonKeys: function(key) {
			return this.isMovementKey(key) || this.isDeleteKey(key);
		}
	}
	function getNoOfDecimalPlaces(value) {
		return value.substr(value.indexOf(".")+1).length;
	}

	$("#btnAddToCart").live("click", function() {
		var productId = $(this).attr("product_id");
		$("input[name=products_id]").attr("value", productId);
		$("#productShowCaseForm")
            .attr("action", "shopping_cart.php?products_id=" + productId +
			      "&action=add_new_product")
            .attr("method", "post").submit();
		return false;
	});
	$("#btnTellFriend").live("click", function() {
		var productId = $(this).attr("product_id");
		$.ajax({
			url: "share_with_friends.php",
			type: "GET",
			data: { productId: productId },
			complete: function(response) {
				$("#lightbox-container-details").html(response.responseText);
				$('#lightbox-container-image-box').animate({ top: $(window).height() / 5, width: 500, height: 300 }, 400);
				if (!ie6) {
			      $("#btnCancel, #btnSend").corner();
				}
			}
		});
		return false;
	});

	$("div.panel_table_div").lightBox({ infoTag: "div.panel_table_div" });
	$("td.productListing-data a, button.viewDetails, #products_new_list td a").lightBox();
	$("table.bestSellerBox a, table.orderHistoryBox a, table.shoppingCartBox a, td.whatnews a, #new_products a").lightBox({ infoTag: "td" });

	$("input.number").keypress(function(ev) {
		var enteredKey = ev.which;
		if (Event.isNumberKey(enteredKey) || Event.isCommonKeys(enteredKey)) {
			return true;
		}
		return false;
	}).change(function(ev) {
		var el = $(ev.target);
		var currentValue = el.val();
		if (currentValue.length === 0) {
			el.val(0);
		} else {
			el.val(parseInt(currentValue, 10));
		}
	}).each(function(i, el) {
		el = $(el);
		// if the input field is empty, put a number in it
		if (el.val().length === 0) {
			el.val(0);
		}
	})
	
	$("input.float").keypress(function(ev) {
		var enteredKey = ev.which;
		var el = ev.target;
		var currentValue = el.value;
		if (Event.isNumberKey(enteredKey)) {
			return true;
		}
		if (Event.isCommonKeys(enteredKey)) {
			return true;
		}
		if (Event.isDotKey(enteredKey)) {
			// ensure the dot will not be the first character
			// ensure only one "." in the field
			if (currentValue.length !== 0 && currentValue.indexOf(".") === -1) {
				return true;
			}
		}
		return false;
	}).change(function(ev) {
		var el = ev.target;
		if ($(el).val().length === 0) {
			$(el).val(0);
		}
		var decimal_places = parseInt($(el).attr("decimal_places"), 10);
		var currentValue = parseFloat(el.value, 10);
		$(el).val(doRound(currentValue, decimal_places));
	}).each(function(i, el) {
		var decimal_places = $(el).attr("decimal_places");
		if (!decimal_places) {
			alert("No decimal_places attribute has been specified in the tag.");
			return false;
		}
		// if the input field is empty, put a number in it
		if ($(el).val().length === 0) {
			$(el).val(0);
		}
	});
	
	$("#contactDetailsTopBox, a.newsBox").click(function() {
		location.href=$(this).attr("url");
	});
});
function doRound(x, places) {
  return Math.round(x * Math.pow(10, places)) / Math.pow(10, places);
}

$.extend(Array.prototype, {
	filter: function(fun) {
    	var len = this.length >>> 0;
	    if (typeof fun != "function") {
	      throw new TypeError();
	    }
	
	    var res = new Array();
	    var thisp = arguments[1];
	    for (var i = 0; i < len; i++) {
	      if (i in this) {
	        var val = this[i]; // in case fun mutates this
	        if (fun.call(thisp, val, i, this))
	          res.push(val);
	      }
	    }
	    return res;
	}
});

/* Share with friends */
window.shareWithFriends = {
	init: function() {
		$("#shareWithFriendsForm").validate({
			rules: {
				toFriends: {
					required: true,
					multiemail: true
				}
			},
			messages: {
				toFriends: "Please enter a valid email address"
			}
		});
		$("#btnCancel").click(function() {
			closeShowCase(); 
			return false;
		});
		$("#btnSend").click(function() {
			if ($("#shareWithFriendsForm").valid()) {
				$.ajax({
					type: "POST",
					url: "sendEmail.php",
					data: $("#shareWithFriendsForm").serialize(),
					beforeSend: function() {
						$("#lightbox-container-details").html("<div style='padding-top: 130px;'>Message is now sending. Please wait...</div>");
					},
					complete: function(response) {
						$("#lightbox-container-details").html("<div style='padding-top: 120px;'>" + response.responseText + "</div>");
					}
				});
			}
			return false;
		});
	}
};