

//function SetWebkitFix() {
//    if (typeof (Sys.Browser.WebKit) == "undefined") {
//        Sys.Browser.WebKit = {};
//    };

//    if (navigator.userAgent.indexOf("WebKit/") > -1) {
//        Sys.Browser.agent = Sys.Browser.WebKit;
//        Sys.Browser.version =
//        parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
//        Sys.Browser.name = "WebKit";
//    };
//};

/************************************************************************/
/*                      Reverse Mount Finder                            */
/************************************************************************/
function LoadReverseMountFinder() {
    $('#tab6').live('click', function () {
        PullCompatableManufacturers($('#productSKU span').html(), 'Dell;Epson;INFOCUS;NEC;Panasonic;Samsung;Sharp;Sony;');
    });

    $('#ddCompatabilityManufacturers').live('change', function () {
        // Pull updated model list       
        PullCompatableModels($('#productSKU span').html(), $('#ddCompatabilityManufacturers :selected').attr('value'));
    });
};

function PullCompatableManufacturers(itemCode, topManufacturerList) {
    $('#divReverseMountLoader').show();
    var optGrpTop = $('#optCompatabilityGrpTop');
    var optGrpAll = $('#optCompatabilityGrpAll');

    $.ajax({
        type: "POST",
        url: '/WebServices/ConsumerProductService.asmx/GetCompatableManufacturers',
        data: "{ 'ItemCode': '" + itemCode + "', 'TopManufacturerList': '" + topManufacturerList + "' }",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (msg) {
            optGrpTop.html('');
            optGrpAll.html('');

            if (msg.d.TopManufacturers.length > 0) {
                $.each(msg.d.TopManufacturers, function () {
                    optGrpTop.append('<option label="' + this.ManufacturerName + '" value="' + this.ManufacturerID + '">' + this.ManufacturerName + '</option>');
                });
            }
            else {
                optGrpTop.append('<option> None found</option>');
            }

            if (msg.d.FullList.length > 0) {
                $.each(msg.d.FullList, function () {
                    optGrpAll.append('<option label="' + this.ManufacturerName + '" value="' + this.ManufacturerID + '">' + this.ManufacturerName + '</option>');
                });
            }
            else {
                optGrpAll.append('<option> None found</option>');
            }

            $('#divReverseMountLoader').hide();
        },
        error: function (xhr, textStatus, thrownError) {
            alert("/WebServices/ConsumerProductService.asmx/GetManufacturers Service Error - Unable to pull manufacturers. TextStatus: "
                + textStatus + " ThrownError: " + thrownError);
        }
    });
};

function PullCompatableModels(itemCode, manufacturerID) {
    $('#divReverseMountLoader').show();
    var models = $('#ddCompatabilityModels');
    $.ajax({
        type: "POST",
        url: '/WebServices/ConsumerProductService.asmx/GetCompatableConsumerProductsSearchResults',
        data: "{ 'ItemCode': '" + itemCode + "', 'ManufacturerId' : '" + manufacturerID + "' }",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (msg) {
            models.html('');
            $.map(msg.d, function (item) {
                models.append('<li>' + item.Model + '</li>');
            });
            $('#divReverseMountLoader').hide();
        },
        error: function (xhr, textStatus, thrownError) {
            alert("/WebServices/ConsumerProductService.asmx/GetConsumerProducts Service Error - Unable to pull models. TextStatus: "
                + textStatus + " ThrownError: " + thrownError);
        }
    });
};


/************************************************************************/
/*                          Mount Finder                                */
/************************************************************************/
function LoadMountFinder(CssClassName) {
    $('#divMountFinder').toggleClass(CssClassName);

    // Pull updated manufacture list            
    PullManufacturers($('.ProductType:checked').val(), '', GetTopManufacturers());

    $('.ProductType').change(function () {
        // Hide current results
        $('#divSearchResults').hide();

        // Pull updated manufacture list            
        PullManufacturers($('.ProductType:checked').val(), '', GetTopManufacturers());

        // Reset models drop down
        $('#ddModels').html('');
    });

    $('#ddManufacturers').change(function () {
        // Hide current results
        $('#divSearchResults').hide();

        // Pull updated model list       
        PullModels($('.ProductType:checked').val(), $('#ddManufacturers :selected').attr('value'));
    });

    $('#btnSubmitFinder').click(function () {
        // Pull Results
        window.location = '/Mount-Finder/' + $('#ddManufacturers :selected').attr('label') + '/' + $('#ddModels :selected').attr('label')
    });
};

