/// <reference path="JQuery.Intellisense.js"/>
/*
This script uses jQuery javascript library. For more information,
tutorials, documentation, demos, etc: http://jquery.com
*/
var SharpUSA = {
	// constants
	SafetyUpdateDetailMaxLength:110,
	IE6:($.browser.msie && $.browser.version.substr(0,2)=='6.'),
	IE7:($.browser.msie && $.browser.version.substr(0,2)=='7.'),
	BaseUrl:'',
	FacetNavIsOpen:false,
	AddedToWishListButton:'<img src="/Images/bg-button-addedtowishlist.gif" width="124" height="25" class="addtowishlist" />',
	AddedToWishListSmallButton:'<img src="/Images/bg-button-addedtowishlist-small.gif" width="89" height="15" class="addtowishlist" />'
};

/*
Any functionality initialized on elements within an UpdatePanel, need to be called on pageLoad
These methods will be executed again after a partial postback
*/
function pageLoad(){
	SharpUSA.ProductCategory.InitAspnet();
	SharpUSA.CustomerSupport.GlossaryFaq();
	//SharpUSA.CustomerSupport.SafetyUpdates();
	SharpUSA.Global.UpdateDynamicContent();
	SharpUSA.ProductDetail.InitAspnet();
	SharpUSA.UI.TabbedNav();
	SharpUSA.UI.Pricing();
	SharpUSA.Flash.Video.InitVideoPlayerLinks();
	SharpUSA.IFrame.InitIFrames();
	SharpUSA.Forms.Init();
	SharpUSA.Global.PageUtilCancelButtons();
	SharpUSA.Global.RewriteLinks();
	
	SharpUSA.Global.PageUtilSetup();
	SharpUSA.Global.DownloadTrackingSetup();
	SharpUSA.Global.NavToAnchor();
	SharpUSA.ShoppingCart.EventSetup();
}

