﻿var searchText = "Web Site";

function DownloadFile(path) {
    window.open(webSiteUrl + 'DownloadFile/Index?path=' + path);
    return false;
}

$.ajaxSetup({ cache: false });
$(document).ready(function() {
$("#txtSearchBox").addClass("watermarkOn").val("(Enter Keyword or Part #)");
    if (browser_type.indexOf("Safari") > -1 || browser_type.indexOf("Chrome") > -1) {
        $("#txtSearchBox").attr("class", "searchloginboxsafari");
    }
    else if (browser_type.indexOf("Firefox/3.6") == -1) {
        $("#txtSearchBox").attr("class", "searchloginbox searchloginboxpadding watermarkOn");
    }
    else {
        $("#txtSearchBox").attr("class", "searchloginboxfirefox");
    }
    // Define what happens when the textbox comes under focus Remove the watermark class and clear the box
    $("#txtSearchBox").focus(function() {
        if (browser_type.indexOf("Firefox/3.6") == -1) {
            $(this).filter(function() {

                // We only want this to apply if there's not something actually entered
            return $(this).val() == "" || $(this).val() == "(Enter Keyword or Part #)"

            }).removeClass("watermarkOn").val("");
        }
        else {
            $(this).filter(function() {

                // We only want this to apply if there's not something actually entered
            return $(this).val() == "" || $(this).val() == "(Enter Keyword or Part #)"

            }).removeClass("searchloginboxfirefox").val("");
            $(this).attr("class", "searchloginbox");
        }
    });

    // Define what happens when the textbox loses focus Add the watermark class and default text
    $("#txtSearchBox").blur(function() {
        if (browser_type.indexOf("Firefox/3.6") == -1) {
            $(this).filter(function() {

                // We only want this to apply if there's not something actually entered
                return $(this).val() == ""

            }).addClass("watermarkOn").val("(Enter Keyword or Part #)");
        }
        else {
            $(this).filter(function() {

                // We only want this to apply if there's not something actually entered
                return $(this).val() == ""

            }).addClass("searchloginboxfirefox").val("(Enter Keyword or Part #)");
        }
    });
});

//// Added By Amlesh - Issue id 539
function keyCapture(e) {
    var key = window.event ? window.event.keyCode : e.keyCode;
    if (key == 0) key = e.which;

    if (key == '13') {
        var focusControl;
        var browserType = detectBrowserType();
        if (browserType == 1) // FF 3.5
        {
            focusControl = e.target;
        }
        else if (browserType == 2) // FF 3.6
        { // FF and others
            focusControl = e.target;
        }
        else if (browserType == 8) { // IE 6, 7, 8
            focusControl = event.srcElement;
        }
        else if (browserType == 7) {
            focusControl = event.srcElement;
        }
        else {
            focusControl = event.srcElement; // Safari & Chrome
        }

        if (focusControl.id == 'txtSearchBox')
            if (document.getElementById('txtSearchBox').value.trim().length > 0)
            Redirect();
        return false;
    }
    return;
}


function searchFocus() {

    document.onkeypress = keyCapture;

}

String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
//// Added By Amlesh - Issue id 539

function Redirect() {
    var keywords = document.getElementById("txtSearchBox").value.trim();
    var result = true;
    if (keywords == "" || keywords == "(Enter Keyword or Part #)") {
        alert("Please enter a keyword to search");
        document.getElementById("txtSearchBox").value = "";
        document.getElementById("txtSearchBox").focus();
        return false;
    }
    else if (searchText == "Stock Check") {
        OpenStock();
        result = false;
    }
    else {
        var GoodChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-àÀáÁâÂãÃäÄåÅæÆçÇèÈéÉêÊëËìÌíÍîÎïÏðÐñÑòÒóÓôÔõÕöÖùÙúÚûÛüÜýÝÿß®-0123456789 /()';
        for (var i = 0; i <= keywords.length - 1; i++) {
            if (GoodChars.indexOf(keywords.charAt(i)) == -1) {
                result = false;
            }
        }

        if (result == false) {
            alert("Invalid serach keywords");
            document.getElementById("txtSearchBox").focus();
        }
        else {
            document.location.pathname = "/BasicSearch/Index/" + keywords;
        }
    }
    return result;
}

