﻿/// <reference path="jquery-1-6-4-vsdoc.js" />
/// <reference path="scan.js" />
/// <reference path="scan.basket.js" />
/// <reference path="scan.imagepreview.js" />
/// <reference path="scan.layout.js" />
/// <reference path="scan.livesearch.js" />
/// <reference path="scan.navigtion.js" />
/// <reference path="scan.productlist.js" />
/// <reference path="scan.search.js" />
/// <reference path="scan.template.js" />
/// <reference path="scan.systembundles.js" />

/*!
* scan.js
*/

var Scan = {};
Scan.ApplicationRoot = "";
Scan.SecureRoot = "";

Scan.SetApplicationRoot = function (applicationRoot, secureRoot) {
	Scan.ApplicationRoot = applicationRoot;
	Scan.SecureRoot = secureRoot; 
};




var TimeoutInterval = 5000;
var CurrentMasterSpecialistApplicationId = 0;
var CurrentSpecialistApplicationId = 0;
var CurrentMasterCategoryId = 0;
var CurrentMasterSpecialistApplicationTitle;
var CurrentSpecialistApplicationTitle;
var CurrentMasterCategoryTitle;
var CurrentMasterCategorySponsorImage;

var ApplicationUrl;
var BaseUrl;
var UpperMenuId;
var LowerMenuId;
var EmptySpecialistApplicationsDivId;
var MasterCategoryTitleId;

var indexMasterSpecialistApplicationId = 0, indexSpecialistApplicationId = 1, indexMasterCategoryId = 2, indexCategoryId = 3, indexCategoryTitle = 4, indexCategoryUrlText = 5;

function InitialiseMenu(applicationUrl, baseUrl, upperMenuId, lowerMenuId, emptySpecialistApplicationsDivId, masterCategoryTitleId) {
    if (!applicationUrl.match("/$")) applicationUrl += "/";
    ApplicationUrl = applicationUrl;
    BaseUrl = baseUrl;
    UpperMenuId = upperMenuId;
    LowerMenuId = lowerMenuId;
    EmptySpecialistApplicationsDivId = emptySpecialistApplicationsDivId;
    MasterCategoryTitleId = masterCategoryTitleId;
    //SiteNavigationWebService.set_timeout(TimeoutInterval);
}

function InitialiseMenuLocation(currentMasterSpecialistApplicationId, currentSpecialistApplicationId, currentMasterCategoryId, currentMasterSpecialistApplicationTitle, currentSpecialistApplicationTitle, currentMasterCategoryTitle) {
    CurrentMasterSpecialistApplicationId = currentMasterSpecialistApplicationId;
    CurrentSpecialistApplicationId = currentSpecialistApplicationId;
    CurrentMasterCategoryId = currentMasterCategoryId;
    CurrentMasterSpecialistApplicationTitle = currentMasterSpecialistApplicationTitle;
    CurrentSpecialistApplicationTitle = currentSpecialistApplicationTitle;
    CurrentMasterCategoryTitle = currentMasterCategoryTitle;
}

