//global variables
var gUrlPrefix = "/";
var gDivProductEssentials = "#divProductEssentials";
var gProductWarrantyTabDiv = "#ProductWarrantyTabDiv";
var gProductComponentsTabDiv = "#ProductComponentsTabDiv";
var gProductAccessoriesTabDiv = "#ProductAccessoriesTabDiv";
var gHiddenDiv = "#divPopup";

var gCategoryHiddenContent = "#categoryHiddenContent";
var dragObj = new Object();
dragObj.zIndex = 0;

var productsToCompare = new Array();
var pricetreeTabs;
var productDetailTabs;
var nTabIndex;
var nTabIndex;

function onCompareRelatedProducts(mainPID) {
    var url = 'ProductCompare.aspx?prodList=' + mainPID;

    if (productsToCompare.length == 0)
        return;

    for (var i = 0; i < productsToCompare.length; i++) {

        url += '%2c' + productsToCompare[i];
    }

    window.location = url;

}

function compareClick(box) {
    if (box != null) {
        if (box.checked) {
            productsToCompare.push(box.value);

            if (productsToCompare.length > 2) {
                var c = $('input.cbCompare');
                for (var i = 0; i < c.length; i++) {
                    //var cb = c[i];
                    var box = $(c[i]);
                    if(!box.is(':checked'))
                    {
                        box.attr('disabled','true'); 
                    }

                    /*if (!box.checked) {
                        box.disabled = true;
                    }*/
                    /*if (!cb.checked) {
                        cb.disabled = true;
                    }*/
                }
            }
        }
        else {
            for (var index = 0; index < productsToCompare.length; ++index) {
                var item = productsToCompare[index];

                if (item == box.value) {
                    productsToCompare.splice(index, 1);
                }

            }

            if (productsToCompare.length < 3) {
                var c = $$('input.cbCompare');

                for (var i = 0; i < c.length; i++) {
                    var cb = c[i];

                    if (!cb.checked) {
                        cb.disabled = false;
                    }
                }
            }

        }
    }
}

function productPageInitjQuery(pid) {
    LoadWarrantyTabAltjQuery(pid);
}

function productPageInitAlt(pid) {
    pricetreeTabs = new YAHOO.widget.TabView("pricetree");
    productDetailTabs = new YAHOO.widget.TabView("productDetailTabs");
}

function productPageInit(pid) {
    pricetreeTabs = new YAHOO.widget.TabView("pricetree");
    productDetailTabs = new YAHOO.widget.TabView("productDetailTabs");

    LoadAccessoryTab(pid);
    LoadProductDetailMerch(pid);
    LoadWarrantyTab(pid);
    LoadComponentsTab(pid);
    LoadEssentials(pid);
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}


function RemoveDetailTabByName(tabNameToRemove) {
    var tabs = productDetailTabs.get('tabs');
    if (tabs) {
        var theTab;
        for (var t = 0; t < tabs.length; t++) {
            theTab = tabs[t];
            var label = theTab.get('label');
            if (label == tabNameToRemove)
                break;

        }

        if (theTab)
            productDetailTabs.removeTab(theTab);
    }
}


function AddToCart(pid) {
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/MiniCart/MiniAddToCart.aspx',
        data: ({ pid: pid, time: new Date() }),
        //dataType: "html",
        async: false
    });

    setTimeout(function() {
        window.location.href = gUrlPrefix + "Cart.aspx";
    }, 0);
}

function AddItemToCart(productToAdd) {
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/MiniCart/MiniAddToCart.aspx',
        data: ({ pid: productToAdd, time: new Date() }),
        //dataType: "html",
        async: false
    });

    setTimeout(function() {
        window.location.href = gUrlPrefix + "Cart.aspx";
    }, 0);

}

function RemoveItemFromCart(productToRemove, omnievent) {
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/MiniCart/MiniAddToCart.aspx',
        data: ({ pid: productToRemove, time: new Date() }),
        //dataType: "html",
        async: false
    });
}

// omnievent  "scAdd", or "scOpen,scAdd", etc.
function AddToCart2(pid, omnievent) {
    AddItemToCart(pid, omnievent);
    if (window.event) {
        window.event.returnValue = false;
    }
    setTimeout(function() {
        window.location.href = gUrlPrefix + "Cart.aspx";
    }, 0);

}

function LoadProductDetailMerch(pid) {
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/Products/TabLoader.aspx',
        data: ({ pid: pid, control: 'productdetailmerch', time: new Date() }),
        dataType: "html",
        success: function(html) { LoadProductDetailMerchDiv(html); }
    });
}

function LoadAccessoryTab(pid) {
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/Products/TabLoader.aspx',
        data: ({ pid: pid, control: 'accessories', time: new Date() }),
        dataType: "html",
        success: function(html) { LoadProductAccessoriesTab(html); }
    });
}
function LoadAccessoryTabWithCategory(pid,cat)
{
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/Products/TabLoader.aspx',
        data: ({ pid: pid, control: 'accessories', cat: cat, time: new Date() }),
        dataType: "html",
        success: function(html) { LoadProductAccessoriesTab(html); }
    });
	
}

function LoadProductDetailMerchDiv(originalRequest) {
    try {
        var productDetailMerchDiv = $(gCategoryHiddenContent);
        if (productDetailMerchDiv) {
            if (originalRequest.length > 0) {
                productDetailMerchDiv.html(originalRequest);
            }
        }
    }
    catch (e) { }
}

function LoadProductAccessoriesTab(originalRequest) {
    try {
        var productAccessoriesTabDiv = $(gProductAccessoriesTabDiv);
        if (productAccessoriesTabDiv) {
            if (originalRequest.length > 0) {
                productAccessoriesTabDiv.html(originalRequest);
            }
            else {
                RemoveDetailTabByName('Accessories');
            }
        }
    }
    catch (e) {}
}

function LoadWarrantyTab(pid) {
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/Products/TabLoader.aspx',
        data: ({ pid: pid, control: 'warranty', time: new Date() }),
        dataType: "html",
        success: function(html) { LoadProductWarrantyTab(html); }
    });
}

function LoadWarrantyTabAlt(pid) {
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/Products/TabLoader.aspx',
        data: ({ pid: pid, control: 'warrantyAlt', time: new Date() }),
        //data: 'pid=' + pid + '&control=warrantyAlt&time=date',
        dataType: "html",
        error: function() { },
        success: function(html) { LoadProductWarrantyTabAlt(html); }
    });
}