function OpenStock() {
    var keywords = "";
    var url = "";
    if (arguments.length == 1) // Part number is passed as argument
    {
        keywords = arguments[0];
    }
    else {
        keywords = document.getElementById("txtSearchBox").value.trim();
    }
    //            url += "=b&parts=" + keywords;
    if (keywords == "" || keywords == "(Enter Keyword or Part #)") {
        alert("Please enter a part number to search stock");
    }
    else {
        url = stockCheckUrl + keywords;
        window.open(url, "Stock", "", "no");
    }
}

function PLCHome() {
    document.location.pathname = "/PLCHome/Index/";
}

function displayShare(data) {
    if (data.Selected == "true") {
        if (document.getElementById('AddThisShare') != null)
            document.getElementById('AddThisShare').style.display = "";
    }
    else {
        if (document.getElementById('AddThisShare') != null)
            document.getElementById('AddThisShare').style.display = "none";
    }
}
/* Function to detect browser */
function detectBrowserType() {
    var browser = navigator.appName;
    var b_version = navigator.appVersion;
    var version = parseFloat(b_version);

    var retType = -1;

    if (browser == "Microsoft Internet Explorer") {
        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
            //test for MSIE x.x;
            var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
            retType = ieversion;
        }
    }
    else {
        if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
            //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
            var ffversion = new Number(RegExp.$1) // capture x.x portion and store as a number

            if (ffversion == 3.5) {
                retType = 1;
            }
            else if (ffversion == 3.6) {
                retType = 2
            }
            else {
                retType = -1;
            }
        }
    }

    return retType;
}


function collapseExpand(item) {
    obj = document.getElementById(item);
    col = document.getElementById("image" + item);
    if (obj.style.display == "none") {
        obj.style.display = "block";
        col.src = "../../Content/images/arrow-down.png";
    }
    else {
        obj.style.display = "none";
        col.src = "../../Content/images/arrow-straight.png";
    }
}

/**********************************WHERE TO BUY*************************************************************/

function bindRegions(regions) {

    $.ajaxSetup({ cache: false });
    var length = regions.length;
    for (var i = 0; i < length; i++) {
        var stringgrp = "";
        if (regions[i].DisplayType == 2) {
            if (regions[i].Name != "Australia"
                     && regions[i].Name != "GreenLand" && regions[i].Name != "Mexico"
                     && regions[i].Name != "PuertoRico" && regions[i].Name != "Russia" && regions[i].Name != "Bermuda")
                stringgrp = '<optgroup label="' + regions[i].Name + '"  >';
        }

        if (regions[i].DisplayType == 3 || regions[i].DisplayType == 4) {
            stringgrp += '<option value="' + regions[i].RegionID + '"   >' + regions[i].Name + '</option>';
        }
        var childLength = regions[i].ChildRegions.length;
        for (var j = 0; j < childLength; j++) {
            stringgrp += '<option value="' + regions[i].ChildRegions[j].RegionID + '"  >' + regions[i].ChildRegions[j].Name + '</option>';
        }
        stringgrp += '</optgroup>';
        $('#ddlRegion').append(stringgrp);
    }
}

function selectRegion(region) {
    $.ajaxSetup({ cache: false });
    //    waterMark();
    //    debugger;
    if (region != undefined) {
        var regionId = region.RegionID;
        if (region.DisplayType == 4) {
            document.getElementById("ddlSubRegion").style.display = "";
            document.getElementById("txtZipCode").style.display = "";

            $.getJSON(webSiteUrl + "WhereToBuy/InternalMethod/GetRegionsMappingByRegionId", { regionId: regionId }, function(data) {
                bindProvinces(data);
                $('#ddlRegion').val(region.RegionID);
                $('#ddlSubRegion').val(region.RegionTypeID);
                Search();
            });
        }
        else if (region.DisplayType == 3) {

            $.getJSON(webSiteUrl + "WhereToBuy/InternalMethod/GetRegionsMappingByRegionId", { regionId: regionId }, function(data) {
                bindProvinces(data);
                $('#ddlRegion').val(region.RegionID);
                $('#ddlSubRegion').val(region.RegionTypeID);
                Search();
            });

            //            document.getElementById("trSubRegion").style.display = "";
            document.getElementById("trZipCode").style.display = "";
        }
        else {
            document.getElementById("trSubRegion").style.display = "none";
            document.getElementById("trZipCode").style.display = "none";

            $('#ddlRegion').val(region.RegionTypeID);

            Search();
        }
    }
}

