﻿/// <reference path="/Scripts/jquery-1.4.2.js" />
/// <reference path="/Scripts/jquery-plugins/fancybox/jquery.fancybox-1.3.3.js" />

function roundNumber(num, dec) {
	var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
	return result;
}

function submitForm(o)
{
	var form = $(o).parents("form:first");
	var name = $(o).attr("name");
	form.append("<input type='hidden' name='" + name + "' value='" + name + "' />");
	form.submit();
	return true;
}

function initLeftMenuBar() {
	$("#quickOrderBox").fancybox({
		'hideOnContentClick': false,
		'frameWidth': 700,
		'frameHeight': 340
	});

	$(".leftMenuSearch .fancybox").fancybox({
		onComplete: function () {
			var form = $("#forgotPasswordForm");
			form.submit(function () {

				$.ajax({
					url: form.attr("action"),
					type: form.attr("method"),
					dataType: "json",
					data: { email: form.find("#email").val() },
					success: function (data) {
						$("ul", form).remove();

						if (data.Success) {
							form.html(data.Message);
						} else {
							var html = "";
							$.each(data.Errors, function () {
								html += "<li>" + this + "</li>";
							});

							form.find("h1").before("<ul class=\"validation-summary-errors\"/>");
							$("ul", form).html(html);
						}
						
					}
				});

				return false;
			});
		}
	});


    $(".leftMenuBar").click(function() {
        var contentArea = $(this).parent().find(".leftMenuContent");
        contentArea.slideToggle("fast", function() {
            var height = $(this).parent().height();

            $(this).parent().toggleClass("open", height > 22).toggleClass("close", height < 22);

            var panelContainer = $(this).parent();
            var panelId = $(panelContainer).attr("id");
            var panelState = $(this).parent().attr("class");

            if (panelState.indexOf("open") != -1) {
                panelState = "open";
            } else {
                panelState = "close";
            }

            // Save panel state
            $.post("/Settings/SetPanelConfiguration", { panelId: panelId, panelState: panelState });
        });

    });

}

function initPlaceOrderCartItems() {
	$("#Cart_PlaceOrder .cartItemsBox .greyPanel").click(function() {
	var contentArea = $("#cartItemListingBox")
		contentArea.slideToggle("fast", function() {
			var height = $(this).parent().height();
			$(this).parent().toggleClass("open", height >55).toggleClass("close", height < 55);
		});

	});

	$("#cartItemListingBox").hide();
}

// Tree Navigation
var currentMenuItem = null;

function BindMenuItems(treeMenu, defaultTabIndex) {

	$("#navigationTreeTabs").tabs({ selected: defaultTabIndex });
	$("#navigationTreeTabs").bind("tabsselect", function (event, ui) {
		var i = ui.index;
		$.ajax({
			type: "POST",
			url: "/Home/SetTabIndex",
			data: ({ index: ui.index }),
			dataType: "html"
		});
	});

    $(treeMenu).unbind("click");

    $(treeMenu).click(function(e) {

        var target = e ? e.target : window.event.srcElement;
        var menuItem = $(target);
        
        if (target.nodeName.toLowerCase() == "a" && $(target).attr("href").indexOf("#") != -1 && $(menuItem).parent().attr("class") != "collapsable") {

            var parentSectionId = $(menuItem).attr("href").substring($(menuItem).attr("href").indexOf("#") + 1);

            $.ajax({
                url: "/Navigation/TreeMenuSubItems/",
                cache: false,
                data: { "parentSectionId": parentSectionId },
                success: function(html) {

                    $(menuItem).parent().parent().find("ul").remove(); // Collapse current level selection
                    $(menuItem).parent().parent().find("li").attr("class", "");
                    $(menuItem).parent().append(html).find("ul:first").hide();
                    $(menuItem).parent().find("ul:first").show("slide", { direction: "up" }, "10");
                    $(menuItem).parent().attr("class", "collapsable");
                    currentMenuItem = $(menuItem);

                }
            });

            return false;
        }

    });

}