$.noConflict();
(function($) {

    /*
    Any functionality initialized on elements that are not in an UpdatePanel should be called here
    */
    $(document).ready(
	function() {
	    /* global */
	    SharpUSA.Search.InitClient();
	    SharpUSA.Navigation.Init();
	    SharpUSA.UI.Init();
	    SharpUSA.Global.Init();
	    SharpUSA.Callouts.Init();
	    SharpUSA.Flash.Video.InitVideoPlayerLinks();
	    SharpUSA.IFrame.InitIFrames();
	    SharpUSA.ProductCategory.InitClient();

	    SharpUSA.ProductCompare.InitClient();
	    SharpUSA.ProductDetail.Init();

	    SharpUSA.AboutSharp.Init();
	    SharpUSA.MySharp.Init();
	}
);
    SharpUSA.HomePage = {
        Init: function() {
            if ($('#flashcontent').exists()) {
                SharpUSA.Flash.WriteSWF(SharpUSA.Flash.HomeFlash, SharpUSA.Flash.SharedFlashParams, 'flashcontent');
            }
        }
    };

    SharpUSA.HowSolarWorks = {
        Init: function() {
            if ($('#flashcontent').exists()) {
                SharpUSA.Flash.WriteSWF(SharpUSA.Flash.HowSolarWorksFlash, SharpUSA.Flash.SharedFlashParams, 'flashcontent');
            }
        }
    };

    SharpUSA.Search = {
        InitClient: function() {
            SharpUSA.Search.SearchBox();
            SharpUSA.Search.SearchResults();
        },
        SearchBox: function() {
            if ($('#header fieldset#searchbox').exists()) {
                var searchInput = $('#header fieldset#searchbox input:text');
                var defaultValue = searchInput.val();
                SharpUSA.UI.InputClear(searchInput, defaultValue);
            }

            var goButton = $('input.button', '#header fieldset#searchbox');
            if (goButton.exists()) {
                goButton.click(function() {
                    var inputVal = goButton.prevAll('input.text').val();
                    if ($.trim(inputVal).toLowerCase() === "search" || $.trim(inputVal) === "") {
                        return false;
                    }
                });
            }
        },
        SearchResults: function() {
            if ($('ul.search-results').exists()) {
                SharpUSA.UI.ElementHover($('ul.search-results li'));
            }
        }
    };

    SharpUSA.Navigation = {
        NumberOfNavColumns: 5,
        Init: function() {
            if ($('ul#main-nav').exists()) {
                // fix for ie6 <select> z-index
                $('div.subnav').bgiframe();

                // add spans (for images)
                $('ul#main-nav > li > a').append('<span></span>');

                // hide all subnavs
                $('div.subnav').hide();

                // set the first item of each row as class="first"
                $('ul#main-nav > li:not(.singlelevel)').each(function(i) {
                    var theseGroups = $(this).children('div.subnav').children('ul').children('li');

                    theseGroups.each(
					function(j) {
					    if (j % SharpUSA.Navigation.NumberOfNavColumns === 0) {
					        $(this).addClass('first');
					    }
					}
				);
                });


                $('ul#main-nav > li').hover(
				function() {
				    var subnavs = $(this).siblings('ul#main-nav > li').children('.subnav');
				    subnavs.hide();

				    $(this).addClass('current');
				    $(this).children('.subnav').show();
				},
				function() {
				    var thisSubnav = $(this).children('.subnav');
				    $(this).removeClass('current');
				    thisSubnav.hide();
				}
			);
            }
        }
    };

    SharpUSA.Callouts = {
        Init: function() {
            if ($('div.wheretobuyform').exists()) {
                SharpUSA.Callouts.WhereToBuyForm();
            }
        },
        WhereToBuyLinkText: 'Where to Buy',
        WhereToBuyForm: function() {
            // wrap content with flyout wrapper divs and hide the flyout
            $('div.wheretobuyform').wrapInner('<div class="flyout-innerinner">').wrapInner('<div class="flyout-inner">').wrapInner('<div class="flyout">');
            $('div.wheretobuyform div.flyout').hide();
            $('.flyout-inner').prepend('<a href="#" class="close">Close</a>');
            $('.flyout-innerinner h4').remove();
            $('.flyout-inner').prepend('<h4>Where to Buy</h4>');

            // add the Where to Buy link
            $('div.wheretobuyform').prepend('<p><a href="#" class="wheretobuylink alt">' + SharpUSA.Callouts.WhereToBuyLinkText + '</a></p>');

            // add show when clicked behavior
            $('div.wheretobuyform a.wheretobuylink').click(function(e) {
                // first close other open wheretobuy flyouts
                $('div.wheretobuyform').removeClass('current').children('.flyout').fadeOut('fast');

                // position the top offset of the flyout based on its height
                var theFlyout = $(this).parent().siblings('.flyout');
                if (SharpUSA.IE7) { theFlyout.css('backgroundColor', '#FFFFFF'); }

                theFlyout.css('top', -(theFlyout.height() / 2));
                theFlyout.parent('.wheretobuyform').addClass('current');
                theFlyout.fadeIn('normal', function() {
                    if (SharpUSA.IE7) { $(this).css('backgroundColor', 'transparent'); }
                });
                return false;
            });

            // add close on click to close image
            $('div.flyout a.close').click(function() {
                if (SharpUSA.IE7) { $(this).parents('.flyout').css('backgroundColor', '#FFFFFF'); }
                $(this).parents('div.flyout').fadeOut('fast');
                return false;
            });
        }
    };

    SharpUSA.Forms = {
        Init: function() {
            SharpUSA.Forms.AddTooltips();
            SharpUSA.Forms.DefaultEnterButton();
            SharpUSA.Forms.SelectFix();
            //SharpUSA.Forms.UpdateProfile();
        },
        AddTooltips: function() {

            // convert the tooltip markup into GUI ready tooltip
            // add span
            $('p.tooltip').wrapInner('<span></span>');
            // add graphic
            $('p.tooltip span').prepend('<img src="/Images/tooltip-tab.gif" width="7" height="28" alt="" />');
            // add label
            $('p.tooltip span img').each(function(i) {
                //get label and remove asterisk
                //var lbl = $('p.tooltip:nth('+i+')').siblings('label').text().replace('*','');
                //$(this).after('<strong>'+$.trim(lbl)+'</strong><br/>');
            });
            // change class to 'tooltip-enabled' (from 'tooltip') for css
            $('p.tooltip').addClass('tooltip-enabled');
            $('p.tooltip-enabled').removeClass('tooltip');

            // attach the hover in/out event
            $('p.tooltip-enabled span').hide();
            $('p.tooltip-enabled').hover(
			function() { // hover
			    // check if flyout is animated
			    if ($(this).children('span:animated').length === 0) {
			        $(this).parent('li').addClass('open-tooltip'); // needed for z-index in IE
			        $(this).addClass('hovered');
			        $(this).children('span').fadeIn('fast');
			    }
			},
			function() { // mouseout
			    $(this).removeClass('hovered');
			    $(this).children('span').fadeOut('fast', function() {
			        $(this).parent('p').parent('li').removeClass('open-tooltip');
			    });
			}
		);
        },
        DefaultEnterButton: function() {
            $(document).unbind('keypress');
            $(document).keypress(function(e) {
                if (e.which == 13 && SharpUSA.Forms.SubmitThisWhenClicked !== '') {

                    var button = $('#' + SharpUSA.Forms.SubmitThisWhenClicked);
                    if (button.exists()) {
                        if (button.is('a') && button.attr('href').indexOf('javascript:') === 0) {
                            eval(button.attr('href'));
                        }
                        else if (button.is('a,input:button,input:image,input:submit')) {
                            button.click();
                        }
                        return false;
                    }
                }
            });

            $('input,select,textarea', 'fieldset[defaultbutton]').focus(function() {
                var fieldset = $(this).parents('fieldset[defaultbutton]:first');
                SharpUSA.Forms.SubmitThisWhenClicked = fieldset.attr('defaultbutton');
            });

            $('input,select,textarea', 'fieldset').blur(function() {
                SharpUSA.Forms.SubmitThisWhenClicked = '';
            });
        },
        SelectFix: function() {
            if ($.browser.msie) {
                // unbind previously bound focus.fix/blur.fix events so as not to trigger event multiple times
                $('#content select.fixwidth').unbind('.fix');

                $('#content select.fixwidth')
			.bind('focus.fix', function() {
			    var t = $(this);
			    t.data('origWidth', t.width()); // store original width in data
			    t.width('auto');
			})
			.bind('blur.fix', function() {
			    var t = $(this);
			    t.width(t.data('origWidth')); // set original width from stored data
			    t.removeData('origWidth'); // clear data value
			});
            }
        },
        SubmitThisWhenClicked: '',
        // update profile links to enable disabled Email and Password fields
        UpdateProfile: function() {
            ConfirmEnabled = function(context, isEnabled) {
                if (isEnabled) {
                    context.children('span.confirm').show();
                    context.children('.enable-toggle').children('.save').show();
                }
                else {
                    context.children('span.confirm').hide();
                    context.children('.enable-toggle').children('.save').hide();
                }
            };

            // hide confirm inputs
            $('.confirm, .enable-toggle .save').hide();

            // change/cancel (email/password) link
            $('.form ul li p.enable-toggle a').toggle(
			function() {
			    ConfirmEnabled($(this).parents('li'), true);
			    $(this).parents('li').children('input:disabled').removeAttr('disabled');
			    $(this).text('Cancel Change');
			},
			function(e) {
			    ConfirmEnabled($(this).parents('li'), false);
			    $(this).parents('li').children('input:not(:disabled)').attr('disabled', 'disabled');
			    var lbl = $(this).parents('li').children('label:first').text().replace('*', '');
			    $(this).text('Change ' + $.trim(lbl));
			}
		);

            // save button
            $('.enable-toggle .save').click(function() {
                // validate or set of validator??
                $(this).siblings('a').click();
                return false;
            });
        }
    };

    SharpUSA.LandingNav = {
        Init: function() {
            $('.landingdiv #grouplanding-nav').show();
            SharpUSA.LandingNav.AttachFeatureInteraction();
            SharpUSA.UI.SIFR();
        },
        AttachFeatureInteraction: function() {
            // do not add interaction to Verticals page
            if ($('.landingdiv').attr('id') != 'verticalshome') {

                // add additional <span> to style bg opacity
                $('.example-product', '#grouplanding-nav').prepend('<span />');

                $('.landingdiv .feature').addClass('feature-js');
                $('.landingdiv .feature:first').addClass('current');

                // add close links to feature modules
                $('.landingdiv .feature:not(:first)').prepend('<a href="#" class="close">Close</a>');
                $('.landingdiv .feature a.close').click(function() {
                    $('#grouplanding-nav li').removeClass('selected').removeClass('hovered');
                    $('.landingdiv .feature').hide();
                    $('.landingdiv .feature').eq(0).show();
                    SharpUSA.UI.SIFRHidden($('.landingdiv .feature').eq(0).children('h2'), '#FFFFFF');
                    return false;
                });


                $('#grouplanding-nav li').click(
				function() {
				    var thisIndex = $(this).prevAll('li').length;

				    // change if the selected feature isn't already current
				    if (($('.feature:visible').size() == 1) && ($('.feature:nth(' + (thisIndex + 1) + '):visible').size() < 1)) {

				        $('.landingdiv #grouplanding-nav li').removeClass('selected');
				        $(this).addClass('selected');

				        // hide all, then show appropriate feature based on index
				        $('.landingdiv .feature').hide();
				        $('.landingdiv .feature').eq(thisIndex + 1).show();
				        SharpUSA.UI.SIFRHidden($('.landingdiv .feature').eq(thisIndex + 1).children('h2'), '#CC0000');

				        // shift up sub-pages <ul> if more than 6 items
				        var thisUl = $('.landingdiv .feature').eq(thisIndex + 1).children('ul');
				        var listItems = thisUl.children('li');
				        if (listItems.length > 6) {
				            var marginTopVal = (listItems.length - 6) * 18;
				            thisUl.css('marginTop', '-' + marginTopVal + 'px');
				        }

				    }
				}
			);

                $('#grouplanding-nav li').hover(
				function() {
				    $(this).addClass('hovered');
				},
				function() {
				    $(this).removeClass('hovered');
				}
			);
            }
        }
    };

    SharpUSA.ProductCategory = {
        InitAspnet: function() {
            SharpUSA.UI.ElementHover($('table.products-grid tr td:not(:empty), ul.products-list > li:not(:empty)'));
            SharpUSA.ProductCategory.QuickView();
            // Fill empty cells as generated by the DataList
            $('table.products-grid tr td:empty').html('&nbsp;');

            SharpUSA.ProductCategory.FilterInit();
        },
        InitClient: function() {
            SharpUSA.UI.ElementHover($('table.products-grid tr td:not(:empty), ul.products-list > li:not(:empty)'));
            SharpUSA.ProductCategory.MfpLanding();
            SharpUSA.ProductCategory.TabClicks();
        },
        MfpLanding: function() {
            $('a', 'div.findmfp .note').click(function() {
                var ppmTooltip = $(this).next('#ppmdescription');
                ppmTooltip.fadeIn('fast');

                ppmTooltip.children('a.close').click(function() {
                    ppmTooltip.fadeOut('fast');
                    return false;
                });

                return false;
            });
        },
        TabClicks: function() {
            $('#viewallproducts a', '#product-category-nav').click(function() {
                if (typeof s !== 'undefined') {
                    var clickTrackCode = 'View Products:' + s.pageName;

                    s.linkTrackVars = 'prop25,eVar25,events';
                    s.linkTrackEvents = 'event25';
                    s.prop25 = clickTrackCode;
                    s.eVar25 = clickTrackCode;
                    s.events = 'event25';
                    var lt = (this.href != null) ? s.lt(this.href) : "";

                    if (lt == "") {
                        s.tl(this, 'o', clickTrackCode);
                    }

                }
            });

            $('#learnmore a', '#product-category-nav').click(function() {
                if (typeof s !== 'undefined') {
                    var clickTrackCode = 'Learn More:' + s.pageName;

                    s.linkTrackVars = 'prop24,eVar24,events';
                    s.linkTrackEvents = 'event24';
                    s.prop24 = clickTrackCode;
                    s.eVar24 = clickTrackCode;
                    s.events = 'event24';
                    //s.tl(true,'o',clickTrackCode);
                    var lt = (this.href != null) ? s.lt(this.href) : "";

                    if (lt == "") {
                        s.tl(this, 'o', clickTrackCode);
                    }
                }
            });
        },
        QuickView: function() {
            // quick view button hover
            $('table.products-grid div.product-image a.quick-view').hide();
            $('table.products-grid tr td:not(:empty)').hover(
			function() {
			    $(this).children('.product-image').children("a.quick-view").show();
			},
			function() {
			    $(this).children('.product-image').children("a.quick-view").hide();
			}
		);

            // quick view button click
            $('table.products-grid').unbind('click');
            $('table.products-grid').click(function(e) {

                var targetEl = $(e.target);

                // catch the Quick View link click
                if (targetEl.is('a.quick-view')) {
                    // click tracking on quick view
                    if (typeof targetEl.attr('rel') !== 'undefined' && typeof s !== 'undefined') {
                        var clickTrackCode = 'QuickView:' + s.pageName + ":" + targetEl.attr('rel');
                        s.tl(true, 'o', clickTrackCode);
                    }

                    $.ajax({
                        url: targetEl.attr('href'),
                        cache: false,
                        dataType: 'text',
                        success: function(data) {
                            // get just the quickview div
                            startIndex = data.indexOf('<div id="quickview">');
                            endIndex = data.indexOf('<!-- end #quickview -->');
                            data = data.substring(startIndex, endIndex);
                            SharpUSA.Global.BlockUI(data, 500, 450);

                            // rebind events
                            SharpUSA.ShoppingCart.EventSetup();

                            // attach wheretobuy click
                            $('div#quickview .wheretobuy a.gobutton').click(function() {
                                var prev = $(this).prev('input#wheretobuyzip');
                                if (prev.exists()) {
                                    location.href = $(this).attr('href') + prev.val();
                                    return false;
                                }
                                return false;
                            });

                            SharpUSA.ProductCategory.QuickViewThumbnails();
                            SharpUSA.UI.Init();
                        },
                        error: SharpUSA.Global.ErrorModal
                    });
                    return false;
                }
            });
        },
        QuickViewThumbnails: function() {
            var mainImg = $('img.mainimage', '#quickview');
            SharpUSA.UI.Thumbnails(mainImg);
        },
        FilterInit: function(firstLoad) {
            firstRun = (typeof firstLoad == "undefined") ? false : Boolean(firstLoad);
            hasRun = $('#filter-header:contains("[+]"),#filter-header:contains("[-]")').exists();

            if ($('#product-filter').exists() && !hasRun) {
                var filterHeader = $('#filter-header');
                isOpen = SharpUSA.FacetNavIsOpen;
                // init plusMinus image
                var plusMinusIndicator = (isOpen) ? '[-]' : '[+]';
                filterHeader.prepend('<strong>' + plusMinusIndicator + ' </strong>');

                // hide the element if should start closed
                if (!isOpen) { filterHeader.next().hide(); }

                if (isOpen) {
                    filterHeader.toggle(
					function(e) { SlideUp(filterHeader, e); },
					function(e) { SlideDown(filterHeader, e); }
				);
                }
                else {
                    filterHeader.toggle(
					function(e) { SlideDown(filterHeader, e); },
					function(e) { SlideUp(filterHeader, e); }
				);
                }

                var SlideDown = function(jEls, evt) {
                    if ($(evt.target).is('a')) {
                        window.location = evt.target.href;
                    }
                    else {
                        jEls.html(jEls.html().replace('[+]', '[-]'));
                        jEls.html(jEls.html().replace('Show', 'Hide'));
                        jEls.next().slideDown('normal');
                        SharpUSA.FacetNavIsOpen = true;
                    }

                };
                var SlideUp = function(jEls, evt) {
                    if ($(evt.target).is('a')) {
                        window.location = evt.target.href;
                    }
                    else {
                        jEls.html(jEls.html().replace('[-]', '[+]'));
                        jEls.html(jEls.html().replace('Hide', 'Show'));
                        jEls.next().slideUp('normal');
                        SharpUSA.FacetNavIsOpen = false;
                    }
                };
            }

            // add hover to filter heading and filter options
            $('#filter-header, #product-filter ul li li').hover(
			function() { $(this).addClass('hover'); },
			function() { $(this).removeClass('hover'); }
		);
        }
    };

    SharpUSA.ProductCompare = {
        InitClient: function() {
            SharpUSA.ProductCompare.AttachHandlers();
        },
        MinimumNumberOfProducts: 1,
        RemoveConfirmationMessage: 'Are you sure you want to remove this item?',
        AttachHandlers: function() {
            /* expand/collapse attribute */
            plusMinusFile = $('table.product-compare tbody tr th img.plusminus').attr('src');
            // add click event to Attribute Category row
            $('table.product-compare tbody tr.attribute-category th').toggle(
			function() {
			    $(this).parent('tr').siblings('tr').hide();
			    $(this).parent('tr').children('th:first').children('img').attr('src', plusMinusFile.replace('minus', 'plus'));

			    $(this).parent('tr').siblings('tr').children('th,td').addClass('hidden');
			},
			function() {
			    $(this).parent('tr').siblings('tr').show();
			    $(this).parent('tr').children('th:first').children('img').attr('src', plusMinusFile.replace('plus', 'minus'));

			    $(this).parent('tr').siblings('tr').children('th,td').removeClass('hidden');
			}
		);

            /* remove product from compare */
            $('table.product-compare p.remove a').click(
			function() {
			    var confirmed = confirm(SharpUSA.ProductCompare.RemoveConfirmationMessage);
			    if (confirmed) {
			        // remove column
			        var indexToRemove = $(this).parent().parent().prevAll().size() + 1;
			        $('table.product-compare tr th:nth-child(' + indexToRemove + '),table.product-compare tr td:nth-child(' + indexToRemove + ')').remove();
			        $('table.product-compare colgroup.products-columns col:last').remove();

			        // add new width to colgroup and col
			        var columnWidth = 100 / ($('table.product-compare colgroup.products-columns col').size() + 1);
			        $('table.product-compare col.attribute-labels-column').attr('width', columnWidth + '%');
			        $('table.product-compare colgroup.products-columns col').attr('width', columnWidth + '%');

			        // disable remove link if only min # of products left
			        if ($('table.product-compare thead:first tr').children().size() <= (SharpUSA.ProductCompare.MinimumNumberOfProducts + 1)) {
			            $('table.product-compare p.remove a').remove();
			        }
			    }
			    return false;
			}
		);

            // attach wheretobuy click
            $('table.product-compare .wheretobuyform a.gobutton').click(function() {
                var prev = $(this).prev('input#wheretobuyzip');
                if (prev.exists()) {
                    location.href = $(this).attr('href') + prev.val();
                    return false;
                }
                return false;
            });
        }
    };

    SharpUSA.MySharp = {
        Init: function() {
            SharpUSA.MySharp.SlidingListInit();
            SharpUSA.UI.ElementHover($('#mysharp .accessories ul > li'));
            SharpUSA.MySharp.SavedPages();
            SharpUSA.MySharp.ProductDownloads();
        },
        SlidingListInit: function() {
            $('h3.slider-trigger-expanded').ExpandingSlider();
            $('h3.slider-trigger').ExpandingSlider(false);
        },
        SavedPages: function() {
            // up/down arrows
            MarkFirstLast = function() {
                $('table.savedpages tbody tr').removeClass('first last');
                $('table.savedpages tbody tr:first').addClass('first');
                $('table.savedpages tbody tr:last').addClass('last');
            };

            MarkFirstLast();

            $('table.mysharp-table tbody tr a.moveup').click(function() {
                // if it's not the first one.
                var parentRow = $(this).parents('tr');
                if (parentRow.prev('tr').size() > 0) {

                    parentRow.prev('tr').before(parentRow);

                    // set disabled arrows
                    MarkFirstLast();

                    parentRow.ColorFlash('#E4F3F6', '#FFFFFF', 800);

                    // need to call something to update order
                }
                return false;
            });
            $('table.mysharp-table tbody tr a.movedown').click(function() {
                var parentRow = $(this).parents('tr');
                if (parentRow.next('tr').size() > 0) {
                    parentRow.next('tr').after(parentRow);

                    // set disabled arrows
                    MarkFirstLast();

                    parentRow.ColorFlash('#E4F3F6', '#FFFFFF', 800);

                    // need to call something to update order
                }
                return false;
            });

            // saved pages remove links
            $('a.remove', 'table.mysharp-table td').click(function() {
                $(this).parents('tr').remove();
                MarkFirstLast();
                return false;
            });
        },
        ProductDownloads: function() {
            DisableDependentDDL = function(primarySelect) {
                primarySelect.each(function(i) {
                    var dependentSelect = $(this).parent('li').siblings('li').children('select.dependent');
                    if ($(this).children('option:first:selected').size() > 0) {
                        dependentSelect.attr('disabled', 'disabled');
                    }
                    else {
                        dependentSelect.removeAttr('disabled');
                    }
                });
            };

            // disable a dependent dropdown if the first element is selected
            // use class="primary" and class="dependent" w/in ul li structure
            DisableDependentDDL($('select.primary'));

            $('select.primary').change(function() {
                DisableDependentDDL($('select.primary'));
            });

            SharpUSA.UI.TabbedNav();
        }
    };

    SharpUSA.ProductDetail = {
        Init: function() {
            SharpUSA.ProductDetail.Thumbnails();
            SharpUSA.ProductDetail.ViewLargerImage();
            SharpUSA.ProductDetail.IconFlyouts();
            SharpUSA.ProductDetail.ProductTour();
        },
        InitAspnet: function() {
            SharpUSA.UI.Flyouts();
            SharpUSA.ProductDetail.SpecTable();
            SharpUSA.UI.Buttons();
        },
        Thumbnails: function() {
            var mainImg = $('img.mainimage', '#productdetail');
            SharpUSA.UI.Thumbnails(mainImg);
        },
        ViewLargerImage: function() {
            var largerImageLink = $('a.viewlargerimage', '#product-imageviews');
            if (largerImageLink.exists()) {
                largerImageLink.click(function() {
                    var imageWidth = 745;
                    var imageHeight = 445;
                    var data = '<div id="fullimagemodal"><a close="#" class="close">close</a><img width="' + imageWidth + '" height="' + imageHeight + '" src=' + largerImageLink.attr('href') + ' /></div>';
                    SharpUSA.Global.BlockUI(data, imageWidth + 30, imageHeight + 30);
                    return false;
                });
            }
        },
        IconFlyouts: function() {
            if ($('.iconography').exists()) {
                $('.iconography li:not(.viewmore) a.icon').click(function() {
                    $(this).parent('li').siblings('li').children('.description').hide();
                    $(this).parent('li').siblings('li').css('zIndex', '1');
                    $(this).parent('li').css('zIndex', '1000');
                    $(this).siblings('.description').fadeIn();
                    return false;
                });

                $('.iconography li.viewmore a').click(function() {

                    viewmoreContent = '<div id="iconmodal">' + $(this).siblings('.description').html() + '</div>';
                    SharpUSA.Global.BlockUI(viewmoreContent, 350, 400);

                    return false;
                });

                $('.iconography li:not(.viewmore) .description a.close').click(function() {
                    $(this).parent().fadeOut();
                    $('.iconography li').css('zIndex', '1');
                    return false;
                });

            }
        },
        MakeTabs: function() {
            // only do this if not on print page
            if (!SharpUSA.Helpers.IsPrint) {
                var fileName = SharpUSA.BaseUrl + '/images/selected-tab-indicator.gif';
                var productDetailTabs = $('a', '#productinformation ul.tabs li');
                productDetailTabs.append('<img src="' + fileName + '" class="indicator">');

                productDetailTabs.click(function() {
                    // selected tab state
                    $(this).parent('li').siblings('li').removeClass('selected');
                    $(this).parent('li').addClass('selected');

                    // web tracking
                    if (typeof s !== 'undefined') {
                        var clickTrackCode = $(this).text() + ':' + s.pageName;
                        s.linkTrackVars = 'prop26,eVar26,events';
                        s.linkTrackEvents = 'event26';
                        s.prop26 = clickTrackCode;
                        s.eVar26 = clickTrackCode;
                        s.events = 'event26';
                        s.tl(true, 'o', clickTrackCode);
                    }
                });

                $.urlParam = function(name) {
                    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
                    if (results !== null) {
                        return results[1] || "";
                    }
                    else {
                        return "";
                    }
                };

                var viewParam = $.urlParam('view');
                if (viewParam !== "") {
                    var tabText;
                    $('li', '#productinformation ul.tabs').removeClass('selected');
                    $('li', '#productinformation ul.tabs').each(function() {
                        tabText = $(this).children('a').text().toLowerCase().replace(/[&\s]*/g, '');
                        if (tabText.indexOf(viewParam) > -1) {
                            $(this).addClass('selected');
                        }
                    });
                }
            }
            else {
                $('.contentpanel').prepend('<a href="#" class="remove">remove</a>');
                $('a.remove', '.contentpanel').click(function() {
                    $(this).parents('.contentpanel').remove();
                    return false;
                });
            }
        },
        SpecTable: function() {
            if (!SharpUSA.Helpers.IsPrint) {
                // add plus/minus
                $('table.specifications thead th').wrapInner('<span class="open"></span>');
                //$('table.specifications thead th').prepend('- ');


                $('table.specifications thead th').toggle(
				function() {
				    $(this).parents('thead').siblings('tbody').children('tr').hide();
				    $(this).children('span').removeClass('open').addClass('closed');
				},
				function() {
				    $(this).parents('thead').siblings('tbody').children('tr').show();
				    $(this).children('span').removeClass('closed').addClass('open');
				}
			);
            }
            // zebra stripe
            $('tr:even', 'table.specifications tbody').addClass('alt');
        },
        WhereToBuy: function() {
            var input = $('#product-details input.text');
            var label = input.prev('label');
            input.val(label.text());
            label.remove();

            SharpUSA.UI.InputClear(input, label.text());
        },
        ProductTour: function() {
            $('a.producttour').click(function() {
                var productTourUrl = $(this).attr('href');
                var height = $(this).attr('height');
                var width = $(this).attr('width');
                var scrolling = $(this).attr('scrolling');
                //777,320
                if (width == null) width = 777;
                if (height == null) height = 320;
                if (scrolling == null) scrolling = "no";
                var iframe = '<div id="producttour"><a href="#" class="close">close</a><iframe src="' + productTourUrl + '" width="' + width + '" height="' + height + '" scrolling="' + scrolling + '" frameborder="0" border="1" /></div>';
                SharpUSA.Global.BlockUI(iframe, width, height);

                // omniture track
                if (typeof s !== 'undefined') {
                    var clickTrackCode = 'ProductTour:' + s.pageName;
                    s.tl(true, 'o', clickTrackCode);
                }
                var tokens = productTourUrl.split("/");
                if (pageTracker) {
                    //alert(pageTracker);
                    if (tokens.length >= 2)
                        pageTracker._link("/productTour/" + token[tokens.length - 2]);
                }

                return false;
            });
        }
    };

    SharpUSA.AboutSharp = {
        Init: function() {
            SharpUSA.AboutSharp.PressMedia();
            SharpUSA.AboutSharp.Awards();
        },
        PressMedia: function() {
            var presssearch = $('fieldset.search-filter input:text');
            SharpUSA.UI.InputClear(presssearch, presssearch.val());

            var presssearch2 = $('div.pressdisplaycontrols input:text');
            SharpUSA.UI.InputClear(presssearch2, presssearch2.val());
        },
        Awards: function() {
            // outline hover
            SharpUSA.UI.ElementHover($('ul.awards-listing li'));
            // zebra stripe
            $('li:even', 'ul.awards-listing').addClass('alt');
        }
    };

    SharpUSA.CustomerSupport = {
        Init: function() {
            SharpUSA.CustomerSupport.GlossaryFaq();
            //SharpUSA.CustomerSupport.SafetyUpdates();
        },
        GlossaryFaq: function() {
            if ($('ul.glossary-faq').exists()) {
                $('ul.glossary-faq div.defn').hide();
                $('ul.glossary-faq h3').wrapInner('<span></span>');
                $('ul.glossary-faq h3').toggle(
				function() {
				    $(this).next('div.defn').slideDown('fast');
				    $(this).removeClass('closed');
				    $(this).addClass('open');
				    //$(this).html($(this).html().replace('+','&minus;'));
				},
				function() {
				    $(this).next('div.defn').slideUp('fast');
				    //$(this).html($(this).html().replace('-','+'));
				    $(this).removeClass('open');
				    $(this).addClass('closed');
				}
			)
			.addClass('closed')
			.addClass('clickable');

                SharpUSA.UI.ElementHover($('li', 'ul.glossary-faq'));
                // zebra stripe
                $('li:even', 'ul.glossary-faq').addClass('alt');
            }
        },
        SafetyUpdates: function() {
            // trim the description and add "Read More" link
            if ($('table.safetyupdates').exists()) {
                $('table.safetyupdates td.details').each(function(i, el) {

                    // if details are longer than SafetyUpdateDetailMaxLength, truncate and add Read more link
                    if ($(el).children('p:first').text().length > SharpUSA.SafetyUpdateDetailMaxLength) {
                        // put html in new element to hide
                        var flyoutText = $(el).html();
                        var truncatedText = $(el).children('p:first').text().substr(0, SharpUSA.SafetyUpdateDetailMaxLength);
                        $(el).empty();
                        $(el).prepend(truncatedText);
                        $(el).append('&hellip; <a href="#" class="readmore">Read more</a>');
                        $(el).wrapInner('<div class="flyoutwrapper"></div>');
                        $(el).children('.flyoutwrapper').append('<div class="flyout"><a href="#" class="close">close</a><div class="flyoutinner">' + flyoutText + '</div></div>');
                    }
                });

                var closeOpenFlyout = function() {
                    $('table.safetyupdates div.flyout').hide();
                    $('table.safetyupdates tr').removeClass('selected');
                };

                $('table.safetyupdates a.readmore').click(function() {
                    // close other open detail flyouts
                    closeOpenFlyout();
                    var thisFlyout = $(this).parents('td').children('div.flyoutwrapper');
                    $(this).parents('tr').addClass('selected');
                    thisFlyout.children('.flyout').fadeIn();
                    thisFlyout.children('.flyout').css('zIndex', 9999);
                    return false;
                });

                $('table.safetyupdates a.close').click(function() {
                    closeOpenFlyout();
                    return false;
                });
            }
        }
    };

    SharpUSA.Solar = {
};

SharpUSA.Verticals = {
    Init: function() {
        SharpUSA.UI.SIFR();
        SharpUSA.UI.ElementHover($('li', '.verticalslist'));
    }
};

SharpUSA.UI = {
    Init: function() {
        SharpUSA.UI.Buttons();
        SharpUSA.UI.SIFR();
        SharpUSA.UI.Flyouts();

        $('a.backlink').click(function() {
            if (history && history.back) {
                history.back();
            }
        });
    },
    Buttons: function() {
        $('a.button span').remove();
        $('a.button').append('<span></span').hover(
			function() { $(this).addClass('hover'); },
			function() { $(this).removeClass('hover'); }
		);
        $('input.registerproduct').unbind('mouseenter');
        //$('input.registerproduct').unbind('mouseout');
        $('input.registerproduct').hover(
			function() {
			    $(this).attr('src', $(this).attr('src').replace('.gif', '-over.gif'));
			},
			function() {
			    $(this).attr('src', $(this).attr('src').replace('-over.gif', '.gif'));
			}
		);
    },
    SIFR: function() {
        if (!SharpUSA.Helpers.IsPrint) {
            $('#mysharp-nav .replace, .callout .replace, .presscallout .replace, .feature h2, #customerSupportIntro .replace, #contentcallouts .replace').sifr(
				{
				    path: SharpUSA.Helpers.GetFlashPath(),
				    font: 'ParalucentLight',
				    color: '#CC0000',
				    version: SharpUSA.Flash.SifrPlayerVersion,
				    expressInstall: false
				}
			);
            $('#feature-closed h2, #vertical-landing h1').sifr(
				{
				    path: SharpUSA.Helpers.GetFlashPath(),
				    font: 'ParalucentLight',
				    color: '#FFFFFF',
				    version: SharpUSA.Flash.SifrPlayerVersion,
				    expressInstall: false
				}
			);
            $('ul#grouplanding-nav h3').sifr(
				{ path: SharpUSA.Helpers.GetFlashPath(), font: 'ParalucentMedium', color: '#FFFFFF', version: SharpUSA.Flash.SifrPlayerVersion, expressInstall: false }
			);
            $('ul.verticalslist a strong').sifr(
				{
				    path: SharpUSA.Helpers.GetFlashPath(),
				    font: 'ParalucentMedium',
				    color: '#FFFFFF',
				    version: SharpUSA.Flash.SifrPlayerVersion,
				    expressInstall: false,
				    css: { lineHeight: '12px' }
				}
			);
            $('#product-details .replace, #quickview .replace').sifr(
				{
				    path: SharpUSA.Helpers.GetFlashPath(),
				    font: 'ParalucentLight',
				    color: '#333333',
				    version: SharpUSA.Flash.SifrPlayerVersion,
				    expressInstall: false
				}
			);
        }
    },
    SIFRHidden: function(el, hexColor) {
        el.sifr(
			{ path: SharpUSA.Helpers.GetFlashPath(), font: 'ParalucentLight', color: hexColor, version: SharpUSA.Flash.SifrPlayerVersion, expressInstall: false }
		);
    },
    ElementHover: function(jElems) {
        jElems.hover(
			function() { $(this).addClass('selected'); },
			function() { $(this).removeClass('selected'); }
		);
    },
    Thumbnails: function(mainImg) {
        //var mainImg = $('ul.thumbnails').prev('img.mainimage');
        var origSrc = mainImg.attr('src');
        $('ul.thumbnails li img').click(
			function() {
			    var thisSrc = $(this).attr('src');
			    var thisBase = thisSrc.substr(0, thisSrc.indexOf('?'));
			    var origParams = origSrc.substr(origSrc.indexOf('?'));

			    mainImg.attr('src', thisBase + origParams);

			    // switch viewlarger if exists
			    var largerImageLink = $('a.viewlargerimage', '#productdetail');
			    if (largerImageLink.exists()) {
			        var href = largerImageLink.attr('href');
			        var origLargeParams = href.substr(href.indexOf('?'));
			        largerImageLink.attr('href', thisBase + origLargeParams);
			    }
			}
		);
    },
    Pricing: function() {
        $('div.flyout', 'tr.discount').hide();

        $('label', 'tr.discount').click(
			function() {
			    var flyoutDiv = $(this).next('div.flyout');

			    if (!flyoutDiv.children('a.close').exists()) {
			        flyoutDiv.prepend('<a close="#" class="close">close</a>');
			        flyoutDiv.children('a.close').click(
						function() {
						    flyoutDiv.hide();
						}
					);
			    }

			    flyoutDiv.show();


			}
		);
    },
    Flyouts: function() {

        var theDivs = $('div.availablemodels');
        // make sure we don't write this out more than once.
        if (!theDivs.parent('.wrapper').exists()) {
            theDivs.wrap('<div class="wrapper"></div>');
            theDivs.before('<p><a href="#" class="modelslist">Available Models &rsaquo;</a></p>');
        }
        theDivs.prepend('<a href="#" class="close">close</a>');

        theDivs.hide();
        // open on click
        $('a.modelslist').click(function() {
            $(this).parent('p').next('div.availablemodels').fadeIn();
            return false;
        });
        $('a.close', 'div.availablemodels').click(function() {
            $(this).parent('div').fadeOut();
            return false;
        });
    },
    // like tabs on Product Details
    Tabs: function() {
        // add the arrow
        var fileName = SharpUSA.BaseUrl + '/images/selected-tab-indicator.gif';
        $('li', 'ul.tabs').append('<img src="' + fileName + '" class="indicator">');

        // init to first tab/panel shown
        $('.contentpanel', '#content').hide();
        $('.contentpanel:first', '#content').show();

        $('li', 'ul.tabs').removeClass('selected');
        $('li:first', 'ul.tabs').addClass('selected');


        // attach clicks to tabs
        $('li', 'ul.tabs').click(function() {
            // switch visible panel
            $(this).parents('ul.tabs').siblings('.contentpanel').hide();
            $($(this).children('a').attr('href')).show();

            // selected tab state
            $(this).siblings('li').removeClass('selected');
            $(this).addClass('selected');

            return false;
        });
    },
    // like tabs on Customer Support landing
    TabbedNav: function() {
        // where NOT to run this
        var exclude = $('.wheretobuyresults ul.tabbed-nav');

        if (!exclude.exists()) {
            //init 
            $('li:first', 'ul.tabbed-nav').addClass('selected');
            $('ul.tabbed-nav').siblings('.content-module:not(:first)').hide();

            // check for data to save tab state
            var tabState = $(document).data('ul.tabbed-nav');
            var liId;
            if (tabState) {
                liId = 'li' + tabState + '-nav';

                var statefulTab = $(liId, 'ul.tabbed-nav');

                statefulTab.parents('ul').children('li').removeClass('selected');
                statefulTab.addClass('selected');
                $('ul.tabbed-nav').siblings('.content-module').hide();
                $('ul.tabbed-nav').siblings('.content-module:nth(' + statefulTab.prevAll().length + ')').show();
            }

            // check url for pre-populated tab			
            var hash = document.location.hash;
            liId = 'li' + hash + '-nav';
            var hashedTab = $(liId, 'ul.tabbed-nav');
            if (hash !== "" && (hashedTab.size() > 0)) {
                hashedTab.addClass('selected');
                $('ul.tabbed-nav').siblings('.content-module').hide();
                $('ul.tabbed-nav').siblings('.content-module:nth(' + hashedTab.prevAll().length + ')').show();
                $(document).data('ul.tabbed-nav', hash);
            }

            // tab clicks
            $('ul.tabbed-nav li a').unbind('click');
            $('ul.tabbed-nav li a').click(function() {
                //set tab state
                $(this).parents('ul').children('li').removeClass('selected');
                $(this).parent('li').addClass('selected');

                $(document).data('ul.tabbed-nav', $(this).attr('href'));

                // show/hide appropriate panel
                $(this).parents('ul').siblings('.content-module').hide();
                $($(this).attr('href')).show();

                //$('#content').prepend($($(this).attr('href')).children('.support-nav').children('li').css('marginLeft'));

                return false;
            });
        }
    },
    InputClear: function(inputs, defaultValue) {
        inputs.focus(
			function() {
			    if ($(this).val() == defaultValue) {
			        $(this).val('');
			    }
			}
		);

        inputs.blur(
			function() {
			    if ($(this).val() === '') {
			        $(this).val(defaultValue);
			    }
			}
		);
    }
};

SharpUSA.Global = {
    Init: function() {
        SharpUSA.Global.FooterModal();
        SharpUSA.Global.PrintPreview();
        SharpUSA.Global.SectionNav();
        SharpUSA.Global.AjaxLoading();
    },
    DownloadTrackingSetup: function() {
        $('#productinformation a[rel^=download],#productinformation table.downloads a').unbind('click').click(function() {
            SharpUSA.WebTracking.Omniture.TrackDownloads(this, SharpUSA.WebTracking.Omniture.DownloadTrackingEnum.ProductDetail);
        });
        $('a[rel^=download]', '#downloadsearch').unbind('click').click(function() {
            SharpUSA.WebTracking.Omniture.TrackDownloads(this, SharpUSA.WebTracking.Omniture.DownloadTrackingEnum.CustomerSupport);
        });
        $('#mysharp #myproducts table.downloads a').unbind('click').click(function() {
            SharpUSA.WebTracking.Omniture.TrackDownloads(this, SharpUSA.WebTracking.Omniture.DownloadTrackingEnum.MySharp);
        });
        $('.solardownloads a').unbind('click').click(function() {
            SharpUSA.WebTracking.Omniture.TrackDownloads(this, SharpUSA.WebTracking.Omniture.DownloadTrackingEnum.Solar);
        });
    },
    NavToAnchor: function() {
        if ($('#AnchorToNavTo').length > 0) {
            window.location.hash = $('#AnchorToNavTo').attr('anchor');
        }
    },
    UpdateDynamicContent: function() {
        $.post('/DynamicContent.aspx', function(data) {
            var commerceNav = SharpUSA.Global.GetChunk(data, "commerce-nav");
            $('#commerce-nav').replaceWith(commerceNav);
            SharpUSA.ShoppingCart.CartFlyout();
            var aaChatButton = SharpUSA.Global.GetChunk(data, "aaChatButton");
            $('#aaChatButton').replaceWith(aaChatButton);
        });
    },
    GetChunk: function(data, tag) {
        var pos1 = data.indexOf("<" + tag + ">");
        var pos2 = data.indexOf("</" + tag + ">");
        if (pos1 > -1 && pos2 > -1)
            return data.substring(pos1 + tag.length + 2, pos2);
        return "";
    },
    ModalOpen: function() {
        return $('form > .blockPage #modalcontent, form > .blockPage #addtowishlist, form > .blockPage #quickview').exists();
    },
    BlockModal: function(selector) {
        $(selector).block();
    },
    PageUtilClosing: function(isClosing) {
        // set if value is passed in
        if (typeof isClosing !== null) {
            $(document).data('pageutilclosing', isClosing);
        }
        return ($(document).data('pageutilclosing') === true);
    },
    // This handles the page blocking / modal "loading" message when XHR calls are in progress
    AjaxLoading: function() {
        $.blockUI.defaults.css = {};

        var loadingHTML = '<div class="loading"><img height="32" width="32" alt="" src="/Images/loader.gif"/> loading</div>';

        // for jQuery ajax calls
        $('html').ajaxStart(function() {
            // check to make sure a modal window isn't already opened (privacy, terms and conditions, quick view, etc.)
            if (!SharpUSA.Global.ModalOpen()) {
                SharpUSA.Global.BlockUI(loadingHTML, 200, 56);
            }
            else {
                // block just the element
                // TODO: modalcontent might also need to be added, .net calls might need this?
                $('#quickview').block({ message: loadingHTML });
            }
        });
        $('html').ajaxSuccess(function() {
            // check to make sure a modal window isn't already opened (privacy, terms and conditions, quick view, etc.)
            if (!SharpUSA.Global.ModalOpen() && asyncRequestQueue.length === 0) {
                $.unblockUI();
                $.blockUI.defaults.css = {};
            }
            else if (SharpUSA.Global.ModalOpen() && asyncRequestQueue.length === 0) {
                // unblock just the element
                // TODO: modalcontent might also need to be added, .net calls might need this?
                if ($('#quickview').exists()) {
                    $('#quickview').unblock();
                }
            }
        });

        // for .NET ajax calls
        if (typeof Sys !== 'undefined' && Sys.WebForms.PageRequestManager.getInstance()) {
            var prm = Sys.WebForms.PageRequestManager.getInstance();

            prm.add_beginRequest(function() {
                if (!SharpUSA.Global.ModalOpen() && !SharpUSA.Global.PageUtilClosing()) {
                    SharpUSA.Global.BlockUI(loadingHTML, 200, 56);
                }
            });
            prm.add_endRequest(function() {
                if (!SharpUSA.Global.ModalOpen() && asyncRequestQueue.length === 0) {
                    $.unblockUI();
                    $.blockUI.defaults.css = {};
                }
                SharpUSA.Global.PageUtilClosing(false);

                // check scroll position of related accessories on shopping cart page
                if (typeof $(document).data('maintainscroll') != 'undefined') {
                    if ($('#related-accessories', 'div.accessories').exists) {
                        // TODO: move to separate function
                        var $target = $($(document).data('maintainscroll'));
                        if ($target.length) {
                            var targetOffset = $target.offset().top;
                            $('html,body').animate({ scrollTop: targetOffset }, 500);
                        }
                        $(document).removeData('maintainscroll');
                    }
                }
            });

            // add for queueing of .NET ajax calls
            if (!prm.get_isInAsyncPostBack()) {
                prm.add_initializeRequest(InitializeRequest);
                prm.add_endRequest(CompleteRequest);
            }
        }
    },
    PageUtilSavePage: function() {
        $('#page-utilities a#savepage').unbind('click');
        $('#utilholder').hide();

        $('#page-utilities a#savepage').click(function() {
            SharpUSA.Global.PageUtils('savepage', 225);
            return false;
        });
    },
    PageUtilEmailPage: function() {
        $('#page-utilities a#emailpage, table.savedpages td.emailpage a').unbind('click');
        $('#utilholder').hide();
        $('#page-utilities a#emailpage, table.savedpages td.emailpage a[rel]').click(function() {
            // set url if in 'rel' attr of link
            if ($(this).parent('td.emailpage').exists()) {
                $('#' + SharpUSA.ASPNET.EmailPageUrlFieldId).val($(this).attr('rel'));
            }

            SharpUSA.Global.PageUtils('emailpage', 450);
            return false;
        });
    },
    PageUtilSetup: function() {
        SharpUSA.Global.PageUtilEmailPage();
        SharpUSA.Global.PageUtilSavePage();
    },
    PageUtils: function(modalPrefix, modalHeight) {
        // move HTML in hidden div to the blockUI div
        //var sourceId = jQuery(this).attr('id');
        var elementHandle = modalPrefix + 'modal';
        var data = '<div id="modalcontent" class="' + elementHandle + '"><a href="#" class="close">close</a>' + $('.' + modalPrefix + 'modal').html() + '</div>';
        $('.' + elementHandle).empty();

        SharpUSA.Global.BlockUI(data, 600, modalHeight);

        SharpUSA.Global.PageUtilCancelButtons();
    },
    PageUtilCloseModal: function(targetClass, callback) {
        SharpUSA.Global.PageUtilClosing(true);
        $('#modalcontent a.close').remove();
        $('#utilholder .' + targetClass).append($('#modalcontent.' + targetClass).html());

        var callbackOnUnblock = function() { };

        if (typeof callback != "undefined" && callback.constructor == Function) {
            callbackOnUnblock = callback;
        }

        $.unblockUI({
            onUnblock: callbackOnUnblock
        });
    },
    PageUtilCancelButtons: function() {
        // send another email button
        $('.emailpagemodal a.sendanotheremail').click(function() {
            // clear fields
            $('.emailpagemodal .emailpage input:text').val('');
            __doPostBack(SharpUSA.ASPNET.EmailPageUpdatePanelId, 'resetform');
            return false;
        });

        // close/cancel email this page
        $('#modalcontent.emailpagemodal a.close, .emailpagemodal .emailpage a.cancel, .emailpagemodal .closewindow').click(function() {
            // clear fields
            $('.emailpagemodal .emailpage input:text').val('');
            SharpUSA.Global.PageUtilCloseModal('emailpagemodal', function() {
                __doPostBack(SharpUSA.ASPNET.EmailPageUpdatePanelId, 'resetform');
            });

            return false;
        });
        // close save this page
        $('#modalcontent.savepagemodal a.close, .savepagemodal a.closereturn').click(function() {

            SharpUSA.Global.PageUtilCloseModal('savepagemodal', function() {
                __doPostBack(SharpUSA.ASPNET.SavePageUpdatePanelId, '');
            });
            return false;
        });
    },
    RewriteLinks: function() {
        $('a[href$="/ForHome/Mobile/Smartphones.aspx"]').attr("target", "_newwindow");
    },
    FooterModal: function() {
        // footer modal
        $('a[rel*="modal"]').click(function() {
            var headline = $(this).text();
            var currentUrl = $(this).attr('href');
            $.ajax({
                url: currentUrl,
                cache: false,
                dataType: 'text',
                success: function(data) {
                    // get content
                    startIndex = data.indexOf('<div id="content"');
                    endIndex = data.indexOf('<!-- end #content -->');
                    data = data.substring(startIndex, endIndex);

                    // extract first <h1> from returned data
                    var firstH1 = data.indexOf("<h1>");
                    var firstH1close = data.indexOf("</h1>");
                    headline = data.slice(firstH1, firstH1close + 5);

                    // remove h1 from original data
                    data = data.substring(0, firstH1) + data.substring(firstH1close + 5, data.length);

                    data = '<div id="modalcontent"><a class="print" href="' + currentUrl + '?print=true" target="_blank">print</a> <a href="#" class="close">Close</a>' + headline + data + '</div>';

                    SharpUSA.Global.BlockUI(data, 489, 500);

                    SharpUSA.UI.Init();
                    $('div#modalcontent a.close').click(function() {
                        $.unblockUI();
                        return false;
                    });
                },
                error: SharpUSA.Global.ErrorModal
            });
            return false;
        });
    },
    PrintPreview: function() {
        // add close and print buttons to print preview screen
        if (SharpUSA.Helpers.IsPrint) {
            $('body').prepend('<div id="print-controls-top"><a href="#" class="close">Close Window</a> <button class="print">Print Page</button></div>');
            $('body').append('<div id="print-controls-bottom"><a href="#" class="close">Close Window</a> <button class="print">Print Page</button></div>');
        }
        $('#print-controls-top a.close,#print-controls-bottom a.close').click(function() {
            if (window.close) {
                window.close();
            }
            else {
                alert('Your browser (or its current settings) does not support this close link. You may need to manually close this browser window or tab.');
            }
            return false;
        });
        $('#print-controls-top button.print,#print-controls-bottom button.print').click(function() {
            if (window.print) {
                window.print();
            }
            else {
                alert('Your browser (or its current settings) does not support print button. You may need to manually print this page.');
            }
            return false;
        });
    },
    SectionNav: function() {
        // accordian

        $('.section-nav > ul.accordian > li:not(.current) > ul').hide();
        SharpUSA.UI.ElementHover($('.section-nav > ul.accordian > li'));

        $('.section-nav > ul.accordian > li:not(.sectionhome)').click(function() {
            var siblingNodes = $(this).siblings('li');
            var thisNode = $(this);

            siblingNodes.removeClass('current');
            thisNode.addClass('current');

            siblingNodes.children('ul').slideUp(100);
            thisNode.children('ul').slideDown(50);
        });

    },
    ErrorModal: function() {
        var errorHeading = 'System Error';
        var errorMessage = 'There was an error with your request. We are sorry for the inconvenience.';
        $.unblockUI({ fadeOut: 0 });
        $.blockUI({
            message: '<div id="error"><h1>' + errorHeading + '</h1><p>' + errorMessage + '</p></div>',
            css: {
                border: 'none'
            },
            applyPlatformOpacityRules: false

        });
        setTimeout($.unblockUI, 3000);
    },
    BlockUI: function(data, width, height) {
        $.blockUI.defaults.css = {};

        var topOffset = (SharpUSA.Helpers.FindTopOffsetInPixels(height) > 0) ? SharpUSA.Helpers.FindTopOffsetInPixels(height) : 0;
        var leftOffset = (SharpUSA.Helpers.FindLeftOffsetInPixels(width) > 0) ? SharpUSA.Helpers.FindLeftOffsetInPixels(width) : 0;
        $.blockUI.defaults.css = {
            left: SharpUSA.Helpers.FindLeftOffsetInPixels(width) + 'px',
            top: topOffset + 'px'
        };


        $.blockUI({
            message: data,
            applyPlatformOpacityRules: false
        });

        var closeLink = $('a.close', 'div.blockUI');
        if (closeLink.exists()) {
            closeLink.unbind('click');
            closeLink.click(function() {
                $.unblockUI();
                return false;
            });
        }
    }
};

SharpUSA.ASPNET = {
    CartFlyoutUpdatePanelId: '',
    CartPageUpdatePanelId: '',
    CartPageRelatedAccessoriesUpdatePanelId: '',
    WishListPageUpdatePanelId: '',
    EmailPageUpdatePanelId: '',
    EmailPageUrlFieldId: '',
    SavePageUpdatePanelId: '',
    MyProductsUpdatePanel: ''
};

SharpUSA.ShoppingCart = {
    PagePath: '/ShoppingCart.aspx',
    CartItems: {},
    CartFlyout: function() {
        var cartList = $('#cartlist');
        cartList.hide();
        $('#cart-nav').hover(
			function() {
			    if ($(this).children().children('span#cartQuantity').text() !== '0') {
			        cartList.show();
			        $(this).addClass('selected');
			    }
			},
			function() {
			    $(this).removeClass('selected');
			    cartList.fadeOut();
			}
		);
    },
    QuantitiesValid: true,
    EventSetup: function() {
        // removing bindings to avoid double binding
        $('a.related-accessories[rel],a.addtocart[rel],a.addtocart-small[rel],a.addtowishlist,a.addtowishlist-small,table.cart a.remove[rel],ul.productlist p.remove > a[rel],table.cart a.updatecart').unbind('click');

        $('a.related-accessories[rel]').click(function() {
            var esto = $(this);
            $('select.relatedaccessories', 'div.accessories').val(esto.attr('rel')).change();
            // set maintain scroll data
            $(document).data('maintainscroll', esto.attr('href'));

            return false;
        });

        $('a.addtocart[rel],a.addtocart-small[rel]').click(function() {
            SharpUSA.ShoppingCart.AddItemToCart($(this).attr('rel'));
            return false;
        });
        $('a.movetocart[rel]').click(function(e) {
            SharpUSA.ShoppingCart.MoveWishListItemToCart($(this).attr('rel'));
            return false;
        });
        $('a.addtowishlist,a.addtowishlist-small').click(function(e) {
            var url = $(this).attr('href');
            var evt = e;
            SharpUSA.ShoppingCart.WishListModal(evt, url);
            return false;
        });

        $('table.cart a.remove[rel]').click(function() {
            SharpUSA.ShoppingCart.RemoveItemFromCart($(this).attr('rel'));
            return false;
        });
        $('ul.productlist p.remove > a[rel]').click(function() {
            SharpUSA.ShoppingCart.RemoveItemFromWishList($(this).attr('rel'));
            return false;
        });

        $('table.cart a.updatecart').click(function() {
            SharpUSA.ShoppingCart.UpdateCartItemsQuantity();
            return false;
        });
        $('table.cart td.quantity input:text').blur(function() {
            var val = $(this).val();
            var digitsRegex = new RegExp(/^\d+$/);
            $(this).next('p.error').remove();

            if (digitsRegex.test(val)) { // OK
                SharpUSA.ShoppingCart.QuantitiesValid = true;
            }
            else { // invalid
                $(this).after('<p class="error">invalid</p>');
                SharpUSA.ShoppingCart.QuantitiesValid = false;
            }
        });
    },
    AddItemToCart: function(productId) {
        var quantity = 0;
        var DTO = { 'productId': productId }; // data transfer obj

        $.ajax({
            type: "POST",
            url: "/PageMethods.aspx/AddItemToCart",
            data: JSON.stringify(DTO),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                SharpUSA.ShoppingCart.UpdateCart(true);
            },
            error: SharpUSA.Global.ErrorModal
        });
    },
    AddItemToWishList: function(productId) {
        var quantity = 0;
        var DTO = { 'productId': productId }; // data transfer obj

        $.ajax({
            type: "POST",
            url: "/PageMethods.aspx/AddItemToWishList",
            data: JSON.stringify(DTO),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                SharpUSA.ShoppingCart.UpdateWishList();
            },
            error: SharpUSA.Global.ErrorModal
        });
    },
    WishListModal: function(e, url) {
        $.ajax({
            url: url,
            cache: false,
            dataType: 'text',
            success: function(data) {
                // get just the addtowishlist div
                startIndex = data.indexOf('<div id="addtowishlist">');
                endIndex = data.indexOf('<!-- end #addtowishlist -->');
                data = data.substring(startIndex, endIndex);

                SharpUSA.Global.BlockUI(data, 397, 210);

                // change original button to "added"
                // only if authenticated and added - look for hidden "success" input
                var success = $(data).find('input:hidden#success').exists();

                if (success) {
                    // update global wish list count
                    SharpUSA.ShoppingCart.UpdateWishList();

                    var target = $(e.target);
                    var isSmallButton = target.parent().is('.addtowishlist-small');
                    var replaceButton = (isSmallButton) ? SharpUSA.AddedToWishListSmallButton : SharpUSA.AddedToWishListButton;
                    target.parent().replaceWith(replaceButton);
                }
                $('div#quickview a.close').click(
					function() {
					    $.unblockUI();
					    return false;
					}
				);

                SharpUSA.UI.Init();
                $('div#addtowishlist a.close').click(function() {
                    $.unblockUI();
                    return false;
                });
            },
            error: SharpUSA.Global.ErrorModal
        });
    },
    RemoveItemFromCart: function(meridianId) {
        var confirmed = confirm('Are you sure you want to remove this item from  your shopping cart?');
        if (confirmed) {
            var quantity = 0;
            var DTO = { 'meridianId': meridianId }; // data transfer obj

            $.ajax({
                type: "POST",
                url: "/PageMethods.aspx/RemoveCartItem",
                data: JSON.stringify(DTO),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    SharpUSA.ShoppingCart.UpdateCart(false);
                },
                error: SharpUSA.Global.ErrorModal
            });
        }
    },
    RemoveItemFromWishList: function(meridianId) {
        var confirmed = confirm('Are you sure you want to remove this item from your wishlist?');
        if (confirmed) {
            var quantity = 0;
            var DTO = { 'meridianId': meridianId }; // data transfer obj

            $.ajax({
                type: "POST",
                url: "/PageMethods.aspx/RemoveWishListItem",
                data: JSON.stringify(DTO),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    SharpUSA.ShoppingCart.UpdateWishList();
                },
                error: SharpUSA.Global.ErrorModal
            });
        }
    },
    MoveWishListItemToCart: function(meridianId) {
        var quantity = 0;
        var DTO = { 'meridianId': meridianId }; // data transfer obj

        $.ajax({
            type: "POST",
            url: "/PageMethods.aspx/MoveWishListItemToCart",
            data: JSON.stringify(DTO),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                SharpUSA.ShoppingCart.UpdateWishList();
                SharpUSA.ShoppingCart.UpdateCart(true);
            },
            error: SharpUSA.Global.ErrorModal
        });
    },
    UpdateCartItemsQuantity: function(meridianId) {
        var IdQty = {};
        meridianId = '';
        var quantity = '';
        $('table.cart tbody tr').each(function() {
            if ($(this).children('td.quantity').exists()) {
                meridianId = $(this).children('td.remove').children('a.remove[rel]').attr('rel');
                quantity = $(this).children('td.quantity').children('input:text').val();

                if (meridianId !== "" && quantity !== "") {
                    IdQty[meridianId] = quantity;
                }
            }
        });

        if (SharpUSA.ShoppingCart.QuantitiesValid) {
            var DTO = { 'cartQtyJson': IdQty }; // data transfer obj

            $.ajax({
                type: "POST",
                url: "/PageMethods.aspx/UpdateCartItems",
                data: JSON.stringify(DTO),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    SharpUSA.ShoppingCart.UpdateCart();
                },
                error: SharpUSA.Global.ErrorModal
            });
        }
    },
    UpdateGlobalCart: function(cartItems) {

        // update the cart quantity and flyout
        var qty = 0;
        var subTotal = 0;
        var flyoutHTML = '';
        jQuery.each(cartItems, function(i, cartItem) {
            qty += cartItem.Quantity;
            subTotal += cartItem.Quantity * cartItem.Price;

            var newLI = SharpTemplates.GetCartFlyoutListItemTemplate();
            newLI = newLI.replace(/{ModelNumber}/g, cartItem.DisplayModelNumber);
            newLI = newLI.replace(/{ModelNumberLinkOrText}/g, cartItem.ModelNumberLinkOrText);
            newLI = newLI.replace(/{ImageUrl}/g, cartItem.Image);
            newLI = newLI.replace(/{Quantity}/g, cartItem.Quantity);
            newLI = newLI.replace(/{Price}/g, SharpUSA.Helpers.FormatCurrency(cartItem.Price * cartItem.Quantity));
            flyoutHTML += newLI;
        });
        jQuery('span#cartQuantity').text(qty);

        // first check for ul.cartitems
        if (!$('ul.cartitems', '#cartlist').exists()) {
            $('div#cartlist p.subtotal').before('<ul class="cartitems"></ul>')
        }

        $('div#cartlist ul.cartitems').html(flyoutHTML);
        $('div#cartlist p.subtotal').text('$' + SharpUSA.Helpers.FormatCurrency(subTotal));

    },
    UpdateCartPageList: function(cartItems) {
        var qty = 0;
        var subTotal = 0;
        var rowsHTML = '';

        if (SharpUSA.ASPNET.CartPageRelatedAccessoriesUpdatePanelId !== "") {
            __doPostBack(SharpUSA.ASPNET.CartPageRelatedAccessoriesUpdatePanelId, '');
        }

        if (cartItems.length > 0) {
            jQuery.each(cartItems, function(i, cartItem) {
                qty += cartItem.Quantity;
                subTotal += cartItem.Price * cartItem.Quantity;

                var newTR = SharpTemplates.GetCartDataRowTemplate();
                newTR = newTR.replace(/{ModelNumber}/g, cartItem.DisplayModelNumber);
                newTR = newTR.replace(/{ModelNumberLinkOrText}/g, cartItem.ModelNumberLinkOrText);
                newTR = newTR.replace(/{ImageUrl}/g, cartItem.Image);
                var features = '';
                if (cartItem.FeatureHighlights !== null && cartItem.FeatureHighlights.length > 0) {
                    features += '<ul class="features">';
                    jQuery.each(cartItem.FeatureHighlights, function(j, feature) {
                        features += '<li>' + feature.FeatureContent + '</li>';
                    });
                    features += '</ul>';
                }
                newTR = newTR.replace(/{FeatureHighlights}/g, features);

                var dateAdded = new Date(parseInt(cartItem.DateAdded, 10));
                formattedDate = SharpUSA.Helpers.FormatDate(dateAdded);

                newTR = newTR.replace(/{DateAdded}/g, formattedDate);
                newTR = newTR.replace(/{Quantity}/g, cartItem.Quantity);
                newTR = newTR.replace(/{Price}/g, SharpUSA.Helpers.FormatCurrency(cartItem.Price));
                newTR = newTR.replace(/{SubTotal}/g, SharpUSA.Helpers.FormatCurrency(cartItem.Price * cartItem.Quantity));
                newTR = newTR.replace(/{MeridianId}/g, cartItem.MeridianItemId);
                rowsHTML += newTR;
            });
            jQuery('table.cart tbody tr:has(td.details)').remove();
            jQuery('table.cart tbody').prepend(rowsHTML);
            jQuery('table.cart tfoot span.subtotal').text('$' + SharpUSA.Helpers.FormatCurrency(subTotal));
        }
        else {
            jQuery('table.cart, div.shoporcheckout:not(:first),div.shoporcheckout:first a.proceedtocheckout').remove();
        }
        var itemNumberText = (qty == 1) ? '1 item' : qty + ' items';
        jQuery('span.cartitemcount').text(itemNumberText);
    },
    UpdateCart: function(redirect) {
        $.ajax({
            type: "POST",
            url: "/PageMethods.aspx/GetCartItems",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            dataFilter: function(data, type) {
                //return data.replace(/\"\\\/(Date\([0-9-]+\))\\\/\"/gi, 'new $1');
                var cleanData = data.replace(/\\\\\/Date\(([0-9-]+)\)\\\\\//gi, '$1');
                return cleanData;
            },
            success: function(msg) {
                if (redirect && window.location.pathname != SharpUSA.ShoppingCart.PagePath) {
                    window.location.href = SharpUSA.ShoppingCart.PagePath;
                }
                else {
                    var cartItems = JSON.parse(msg.d);
                    SharpUSA.ShoppingCart.UpdateGlobalCart(cartItems);
                    SharpUSA.ShoppingCart.UpdateCartPageList(cartItems);
                    SharpUSA.ShoppingCart.EventSetup();
                    SharpUSA.ProductCategory.QuickView();
                }
            },
            error: SharpUSA.Global.ErrorModal
        });
    },
    UpdateWishList: function() {
        SharpUSA.ShoppingCart.UpdateGlobalWishList();
        if ($('#' + SharpUSA.ASPNET.WishListPageUpdatePanelId).exists()) {
            __doPostBack(SharpUSA.ASPNET.WishListPageUpdatePanelId, '');
        }
    },
    UpdateGlobalWishList: function() {
        $.ajax({
            type: "POST",
            url: "/PageMethods.aspx/GetWishListQuantity",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $('span#wishListQuantity').text(msg.d);
            },
            error: SharpUSA.Global.ErrorModal
        });
    }
};