function LoadComponentsTab(pid) {
    var date = new Date();
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/Products/TabLoader.aspx',
        data: ({ pid: pid, control: 'components', time: new Date() }),
        dataType: "html",
        success: function(html) { LoadProductComponentsTab(html); }
    });
}



function LoadProductWarrantyTabAlt(originalRequest) {
    try {
        var productWarrantyTabDivAlt = $('#ProductWarrantyTabDivAlt');
        if (productWarrantyTabDivAlt) {
            if (originalRequest.length > 0) {
                productWarrantyTabDivAlt.html(originalRequest);
            }
            var warrTab = $('$warrTab');
            if (warrTab) {
                warrTab.css("display", "none");
            }

            var warrButton = $('#warrButton');
            if (warrButton) {
                warrButton.css("display", "none");
            }
        }
    }
    catch (e) { }
}

function LoadProductWarrantyTab(originalRequest) {
    try {
        var productWarrantyTabDiv = $(gProductWarrantyTabDiv);
        if (productWarrantyTabDiv) {
            if (originalRequest.length > 0) {
                productWarrantyTabDiv.html(originalRequest);
            }
            else {
                RemoveDetailTabByName('Warranty');
            }
        }
    }
    catch (e) { }
}

function LoadProductComponentsTab(originalRequest) {
    try {
        var productComponentsTabDiv = $(gProductComponentsTabDiv);
        if (productComponentsTabDiv) {
            if (originalRequest.length > 0) {
                productComponentsTabDiv.html(originalRequest);
            }
            else {
                RemoveDetailTabByName('Packages');
            }
        }
    }
    catch (e) { }
}


function LoadEssentials(pid) {
    var date = new Date();
    $.ajax({
        type: "GET",
        url: gUrlPrefix + 'Controls/Products/TabLoader.aspx',
        data: ({ pid: pid, control: 'essentials', time: new Date() }),
        dataType: "html",
        success: function(html) { LoadProductEssentials(html); }
    });
}

function LoadProductEssentials(originalRequest) {
    try {
        var productEssentialsDiv = $(gDivProductEssentials);
        if (productEssentialsDiv) {
            if (originalRequest.length > 0) {
                productEssentialsDiv.html(originalRequest);
            }
        }
    }
    catch (e) { }
}

function OpenEmailPriceTab() {
    if (nTabIndex != 3)
        return;

    var tabs = pricetreeTabs.get('tabs');
    if (tabs) {
        var theTab = tabs[tabs.length - 1];
        if (theTab)
            pricetreeTabs.set('activeIndex', pricetreeTabs.getTabIndex(theTab));
    }
}

function OpenMyPriceTab() {
    if (nTabIndex != 2)
        return;

    var tabs = pricetreeTabs.get('tabs');
    if (tabs) {
        var theTab = tabs[tabs.length - 1];
        if (theTab)
            pricetreeTabs.set('activeIndex', pricetreeTabs.getTabIndex(theTab));
    }
}

function SelectAccTab(categoryName) {
    ChangeDetailTabs(2);

    if (categoryName)
        location.hash = categoryName;
}

function SelectReviewsTab() {
    ChangeDetailTabs(1);
    location.hash = 'tabDetails';
}

function ChangeDetailTabs(nDetailIndex) {
    productDetailTabs.set('activeIndex', nDetailIndex);
}

function ChangeTabs() {
    if (nTabIndex) {
        pricetreeTabs.set('activeIndex', nTabIndex);
    }
}

sfHover = function() {
    var sfEls = document.getElementById("nav").getElementsByTagName("LI");
    for (var i = 0; i < sfEls.length; i++) {
        sfEls[i].onmouseover = function() {
            this.className += " sfhover";
        }
        sfEls[i].onmouseout = function() {
            this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
        }
    }
}
/***************************************************************************
[AppFunctions.js]
 
*****************************************************************************/
function Omniture(OmEvent, prdId) {
    /* You may give each page an identifying name, server, and channel on the next lines. */
    s.pageName = ""
    s.server = ""
    s.channel = ""
    s.pageType = ""
    s.prop1 = ""
    s.prop2 = ""
    s.prop3 = ""
    s.prop4 = ""
    s.prop5 = ""
    /* E-commerce Variables */
    s.campaign = ""
    s.state = ""
    s.zip = ""
    s.events = OmEvent
    s.products = ";" + prdId
    s.purchaseID = ""
    s.eVar1 = ""
    s.eVar2 = ""
    s.eVar3 = ""
    s.eVar4 = ""
    s.eVar5 = ""
    /************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
    try {
        if (s.t) {
            var s_code = s.t(); if (s_code) document.write(s_code)//
        }
    }
    catch (ex) {
    }
}
var chatWin = null;
function DoEmail() {
    if (chatWin != null) {
        try {
            chatWin.close();
        }
        catch (e) // Error, so null it
		{
            chatWin = null;
        }
    }

    chatWin = window.open(GetUrl("popups/SendEmail.aspx"), "chatWin", "width=369px, height=442px, scrollbars=no,status=yes");
};

function DoCallback() {
    if (chatWin != null) {
        try {
            chatWin.close();
        }
        catch (e) // Error, so null it
		{
            chatWin = null;
        }
    }

    chatWin = window.open(GetUrl("popups/GetCallBack.aspx?ReturnUrl=" + location.href), "chatWin", "width=300px, height=400px, scrollbars=no,status=yes");
};

function GetUrl(relativeUrl, secure) // Converts relative to absolute
{
    var BaseUrl = location.href.toLowerCase().replace('user/', '').replace('affiliate/', '').replace('includes/', '').replace('popups/', '');
    BaseUrl = BaseUrl.substr(0, BaseUrl.lastIndexOf('/'));
    if (secure != null) {
        if (secure)
            BaseUrl = BaseUrl.replace('http://', 'https://');
        else
            BaseUrl = BaseUrl.replace('https://', 'http://');
    }

    return BaseUrl + '/' + relativeUrl;
}

function openOrderStatus(tbID) {
    try {
        if (!tbID)
            tbID = "inputOrderStatus";

        document.location.href = "OrderStatus.aspx?FON=" + document.getElementById(tbID).value;
    }
    catch (e) {
        //alert(e.message);
    }
}

function openFedex(tbID) // moved from Footer.ascx
{
    try {
        if (!tbID)
            tbID = "inputTrackNum";
        var textbox = document.getElementById(tbID);
        var num = textbox.value;

        if (num.substr(0, 2) == 'A0' || num.substr(0, 2) == 'N0' || num.substr(0, 2) == 'P0' || num.substr(0, 4) == '1154') {
            var order = confirm('The number you entered appears to be an order number.  \n\nWould you like to track this as an order instead?');
            if (order) {
                location.href = GetUrl('user/DisplayOrderItems.aspx?orderID=' + num);
                return;
            }
        }

        // strip bad characters
        var regEx = new RegExp("[0-9]");
        for (var i = 0; i < num.length; i++) {
            var n = num.charAt(i);
            if (!regEx.test(n)) {
                num = num.replace(num.charAt(i), '');
                i--; // just shrunk the list, don't skip over
            }
        }

        var url = "http://www.fedex.com/Tracking?ascend_header=1&clienttype=dotcom&cntry_code=us&language=english&tracknumbers=";
        if (num.length > 11) {
            url = url + num;
            PopupWindow(url);
        }
        else {
            alert('Sorry, that FedEx tracking number is too short');
        }
    }
    catch (e) {
        //alert(e.message);
    }
};

function PopupWindow(url, width, height, name, scrollbars) {
    if (name == null)
        name = '_blank';
    if (scrollbars == null)
        scrollbars = 'yes';

    /*if (theWindow) // Don't get too many popups (gets "'theWindow' is undefined" error)
    theWindow.close();*/

    if (width == null || height == null) {
        var win = window.open(url, name, "top=50,left=50,directories=no,status=yes,location=no,toolbar=no,scrollbars=" + scrollbars + ",resizable=yes,menubar=no,copyhistory=no");
    }
    else {
        var win = window.open(url, name, "width=" + width + ",height=" + height + ",top=50,left=50,directories=no,status=yes,location=no,toolbar=no,scrollbars=" + scrollbars + ",resizable=yes,menubar=no,copyhistory=no");
    }
    if (win) {
        win.focus();
        theWindow = win;
    }
    else // Warn popup blockers
    {
        alert('A window could not be opened.\nIf you have a popup blocker, please check your popup blocker settings and try again.');
    }
};