function ClickStaticMC(MasterSpecialistApplicationId, SpecialistApplicationId, MasterCategoryId, MasterCategoryTitle, MasterCategoryUrl, MasterCategorySponsorImage) {
    CurrentMasterCategoryTitle = MasterCategoryTitle;
    CurrentMasterCategorySponsorImage = MasterCategorySponsorImage;

    HideCategoryList();
    ShowCategoryHolder();

    var html = "";
    var ViewAllUrl = ApplicationUrl + "shop/" + MasterCategoryUrl;

    $("#" + MasterCategoryTitleId).html("<a href=\"" + ViewAllUrl + "\">" + CurrentMasterCategoryTitle + "</a>");
    $("#ViewAllCategories").attr("href", ViewAllUrl);

    $("#menu-new").attr("href", ViewAllUrl + "/new-arrivals")
    $("#menu-hotseller").attr("href", ViewAllUrl + "/hot-sellers")
    $("#menu-clearance").attr("href", ViewAllUrl + "/clearance")

    var columnCount = 3;
    var columnArray = [columnCount - 1];
    for (columnIndex = 0; columnIndex < columnCount; columnIndex++) {
        columnArray[columnIndex] = $("#divCategoryListing > .column" + (columnIndex + 1));
        $(columnArray[columnIndex]).empty();
    }

    if (Scan.Navigation.MainMenu.MenuStructure) {
        //Get total items (groups and categories)
        var totalItems = 0;
        var showGroups = true;

        $.each(Scan.Navigation.MainMenu.MenuStructure, function (index, MSA) {
            $.each(MSA.c, function (index, SA) {
                $.each(SA.c, function (index, MC) {
                    if (MSA.id == MasterSpecialistApplicationId && SA.id == SpecialistApplicationId && MC.id == MasterCategoryId) {
                        if (MC.c.length == 1 && MC.c[0].id == 0) {
                            totalItems = MC.c[0].c.length;
                            showGroups = false;
                        }
                        else {
                            $.each(MC.c, function (index, CG) {
                                totalItems += 1;
                                $.each(CG.c, function (index, C) {
                                    totalItems += 1;
                                });
                            });
                        }
                    }
                });
            });
        });

        var itemsPerColumn = Math.ceil(totalItems / columnCount);

        $.each(Scan.Navigation.MainMenu.MenuStructure, function (index, MSA) {
            $.each(MSA.c, function (index, SA) {
                $.each(SA.c, function (index, MC) {
                    if (MSA.id == MasterSpecialistApplicationId && SA.id == SpecialistApplicationId && MC.id == MasterCategoryId) {
                        var columnIndex = 0;
                        var itemIndex = 0;

                        $.each(MC.c, function (groupIndex, CG) {
                            var Url = ApplicationUrl;
                            if (!Url.match("/$")) Url += "/";
                            Url += "shop/";

                            var CategoryGroupUrl = Url + MSA.ut + "/" + SA.ut + "/" + MC.ut;

                            $.each(CG.c, function (categoryIndex, C) {
                                CategoryGroupUrl += "/" + C.id;
                            });

                            if (showGroups) {
                                columnIndex = Math.floor(itemIndex / itemsPerColumn);
                                if (CG.t == "") {
                                	$(columnArray[columnIndex]).append("<li class=\"group\"><h2><a href=\"" + CategoryGroupUrl + "\">Other</a></h2></li>");
                                }
                                else {
                                	$(columnArray[columnIndex]).append("<li class=\"group\"><h2><a href=\"" + CategoryGroupUrl + "\">" + CG.t + "</a></h2></li>");
                                }
                                itemIndex += 1;
                            }

                            $.each(CG.c, function (categoryIndex, C) {
                                columnIndex = Math.floor(itemIndex / itemsPerColumn);
                                $(columnArray[columnIndex]).append("<li id=\"menu-cat-" + C.id + "\"><input type=\"checkbox\" name=\"checkboxCategoryId\" value=\"" + MSA.ut + "/" + SA.ut + "/" + MC.ut + "/" + C.ut + "\" onclick=\"if(this.checked == true){ $('#menu-cat-" + C.id + "').addClass('MenuSelected') } else { $('#menu-cat-" + C.id + "').removeClass('MenuSelected') }; UpdateViewSelectedCategoriesLink();\" /><p><a href=\"" + Url + MSA.ut + "/" + SA.ut + "/" + MC.ut + "/" + C.ut + "\">" + C.t + "</a></p></li>");
                                itemIndex += 1;
                            });
                        });
                    }
                });
            });
        });
    }

    ShowCategoryList();
    UpdateViewSelectedCategoriesLink();
}

function NavigateToAllCategories() {
    var NavigationToken
    NavigationToken = CurrentMasterSpecialistApplicationId + "-" + CurrentSpecialistApplicationId + "-" + CurrentMasterCategoryId + "-"

    var CheckboxArray = document.getElementsByName("checkboxCategoryId");
    var FirstItem = true;
    for (var index = 0; index < CheckboxArray.length; index++) {
        if (!FirstItem)
            NavigationToken += ".";
        else
            FirstItem = false;
        NavigationToken += CheckboxArray[index].value;
    }
    NavigationToken += "-0";
    window.location = BaseUrl + "?NT=" + NavigationToken;
}