function GetTopManufacturers() {
    var TopManufacturersList;

    if ($('.ProductType:checked').val() == 'Projector') {
        TopManufacturersList = 'Dell;Epson;INFOCUS;NEC;Panasonic;Sony;';
    }
    else {
        TopManufacturersList = 'NEC;Panasonic;Samsung;Sharp;Sony;'
    }
    return TopManufacturersList;
};

function PullManufacturers(type, limitedList, topManufacturers) {
    $('#divMountLoader').show();
    var optGrpTop = $('#optGrpTop');
    var optGrpAll = $('#optGrpAll');

    $.ajax({
        type: "POST",
        url: '/WebServices/ConsumerProductService.asmx/GetManufacturers',
        data: "{ 'limitedList': '" + limitedList + "', 'type': '" + type + "', 'topManufacturers': '" + topManufacturers + "' }",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (msg) {
            optGrpTop.html('');
            optGrpAll.html('');
            if (msg.d != null) {
                $.each(msg.d.TopManufacturers, function () {
                    optGrpTop.append('<option label="' + this.ManufacturerName + '" value="' + this.ManufacturerID + '">' + this.ManufacturerName + '</option>');
                });

                $.each(msg.d.FullList, function () {
                    optGrpAll.append('<option label="' + this.ManufacturerName + '" value="' + this.ManufacturerID + '">' + this.ManufacturerName + '</option>');
                });
            }
            else {
                optGrpTop.append('<option class="listHeader"> None found</option>');
                optGrpAll.append('<option class="listHeader"> None found</option>');
            }
            $('#divMountLoader').hide();
        },
        error: function (xhr, textStatus, thrownError) {
            alert("/WebServices/ConsumerProductService.asmx/GetManufacturers Service Error - Unable to pull manufacturers. TextStatus: "
                + textStatus + " ThrownError: " + thrownError);
        }
    });
};

function PullModels(type, manufacturerID) {
    $('#divMountLoader').show();
    var models = $('#ddModels');
    $.ajax({
        type: "POST",
        url: '/WebServices/ConsumerProductService.asmx/GetConsumerProducts',
        data: "{ 'manufacturerID': '" + manufacturerID + "', 'type' : '" + type + "' }",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (msg) {
            models.html('');
            models.append('<option class="listHeader">Select Model</option>');
            $.map(msg.d, function (item) {
                models.append('<option label="' + item.Model + '" value="' + item.ConsumerProductID + '">' + item.Model + '</option>');
            });
            $('#divMountLoader').hide();
        },
        error: function (xhr, textStatus, thrownError) {
            alert("/WebServices/ConsumerProductService.asmx/GetConsumerProducts Service Error - Unable to pull models. TextStatus: "
                + textStatus + " ThrownError: " + thrownError);
        }
    });
};

/************************************************************************/


/* ZOOM PRODUCT IMAGE */
$('#imageHook img').click(function () {
    var imageLocation = this.src;
    $('#imageZoom').html('<img src="http://www.chiefmfg.com/images/bg_x.gif" /><br><img id="imageZoomed" src="' + imageLocation + '" width="500" height="500" />');
    $('#imageZoom').show();
});

$('#imageZoom').click(function () {
    $('#imageZoom').hide();
});