// Moves focus from the "src" TextBox (self id) to the "dst" TextBox after reaching length "len"
function MoveFocus(src, dst, len, e) {
    var isNN = (navigator.appName.indexOf("Netscape") != -1);
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0, 8, 9] : [0, 8, 9, 16, 17, 18, 37, 38, 39, 40, 46];

    var source = document.getElementById(src);
    var dest = document.getElementById(dst);

    if (source.value.length >= len && !containsElement(filter, keyCode)) {
        dest.focus();
        dest.select();
    }

    function containsElement(arr, ele) {
        var found = false, index = 0;

        while (!found && index < arr.length)
            if (arr[index] == ele)
            found = true;
        else
            index++;

        return found;
    }
    return true;
};

function CheckSubmit(e, func) {
    if (!e) e = window.event;

    // still don't have anything (happens on some browsers after the good one went)
    if (!e) return;

    var key = (typeof (e.which) == 'number') ? e.which : e.keyCode;
    if (key == 13) {
        // Cancel the event (IE doesn't need this, but trying to get Firefox to behave)
        e.cancelBubble = true; // Cancel the event!!!  We're in control of it now.
        e.returnValue = false; // Still trying to convince Firefox to listen to us... (nevermind, was a Firefox 0.8 bug)

        //eval(func); // This way the function can be added in code-behind
        setTimeout(func, 100); // Want to run after we return (this works with autocomplete!
        return false;
    }
    else {
        return true; // Allow key to be processed/entered
    }
};

///////////////////////////////////////////////////
/// For custom validator (CustomRegexValidator.cs)
///////////////////////////////////////////////////
function CustomValidate(source, arguments) {
    var obj = document.getElementById(source.controltovalidate);
    var NOT = false;

    if (source.ValidationExpression.indexOf("NOT->") == 0) {
        NOT = true;
    }

    var regEx = new RegExp("^" + source.ValidationExpression.replace("NOT->", "") + "$");

    if (arguments.Value != "" && arguments.Value.match(regEx)) {
        if (NOT == false) {
            obj.style.borderColor = "#000000";
            obj.style.backgroundColor = "#FFFFFF";
        }
        else {
            arguments.IsValid = false; // mark as false so it shows in the summary
            obj.style.borderColor = "#EE8888"; //"#FF0000";
        }
    }
    else {
        if (NOT == false) {
            arguments.IsValid = false; // mark as false so it shows in the summary
            obj.style.borderColor = "#EE8888"; //"#FF0000";
        }
        else {
            obj.style.borderColor = "#000000";
            obj.style.backgroundColor = "#FFFFFF";
        }
        //obj.style.backgroundColor = "#FFDDDD";
    }
};

function ShowRequired(obj, onlyRequired) {
    if (obj.value != "") {
        if (onlyRequired) // otherwise expression validator must reset it
        {
            obj.style.borderColor = "#000000";
            obj.style.backgroundColor = "#FFFFFF";
        }
    }
    else {
        obj.style.borderColor = "#EE8888"; //"#FF0000";
        //obj.style.backgroundColor = "#FFDDDD";
    }
};

function ResetIfEmpty(obj) {
    if (obj.value == "") {
        obj.style.borderColor = "#000000";
        obj.style.backgroundColor = "#FFFFFF";
    }
};
function BlurAll(source, arguments) {
    var ids = document.getElementsByTagName("input");
    for (var i = 0; i < ids.length; i++) {
        if (ids[i].id != "" && !ids[i].disabled) {
            ids[i].fireEvent("onBlur");
        }
    }
};

///////////////////////////////
// For product search item checkbox auto-saving
///////////////////////////////
var CompareIDs = '';

function AddRemoveCompare(cb) // Saves selection every time a checkbox is clicked
{
    var id = ',' + cb.parentNode.id;
    if (cb.checked && CompareIDs.indexOf(id) == -1) // checked & doesn't exist
    {
        CompareIDs += id;
    }
    else if (CompareIDs.indexOf(id) > -1) // not checked, but exists -> need to remove
    {
        CompareIDs = CompareIDs.replace(id, '');
    }

    //alert(CompareIDs);
}

