﻿/// <reference path="/Scripts/jquery-1.4.2.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() {

    $(".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 priceCalculationEvents() {
	$(".suggestedpriceInput").keyup(function() {
		var tgInput = $(this).closest("tr").find("#tg");
		var price = $(this).closest("tr").find("#price").val();
		var vatMultiplier = $(this).closest("tr").find("#vatMultiplier").val();

		var suggPrice = $(this).val();
		suggPrice = suggPrice / vatMultiplier;

		if (parseInt(suggPrice)) {
			var newMargin = ((suggPrice - price) / suggPrice) * 100
			tgInput.val(Math.round(newMargin));
		}
		else {
			tgInput.val('');
		}
	});

	$(".tgInput").keyup(function() {
		var suggestedpriceInput = $(this).closest("tr").find("#suggestedprice");
		var price = $(this).closest("tr").find("#price").val();
		var vatMultiplier = $(this).closest("tr").find("#vatMultiplier").val();
		var tg = $(this).val();

		if (parseInt(tg) || tg == "0") {
			var newPrice = (((price*vatMultiplier) / (100 - tg)) * 100)
			suggestedpriceInput.val(Math.round(newPrice));
		}
		else {
			suggestedpriceInput.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;

}