// /Tree Navigation


//function initTreeMenu(location) {
//    $("#navigationTreeTabs").tabs({ cookie: { expires: 30, name: 'navigationTreeTabs'} });
//	$("#menuTreeManufacturer").treeview(
//		{ collapsed: true,
//			unique: true,
//			animated: "fast",
//			persist: "locationValue",
//			locationValue: location
//		});

//	$("#menuTreeProductGroup").treeview(
//		{ collapsed: true,
//			unique: true,
//			animated: "fast",
//			persist: "locationValue",
//			locationValue: location
//		});
//}
function tableSorterOnProductListing() {
	$("#productListing")
		.tablesorter()
		.tablesorterFilter({ filterContainer: $("#filterListingValue"), filterColumns: [1], filterCaseSensitive: false });
}

function CalculatePrices(priceRow, calcPrice, calcPriceMargin, calcSuggestedPrice) {

//    if (calcPrice != null) {
//        price = parseFloat(calcPrice);
//        priceInput.val(price);
//    }
//    else if (calcPriceMargin != null) {
//        priceMargin = parseFloat(calcPriceMargin);
//    }
//    else if (calcSuggestedPrice != null) {
//        suggestedPrice = parseFloat(calcSuggestedPrice);
//    }

//    if (vatMultiplier > 0) {
//        if (price > 0) {
//            var suggestedPriceExcl = suggestedPrice / vatMultiplier;
//            var newPriceMargin = ((suggestedPriceExcl - price) / suggestedPriceExcl) * 100;
//            tgInput.val(Math.round(newPriceMargin));
//        } else {
//            tgInput.val("");
//        }

//        if (priceMargin > 0) {
//            var newSuggestedPrice = ((price * vatMultiplier) / (100 - priceMargin));
//            newSuggestedPrice = newSuggestedPrice * 100;
//            suggestedPriceInput.val(Math.round(newSuggestedPrice));
//        }
//        else {
//            suggestedPriceInput.val("");
//        }

//        if (suggestedPrice > 0) {
//            var suggestedPriceExcl = suggestedPrice / vatMultiplier;
//            var newPriceMargin = ((suggestedPriceExcl - price) / suggestedPriceExcl) * 100;
//            tgInput.val(Math.round(newPriceMargin));
//        }
//        else {
//            tgInput.val("");
//        }
//    }

}


function GetPriceFieldsAndValues(priceRow) {

    this.priceHiddenInput = $("#price:first", priceRow);
    this.tgInput = $("#tg", priceRow);
    this.suggestedPriceInput = $("#suggestedprice:first", priceRow);
    this.vatMultiplierInput = $("#vatMultiplier:first", priceRow);

    this.price = parseFloat(this.priceHiddenInput.val());
    this.suggestedPrice = parseFloat(this.suggestedPriceInput.val());
    this.priceMargin = parseFloat(this.tgInput.val());
    this.vatMultiplier = parseFloat(this.vatMultiplierInput.val());
    this.suggestedPriceExcl = this.suggestedPrice / this.vatMultiplier;
}