function ReadCheckboxes() // Reads current selection from query string (to start in proper state)
{
    var list = location.href.replace('%2c', ',');

    if (list.indexOf('?') > -1 && list.indexOf('prodList=') > -1) {
        list = list.substr(list.indexOf('prodList=') + 9);
        if (list.indexOf('&') > -1)
            list = list.substring(0, list.indexOf('&'));
    }
    else // clear it out, doesn't have any
    {
        list = '';
    }

    //alert('read: '+list);
    if (list.length > 1)
        CompareIDs = ',' + list; // the list always starts with a ',' (to make searching easy)

    // Hook event into all the hyperlinks (that aren't linkbuttons, since they postback...)
    var links = document.getElementsByTagName('a');
    var count = 0;
    for (var i = 0; i < links.length; i++) {
        if (links[i].href.toLowerCase().indexOf('shist') > -1) {
            if (links[i].addEventListener) {
                links[i].addEventListener('click', SaveCheckboxes, false);
            }
            else if (links[i].attachEvent) {
                links[i].attachEvent('onclick', SaveCheckboxes);
            }
        }
    }
}

// This method needs to be called whenever a link is clicked from the breadcrumb, filters, or paging
// It needs to somehow override where the link is going, and append the 'prodList=' to it.
function SaveCheckboxes(e) {
    if (!e) e = window.event;

    // still don't have anything (happens on some browsers after the good one went)
    if (!e) return;

    var target;

    // Find the link that sent this request
    if (e.srcElement != null)
        target = e.srcElement;
    if (e.target != null)
        target = e.target;

    var url = target.href; // save the indended url (may change this later)

    var pids = CompareIDs;
    if (pids.length > 1 && pids.charAt(0) == ',') {
        pids = pids.substring(1);
    }
    else if (pids.length == 0) {
        return;
    }

    // Must parse the url according to what's already there
    if (url.indexOf('?') > -1 && url.indexOf('prodList=') > -1) {
        var end = url.substr(url.indexOf('prodList=') + 9);
        if (end.indexOf('&') > -1)
            end = end.substr(end.indexOf('&'));
        else
            end = '';

        var start = url.substring(0, url.indexOf('prodList=') + 9);

        url = start + pids + end;
    }
    else if (url.indexOf('?') > -1) {
        url = url + '&prodList=' + pids;
    }
    else // This isn't ever used, but here just in case
    {
        url = url + '?prodList=' + pids;
    }

    //alert(url);

    // swap the url right before navigating (a very sneaky fix...)
    target.href = url;
}

function keyPress_ClickButton(e, toClick) {
    var key = (typeof (e.which) == 'number') ? e.which : e.keyCode;
    //alert(key);

    if (key == 13)// Enter key
    {
        try {
            //alert('cancelin and clickin');
            var objectToClick = document.getElementById(toClick);
            objectToClick.click();
        }
        catch (e)
		{ }

        e.cancelBubble = true;
        e.returnValue = false;
        return false;
        //return true;
    }
}

function keyPress_SkipFocus(e, toFocus) {
    try {
        var key = (typeof (e.which) == 'number') ? e.which : e.keyCode;
        //alert(key);

        if (key == 13)// Enter key
        {
            try {
                //alert('cancelin and focusin');
                var objectToFocus = document.getElementById(toFocus);
                objectToFocus.focus();
            }
            catch (e)
			{ }

            e.cancelBubble = true;
            e.returnValue = false;
            return false;
        }
    }
    catch (e) {
        return false;
    }
}

var bmlWin = null;
function BMLCore() {
    if (bmlWin != null) {
        try {
            bmlWin.close();
        }
        catch (e) {
            bmlWin = null;
        }
    }

    //bmlWin=window.open( GetUrl("popups/BMLCore.aspx"),"bmlWin","width=502px, height=640px, scrollbars=yes,status=yes");
    bmlWin = window.open("https://www.securecheckout.billmelater.com/paycapture-content/fetch?hash=W5T27ENT&content=/bmlweb/coreiw.html", "bmlWin", "width=502px, height=640px, scrollbars=yes, status=yes");
};

var palaWin = null;
function BML_PALA() {
    if (palaWin != null) {
        try {
            palaWin.close();
        }
        catch (e) {
            palaWin = null;
        }
    }

    //chatWin=window.open( GetUrl("popups/BML_PALA.aspx"),"chatWin","width=502px, height=790px, scrollbars=yes,status=yes");
    chatWin = window.open("https://www.securecheckout.billmelater.com/paycapture-content/fetch?hash=W5T27ENT&content=/bmlweb/coreiw.html", "chatWin", "width=502px, height=790px, scrollbars=yes, status=yes");

};

var OrigImage = "";
function RolloverMainProductImage(isrc, ialt) {
    if (OrigImage == "")
        OrigImage = document['MainProductImage'].src;

    document['MainProductImage'].src = isrc;
}

function RolloutMainProductImage() {
    if (OrigImage != "")
        document['MainProductImage'].src = OrigImage;
}

function ShowAllResults(resultGroup) {
    $('#'+resultGroup).css('display','inline');
}

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;

    return curleft;
};
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;

    return curtop;
};
/***************************************************************************
[Utils_new.js]

*****************************************************************************/
var gRelatedCategoryMain = "#categoryMainContent";
var gHiddenPriceDiv = "#divPricePopup";

function SetBundleRelatedCategoryTab() {
    var tab = $('#bundleTab');
    var content = $('#bundleContent');
    SelectTab(tab, content);
}

function SetPromotionRelatedCategoryTab() {
    var tab = $('#promotionTab');
    var content = $('#promotionContent');
    SelectTab(tab, content);
}

function SelectTab(clickedTab, content) {
    var mainDiv = $(gRelatedCategoryMain);
    mainDiv.html(content.html());

    var tabs = $('.categoryItemSelected');
    for (i = 0; i < tabs.length; i++) {
        var tab = $(tabs[1]);
        tab.removeClass('categoryItemSelected');
        tab.addClass('categoryItemNotSelected');
    }

    clickedTab.removeClass('categoryItemNotSelected');
    clickedTab.addClass('categoryItemSelected');

}

function SetFirstRelatedCategoryTab() {
    var tab1 = $('#relatedCategoryTab1');
    if (tab1) {
        tab1.removeClass('categoryItemNotSelected');
        tab1.addClass('categoryItemSelected');
    }
}