function bindProvinces(provinces) {
    $.ajaxSetup({ cache: false });
    //    debugger
    $('#ddlSubRegion').children().remove().end().append('<option selected value="0" >(Choose a Sub Region)</option>');

    var count = provinces.length;
    for (var i = 0; i < count; i++) {
        if (provinces[i].Name != "All of United States") {
            var stringgrp = '';
            stringgrp += '<option value="' + provinces[i].RegionID + '" >' + provinces[i].Name + '</option>';
            $('#ddlSubRegion').append(stringgrp);
        }
    }
}

function RegionChanged() {
    $.ajaxSetup({ cache: false });
    var regionId = document.getElementById("ddlRegion").value;
    if (regionId != "") {
        $.getJSON(webSiteUrl + "WhereToBuy/InternalMethod/GetRegionDisplayType", { regionId: regionId }, function(data) {
            displayControls(data);
            if (regionId != "1" && regionId != "4" && regionId != "42229") {
                Search();
            }
        });
    }
    else {
        document.getElementById("trSubRegion").style.display = "none";
        document.getElementById("trZipCode").style.display = "none";

        Search();
    }

}

function bindRebateUrl(rebateUrl) {
    if (rebateUrl != "") {
        $("a#rebateUrl").attr("href", rebateUrl);
        $("#lblrebateUrl")[0].style.display = "none";
        $("a#rebateUrl")[0].style.display = "";
    }
    else {
        $("a#rebateUrl")[0].style.display = "none";
        $("#lblrebateUrl")[0].style.display = "";
    }
    
}

function displayControls(displayType) {
    $.ajaxSetup({ cache: false });
    //    waterMark();
    var regionId = document.getElementById("ddlRegion").value;
    if (displayType == 4) {
        document.getElementById("trSubRegion").style.display = "";
        document.getElementById("trZipCode").style.display = "";

        $.getJSON(webSiteUrl + "WhereToBuy/InternalMethod/GetRegionsMappingByRegionId", { regionId: regionId }, function(data) {
            bindProvinces(data);
            //        Search();
            document.getElementById("divCompanies").innerHTML = "";
        });
    }
    else if (displayType == 3) {

        $.getJSON(webSiteUrl + "WhereToBuy/InternalMethod/GetRegionsMappingByRegionId", { regionId: regionId }, function(data) {
            bindProvinces(data);
            //        Search();
            document.getElementById("divCompanies").innerHTML = "";
        });

        document.getElementById("trSubRegion").style.display = "";
        document.getElementById("trZipCode").style.display = "none";
        document.getElementById("txtZipCode").value = "";
    }
    else {
        document.getElementById("trSubRegion").style.display = "none";
        document.getElementById("trZipCode").style.display = "none";
        document.getElementById("txtZipCode").value = "";
    }
}