function AssignEnterButton(buttonName, skipClass) {
    $("form input").keypress(function (e) {
        //alert($(this).attr('class').indexOf(skipClass));
        if (((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) && ($(this).attr('class').indexOf(skipClass) == -1)) {
            $('#' + buttonName).click();
            return false;
        } else {
            return true;
        }
    });
};

/* PRODUCT TABS */
function switchTabs(x) {
    var tabCount = document.getElementById('tabs').getElementsByTagName('LI').length + 1;
    for (var i = 0; i < tabCount; i++) {
        if (document.getElementById('tab' + i)) {
            document.getElementById('tab' + i).className = 'tabOff';
        }
        document.getElementById('tabContent' + i).style.display = 'none';
    }
    document.getElementById('tab' + x).className = 'tabOn';
    document.getElementById('tabContent' + x).style.display = 'block';
}

/* SEARCH RESULTS ITEMS PER PAGE */
/*var resultCountValue = 15;

function changeResultCount() {
resultCountValue = $('#resultCount').val();
initPagination();
}*/

/** * Callback function that displays the content.
* Gets called every time the user clicks on a pagination link.
* @param {int} page_index New Page index
* @param {jQuery} jq the container with the pagination links as a jQuery object */

/*function pageselectCallback(page_index, jq) {
var items_per_page = resultCountValue;
var num_entries = jQuery('#hiddenresult .result').length;
var max_elem = Math.min((page_index + 1) * items_per_page, num_entries);
$('#galereryitems').empty()

for (var i = page_index * items_per_page; i < max_elem; i++) {
var new_content = jQuery('#hiddenresult .result:eq(' + i + ')').clone();
$('#galereryitems').append(new_content);
}
return false;
}*/

/** * Initialisation function for pagination*/

function initPagination(hiddenResultId, paginationId, galeryItemsId, resultCountValue) {
    // count entries inside the hidden content
    var num_entries = jQuery('#' + hiddenResultId + ' .result').length;

    // Create content inside pagination element
    $('#' + paginationId).pagination(num_entries, {
        callback: function (page_index, jq) {
            var items_per_page = resultCountValue;
            var num_entries = jQuery('#' + hiddenResultId + ' .result').length;
            var max_elem = Math.min((page_index + 1) * items_per_page, num_entries);
            $('#' + galeryItemsId).empty()

            for (var i = page_index * items_per_page; i < max_elem; i++) {
                var new_content = jQuery('#' + hiddenResultId + ' .result:eq(' + i + ')').clone();
                $('#' + galeryItemsId).append(new_content);
            }
            return false;
        },
        items_per_page: resultCountValue // Show only one item per page
    });
}

// PRODUCT IMAGE SWAP 
$('#productImageThumbs img').click(function () {
    var newImage = $(this).attr('src');
    $('#LargeImg').attr('src', newImage);
});

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

/* ACCESSORY MENU SWITCHER */
function menuSelect(x) {
    var menuCount = document.getElementById('productAccessoryFilters').getElementsByTagName('li').length;
    for (var i = 0; i < menuCount; i++) {
        document.getElementById('menuItem' + i).className = '';
    }
    document.getElementById('menuItem' + x).className = 'menuOn';
}

/* RANDOM IMAGE */
function randomImage() {
    var imageName = new Array("K1D100", "K1D200", "RPMx", "LTM", "JPP", "XSM", "LSM", "MSMVU", "ROTR-HD");
    var l = imageName.length;
    var x = Math.floor(l * Math.random());
    var y = imageName[x];

    document.getElementById("randomProductPhoto").src = "http://cdn.chiefmfg.com/chiefmfg/homeThumbs/" + y + ".jpg";
    document.getElementById("randomProductLink").href = "http://www.chiefmfg.com/Series/" + y;
}

/* MS Z-INDEX FIX */
function fixZindex() {
    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

    if (ieversion < 8) {
        document.getElementById('mainContent').style.zIndex = "0";
        document.getElementById('photos').style.zIndex = "1";
    }
}

/*MEGA MENUS*/
function megaMenuStart() {

    function megaHoverOver() {
        $(this).find(".sub").stop().fadeTo('fast', 1).show();

        //Calculate width of all ul's
        (function ($) {
            jQuery.fn.calcSubWidth = function () {
                rowWidth = 0;
                //Calculate row
                $(this).find("ul").each(function () {
                    rowWidth += $(this).width();
                });
            };
        })(jQuery);

        if ($(this).find(".row").length > 0) { //If row exists...
            var biggestRow = 0;
            //Calculate each row
            $(this).find(".row").each(function () {
                $(this).calcSubWidth();
                //Find biggest row
                if (rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });
            //Set width
            $(this).find(".sub").css({ 'width': biggestRow });
            $(this).find(".row:last").css({ 'margin': '0' });

        } else { //If row does not exist...

            $(this).calcSubWidth();
            //Set Width
            $(this).find(".sub").css({ 'width': rowWidth });
        }

        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
        }

        if (ieversion < 8) {//&& document.location.pathname.indexOf('html/default.html') > 0
            document.getElementById('mainContent').style.zIndex = "-2";
            document.getElementById('photos').style.zIndex = "-1";
        }
    }

    function megaHoverOut() {
        $(this).find(".sub").stop().fadeTo('fast', 0, function () {
            $(this).hide();
        });
    }

    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
        interval: 0, // number = milliseconds for onMouseOver polling interval    
        over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
        timeout: 0, // number = milliseconds delay before onMouseOut    
        out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
    };

    $("ul#topnav li .sub").css({ 'opacity': '0' });
    $("ul#topnav li").hoverIntent(config);
    $("ul#headerLogin li .sub").css({ 'opacity': '0' });
    $("ul#headerLogin li").hoverIntent(config);
}