function SetSelectedRelatedCategory(category, page, clickedTab) {

    var tmp = $(clickedTab);
    SelectRelatedCategory(category, page);

    var tabs = $('.categoryItemSelected');
    for (i = 0; i < tabs.length; i++) {
        var tab = $(tabs[i]);
        tab.removeClass('categoryItemSelected');
        tab.addClass('categoryItemNotSelected');
    }

    tmp.removeClass('categoryItemNotSelected');
    tmp.addClass('categoryItemSelected');

}
function SelectRelatedCategory(category, page) {
    
    var mainDiv = $(gRelatedCategoryMain);
    var tmp = '#category_' + category + '_page_' + page;
    alert(tmp);
    var content = $(tmp);
    
    //var content = $("div[id*='category_']");
    //var content = $("div[id='" + tmp + "']");
    //var content = $('#category_' + category + '_page_' + page);
    //var content = $('#category_1_page_1');
    alert(content.html());
    mainDiv.html(content.html());

    if (productsToCompare.length > 0) {
        var c = $('div#' + gRelatedCategoryMain + ' input.cbCompare');
        var p = $(productsToCompare);

        for (var i = 0; i < c.length; i++) {
            var cb = $(c[i]);
            if ($.inArray(cb.val(), p) > -1) {
                cb.attr('disabled', 'false');
                cb.attr('checked', 'true');
            }
        }
    }
    
}

function SwitchTabs_Alternate(tab) {

    switch (tab) {
        case 'info':
            OnAltInfoTabClick();
            document.location = '#altTabDetails1';
            break;
        case 'reviews':
            OnAltReviewsTabClick();
            document.location = '#altTabDetails2';
            break;
        case 'warranty':
            OnAltWarrantyTabClick();
            document.location = '#altTabDetails3';
            break;
    }
}

function OnAltPricingTabClick() {


    
    var priceTab = $('#pricingTab');
    if (priceTab) {
        priceTab.removeClass('altPricingTab');
        priceTab.addClass('altPricingTabClicked');
    }
    
    var openBoxTab = $('#openboxTab');
    if (openBoxTab) {
        openBoxTab.removeClass('altOpenBoxTabClicked');
        openBoxTab.addClass('altOpenBoxTab');
    }

    /*var priceDiv = $('#pricingDiv');
    if (priceDiv) {
        priceDiv.removeClass('altPricingDiv');
        priceDiv.addClass('altPricingDivClicked');
    }

    var openBoxDiv = $('#openboxDiv');
    if (openBoxDiv) {
        openBoxDiv.removeClass('altOpenBoxDivClicked');
        openBoxDiv.addClass('altOpenBoxDiv');
    }*/
    var priceDiv = $('#pricingDiv');
    if (priceDiv) {
        priceDiv.removeClass('altPricingDiv outlineButtonHover').addClass('altPricingDivClicked');
        priceDiv.unbind('mouseenter mouseleave');
    }

    var openBoxDiv = $('#openboxDiv');
    if (openBoxDiv) {
        openBoxDiv.removeClass('altOpenBoxDivClicked').addClass('altOpenBoxDiv');
        openBoxDiv.hover(
            function() {
                $(this).addClass('outlineButtonHover');
            },
            function() {
                $(this).removeClass('outlineButtonHover');
            }
        );
    }

    var productStatement = $('#AltProductStatement');
    if (productStatement) {
        productStatement.css("display", "block");
    }
    var openBoxProductStatement = $('#AltOpenBoxProductStatement');
    if (openBoxProductStatement) {
        openBoxProductStatement.css("display", "none");
    }

    var whatisDiv = $('#WhatIsOpenBoxDiv');
    if (whatisDiv) {
        whatisDiv.css("display", "none");
    } 
}

function OnAltOpenboxTabClick() {

    var priceTab = $('#pricingTab');
    if (priceTab) {
        priceTab.removeClass('altPricingTabClicked');
        priceTab.addClass('altPricingTab');
    }

    var openBoxTab = $('#openboxTab');
    if (openBoxTab) {
        openBoxTab.removeClass('altOpenBoxTab');
        openBoxTab.addClass('altOpenBoxTabClicked');
    }

    /*var priceDiv = $('#pricingDiv');
    if (priceDiv) {
        priceDiv.removeClass('altPricingDivClicked');
        priceDiv.addClass('altPricingDiv');
    }
    
    var openBoxDiv = $('#openboxDiv');
    if (openBoxDiv) {
        openBoxDiv.removeClass('altOpenBoxDiv');
        openBoxDiv.addClass('altOpenBoxDivClicked');
    }*/
    var priceDiv = $('#pricingDiv');
    if (priceDiv) {
        priceDiv.removeClass('altPricingDivClicked').addClass('altPricingDiv');
        priceDiv.hover(
            function() {
                $(this).addClass('outlineButtonHover');
            },
            function() {
                $(this).removeClass('outlineButtonHover');
            }
        );
    }

    var openBoxDiv = $('#openboxDiv');
    if (openBoxDiv) {
        openBoxDiv.removeClass('altOpenBoxDiv outlineButtonHover').addClass('altOpenBoxDivClicked');
        openBoxDiv.unbind('mouseenter mouseleave');
    }

    var productStatement = $('#AltProductStatement');
    if (productStatement) {
        productStatement.css("display", "none");
    }
    var openBoxProductStatement = $('#AltOpenBoxProductStatement');
    if (openBoxProductStatement) {
        openBoxProductStatement.css("display", "block");
    }
    var whatisDiv = $('#WhatIsOpenBoxDiv');
    if (whatisDiv) {
        whatisDiv.css("display", "block");
    }
}

