﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

function DoSearchInputKeyUp() {
    var searchValue = $("#searchInput").val();
    if (searchValue == "") {
        $(".predictiveSearchBox").hide();
    }
    if (searchValue != "") {
        $.post("/Home/GetPredictiveSearchResults", { entry: searchValue },
                function (results) {
                    if (results.items.length != 0) {
                        var item = "";
                        var mutex = 0;
                        $.each(results.items, function (i, result) {
                            var style = "";
                            if (mutex) {
                                style = " class='alternative'";
                            }
                            item += "<li" + style + ">" + "<b>" + result.name.substring(0, searchValue.length) + "</b>" + result.name.substring(searchValue.length) + "</li>";
                            mutex = 1 - mutex;
                        });
                        $(".predictiveSearchBox ul").html(item);
                    }
                    else {
                        $(".predictiveSearchBox ul").html("<li>No matches found</li>");
                    }
                    $(".predictiveSearchBox").show();
                }
                , "json");
    }
}

$(document).ready(function () {

    $(".predictiveSearchBox").css("top", ($("#txtSearch").offset().top + $("#txtSearch").height()).toString() + "px");
    $(".predictiveSearchBox").css("left", $("#txtSearch").offset().left + "px");

    $("#searchInput, .newsletterInput, #MessageText").focus(function () {
        if ($(this).val() == $(this)[0].title) {
            $(this).val("");
        }
    });

    $("#searchInput, .newsletterInput, #MessageText").blur(function () {
        if ($(this).val() == "") {
            var focusText = $(this).attr("title");
            $(this).val(focusText);
        }
    });

    $("#searchInput, .newsletterInput, #MessageText").blur();

    $("#searchInput").keyup(function (event) {
        if (event.keyCode == '27') {
            $(".predictiveSearchBox").hide();
        }
        else {
            setTimeout("DoSearchInputKeyUp();", 500);
        }
    });

    //    if ($.browser.mozilla) {
    //        $("#searchInput").live("keypress", searchResultsUpAndDown);
    //    } else {
    //        $("#searchInput").live("keydown", searchResultsUpAndDown);
    //    }

    $(".predictiveSearchBox li").live('mouseover mouseout', function (event) {
        $(this).toggleClass("active");
    });

    $(".predictiveSearchBox li").live('click', function (event) {
        $("#searchInput").val($(this).html().replace("<B>", "").replace("</B>", "").replace("<b>", "").replace("</b>", ""));
        $(".predictiveSearchBox").hide();
    });

    $("#searchInput").live('blur', function (event) {
        setTimeout("$('.predictiveSearchBox').hide();", 500);
    });
    //    $("#productThumbs img").click(function() {
    //        var mainProductImg = $(this).attr("src").replace("80", "260").replace("80", "260");
    //        $("#mainProductImg").attr("src", mainProductImg);
    //    });

    $("#addCustomRow").click(function () {
        if ($(this).parents("tr").prev("tr").is(":visible")) {
            $(this).parents("tr").prev("tr").hide();
            $(this).text("Add custom options to enquiry");
        }
        else {
            $(this).parents("tr").prev("tr").show();
            $(this).text("Hide custom options to enquiry");
        }
        return false;
    });
});

function CategoryExpand(catID) {
    var currentUrl = $("#currentUrl").val();
    var SchemeDelimiter = currentUrl.indexOf("://", 0) + 3;
    var urlRootEnd = currentUrl.indexOf("/", SchemeDelimiter);
    if (urlRootEnd != -1) {
        currentUrl = currentUrl.substring(0, urlRootEnd);
    }
    var categoryItem = $("#" + catID);
    if (categoryItem.attr("expanded") == "false") {
        categoryItem.attr("expanded", "true");

        var marginIndex = parseInt(categoryItem.attr("marginIndex")) + 1;
        $.post("/Home/GetCategoryItems", { categoryID: catID },
            function (categories) {
                var item = "<div>";
                if (categories.items.length == 0) {
                    //categoryItem.attr("onclick", "");
                    item += "<div style='margin-left:" + 15 * marginIndex + "px; font-size:10px;'>No items found&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><br style='clear:both;'/>";
                }
                else {
                    $.each(categories.items, function (i, category) {
                        item += "<div style='margin-left:" + 15 * marginIndex + "px;'>";
                        item += "<div onclick='CategoryExpand(\"" + category.guid + "\");' class='categoryItem' marginIndex='" + marginIndex + "' expanded='false' id='" + category.guid + "'></div>";
                        item += "<a href='" + currentUrl + "/Products/" + category.path.replace(" ", "_").replace("&", "[and]") + "'>" + category.name + "</a>";
                        item += "</div>";
                        item += "<br style='clear:both;'/>";
                    });
                    item += "</div><br style='clear:both;'/>";
                }
                categoryItem.parent().next().after(item);
            }
        , "json");
    }
    else {
        categoryItem.attr("expanded", "false");
        categoryItem.parent().next().next().remove();
        categoryItem.parent().next().next().remove();
    }
    categoryItem.toggleClass("categoryItemExpanded");
}