function Search() {
    $.ajaxSetup({ cache: false });
    document.getElementById("divCompanies").innerHTML = "";
    //                debugger
    var productLineId = "";
    if (document.getElementById("ddlProductLine") == null)
        productLineId = "421024";
    else
        productLineId = document.getElementById("ddlProductLine").value;

    if (productLineId == "")
        productLineId = "421024";

    if (document.getElementById("ddlRegion").value != "") {

        document.getElementById("divLoading").style.display = "";
        document.getElementById("divCompanies").innerHTML = "";

        var regionId;

        if (document.getElementById("trSubRegion").style.display == "none" && document.getElementById("trZipCode").style.display == "none") {
            regionId = document.getElementById("ddlRegion").value;
            $.getJSON(webSiteUrl + "WhereToBuy/InternalMethod/SearchCompanyDetails", { regionId: regionId, productLineId: productLineId }, function(data) {
                displayCompanies(data);
            });

            $.getJSON(webSiteUrl + "Calculator/InternalMethod/GetRebateUrl", { regionId: regionId }, function(data) {
                bindRebateUrl(data);
            });
        }
        else if (document.getElementById("trSubRegion").style.display == "" && document.getElementById("trZipCode").style.display == "none") {

            regionId = document.getElementById("ddlSubRegion").value;
            $.getJSON(webSiteUrl + "WhereToBuy/InternalMethod/SearchCompanyDetails", { regionId: regionId, productLineId: productLineId }, function(data) {
                displayCompanies(data);
            });

            $.getJSON(webSiteUrl + "Calculator/InternalMethod/GetRebateUrl", { regionId: regionId }, function(data) {
                bindRebateUrl(data);
            });
        }
        else {
            if (document.getElementById("txtZipCode").value == "" || document.getElementById("txtZipCode").value == "(Enter a Zip Code)") {
                regionId = document.getElementById("ddlSubRegion").value;
                $.getJSON(webSiteUrl + "WhereToBuy/InternalMethod/SearchCompanyDetails", { regionId: regionId, productLineId: productLineId }, function(data) {
                    displayCompanies(data);
                });

                $.getJSON(webSiteUrl + "Calculator/InternalMethod/GetRebateUrl", { regionId: regionId }, function(data) {
                    bindRebateUrl(data);
                });
            }
            else {
                regionId = document.getElementById("txtZipCode").value;
                $.getJSON(webSiteUrl + "WhereToBuy/InternalMethod/SearchCompanyDetail", { regionId: regionId, productLineId: productLineId }, function(data) {
                    displayCompanies(data);
                });
            }
        }
    }
}

var regionalManagerEmailId = "";