function OnAltInfoTabClick() {

    /*$('#infoDiv,#revDiv,#warrDiv').click(function() {
        $(this).unbind('mouseout mouseover');
    });*/
    //$('#infoDiv').unbind('mouseout mouseover');

    var divTab2 = $("#altdetailtab2");
    if (divTab2) {
        divTab2.css("display", "none");
    }

    var divTab3 = $('#altdetailtab3');
    if (divTab3) {
        divTab3.css("display", "none");
    }

    var divTab1 = $('#altdetailtab1');
    if (divTab1) {
        divTab1.css("display", "block");
    }

    var infoTab = $('#infoTab');
    if (infoTab) {
        infoTab.removeClass('altTab').addClass('altTabClicked');

    }

    var reviewsTab = $('#revTab');
    if (reviewsTab) {
        reviewsTab.removeClass('altTabClicked').addClass('altTab');
    }
    
    var warrantyTab = $('#warrTab');
    if (warrantyTab) {
        warrantyTab.removeClass('altTabClicked').addClass('altTab');
    }

    /*
    var infoDiv = $('#infoDiv');
    if (infoDiv) {
        infoDiv.removeClass('altDiv').addClass('altDivClicked');
    }
    
    var reviewsDiv = $('#revDiv');
    if (reviewsDiv) {
    reviewsDiv.removeClass('altDivClicked').addClass('altDiv');
    reviewsDiv.mouseover(function() {
    $('#revDiv').addClass('outlineButtonHover');
    });
    reviewsDiv.mouseout(function() {
    $('#revDiv').removeClass('outlineButtonHover');
    });
    }
    
    var warrantyDiv = $('#warrDiv');
    if (warrantyDiv) {
    warrantyDiv.removeClass('altDivClicked').addClass('altDiv');
    warrantyDiv.mouseover(function() {
    $('#warrDiv').addClass('outlineButtonHover');
    });
    warrantyDiv.mouseout(function() {
    $('#warrDiv').removeClass('outlineButtonHover');
    });
    }*/

    var infoDiv = $('#infoDiv');
    if (infoDiv) {
        infoDiv.removeClass('altDiv outlineButtonHover').addClass('altDivClicked');
        infoDiv.unbind('mouseenter mouseleave');
    }
    
    var reviewsDiv = $('#revDiv');
    if (reviewsDiv) {
        reviewsDiv.removeClass('altDivClicked').addClass('altDiv');
        reviewsDiv.hover(
            function() {
                $(this).addClass('outlineButtonHover');
            },
            function() {
                $(this).removeClass('outlineButtonHover');
            }
        );
    }

    var warrantyDiv = $('#warrDiv');
    if (warrantyDiv) {
        warrantyDiv.removeClass('altDivClicked').addClass('altDiv');
        warrantyDiv.hover(
            function() {
                $(this).addClass('outlineButtonHover');
            },
            function() {
                $(this).removeClass('outlineButtonHover');
            }
        );
    }
}

function OnAltReviewsTabClick() {

    //$('#revDiv').unbind('mouseout mouseover');
    
    var divTab2 = $('#altdetailtab2');
    if (divTab2) {
        divTab2.css("display", "block");
    }

    var divTab3 = $('#altdetailtab3');
    if (divTab3) {
        divTab3.css("display", "none");
    }

    var divTab1 = $('#altdetailtab1');
    if (divTab1) {
        divTab1.css("display", "none");
    }


    var infoTab = $('#infoTab');
    if (infoTab) {
        infoTab.removeClass('altTabClicked').addClass('altTab');
    }

    var reviewsTab = $('#revTab');
    if (reviewsTab) {
        reviewsTab.removeClass('altTab').addClass('altTabClicked');
    }

    var warrantyTab = $('#warrTab');
    if (warrantyTab) {
        warrantyTab.removeClass('altTabClicked').addClass('altTab');
    }
/*
    var infoDiv = $('#infoDiv');
    if (infoDiv) {
        infoDiv.removeClass('altDivClicked').addClass('altDiv');
        infoDiv.mouseover(function() {
            $('#infoDiv').addClass('outlineButtonHover');
        });
        infoDiv.mouseout(function() {
            $('#infoDiv').removeClass('outlineButtonHover');
        });
    }

    var reviewsDiv = $('#revDiv');
    if (reviewsDiv) {
        reviewsDiv.removeClass('altDiv outlineButtonHover').addClass('altDivClicked');
    }

    var warrantyDiv = $('#warrDiv');
    if (warrantyDiv) {
        warrantyDiv.removeClass('altDivClicked').addClass('altDiv');
        warrantyDiv.mouseover(function() {
            $('#warrDiv').addClass('outlineButtonHover');
        });
        warrantyDiv.mouseout(function() {
            $('#warrDiv').removeClass('outlineButtonHover');
        });       
    }*/
    var infoDiv = $('#infoDiv');
    if (infoDiv) {
        infoDiv.removeClass('altDivClicked').addClass('altDiv');
        infoDiv.hover(
            function() {
                $(this).addClass('outlineButtonHover');
            },
            function() {
                $(this).removeClass('outlineButtonHover');
            }
        );
    }

    var reviewsDiv = $('#revDiv');
    if (reviewsDiv) {
        reviewsDiv.removeClass('altDiv outlineButtonHover').addClass('altDivClicked');
        reviewsDiv.unbind('mouseenter mouseleave');
    }

    var warrantyDiv = $('#warrDiv');
    if (warrantyDiv) {
        warrantyDiv.removeClass('altDivClicked').addClass('altDiv');
        warrantyDiv.hover(
            function() {
                $(this).addClass('outlineButtonHover');
            },
            function() {
                $(this).removeClass('outlineButtonHover');
            }
        );
    }
}

function OnAltWarrantyTabClick() {

    $('#warrDiv').unbind('mouseout mouseover');
    
    var divTab3 = $('#altdetailtab3');
    if (divTab3) {
        divTab3.css("display", "block");
    }

    var divTab2 = $('#altdetailtab2');
    if (divTab2) {
        divTab2.css("display", "none");
    }

    var divTab1 = $('#altdetailtab1');
    if (divTab1) {
        divTab1.css("display", "none");
    }

    var infoTab = $('#infoTab');
    if (infoTab) {
        infoTab.removeClass('altTabClicked').addClass('altTab');
    }

    var reviewsTab = $('#revTab');
    if (reviewsTab) {
        reviewsTab.removeClass('altTabClicked').addClass('altTab');
    }

    var warrantyTab = $('#warrTab');
    if (warrantyTab) {
        warrantyTab.removeClass('altTab').addClass('altTabClicked');
    }


    var infoDiv = $('#infoDiv');
    if (infoDiv) {
        infoDiv.removeClass('altDivClicked').addClass('altDiv');
        infoDiv.hover(
            function() {
                $(this).addClass('outlineButtonHover');
            },
            function() {
                $(this).removeClass('outlineButtonHover');
            }
        );
    }
    
    var reviewsDiv = $('#revDiv');
    if (reviewsDiv) {
        reviewsDiv.removeClass('altDivClicked').addClass('altDiv');
        reviewsDiv.hover(
            function() {
                $(this).addClass('outlineButtonHover');
            },
            function() {
                $(this).removeClass('outlineButtonHover');
            }
        );      
    }

    var warrantyDiv = $('#warrDiv');
    if (warrantyDiv) {
        warrantyDiv.removeClass('altDiv outlineButtonHover').addClass('altDivClicked');
        warrantyDiv.unbind('mouseenter mouseleave');
    }

}