function priceCalculationEvents() {

    var priceInput = $("td.price input[type=text]");
    var suggestedPriceInput = $(".suggestedpriceInput");
    var tgInput = $(".tgInput");

    if (priceInput.length == 0) {
        priceInput = $("td.priceColumn input[type=text]");
    }

    priceInput.bind("keyup", function () {
        var priceRow = $(this).closest("tr");
        var priceInfo = new GetPriceFieldsAndValues(priceRow);

        var newPrice = parseFloat($(this).val());

        if (newPrice > 0) {
            priceInfo.priceHiddenInput.val(newPrice);
            priceInfo.price = newPrice;

            var newPriceMargin = ((priceInfo.suggestedPriceExcl - priceInfo.price) / priceInfo.suggestedPriceExcl) * 100;
            priceInfo.tgInput.val(Math.round(newPriceMargin));
        } else {
            priceInfo.tgInput.val("");
        }

    });

    tgInput.bind("keyup", function () {
        var priceRow = $(this).closest("tr");
        var priceInfo = new GetPriceFieldsAndValues(priceRow);
        var priceMargin = parseFloat($(this).val());

        if (priceMargin > 0) {

            var newSuggestedPrice = 0;
            var priceInclVat = priceInfo.price * priceInfo.vatMultiplier;

            if (priceMargin < 100) {
                newSuggestedPrice = ((priceInclVat / (100 - priceMargin)) * 100);
            }
            else {
                priceInfo.suggestedPriceInput.val("");
            } 

            priceInfo.suggestedPriceInput.val(Math.round(newSuggestedPrice));
        }
        else {
            priceInfo.suggestedPriceInput.val("");
        }

    });

    suggestedPriceInput.bind("keyup", function () {
        var priceRow = $(this).closest("tr");
        var priceInfo = new GetPriceFieldsAndValues(priceRow);

        if (priceInfo.suggestedPriceExcl > 0) {

            var newPriceMargin = ((priceInfo.suggestedPriceExcl - priceInfo.price) / priceInfo.suggestedPriceExcl) * 100;
            priceInfo.tgInput.val(Math.round(newPriceMargin));
        }
        else {
            priceInfo.tgInput.val("");
        }

    });

}

function cartDiscountCalculationEvents() {
    
    $(".cartTable").delegate("input._discountPercentage", "keyup", function() { 
        
		var customersDefaultPrice = $(this).closest("tr").find("#customersDefaultPrice").val();
		var price = $(this).closest("tr").find("._price");
		var discount = $(this).val();
		discount = discount.replace(",", ".");

		if (parseFloat(discount) && discount > 0 && discount < 100) {
			var newPrice = (customersDefaultPrice * (1 - (discount / 100.0)))
			price.val(roundNumber(newPrice, 2));
			price.val(price.val().replace(".", ","));
		}
        else
        {
            $(price).val(customersDefaultPrice);
            $(this).val("0");
        }
	});
}


function setFullHeightOnDivInTd() {
	/* Removed due to performanc*/
	var images = $("table").find(".productListingImage");
	$(images).each(function() {
	$(this).height($(this).closest("td").height() - 2);
	});
}

function initClueTips() {
	$(".cluetipSplitTitle").cluetip({
		splitTitle: '|',
		arrows: true,
		dropShadow: true,
		cluetipClass: 'jtip'
    });

    $(".boxQuantityTip").focusout(function () {
        $("#cluetip").hide();
    });

    $(".boxQuantityTip").cluetip({
        local: 'true',
        width: 190,
        cluetipClass: 'jtip',
        arrows: true,
        dropShadow: true,
        closePosition: 'title',
        closeText: '<img src="/images/global/cross.png" alt="" />',
        sticky: true,
        showTitle: true,
        activation: 'focus'
    });
}

function OpenPrintOrderWindow(orderId) {
    window.open("/Home/OrderPrint/?id=" + orderId + "&printOption=orderSheet&printFormat=printer");
}

function OpenPDFOrderWindow(orderId) {
    window.open("/Home/OrderPrint/?id=" + orderId + "&printOption=orderSheet&printFormat=pdf");
}

function addFavourite(productID, link) {
    $.post("/Cart/AddToFavorites", { productID: productID }, function(response) {
        if (response.Success) {
            $(link).fadeOut();
        }
    }, "json");

}

function openFancybox(sectionId) {
    $.fancybox.showActivity();
    $.post("/Information/SimpleContent", { id: sectionId }, function(data) {
        $.fancybox(data);
    }, "json");
}

(function($) {
	$.fn.vAlign = function(container) {
		return this.each(function(i) {
			if (container == null) {
				container = 'div';
			}
			var paddingPx = 10; //change this value as you need (It is the extra height for the parent element)
			$(this).html("<" + container + ">" + $(this).html() + "</" + container + ">");
			var el = $(this).children(container + ":first");
			var elh = $(el).height(); //new element height
			var ph = $(this).height(); //parent height
			if (elh > ph) { //if new element height is larger apply this to parent
				$(this).height(elh + paddingPx);
				ph = elh + paddingPx;
			}
			var nh = (ph - elh) / 2; //new margin to apply
			$(el).css('margin-top', nh);
		});
	};
})(jQuery);