function UpdateViewSelectedCategoriesLink() {
    var Url = ApplicationUrl + "shop/";

    var CheckboxArray = document.getElementsByName("checkboxCategoryId");
    var NumberOfCheckedItems = 0;
    var FirstCheckedItem = true;

    for (var index = 0; index < CheckboxArray.length; index++) {
        if (CheckboxArray[index].checked == true) NumberOfCheckedItems++;
    }

    for (var index = 0; index < CheckboxArray.length; index++) {
        if (NumberOfCheckedItems > 2) {
            if (CheckboxArray[index].checked == true) {
                var CategoryUrlText = CheckboxArray[index].value;
                var CategoryId = 0;

                if (FirstCheckedItem) Url += CategoryUrlText.substring(0, CategoryUrlText.lastIndexOf("/") + 1);
                for (var SCAIndex = 0; SCAIndex < SCA.length; SCAIndex++) {
                    if (SCA[SCAIndex][indexCategoryUrlText] == CategoryUrlText) {
                        CategoryId = SCA[SCAIndex][indexCategoryId];
                        break;
                    }
                }

                if (!FirstCheckedItem)
                    Url += "/";
                else
                    FirstCheckedItem = false;

                Url += CategoryId;
            }
        }
        else {
            if (CheckboxArray[index].checked == true) {
                var CategoryUrlText = CheckboxArray[index].value;

                if (!FirstCheckedItem) {
                    CategoryUrlText = CategoryUrlText.substring(CategoryUrlText.lastIndexOf("/") + 1)
                    Url += "/";
                }
                else {
                    FirstCheckedItem = false;
                }
                Url += CategoryUrlText;
            }
        }
    }
    if (!FirstCheckedItem) {
        $("#ViewSelectedCategories").attr("href", Url);
    }
    else {
        $("#ViewSelectedCategories").attr("href", "#");
    }

    $("#divCategoryListing input:[type=checkbox][checked=true]").each(function (index, checkbox) {
        $(checkbox).parent().addClass("MenuSelected");
    });

    $("#divCategoryListing input:[type=checkbox][checked=false]").each(function (index, checkbox) {
        $(checkbox).parent().removeClass("MenuSelected");
    });
}

function NavigateToSelectedCategories() {
    var UrlDescription = "";

    var CheckboxArray = document.getElementsByName("checkboxCategoryId");
    var FirstCheckedItem = true;
    for (var index = 0; index < CheckboxArray.length; index++) {
        if (CheckboxArray[index].checked == true) {
            var CategoryUrlText = CheckboxArray[index].value;

            if (!FirstCheckedItem) {
                CategoryUrlText = CategoryUrlText.substring(CategoryUrlText.lastIndexOf("/") + 1)
                UrlDescription += "/";
            }
            else {
                FirstCheckedItem = false;
            }
            UrlDescription += CategoryUrlText;
        }
    }
    if (!FirstCheckedItem) {
        window.location = ApplicationUrl + "shop/" + UrlDescription;
    }
    else {
        var div = $get("divCategoryErrorMessage");
        div.innerHTML = "Please tick the boxes to select the categories you want to display.  To display all categories click View All.";
        $("#divCategoryErrorMessage").show("slow");
    }
}

function FailedCallBack(error, userContext, methodName) {
    if (error !== null)
        alert("Error: " + error.get_message() + "\rMethod: " + methodName + "\rStatus Code: " + error.get_statusCode() + "\rExecution Type: " + error.get_exceptionType() + "\rStack trace: " + error.get_stackTrace());
    alert(SiteNavigationWebService);
}

function ShowCategoryHolder() {
    $("#divCategoryHolder").show();
}

function HideCategoryHolder() {
    $("#divCategoryHolder").hide();
}

function ShowCategoryList() {
    $("#divCategoryErrorMessage").hide();
    $("#divCategoryListing").show();
}

function HideCategoryList() {
    $("#divCategoryListing").hide();
}


function SortMenu() {
    var listItemHeight = 19;
    var listItemWidth = 145;
    var listItemHorizontalMargin = 1;

    var menu = $("#SiteNavigation ul:first");
    var listItems = $("li", menu);

    var menuContainer = $("#divSiteNavigationMeasurement"); 
	var containerWidth = menuContainer.outerWidth();

	if (containerWidth > 0) {
    	var numberOfColumns = Math.floor(containerWidth / (listItemWidth + listItemHorizontalMargin));
    	var listItemsPerColumn = Math.ceil(listItems.length / numberOfColumns);
		menu.height(listItemsPerColumn * listItemHeight);

    	var columnIndex = 1, rowIndex = 1;

    	listItems.each(function (index, element) {
    		var listItem = $(element);

    		listItem.css("marginLeft", (columnIndex - 1) * listItemWidth)
					.css("marginTop", (rowIndex == 1) && (columnIndex > 1) ? (0 - (listItemsPerColumn * listItemHeight)) : 0);

    		rowIndex++;
    		
			if (rowIndex > listItemsPerColumn) {
    			columnIndex++;
    			rowIndex = 1;
    		}

    	});
	}
}