function On360Click(pid) {    
    var arr = [];
    for (var x = 1; x <= 20; x++) {
        if (x < 10) {
            //arr.push("http://media.onecall.com/Image_Products/360/103864/" + 0 + x + ".jpg");
            arr.push("http://media.onecall.com/Image_Products/360/" + pid + "/" + 0 + x + ".jpg");
        }
        else {
            //arr.push("http://media.onecall.com/Image_Products/360/103864/" + x + ".jpg");
            arr.push("http://media.onecall.com/Image_Products/360/" + pid + "/" + x + ".jpg");
        }
    }

    var mousemove = $('#mousemove');
    if (mousemove) {
        //alert('found it');
        mousemove.threesixty({ images: arr, method: 'mousemove', 'cycle': 1, direction: "backward" });
        //alert('done');
    }
        
    //$("#mousemove").threesixty({ images: arr, method: 'mousemove', 'cycle': 3, direction: "backward" }); ;
}

function launch360Window(id, pid)
{
    launchWindow(id);
    
    $('#close360').click(function() {
        $('#mask').hide();
        $('.window').hide();
    });
    
    On360Click(pid);
}

function launchEmailPriceWindow(id)
{
    launchWindow(id);
    
    $('#closeEmailPrice').click(function() {
        $('#mask').hide();
        $('.window').hide();
    });
}
function launchWindow(id) {

    scroll(0, 0);
    //Get the screen height and width
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();
    //var maskWidth = 990;

    //Set heigth and width to mask to fill up the whole screen
    $('#mask').css({ 'width': maskWidth, 'height': maskHeight });

    //transition effect		
    $('#mask').fadeIn(1000);
    $('#mask').fadeTo("fast", 0.8);

    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();

    //Set the popup window to center
    //$(id).css('top', winH / 2 - $(id).height());
    //$(id).css('left', winW / 2 - $(id).width() / 2);

    //$(id).css('top', Math.max(winH / 2 - $(id).height() / 2 + $(window).scrollTop(), 0));
    //$(id).css('left', Math.max(winW / 2 - $(id).width() / 2 + $(window).scrollLeft(), 0));

    $(id).css('top', Math.max(winH / 2 - $(id).height() / 2 ));
    $(id).css('left', Math.max(winW / 2 - $(id).width() / 2));

    //transition effect
    $(id).fadeIn(2000);

    //if close button is clicked
    $('.window #close').click(function() {
        $('#mask').hide();
        $('.window').hide();
    });

    //if mask is clicked
    $('#mask').click(function() {
        $(this).hide();
        $('.window').hide();
    });
}



function ClosePricePopup(pid) {
    var divPopup = $(gHiddenDiv);
    if (divPopup) {
        divPopup.css("display", "none");
    }
}

function CloseMyPricePopup(div) {
    var divPopup = $(gHiddenDiv);
    if (divPopup) {
        divPopup.css("display", "none");
    }
}

function PricePopup(pid, posLeft, posTop, width, height) {
    var divPopup = $(gHiddenPriceDiv + pid);
    var divHidden = $(gHiddenDiv);

    //divHidden.innerHTML = divPopup.innerHTML;
    divHidden.html(divPopup.html());

    // set on div
    divHidden.css("zIndex", "4");
    divHidden.css("width", width + 'px');
    divHidden.css("height", height + 'px');
    divHidden.css("left", posLeft + 'px');
    divHidden.css("top", posTop + 'px');
    divHidden.css("display", "inline");
}


function ClosePriceComparePopup() {
    var divPopup = $("divPricePopup");
    if (divPopup) {
        divPopup.style.display = 'none';
    }
}

function BingPopup(div, posLeft, posTop, width, height) {
    var divPopup = $(div);

    var divHidden = $(gHiddenDiv);

    divHidden.html(divPopup.html());

    // set on div
    divHidden.css("zIndex", "3");
    divHidden.css("width", width);
    divHidden.css("left", posLeft + 'px');
    divHidden.css("top", posTop + 'px');
    divHidden.css("display", "inline");
}

function CloseBingPopup() {
    var divPopup = $(gHiddenDiv);
    if (divPopup) {
        divPopup.css("display", "none");
    }
}

//*****************************************************************************
// Do not remove this notice.
//
// Copyright 2001 by Mike Hall.
// See http://www.brainjar.com for terms of use.
//*****************************************************************************

// Determine browser and version.

function Browser() {

    var ua, s, i;

    this.isIE = false;
    this.isNS = false;
    this.version = null;

    ua = navigator.userAgent;

    s = "MSIE";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isIE = true;
        this.version = parseFloat(ua.substr(i + s.length));
        return;
    }

    s = "Netscape6/";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isNS = true;
        this.version = parseFloat(ua.substr(i + s.length));
        return;
    }

    // Treat any other "Gecko" browser as NS 6.1.

    s = "Gecko";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isNS = true;
        this.version = 6.1;
        return;
    }
}

var browser = new Browser();
// Global object to hold drag information.