(function($) {
	$.fn.vAlignOnParent = function(container) {
		return this.each(function(i) {
			var paddingPx = 10; //change this value as you need (It is the extra height for the parent element)
			var elh = $(this).height(); //new element height
			var ph = $(this).parent().height(); //parent height
			if (elh > ph) { //if new element height is larger apply this to parent
				$(this).height(elh + paddingPx);
				ph = elh + paddingPx;
			}
			var nh = (ph - elh) / 2; //new margin to apply
			$(this).css('margin-top', nh);
		});
	};
})(jQuery);


function IsNumeric(sText)
{
    var ValidChars = "0123456789.,";
    var IsNumber = true;
    var Char;

    if(sText.length == 0){
        return false;
    }

    for (i = 0; i < sText.length && IsNumber == true; i++) 
    { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
        {
            IsNumber = false;
        }
      }

    return IsNumber;

}

$(document).ready(function () {
	$('input.forceInteger').live('change focus unfocus', function () {
		var input = $(this).val();
		$(this).val(input.replace(/([^0-9])/g, ''));
	});

	InitProductDescription();

});

$(document).ready(function () {
	$("#cartBoxContainer a").fancybox();

	$('input.forceInteger').live('keydown', function (event) {
		// allow any ctrl, alt or meta combination.
		if (event.ctrlKey || event.altKey || event.metaKey) {
			return;
		}
		if (!(event.keyCode == '8' ||
        event.keyCode == '9' ||
        event.keyCode == '13' ||
        (event.keyCode >= '33' &&
        event.keyCode <= '57') ||
        (event.keyCode >= '96' &&
        event.keyCode <= '105')
        )) {
			event.preventDefault();
		}
	});
});

function InitProductDescription() {

	$("#showSalesProductMessageContainerLink").live("click", function () {

		var salesProductMessgeContainer = $("#salesProductMessgeContainer");

		if ($(this).data("open") != true) {

			if (salesProductMessgeContainer.length >= 1) {
				salesProductMessgeContainer.show("fast");
			}

			$(this).data("open", true);
		}
		else {

			if (salesProductMessgeContainer.length >= 1) {
				salesProductMessgeContainer.hide("fast");
			}

			$(this).data("open", false);
		}

		return false;

	});

	$("#showAllFeatureReviewsLink").bind("click", function () {
		$("#featuresExpandPanel").slideDown();
		return false;
	});

	$("#hideAllFeatureReviewsLink").bind("click", function () {
		$("#featuresExpandPanel").slideUp();
		return false;
	});

	$(".openReviewLink").bind("click", function () {
		$("#productDetailsTabLink").trigger("click");
		return false;
	});

	$(".openAccessoriesLink").bind("click", function () {
		$("#productAccessoriesTabLink").trigger("click");
		return false;
	});

	var yellowBarContent = $(".content", "#yellowBar");

	if (yellowBarContent.length >= 1) {
		yellowBarContent.css("opacity", "0");
		yellowBarContent.animate({ opacity: 1, "left": "0px" }, 500);
	}

}

function InitReviewLinks() {

	$("a", ".reviewsLanguageLinks").bind("click", function () {

		var url = $(this).attr("href");

		$("#alaTestPanel").load(url, null);

		return false;

	});
	
}