SharpUSA.Flash = {
    SwfPlayerVersion: '9.0',
    SifrPlayerVersion: '6.0',
    HomeFlash: {
        data: '/Multimedia/Home/SharpHome.swf?xmlPath=homepageflash.aspx?JustXML=true',
        //data:'/Multimedia/Home/SharpHome.swf?xmlPath=Handlers/SharpXML.xml',
        width: 955,
        height: 370,
        bgColor: '#FFFFFF'
    },
    LcdFlash: {
        data: '/Multimedia/Flash/LCD-landing.swf',
        width: 955,
        height: 430,
        bgColor: '#FFFFFF'
    },
    MfpVideo: {
        data: '/Multimedia/Flash/videoplayer.swf?flvPath=~/media/Videos/Frontier_TV_Spot.ashx',
        width: 500,
        height: 600,
        bgColor: '#FFFFFF'
    },
    SharpDirectBanner: {
        data: '/Multimedia/Flash/SharpDirect/sharp-direct-banner.swf',
        width: 713,
        height: 200,
        bgColor: '#FFFFFF'
    },
    HowSolarWorksFlash: {
        data: '/Multimedia/Flash/solar_web450x321_3.swf',
        width: 450,
        height: 321,
        bgColor: '#FFFFFF'
    },
    SharedFlashParams: {
        wmode: 'transparent',
        scale: 'noscale'
    },
    WriteSWF: function(FlashObject, FlashParams, htmlId) {
        if (swfobject.hasFlashPlayerVersion(SharpUSA.Flash.SwfPlayerVersion)) {
            swfobject.createSWF(FlashObject, FlashParams, htmlId);
        }
    }
};
SharpUSA.Flash.Video = {
    OpenVideoModal: function(pathToVideo, videoWidth, videoHeight) {
        // launch modal video
        var data = '<div id="flashplayer"></div>';
        var path = pathToVideo;

        // handle media library assets, hich start with "~/"
        if (path.indexOf('~/') === 0) {
            path = '/' + path;
        }
        SharpUSA.Global.BlockUI(data, videoWidth, videoHeight);

        //write flash
        theVideo = {
            data: '/Multimedia/Flash/videoplayer.swf?flvPath=' + path,
            width: videoWidth,
            height: videoHeight,
            bgColor: 'transparent'
        };

        SharpUSA.Flash.WriteSWF(theVideo, SharpUSA.Flash.SharedFlashParams, 'flashplayer');
    },
    InitVideoPlayerLinks: function() {
        $('a[rel^="video"]').each(function(index) {
            $(this).unbind('click');
            $(this).click(function() {
                var pathToVideo = $(this).attr('href');
                var videoWidth = $(this).attr('videoWidth');
                var videoHeight = $(this).attr('videoHeight');
                if (pathToVideo !== "" && videoHeight !== "" && videoWidth !== "") {
                    SharpUSA.Flash.Video.OpenVideoModal(pathToVideo, videoWidth, videoHeight);
                    if (pageTracker)
                        pageTracker._trackPageview(pathToVideo);
                    return false;
                }
            });
        });
    },
    Close: function() {
        $.unblockUI();
    }
};