// DOCK LOAD
function dockLoad() {
    // Dock initialize
    $('#dock').Fisheye(
		{
		    maxWidth: 30,
		    items: 'a',
		    itemsText: 'span',
		    container: '.dock-container',
		    itemWidth: 85,
		    proximity: 90,
		    alignment: 'left',
		    valign: 'bottom',
		    halign: 'center',
		    show_panels: false
		}
	);
}

function bannerLoad() {
    $('#photos').galleryView({
        panel_width: 960,
        panel_height: 250,
        transition_speed: 1500,
        transition_interval: 10000,
        nav_theme: 'dark',
        border: '0px',
        pause_on_hover: true,
        show_filmstrip: false
    });
}

// TOOLTIP LOAD
function toolTips() {
    var tipCount = document.getElementById('rightColumnProducts').getElementsByTagName('img');
    for (var i = 0; i < tipCount.length; i++) {
        tipCount[i].id = ('tip' + i);
        $('#tip' + i).tipsy({ gravity: 's' });
    }
}

// COMPARE PRODUCTS IMAGES HOVER
var cookieName = 'Chief.CompareProducts';
var cookieNameSeries = 'Chief.CompareSeries';
var myarray = init_array();
var myarraySeries = init_array();
var timeToKeep = 7200000;
var expires = new Date();
expires.setTime(expires.getTime() + timeToKeep);
var dbug = 0;

function d_a(ary) {
    var beg = next_entry(ary) - 1;

    for (var i = beg; i > -1; i--) {
        ary[i] = null;
    }
}

function init_array() {
    if (dbug) alert('init_cookie');
    var ary = new Array(null);
    return ary;
}

function set_cookie(name, value, expires) {
    if (dbug) alert('set_cookie');
    if (!expires) expires = new Date();
    document.cookie = name + '=' + escape(value) + '; expires=' + expires.toGMTString() + '; path=/';
}

function get_cookie(name) {
    if (dbug) alert('get_cookie');
    var dcookie = document.cookie;
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;
    while (cbegin < clen) {
        var vbegin = cbegin + cname.length;
        if (dcookie.substring(cbegin, vbegin) == cname) {
            var vend = dcookie.indexOf(";", vbegin);
            if (vend == -1) vend = clen;
            return unescape(dcookie.substring(vbegin, vend));
        }
        cbegin = dcookie.indexOf(" ", cbegin) + 1; if (cbegin == 0) break;
    } return null;
}

function del_cookie(name) {
    if (dbug) alert('del_cookie');
    document.cookie = name + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
}