function ImageSwapper(options) {
	var settings = $.extend( {
      containerSelector: ".productImageColumn",
      itemsSelector: ".productImageContainer",
      pagerSelector: ".pager",
	  zoomLinkSelector: ".productImageZoomLink",
	  speed: 700
    }, options);

    var self = {
    	container: null,
    	items: null,
    	pager: null,
    	zoomLink: null,
    	init: function () {
    		self.container = $(settings.containerSelector);
    		self.items = $(settings.itemsSelector, self.container);
    		self.pager = $(settings.pagerSelector, self.container);
    		self.zoomLink = $(settings.zoomLinkSelector, self.container);

    		if (self.items <= 1) {
    			return;
    		}
    		self.setupZoom();
    		self.setupPager();
    	},
    	setupZoom: function () {

    		$("a", self.items).fancybox({
    			'zoomSpeedIn': 300,
    			'zoomSpeedOut': 300,
    			'overlayShow': false,
    			'hideOnContentClick': true
    		});

    		self.zoomLink.click(function () {
    			self.items.filter(".current").children("a").click();
    			return false;
    		});
    	},
    	setupPager: function () {
    		self.pager.children("a").click(function () {
    			self.showNewItem($(this).is(".prev") ? -1 : 1);
    			return false;
    		});
    	},
    	showNewItem: function (direction) {
    		


    		var currentItem = self.items.filter(".current");
    		var nextItem = direction == 1 ? currentItem.next(settings.itemsSelector) : currentItem.prev(settings.itemsSelector)
    		if (!nextItem.length) {
    			nextItem = direction == 1 ? self.items.first() : self.items.last();
    		}

    		self.container.css({
    			"height": nextItem.height(),
    			"width": nextItem.width()
    		});

    		nextItem.css({
    			"position": "absolute",
    			"left": "0",
    			"top": "0",
    			"z-index": "10"
    		}).fadeIn(settings.speed, function () {
    			$(this).removeAttr("style");
    		}).addClass("current");
    		self.updatePager(nextItem.index());
    		self.updateZoomLink(nextItem);

    		currentItem.css({
    			"z-index": "5",
    			"position": "absolute",
    			"left": "0",
    			"top": "0"
    		}).fadeOut(settings.speed, function () {
    			$(this).removeAttr("style");
    		}).removeClass("current");


    	},
    	updatePager: function (newIndex) {
    		self.pager.children("span").children("span").text((newIndex + 1) + "/" + self.items.length);
    	},
    	updateZoomLink: function (currentElement) {
    		if (currentElement.children("a").length) {
    			self.zoomLink.fadeIn();
    		} else {
    			self.zoomLink.fadeOut();
    		}
    	}
    };

	self.init();

};

/* Only for development */

function InitCSSUpdater() {

if ($(".cssUpdaterEnabled").length >= 1) {

    // Add update button
    // $("body").append("<div style=\"position:absolute; right:0px; top:0px\"><input type=\"button\" id=\"updateCSSButton\" value=\"Update CSS\" onclick=\"Update CSS\" /></div>");
    $("body").append("<div style=\"position:absolute; display:none; right:0px; top:0px\"><input type=\"button\" id=\"updateCSSButton\" value=\"Update CSS\" onclick=\"Update CSS\" /></div>");

    $(document).keydown(function (e) {

        if (e.which == 220) { // Key: "§"
         	$("#updateCSSButton").trigger("click");
        }

    });

    // Add button event
    $("#updateCSSButton").click(function () {
        var cssFileTags = $("link", "head");

        cssFileTags.each(function () {

         	var cssFileTag = $(this);

         	var rnd = Math.random();
         	var cssHref = cssFileTag.attr("href") + "?rnd=" + rnd;

         	cssFileTag.remove();

         	var newCssFileTag = "<link id=\"dynamicCSSFile\" href=\"" + cssHref + "\" rel=\"stylesheet\" type=\"text/css\" />";
         	$("head:first").append(newCssFileTag);
        });

    });

}
}

function Trace(message) {

var traceWindow = $("#traceWindow");

if (traceWindow.length == 0) {

    $("body").append("<div id=\"traceWindow\" class=\"traceWindow\"></div>");
    traceWindow = $("#traceWindow");
}

$(traceWindow).append("<div>" + message + "</div>");
}


$(document).ready(function () {
InitCSSUpdater();
});


/* /Only for development */