SharpUSA.IFrame = {
    InitIFrames: function() {
        $(".iframe").each(function(index) {
            var id = $(this).attr('iid');
            var src = $(this).attr('src');
            var width = $(this).attr('width');
            var height = $(this).attr('height');
            var iframe = '<IFRAME id="' + id + '" src="' + src + '" width="' + width + '" height="' + height + '" frameborder="0" />';
            $(this).replaceWith(iframe);
        });
    }
};

//function callIframe(url, callback) {
//    $(document.body).append('<IFRAME id="myId" ...>');
//    $('iframe#myId').attr('src', url);
//    $('iframe#myId').load(function() {
//        callback(this);
//    });
//}

SharpUSA.WebTracking = {};
SharpUSA.WebTracking.Omniture = {
    TrackHPNav: function(name) {
        if (typeof s !== 'undefined') {
            var trackingString = 'HP Flash: ' + name;
            s.linkTrackVars = 'prop22';
            s.prop22 = trackingString;
            s.tl(true, 'o', trackingString);
        }
    },
    TrackHPButton: function(panelIndex, panelName, buttonLabel) {
        if (typeof s !== 'undefined') {
            if (buttonLabel == "Learn More") {
                s.linkTrackVars = 'prop20,eVar20,events';
                s.linkTrackEvents = 'event20';
                s.prop20 = 'Entrance ' + panelIndex + ': ' + panelName;
                s.eVar20 = 'Entrance ' + panelIndex + ': ' + panelName;
                s.events = 'event20';
            }
            else if (buttonLabel == "View Products") {
                s.linkTrackVars = 'prop21,eVar21,events';
                s.linkTrackEvents = 'event21';
                s.prop21 = 'Entrance ' + panelIndex + ': ' + panelName;
                s.eVar21 = 'Entrance ' + panelIndex + ': ' + panelName;
                s.events = 'event21';
            }
            s.tl(true, 'o', 'HP:' + buttonLabel + ' Click:Entrance' + panelIndex);
        }
    },
    TrackHPVideo: function(name) {
        if (typeof s !== 'undefined') {
            var trackingString = 'HP Video: ' + name;
            s.linkTrackVars = 'prop23,eVar23,events';
            s.linkTrackEvents = 'event23';
            s.prop23 = trackingString;
            s.eVar23 = trackingString;
            s.events = 'event23';
            s.tl(true, 'o', trackingString);
        }
    },
    DownloadTrackingEnum: {
        ProductDetail: 0,
        CustomerSupport: 1,
        MySharp: 2,
        Solar: 3
    },
    TrackDownloads: function(linkObj, downloadPage) {
        if (typeof s !== 'undefined') {

            var trackingCode = linkObj.innerHTML + ':' + s.pageName;
            if (downloadPage == SharpUSA.WebTracking.Omniture.DownloadTrackingEnum.ProductDetail) {
                s.linkTrackVars = 'prop27,eVar27,events';
                s.linkTrackEvents = 'event27';
                s.prop27 = trackingCode;
                s.eVar27 = trackingCode;
                s.events = 'event27';
            }
            else if (downloadPage == SharpUSA.WebTracking.Omniture.DownloadTrackingEnum.CustomerSupport) {
                s.linkTrackVars = 'prop28,eVar28,events';
                s.linkTrackEvents = 'event28';
                s.prop28 = trackingCode;
                s.eVar28 = trackingCode;
                s.events = 'event28';
            }
            else if (downloadPage == SharpUSA.WebTracking.Omniture.DownloadTrackingEnum.MySharp) {
                s.linkTrackVars = 'prop29,eVar29,events';
                s.linkTrackEvents = 'event29';
                s.prop29 = trackingCode;
                s.eVar29 = trackingCode;
                s.events = 'event29';
            }
            else if (downloadPage == SharpUSA.WebTracking.Omniture.DownloadTrackingEnum.Solar) {
                s.linkTrackVars = 'prop30,eVar30,events';
                s.linkTrackEvents = 'event30';
                s.prop30 = trackingCode;
                s.eVar30 = trackingCode;
                s.events = 'event30';
            }
            var lt = (linkObj.href != null) ? s.lt(linkObj.href) : "";
            if (lt == "") {
                s.tl(linkObj, 'd', linkObj.innerHTML);
            }
        }
    }
};