function dragStart(event, id) {

    var el;
    var x, y;

    // If an element id was given, find it. Otherwise use the element being
    // clicked on.

    if (id)
        dragObj.elNode = document.getElementById(id);
    else {
        if (browser.isIE)
            dragObj.elNode = window.event.srcElement;
        if (browser.isNS)
            dragObj.elNode = event.target;

        // If this is a text node, use its parent element.

        if (dragObj.elNode.nodeType == 3)
            dragObj.elNode = dragObj.elNode.parentNode;
    }

    // Get cursor position with respect to the page.

    if (browser.isIE) {
        x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
    }
    if (browser.isNS) {
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }

    // Save starting positions of cursor and element.

    dragObj.cursorStartX = x;
    dragObj.cursorStartY = y;
    dragObj.elStartLeft = parseInt(dragObj.elNode.style.left, 10);
    dragObj.elStartTop = parseInt(dragObj.elNode.style.top, 10);

    if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
    if (isNaN(dragObj.elStartTop)) dragObj.elStartTop = 0;

    // Update element's z-index.

    dragObj.elNode.style.zIndex = ++dragObj.zIndex;

    // Capture mousemove and mouseup events on the page.

    if (browser.isIE) {
        document.attachEvent("onmousemove", dragGo);
        document.attachEvent("onmouseup", dragStop);
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    if (browser.isNS) {
        document.addEventListener("mousemove", dragGo, true);
        document.addEventListener("mouseup", dragStop, true);
        event.preventDefault();
    }
}
function dragGo(event) {

    var x, y;

    // Get cursor position with respect to the page.

    if (browser.isIE) {
        x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
    }
    if (browser.isNS) {
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }

    // Move drag element by the same amount the cursor has moved.

    dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
    dragObj.elNode.style.top = (dragObj.elStartTop + y - dragObj.cursorStartY) + "px";

    if (browser.isIE) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    if (browser.isNS)
        event.preventDefault();
}

function dragStop(event) {

    // Stop capturing mousemove and mouseup events.

    if (browser.isIE) {
        document.detachEvent("onmousemove", dragGo);
        document.detachEvent("onmouseup", dragStop);
    }
    if (browser.isNS) {
        document.removeEventListener("mousemove", dragGo, true);
        document.removeEventListener("mouseup", dragStop, true);
    }
}

function tryFacebox() {
    jQuery.facebox('<span>some html</span>');
}

function typeAheadSearch() {
    $(function() {
        function log(message) {
            $("<div/>").text(message).prependTo("#log");
            $("#log").attr("scrollTop", 0);
        }
        $("#ctl00_ctl00_cphLayout_Header1_SearchNavigation1_txtSearchInput").autocomplete({
            /*$("#city").autocomplete({*/
            source: function(request, response) {
                $.ajax({
                    type: "post",
                    url: gUrlPrefix + 'GetSuggestions.aspx',
                    dataType: "jsonp",
                    data:
	                    {
	                        search_terms: request.term
	                    },
                    success: function(data) {
                        response($.map(data.results, function(item) {
                            return {
                                //label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                //value: item.name
                                label: item.name,
                                //value: item.url
                                value: item.name
                            }
                        }))
                    }
                })
            },
            minLength: 2,
            select: function(event, ui) {
                //log(ui.item ? ("Selected: " + ui.item.label) : "Nothing selected, input was " + this.value);
                //alert('http://localhost' + this.value);
                //document.location.href = 'http://localhost' + this.value;
                //alert(this.url);
            },
            open: function() {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function() {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
            }
        });
    });
}

/*
* end of drag js
*/
//  Simply Buttons, version 2.0
//  (c) 2007-2009 Kevin Miller
//
//  This script is freely distributable under the terms of an MIT-style license.
// 
/*-----------------------------------------------------------------------------------------------*/
// 
// * Adjusts the buttons so that they will not have an outline when they are pressed.
// * If the browser is mobile then we replace the buttons with inputs for compatibility.
// * Disables the text in the buttons from being selected.
// * The default styles here are meant for use with the Sliding Doors technique http://alistapart.com/articles/slidingdoors/
//     to be used for IE so we can have nice states with a horrid browser too!
//
/*-----------------------------------------------------------------------------------------------*/

var SimplyButtons = {

    options: {
        hyperlinkClass: 'button'
    , activeButtonClass: 'button_active'
    , states: {
        outer: {
            active: {
                backgroundPosition: 'bottom left'
            }
        , inactive: {
            backgroundPosition: 'top left'
        }
        }
      , inner: {
          active: {
              backgroundPosition: 'bottom right'
          }
        , inactive: {
            backgroundPosition: 'top right'
        }
      }
    }
    , iphone: {
        replaceButtons: true
    }
    }

  , buttons: []

  , iphone: false

  , init: function(options) {
      for (var property in options) {
          this.options[property] = options[property];
      }

      this.iphone = (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i));

      this.process(document.getElementsByTagName('button'), false);
      this.process(document.getElementsByTagName('a'), true);

      if (this.iphone && this.options.iphone.replaceButtons) {
          this.remove();
      }
  }

  , process: function(elements, links) {
      var linkTest = new RegExp('\\b' + this.options.hyperlinkClass + '\\b');
      for (var a = 0; a < elements.length; a++) {
          if ((links && linkTest.test(elements[a].className)) || !links) {
              if (this.iphone && !links) {
                  this.mobile(elements[a]);
              }
              else {
                  this.disable(elements[a]);
                  this.setup(elements[a]);
              }

              if (!links) {
                  this.buttons.push(elements[a]);
              }
          }
      }
  }

  , mobile: function(element) {
      var input = document.createElement('input');
      input.setAttribute('type', element.getAttribute('type') == 'submit' ? 'submit' : 'button');

      var attributes = new Array('id', 'name', 'value', 'class', 'onclick', 'onmouseover', 'onmouseout', 'onpress', 'onfocus', 'onblur', 'onmouseup', 'onmousedown');
      for (var a = 0; a < attributes.length; a++) {
          if (element.getAttribute(attributes[a])) {
              input.setAttribute(attributes[a], element.getAttribute(attributes[a]));
          }
      }

      input.style.marginLeft = element.style.marginLeft;
      input.style.marginRight = element.style.marginRight;

      element.parentNode.insertBefore(input, element);

  }

	, remove: function() {
	    for (var a = 0; a < this.buttons.length; a++) {
	        this.buttons[a].parentNode.removeChild(this.buttons[a]);
	    }
	}

  , disable: function(element) {
      element.onselectstart = function() { return false; };
      element.style.MozUserSelect = 'none';
      element.style.KhtmlUserSelect = 'none';
      element.style.UserSelect = 'none';
      element.style.cursor = 'default';
  }

  , setup: function(element) {
      if (document.all) {
          if (element.tagName == 'BUTTON') {
              element.attachEvent('onfocus', this.bind(this.toggle, this, element));
          }
          else {
              element.attachEvent('onmousedown', this.bind(this.toggle, this, element));
          }
          element.attachEvent('onmouseup', this.bind(this.toggle, this, element));
      }
      else {
          element.onfocus = function() { this.blur(); };
      }
  }

  , toggle: function(o, element) {
      if (element.tagName != 'BUTTON' && element.tagName != 'A') {
          while (element.tagName != 'A') {
              element = element.parentNode;
          }
      }
      if (event.type == 'focus' || event.type == 'mousedown') {
          element.className += ' ' + o.options.activeButtonClass;
          o.style(element.childNodes[0], o.options.states.inner.active);
          o.style(element.childNodes[0].childNodes[0], o.options.states.outer.active);
          element.blur();
      }
      else {
          element.className = element.className.replace(o.options.activeButtonClass, '');
          o.style(element.childNodes[0], o.options.states.inner.inactive);
          o.style(element.childNodes[0].childNodes[0], o.options.states.outer.inactive);
      }
  }

  , style: function(element, styles) {
      for (var property in styles) {
          element.style[property] = styles[property];
      }
  }

  , bind: function(func) {
      var args = [];
      for (var a = 1; a < arguments.length; a++) {
          args.push(arguments[a]);
      }
      return function() { return func.apply(this, args); };
  }

};