function get_array(name, ary) {
    if (dbug) alert('get_array'); d_a(ary); var ent = get_cookie(name); if (ent) {
        i = 1; while (ent.indexOf('^') != '-1') {
            ary[i] = ent.substring(0, ent.indexOf('^')); i++;
            ent = ent.substring(ent.indexOf('^') + 1, ent.length);
        }
    }
}

function set_array(name, ary, expires) {
    if (dbug) alert('set_array');
    var value = '';
    for (var i = 1; ary[i]; i++) {
        value += ary[i] + '^';
    }
    set_cookie(name, value, expires);
}

function clear_array() {
    myarray = [];
    myarraySeries = [];
}

function del_entry(name, ary, pos, expires) {
    if (dbug) alert('del_entry');
    var value = '';
    get_array(name, ary);
    for (var i = 1; i < pos; i++) {
        value += ary[i] + '^';
    }
    for (var j = pos + 1; ary[j]; j++) {
        value += ary[j] + '^';
    }
    set_cookie(name, value, expires);
}

function next_entry(ary) {
    if (dbug) alert('next_entry');
    var j = 0;
    for (var i = 1; ary[i]; i++) {
        j = i
    }
    return j + 1;
}

function debug_on() { dbug = 1; }

function debug_off() { dbug = 0; }

function dump_cookies() {
    if (document.cookie == '')
        document.write('No Cookies Found');
    else {
        thisCookie = document.cookie.split('; ');
        for (i = 0; i < thisCookie.length; i++) {
            document.write(thisCookie[i] + '<br \/>');
        }
    }
}

//Compare functions
function compareProductsHover(x) {
    //if (document.getElementById('compareImage' + x).src.indexOf('blank.gif') <= -1) {
    //    document.getElementById('compareImage' + x).src = '/images/bg_x.gif';
    //}
}

function compareProductsOut(x) {
    //get_array(cookieName, myarray);
    //compareObject = myarray[x];
    //document.getElementById('compareImage' + x).src = compareObject.image;
}

function compareProductsClick(x) {
    var strChecksrc = document.getElementById('compareProductImage' + x).src.toString();
    if (strChecksrc.indexOf("blank") == -1) removeProductFromCompareList(x);
}

function compareSeriesClick(x) {
    var strChecksrc = document.getElementById('compareImage' + x).src.toString();
    if (strChecksrc.indexOf("blank") == -1) removeSeriesFromCompareList(x);
}

function addProductToCompareList(id, cb, img) {
    var found = false;
    var pos = 0;

    get_array(cookieName, myarray);
    var num = next_entry(myarray);

    for (var i = 1; myarray[i]; i++) {
        if (myarray[i] != null) {
            var values = myarray[i].split('|');
            //means exists in list already so probably an uncheck
            if (values[0] == id) {
                found = true;
                pos = i;
            }
        }
    }

    if (found) {
        removeProductFromCompareList(pos);
        updateCompareImages();
    }
    else {
        if (num > 3) {
            document.getElementById(cb).checked = false;
            alert("You can only select 3 Products");
        }
        else {
            var ckie = id + '|' + cb + '|' + img;
            updateCompareList(ckie)
            updateCompareImages();
        }
    }
}

function addSeriesToCompareList(id, cb, img) {
    var found = false;
    var pos = 0;

    get_array(cookieNameSeries, myarraySeries);
    var num = next_entry(myarraySeries);

    for (var i = 1; myarraySeries[i]; i++) {
        if (myarraySeries[i] != null) {
            var values = myarraySeries[i].split('|');
            //means exists in list already so probably an uncheck
            if (values[0] == id) {
                found = true;
                pos = i;
            }
        }
    }

    if (found) {
        removeSeriesFromCompareList(pos);
        updateCompareSeriesImages();
    }
    else {
        if (num > 3) {
            document.getElementById(cb).checked = false;
            alert("You can only select 3 series type");
        }
        else {
            var ckie = id + '|' + cb + '|' + img;
            updateSeriesList(ckie)
            updateCompareSeriesImages();
        }
    }
}

function validateCompare() {
    var num = myarray.length;
    if (num >= 3) {
        return true;
    }
    else {
        alert("Please select at least 2 products");
        return false;
    }
}