SharpUSA.Helpers = {
    FindLeftOffsetInPixels: function(elWidth) {
        return (jQuery(window).width() - elWidth) / 2;
    },
    FindTopOffsetInPixels: function(elHeight) {
        return (jQuery(window).height() - elHeight) / 2;
    },
    GetFlashPath: function() {
        return SharpUSA.BaseUrl + '/Multimedia/Flash/';
    },
    IsPrint: (location.search.indexOf('print=true') > -1),
    FormatDate: function(dateObj) {
        var formattedDate = '';

        // month
        var month = dateObj.getMonth();
        month++;
        month = (month < 10) ? '0' + month : month;

        // day
        var day = dateObj.getDate();
        day = (day < 10) ? '0' + day : day;

        // year
        var year = dateObj.getFullYear();

        formattedDate = month + '/' + day + '/' + year;

        return formattedDate;
    },
    FormatCurrency: function(number) {
        var returnValue = number;
        if (isNaN(number)) {
            returnValue = 0.00;
        }
        else if (number.toFixed) {
            returnValue = number.toFixed(2);
        }
        return returnValue;
    }
};

// jQuery extensions
// create a reusable collapse/expand module that slides open and closed
jQuery.fn.ExpandingSlider = function(isOpen) {
    isOpen = (typeof isOpen == "undefined") ? true : Boolean(isOpen);
    // init plusMinus image
    var plusMinusImageFile = (isOpen) ? 'bullet-bracketed-minus.gif' : 'bullet-bracketed-plus.gif';
    var plusMinusImage = ' <img src="' + SharpUSA.BaseUrl + '/images/' + plusMinusImageFile + '" width="14" height="9" alt="" class="plusminus" />';
    $(this).append(plusMinusImage);
    var src = $(this).children('img.plusminus').attr('src');

    // hide the element if should start closed
    if (!isOpen) { $(this).next().hide(); }

    if (isOpen) {
        this.toggle(
			function(e) { SlideUp($(this), e); },
			function(e) { SlideDown($(this), e); }
		);
    }
    else {
        this.toggle(
			function(e) { SlideDown($(this), e); },
			function(e) { SlideUp($(this), e); }
		);
    }

    var SlideDown = function(jEls, evt) {
        if ($(evt.target).is('a')) {
            window.location = evt.target.href;
        }
        else {
            jEls.children('img.plusminus').attr('src', src.replace('plus', 'minus'));
            jEls.next().slideDown('normal');
            SharpUSA.FacetNavIsOpen = true;
        }

    };
    var SlideUp = function(jEls, evt) {
        if ($(evt.target).is('a')) {
            window.location = evt.target.href;
        }
        else {
            jEls.children('img.plusminus').attr('src', src.replace('minus', 'plus'));
            jEls.next().slideUp('normal');
            SharpUSA.FacetNavIsOpen = false;
        }
    };
};
jQuery.fn.ColorFlash = function(startColor, endColor, duration) {
    // set defaults
    startColor = (typeof startColor == 'undefined') ? '#FFFCAC' : startColor;
    endColor = (typeof endColor == 'undefined') ? '#FFFFFF' : endColor;
    duration = (typeof duration == 'undefined') ? 1000 : duration;

    this.css('backgroundColor', startColor);
    this.animate({ backgroundColor: endColor }, duration);

};
jQuery.fn.exists = function() {
    return (this.size() > 0);
};
// end jQuery extensions

})(jQuery);


//These methods handle multiple asynchronous .NET requests
//by maintaining a queue to hold subsequent requests

// initialize the queue
var asyncRequestQueue = [];

function CompleteRequest(sender, args){
	if(asyncRequestQueue.length > 0){
        var control = $get(asyncRequestQueue[0]);
        setTimeout('__doPostBack(\'' + control.id + '\',\'\')', 0);
        Array.removeAt(asyncRequestQueue, 0);
    }
}
function InitializeRequest(sender, args){
	if(typeof Sys !== 'undefined'){
		var prm = Sys.WebForms.PageRequestManager.getInstance();
		if (prm.get_isInAsyncPostBack())
		{   // If it's working on another request, cache the current item that cause the request
			args.set_cancel(true);
			a = args;
			Array.add(asyncRequestQueue, args.get_postBackElement().id);
		}
    }
}

// Check order status
function CheckOrderStatus (){
    var orderNumber = jQuery("#orderNumber").val();
    var orderStatusURL = 'http://www.sharp-cart.com/ecom/order_tracking.htm?purchaseOrder=' + orderNumber;
    window.open(orderStatusURL,'Sharp Order Status','scrollbars=yes,width=600,height=400');
}