function ResetAskForm() {
    $("#tblAsk input[type=text], #tblAsk textarea").removeClass("input-validation-error").val("");
    $("#errorMessages").empty();
}

function ClosePopup() {
    ResetAskForm();
    $.fancybox.close();
}

function AskSuccess() {
    ResetAskForm();
    $.fancybox.close();
    setTimeout("alert('Your question has been sent');", 500);
}

function AskFail(id, entry) {
    $("#" + id + " input[type=text], #" + id + " textarea").removeClass("input-validation-error");
    $.each(entry.properties, function (i, property) {
        $("#" + property).addClass("input-validation-error");
    });

    var appendix = "<ul>";
    $.each(entry.errormessages, function (i, message) {
        appendix += "<li style='font-weight:bold; color:red;'>" + message + "</li>";
    });
    appendix += "</ul>";
    $("#" + id).prev(".errorMessages").html(appendix);
    $.fancybox.resize();
}

function CreateOrder() {
    var order = "{";
    if ($("#tblProductOptions td.customRow").size() != 0) {
        order += "'productID':'" + $("#hdn_productID").val() + "',";
        if ($("#tblProductOptions td.customRow").is(":visible")) {
            order += "'customOptions':[";
            $.each($("#tblProductOptions td.customRow"), function (i, entry) {
                order += "{'optionID':'" + $(this).attr("id") + "',";
                order += "'value':'" + $(this).children("input").val() + "',";
                order += "'measureUnitID': '" + $(this).children("select").val() + "'},"
            });
            order = order.substr(0, order.length - 1);
            order += "], 'customRowQuantity':'" + $("#customRowQuantity").val() + "','txtInquiryInfo':'" + $("#txtInquiryInfo").val() + "',";
        }
    }
    order += "'rows':[";
    $.each($("#tblProductOptions input[type=text]:not(.customRow)"), function (i, entry) {
        order += "{'rowID':'" + entry.id + "','quantity':'" + entry.value + "'},";
    });
    order = order.substr(0, order.length - 1);
    order += "],'location':'" + window.location + "'}";
    $.post("/Order/CreateOrder", { orders: order },
            function (e) {
                if (e.properties.length != 0)
                    AskFail("tblProductOptions", e);
                else
                    window.location.href =  "/Order";
            }
        , "json");
}


ShowTooltip = function (e) {
    var text = $(this).next('.show-tooltip-text');
    if (text.attr('class') != 'show-tooltip-text')
        return false;

    text.show()
 .css('top', e.pageY)
 .css('left', e.pageX + 10);

    return false;
}
HideTooltip = function (e) {
    var text = $(this).next('.show-tooltip-text');
    if (text.attr('class') != 'show-tooltip-text')
        return false;

    text.hide();
}

SetupTooltips = function (selector, isTitled) {
    $(selector).each(function () {
        var appendix = $('<div/>').attr('class', 'show-tooltip-text');
        if (isTitled) {
            appendix.html($(this).attr('title'));
            appendix.css("background-color", "#0084B4");
            appendix.css("z-index", "1000");
            $(this).attr('title', '');
        }
        else {
            appendix.html($(this).parents("tr").next("tr.tooltipContent").html());
            appendix.css("background-color", "green");
        }
        $(this).after(appendix);
    })
 .hover(ShowTooltip, HideTooltip);
}

var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{
		    string: navigator.userAgent,
		    subString: "Chrome",
		    identity: "Chrome"
		},
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari",
		    versionSearch: "Version"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.userAgent,
		    subString: "iPhone",
		    identity: "iPhone/iPod"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};
BrowserDetect.init();