function displayCompanies(companies) {
    $.ajaxSetup({ cache: false });
    var length = companies.length;
    var table = "";
    var defaultTable = "";
    //            debugger
    if (length != undefined) {
        table = "";
        for (var i = 0; i < length; i++) {
            if (regionalManagerEmailId == "" && companies[i].RegionalManagerEmailID != null) {
                regionalManagerEmailId = companies[i].RegionalManagerEmailID;
            }
            var ordinal = companies[i].CompanyID;
            table += "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">" +
                        "<tr heigh=\"15px\">" +
                            "<td bgcolor=\"#FFFFFF\">" +
                                "&nbsp;" +
                            "</td>" +
                            "<td bgcolor=\"#FFFFFF\" class=\"blueheadings\" style=\"text-align:left\">" +
                                companies[i].DeptAddressee + "(s)" +
                            "</td>" +
                            "<td bgcolor=\"#FFFFFF\">" +
                                "&nbsp;" +
                            "</td>" +
                            "<td bgcolor=\"#FFFFFF\">" +
                                "&nbsp;" +
                            "</td>" +
                        "</tr>";
            for (var j = i; j < length; j++) {
                if (companies[j].CompanyID == ordinal) {
                    table += "<tr heigh=\"15px\">" +
                            "<td bgcolor=\"#FFFFFF\">" +
                                "&nbsp;" +
                            "</td>" +
                            "<td bgcolor=\"#FFFFFF\" class=\"blueheadings-small\" style=\"padding-left:20px;width:330px;\"  align=\"left\">" +
                                "" + companies[j].CompanyName + "</td>";
                    if (companies[j].Email != undefined && companies[j].Email.length > 0 && companies[j].Email != null) {
                        table += " <td bgcolor=\"#FFFFFF\"><a href=\"mailto:" + companies[j].Email +
                                         "\" style=\"width:70px;\"><img src='/Common/Images/email.png' alt=\"email\" />" +
                                         " </a>&nbsp;&nbsp;&nbsp;</td>";
                    }
                    if (companies[j].URL != null && companies[j].URL.length > 0) {
                        table += "<td bgcolor=\"#FFFFFF\"><a href=\"" + companies[j].URL +
                                 "\" target=\"_blank\" style=\"width:70px;\"><img src='/Common/Images/website.png' " +
                                 "alt=\"website\" /> </a></td>";
                    }

                    table += "</tr>";
                    i++;
                }
                else {
                    i = j - 1;

                    table += "</table><br />";
                    break;
                }
            }
        }

        document.getElementById("divLoading").style.display = "none";
        document.getElementById("divCompanies").innerHTML = table;
    }
    else {
        defaultTable = "<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
        defaultTable += "<tr heigh=\"15px\">" +
                            "<td bgcolor=\"#FFFFFF\">" +
                                "&nbsp;" +
                            "</td>" +
                            "<td bgcolor=\"#FFFFFF\" class=\"blueheadings\" style=\"text-align:left\">" +
                                companies.DeptAddressee +
                            "</td>" +
                            "<td bgcolor=\"#FFFFFF\">" +
                                "&nbsp;" +
                            "</td>" +
                            "<td bgcolor=\"#FFFFFF\">" +
                                "&nbsp;" +
                            "</td>" +
                        "</tr>";
        defaultTable += "<tr heigh=\"15px\">" +
                            "<td bgcolor=\"#FFFFFF\">" +
                                "&nbsp;" +
                            "</td>" +
                            "<td bgcolor=\"#FFFFFF\" class=\"blueheadings-small\" style=\"padding-left:20px;width:330px;\" align=\"left\">" +
                                "" + companies.CompanyName + "</td>";
        if (companies.Email != undefined && companies.Email.length > 0 && companies.Email != null) {
            defaultTable += " <td bgcolor=\"#FFFFFF\"><a href=\"mailto:" + companies.Email +
                                         "\" style=\"width:70px;\"><img src='/Common/Images/email.png' alt=\"email\" />" +
                                         " </a>&nbsp;&nbsp;&nbsp;</td>";
        }
        else {
            defaultTable += " <td bgcolor=\"#FFFFFF\" style=\"width:70px;\">&nbsp;&nbsp;&nbsp;</td>";
        }
        if (companies.URL != null && companies.URL.length > 0) {
            defaultTable += "<td bgcolor=\"#FFFFFF\"><a href=\"" + companies.URL +
                                 "\" target=\"_blank\" style=\"width:70px;\"><img src='/Common/Images/website.png' " +
                                 "alt=\"website\" /> </a></td>";
        }

        defaultTable += "</tr>";
        defaultTable += "</table><br />";

        document.getElementById("divLoading").style.display = "none";
        document.getElementById("divCompanies").innerHTML = defaultTable;
    }

}

$(document).ready(function() {

    var $ui = $(document);
    if (searchText == "Web Site") {
        $ui.find('.rdbtndivWebSite').addClass("radionbtnWeSite")
                    .show();

        $ui.find('.rdbtndivStockCheck').addClass("radionbtnStockCheck")
                    .show();
    }
    else if (searchText == "Stock Check") {
        $ui.find('.rdbtndivStockCheck').addClass("radionbtnStockCheck")
                    .show();

        $ui.find('.rdbtndivWebSite').addClass("radionbtnWeSite")
                    .show();
    }

    $ui.find('.rdbtndivWebSite').bind('click', function() {
        $ui.find('.rdbtndivWebSite').css({ "background-image": "url('/Common/Images/RadioCheck.png')" });
        $ui.find('.rdbtndivStockCheck').css({ "background-image": "url('/Common/Images/RadioUncheck.png')" });
    });

    $ui.find('.rdbtndivStockCheck').bind('click', function() {
        $ui.find('.rdbtndivStockCheck').css({ "background-image": "url('/Common/Images/RadioCheck.png')" });
        $ui.find('.rdbtndivWebSite').css({ "background-image": "url('/Common/Images/RadioUncheck.png')" });
    });


    $('.rdbtndivWebSite').click(function() {
        searchText = "Web Site"
    });


    $('.rdbtndivStockCheck').click(function() {
        searchText = "Stock Check"
    });

});