function validateSeriesCompare() {
    var num = myarraySeries.length;
    if (num >= 3) {
        return true;
    }
    else {
        alert("Please select at least 2 series");
        return false;
    }
}

function removeProductFromCompareList(x) {

    if (myarray[x] != null) {
        var values = myarray[x].split('|');
        document.getElementById(values[1]).checked = false;
    }

    get_array(cookieName, myarray);
    del_entry(cookieName, myarray, x, expires);
    updateCompareImages();
}

function removeSeriesFromCompareList(x) {
    if (myarraySeries[x] != null)
    {
        var values = myarraySeries[x].split('|');
        document.getElementById(values[1]).checked = false;
    }
    get_array(cookieNameSeries, myarraySeries);
    del_entry(cookieNameSeries, myarraySeries, x, expires);
    updateCompareSeriesImages();
}

function clearProductCompareList()  {
    get_array(cookieName, myarray);
    for (var i = 1; myarray[i]; i++)
    {
        del_entry(cookieName, myarray, i, expires);
    }
}

function clearSeriesCompareList() {
    get_array(cookieNameSeries, myarraySeries);
    for (var i = 1; myarray[i]; i++) {
        del_entry(cookieNameSeries, myarraySeries, i, expires);
    }
}

function updateCompareList(ckie) {
    get_array(cookieName, myarray);
    var num = next_entry(myarray);
    myarray[num] = ckie;
    set_array(cookieName, myarray, expires);
}

function updateSeriesList(ckie) {
    get_array(cookieNameSeries, myarraySeries);
    var num = next_entry(myarraySeries);
    myarraySeries[num] = ckie;
    set_array(cookieNameSeries, myarraySeries, expires);
}

function updateCompareImages() {
    get_array(cookieName, myarray);
    for (var i = 1; i <= 3; i++) {
        document.getElementById('compareProductImage' + i).src = '/images/blank.gif';
        document.getElementById('compareProductsRemove' + i).style.display = 'none';

        if (myarray[i] != null) {

            var values = myarray[i].split('|');
            document.getElementById('compareProductImage' + i).src = values[2];
            document.getElementById('compareProductsRemove' + i).style.display = 'block';
        }
    }
}

function updateCompareSeriesImages() {
    get_array(cookieNameSeries, myarraySeries);
    for (var i = 1; i <= 3; i++) {
        document.getElementById('compareImage' + i).src = '/images/blank.gif';
        document.getElementById('compareRemove' + i).style.display = 'none';

        if (myarraySeries[i] != null) {

            var values = myarraySeries[i].split('|');
            document.getElementById('compareImage' + i).src = values[2];
            document.getElementById('compareRemove' + i).style.display = 'block';
        }
    }
}