function SetNT(MasterSpecialistApplicationId, SpecialistApplicationId, MasterCategoryId) {
    var Value = MasterSpecialistApplicationId + '-' + SpecialistApplicationId + '-' + MasterCategoryId;
    document.cookie = "NT=" + Value + "; path=/";
}

/* Client Validation */
function RegexValidate(Control) {
    if (Control.value.length > 0) {
        var RegexPattern = "^[A-z0-9_\\-\\?'!#\"£\\$%&\\*\\+/=\\?\\^`\\{\\}\\|]*$"
        var Matched = Control.value.match(RegexPattern)

        if (!Matched) {
            alert("The value entered is invalid.");
            var ControlId = Control.id;
            setTimeout("document.getElementById('" + ControlId + "').focus();", 0)
            setTimeout("document.getElementById('" + ControlId + "').select();", 0)
        }
    }
}

function RegexValidateEmail(Control) {
    if (Control.value.length > 0) {
        var RegexPattern = "^[A-z0-9_\\-\\?'!#\\$%&\\*\\+/=\\?\\^`\\{\\}\\|~]{1}[A-z0-9_\\-\\.\\?'!#\\$%&\\*\\+/=\\?\\^`\\{\\}\\|~]*@([A-z0-9_\\-\\.]+)(\\.[A-z]{2,10})+$"
        var Matched = Control.value.match(RegexPattern)

        if (!Matched) {
            alert("Please enter a valid email address.");
            var ControlId = Control.id;
            setTimeout("document.getElementById('" + ControlId + "').focus();", 1)
            setTimeout("document.getElementById('" + ControlId + "').select();", 1)
        }
    }
}

/* Google Tracking */
Scan.GoogleTracking = {};

Scan.GoogleTracking.Setup = function () {
	//Tracking events
	$(".ga-gallery-view").live("click", function () {
		_gaq.push(["_trackEvent", "Product view change", "Gallery"]);
	});

	$(".ga-list-view").live("click", function () {
		_gaq.push(["_trackEvent", "Product view change", "List"]);
	});

	$(".ga-compare-view").live("click", function () {
		var checkedProductCount = $(this).parents(".product-container").find("input:[type=checkbox][checked=true]").length;
		var categoryTitle = $(this).parents(".CategoryContainer").find("h2").text();
		_gaq.push(["_trackEvent", "Product view change", "Compare", categoryTitle, checkedProductCount]);
	});

};


/* General */
$(function () {
	SortMenu();
	Scan.Navigation.MainMenu.RefreshLinksFromMenuStructure();

	Scan.Basket.Setup();
	Scan.GoogleTracking.Setup();


	$(window).resize(function () {
		SortMenu();
	});

	$("#divCategoryListing").live("click", function () {
		Scan.Navigation.MainMenu.SetMenuButtons();
	});

	//default buttons
	$(".default-button-container").keypress(function (e) {
		if (e.keyCode == "13") {
			$(this).find("default-button").click();
		}
	});

	//Init live search
	$("#textboxSearch").ScanLiveSearch($("#LiveSearchResults"), Scan.ApplicationRoot);

	//Footer order tracking tab page
	$(".tracking .tabholder a").click(function () {
		var link = $(this);
		link.addClass("on").siblings().removeClass("on");

		$.each($(".trackarea form", $(this).parents(".tracking")), function (index, element) {
			if (link.hasClass($(element).attr("id")))
				$(element).show();
			else
				$(element).hide();
		});
	});

	//Product image zoom
	$("img.zoomable-image").imageZoom();

	$(".sliding-banner").slidingOffers();

	$(".scanshot-subscribe").emailsubscribe();

	$(".scan-product-video").mediaelementplayer({ pluginPath: "/media/player/", plugins: ["silverlight", "flash"] });
	$(".scan-audio").mediaelementplayer({ pluginPath: "/media/player/", plugins: ["silverlight", "flash"] });

});


$.extend({ UrlEncode: function (c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        }
    } return o;
},
    UrlDecode: function (s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});

function getQueryStringParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}




// misc plugins
(function ($) {
    $.fn.center = (function () {
        this.css("position", "absolute");
        this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
        this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
        return this;
    });
})(jQuery);

(function ($) {
    jQuery.fn.liveDraggable = function (opts) {
        this.live("mouseover", function () {
            if (!$(this).data("init")) {
                $(this).data("init", true).draggable(opts);
            }
        });
    };
})(jQuery);