// CONTACT INFORMATION
    var USA = ["US"];
    var CAN = ["CA"];
    var AP = ["CN", "JP", "KP", "KR", "TH", "VN", "MN"];
    var EMEA = ["UK", "RU", "ES", "DE", "FR", "PT", "IE", "BE", "NL", "NO", "SE", "RO", "UA", "IT", "CZ", "DK", "AT", "PL", "GB", "NZ", "BH", "IQ", "IR", "IL", "JO", "KW", "LB", "OM", "PL", "QA", 
                "SA", "SQ", "AE", "YE", "ZA", "ZN", "WC", "NW", "NC", "MP", "LP", "GP", "FS", "EC", "EC", "FS", "GP", "ZN", "LP", "MP", "NC", "NW", "WC", "RU", "TR"];
    var MEX = ["MX"];
    var SA = ["AG", "BO", "BL", "CL", "CK", "EC", "FG", "GY", "PY", "PE", "SR", "UY", "VE", "BR"];    

    // Finds client country based off browser IP
    function GetUserCountry() {
        if ($.cookie("ChiefClientLocation") == null) {
            MapCode(google.loader.ClientLocation.address.country_code);
        }
        return $.cookie("ChiefClientLocation");
    };

    // Maps country code to the correct region
    function MapCode(countryCode) {
        var currentLocation;

        // Set to contact information to correct country
        if ($.inArray(countryCode, AP) >= 0) {
            currentLocation = 'AP';
        }
        else if ($.inArray(countryCode, CAN) >= 0) {
            currentLocation = 'CAN';
        }
        else if ($.inArray(countryCode, EMEA) >= 0) {
            currentLocation = 'EMEA';
        }
        else if ($.inArray(countryCode, MEX) >= 0) {
            currentLocation = 'MEX';
        }
        else if ($.inArray(countryCode, SA) >= 0) {
            currentLocation = 'SA';
        }
        else if ($.inArray(countryCode, USA) >= 0) {
            currentLocation = 'USA';
        }
        else {
            currentLocation = '';
        }

        $.cookie("ChiefClientLocation", currentLocation, { expires: 7 });
    };

    // Method hids all div's within a parent div
    function HideAllVisableDivs(parentDiv) {
        $("#" + parentDiv + " > div").each(function () { $(this).hide(); });
    }

    // Log message to console
    function LogToConsole(message) {
        var validBrowser = true;
        $.each(jQuery.browser, function (i, val) {
            if (i == 'msie') {
                validBrowser = false;
            }
        });
        if ((validBrowser) && (console != null)) {
            console.log(message);
        }
    };

    // Logs to weblogging databse the coutnry code (temporary)
    function LogCountryCode(code) {
        $.ajax({
            url: "/WebServices/LoggingService.asmx/LogCountryCode",
            data: "{ 'q': '" + code + "' }",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data },
            success: function (data) {
                //alert("Worked");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //alert(textStatus);
            }
        });
    };

    // Unobtrusively using the clients IP address to find
    // their current ISP's country to display the correct
    // email and phone numbers
    function InitilizeSupportMenu() {
        GenerateRegionSelect('divNavRegionSelect');            
        var currentLocation = GetUserCountry();
        
        // Close any visalbe contacts
        HideAllVisableDivs("divHelpMenu ");

        // Set to contact information to correct country
        if (currentLocation == 'EMEA') {
            $("#EMEA").show();
        }
        else if (currentLocation == 'AP') {
            $("#AP").show();
        }
        else if (currentLocation == 'CAN') {
            $("#CAN").show();
        }
        else if (currentLocation == 'MEX') {
            $("#MEX").show();
        }
        else if (currentLocation == 'SA') {
            $("#SA").show();
        }
        else {
            $("#USA").show();
        }
    };

    // Initializes the contact page to whatever country they are from.
    // If not found the default is USA
    function InitilizeContactPage() {
        GenerateRegionSelect('divContactRegionSelect');

        // Close any visalbe contacts
        HideAllVisableDivs("contactInfo ");
            
        // Pull client country
        var currentLocation = GetUserCountry();

        if (currentLocation == 'EMEA') {
            $("#contactEMEA").show();
        }
        else if (currentLocation == 'AP') {
            $("#contactAP").show();
        }
        else if (currentLocation == 'CAN') {
            $("#contactCAN").show();
        }
        else if (currentLocation == 'MEX') {
            $("#contactMEX").show();
        }
        else if (currentLocation == 'SA') {
            $("#contactSA").show();
        }
        else {
            $("#contactUSA").show();
        }
    };

    //
    function changeRegion() {
        // Pull selected ID
        var currentLocation;
        var selectedCountry = $("#selChangeRegion").children(":selected").attr("id");       

        // Display div corresponding to the correct region
        if (selectedCountry == 'optUSA') {
            currentLocation = 'USA'
        } else if (selectedCountry == 'optEMEA') {
            currentLocation = 'EMEA'
        } else if (selectedCountry == 'optAP') {
            currentLocation = 'AP'
        } else if (selectedCountry == 'optCAN') {
            currentLocation = 'CAN'
        } else if (selectedCountry == 'optMEX') {
            currentLocation = 'MEX'
        } else if (selectedCountry == 'optSA') {
            currentLocation = 'SA'
        }

        $.cookie("ChiefClientLocation", currentLocation, { expires: 7 });
        InitilizeSupportMenu();
        InitilizeContactPage();
        $('#divChangeRegion').hide();
    }
  
    function GenerateRegionSelect(divName) {
        $('#' + divName).html(
        '<select id="selChangeRegion" onchange="changeRegion();">' +
            '<option id="optNone" selected="selected">Select a Region</option>' +
            '<option id="optUSA" >USA</option>' +
            '<option id="optEMEA" >EMEA - Europe, Middle East, Africa</option>' +
            '<option id="optAP" >Asia/Pacific</option>' +        
            '<option id="optCAN">Canada</option>' +             
            '<option id="optMEX">Mexico</option>' +
            '<option id="optSA">South America</option>' +
        '</select>')
    };

    // Uses the Google Geocoder function from the mapping API
    // and requried that the user enables/allows their lcation
    // to be known
    function ObtrusiveClientLocationFind() {
        // Check to see if this browser supports geolocation.
        if (navigator.geolocation) {
            // Get the location of the user's browser using the
            // native geolocation service. When we invoke this method
            // only the first callback is requied. The second
            // callback - the error handler - and the third
            // argument - our configuration options - are optional.
            navigator.geolocation.getCurrentPosition(
                function (position) {
                    // Log that this is the initial position.
                    //LogToConsole("Position Found: " + position.coords.latitude + ", " + position.coords.longitude);

                    // Reverse Geocode the found posistion
                    var geocoder = new google.maps.Geocoder();
                    var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                    if (geocoder) {
                        geocoder.geocode(
                            { 'latLng': latLng },
                            function (results, status) {
                                if (status == google.maps.GeocoderStatus.OK) {
                                    // Pull address found
                                    var addressSplit = results[0].formatted_address.split(', ');
                                    var country = addressSplit[addressSplit.length - 1];
                                    LogToConsole(country);

                                    var usa = ["USA", "US"];
                                    var canada = ["CA"];
                                    var asia = ["AU", "CN", "HK", "JP", "KP", "KR", "MN", "MY", "SG", "TH", "TW", "VN"];
                                    var emea = ["AE", "AL", "CH",  "CZ", "FI", "GB", "IN", "HU", "LT", "LU", "NZ", "QT", "RS", "RU", "SA", "UK", "ES", "DE", "FR", "PT", "IE", "BE", "NL", "NO", "SE", "RO", "UA", "IT", "DK", "AT", "PL"];

                                    LogToConsole($.inArray(country, usa) >= 0);
                                    if ($.inArray(country, usa) >= 0) {
                                        $("#UnitedStates").hide();
                                        $("#EMEA").show();
                                    }
                                    else if ($.inArray(country, emea) >= 0) {
                                        $("#UnitedStates").hide();
                                        $("#Emea").show();
                                    }
                                    else if ($.inArray(country, asia) >= 0) {
                                        $("#UnitedStates").hide();
                                        $("#Asia").show();
                                    }
                                    else if ($.inArray(country, canada) >= 0) {
                                        $("#UnitedStates").hide();
                                        $("#Canada").show();
                                    }
                                }
                                else {
                                    LogToConsole("Geocoding failed: " + status);
                                }
                            }
                        )
                    }
                },
                function (error) {
                    LogToConsole("Something went wrong: ", error);
                },
                {
                    timeout: (5 * 1000),
                    maximumAge: (1000 * 60 * 15),
                    enableHighAccuracy: true
                }
            );
        }
    };
// END Contact

function GetPrintCSS(type, sku) {
    window.open('/' + type + 'Print/CSS/' + sku, 'Chief', 'height=600,width=1200,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=yes,resizable=yes');
    return false;
}

function GetPDF(t, n) {
    window.open('/' + t + 'Print/PDF/' + n, 'Chief', 'height=600,width=1200,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=yes,resizable=yes');
    return false;
}

/* Item Accessories */
function pageLoaded(sender, args) {
    var panels = args.get_panelsUpdated();
    for (i = 0; i < panels.length; i++) {
        if (panels[i].id == 'upAccessoryPanel') {
            initPagination('hiddenResult', 'pagination', 'galleryItems', 8);
            break;
        }
    }
}
