﻿
/// <reference path="jquery-1.4.1.js"/>

/**********************************************
                       NOTE
jQuery and Prototype are both used on this
site, and in order to eliminate conflicts, all
jQuery chains must start with $j instead of
just $.
**********************************************/

var $j = jQuery.noConflict();
//var $ = ($) ? $ : null; // fix for VS auto-complete to $j all the time

var addthis_config = {
	username: 'hearth'
};

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}


	
// check for specific postback buttons
function ajaxUpdateIncludesTrigger(sender, trigger_id) {
    if (typeof(trigger_id) == "string") trigger_id = [trigger_id];
    var resp = false;
    if (sender && sender._asyncPostBackControlIDs) {
        sender._asyncPostBackControlIDs.each(function(id, i) {
            if (trigger_id.indexOf(id.split("$").last()) >= 0) resp = true;
        });
    }
    if (resp == false && sender && sender._postBackSettings && sender._postBackSettings.panelID) {
        if (trigger_id.indexOf(sender._postBackSettings.panelID.split("$").last()) >= 0) resp = true;
    }
    return resp;
}

//$j(document).ready(function() {
//    checkResolution();
//});


function ShowViewState() {
    // Determine view state size
    var viewStateField = $j("input[id=__VIEWSTATE][type=hidden]");
    if (viewStateField != null) {
        var viewStateLength = viewStateField.val().length;
        var msg = "Viewstate: " + viewStateLength + " bytes";
        $j("#viewstateInfo p:first").text(msg);          
        $j("#viewstateInfo").show();    
    }
}



//function checkResolution() {     
//    var width = screen.width;
//    var height = screen.height;
//    if (width < 1024 || height < 768) {
//       $j("#resolutionWarning").show(); 
//    }
//}

function traceFlash() {
    if (typeof(console) != "undefined") console.log.apply(console, arguments);
}

function ValidateName(nameToValidate) {
	regularExpression = RegExp(/^[\w\*][\w\s\-\.]*$/);

	return regularExpression.test(nameToValidate);
}

function GetSiteImageDirectory() {
	if (window.location.href.indexOf('fireplaces') >= 0) {
		return '/images/FPL/';
	}
	else if (window.location.href.indexOf('heatnglo') >= 0) {
		return '/images/HNG/';
	}
	else if (window.location.href.indexOf('quadrafire') >= 0) {
		return '/images/QDF/';
	}
	else if (window.location.href.indexOf('fireside') >= 0) {
		return '/images/FSD/';
	}
	else if (window.location.href.indexOf('harman') >= 0) {
		return '/images/HAR/';
	}
	else if (window.location.href.indexOf('heatilator') >= 0) {
		return '/images/HTL/';
	}
	else {
		return '/images/FPL/';
	}
}

function GetCurrentSite() {
    if (window.location.href.indexOf('fireplaces') >= 0) {
        return 'fireplaces';
    }
    else if (window.location.href.indexOf('heatnglo') >= 0) {
        return 'heatnglo';
    }
    else if (window.location.href.indexOf('quadrafire') >= 0) {
        return 'quadrafire';
    }
    else if (window.location.href.indexOf('fireside') >= 0) {
        return 'fireside';
    }
    else if (window.location.href.indexOf('harman') >= 0) {
        return 'harman';
    }
    else if (window.location.href.indexOf('heatilator') >= 0) {
        return 'heatilator';
    }
    else {
        return 'fireplaces';
    }
}

function imposeMaxLength(Event, Object, MaxLen) {
	return (Object.value.length <= MaxLen) || (Event.keyCode == 8 || Event.keyCode == 46 || (Event.keyCode >= 35 && Event.keyCode <= 40));
}

function specsMatchHeights(padding) {
	Event.observe(document, "dom:loaded", function() {
		//console.log('specsMatchHeights ran');
		// match row heights in the specifications tab on product details
		var t = $$(".specs_three_col DIV.matchHeight");
		var heights = 0;
		t.each(function(ul, i) {
			//console.log('in t.each');
			heights = Math.max(heights || 0, ul.getHeight());
		});
		t.each(function(ul, i) {
			//console.log('Padding: ' + padding[i]);
			ul.setStyle({ height: heights - padding[i] + "px" });
		});
	});
}

var WaitPopup = {
    isShown: false,
    elm: null,
    show: function() {
        if (this.isShown) return;
        this.elm = new Element("div");
        this.elm.setStyle({ position: 'fixed', top: '0px', left: '0px', width: '100%', zIndex: 30000 });
        this.elm.insert('<div style="margin:200px auto;width: 100px; height: 75px; background: url(/images/FPL/loading_bg.png) no-repeat;"><img src="/images/FPL/loading_anim.gif" width="16" height="16" style="margin-top:27px" /></div>');
        $(document.body).insert(this.elm);
        this.isShown = true;
    },
    hide: function() {
        if (this.isShown) {
            this.elm.remove();
            this.elm = null;
            this.isShown = false;
        }
    }
   };

   var GenericMessagePopup = {
   	show: function(title, message, textColor, textClass) {
   		var titleControl = $j("[id$='ltlTitle']").get(0);
   		if ($j(titleControl.id)) {
   			$j("[id$='ltlTitle']").text(title);
   		}
   		else {
   			console.log('Didn\'t find title.');
   		}
   		var messageControl = $j("[id$='ltlMessage']").get(0);
   		if ($j(messageControl.id)) {
   			$j("[id$='ltlMessage']").text(message);
   			if (textColor != '') {
   				$j("[id$='ltlMessage']").css('color', textColor);
   			}
   			if (textClass != '') {
   				$j("[id$='ltlMessage']").addClass(textClass);
   			}
   		}
   		else {
   			console.log('Didn\'t find message.');
   		}
   		$j('#GenericMessageBoxDiv').toggle();
   	}
   };

   var MediaPopup = {
       ImageList: null,
       CurrentImage: null,
       ImageField: null,
       VideoField: null,
       CameFrom: null,
       DescriptionField: null,
       ThumbnailField: null,
       buttonId: null,
       popupId: "MediaPopupDiv",
       wire: function(p_ImageList, p_CurrentImage, p_ImageField, p_VideoField, p_DescriptionField, p_CameFrom, p_btn, p_ThumbnailField) {
           this.ImageList = p_ImageList;
           this.CurrentImage = p_CurrentImage;
           this.ImageField = p_ImageField;
           this.VideoField = p_VideoField;
           this.DescriptionField = p_DescriptionField;
           this.CameFrom = p_CameFrom;
           this.buttonId = p_btn;
           this.ThumbnailField = p_ThumbnailField
           // add an event listener on MS' Ajax code
           Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.onAfterUpdate.bind(this));
       },
       show: function(inImageList, inCurrentImage, inImageField, inVideoField, inDescriptionField, inCameFrom, inThumbnailField) {
           $(this.ImageList).value = inImageList;
           $(this.CurrentImage).value = inCurrentImage;
           $(this.ImageField).value = inImageField;
           $(this.VideoField).value = inVideoField;
           $(this.DescriptionField).value = inDescriptionField;
           $(this.CameFrom).value = inCameFrom;
           $(this.ThumbnailField).value = inThumbnailField;
           //console.info("__doPostBack('" + this.buttonId + "','')");
           __doPostBack(this.buttonId, '');

           $(this.popupId).show();
       },
       showUpdated: function(inCurrentImage) {
           $(this.CurrentImage).value = inCurrentImage;
           //console.info("__doPostBack('" + this.buttonId + "','')");
           __doPostBack(this.buttonId, '');
           $(this.popupId).show();
       },
       onAfterUpdate: function(sender, args) {
           if (ajaxUpdateIncludesTrigger(sender, ["ImageUpdateButton"])) {

           }
       },
       hidePopup: function() {
           $(this.popupId).hide();
       }
   };

var VisualStateManager = Class.create();
VisualStateManager.prototype = {
    hideArgs: null,
    initialize: function(obj, context) {
        this.fShow = obj.show; this.fHide = obj.hide; this.nTimer = obj.timer;
        this.context = (context != null) ? context : this;
        this.showHideDiv = (obj.showHideDiv == true);
        this.zIndexFix = (obj.zIndexFix == true);
        // parameters (in obj) = show:Function for onShow, hide:Function for onHide, timer:int milliseconds before hiding, showHideDiv:Boolean manage show/hide div
        /* if showHideDiv, expects:
        * obj.show(o_src, p_id) where o_src is the event trigger, and p_id is the ID of the DIV to show/hide
        * the calling element (o_src) to call [VSM instance].show(this,'id') and [VSM instance].hide() methods (i'll wire up the div though)
        */
    },
    show: function() {
        this.clearTimer();
        if (this._showDivPre.apply(this, arguments)) {
            if (this.zIndexFix && this.currentSrc) {
				this.currentSrc.setStyle({ zIndex: 101 });
				var shell = this.currentSrc.up(".toolbox_shell");
				if (shell) shell.setStyle({zIndex: 101 });
			}
            if (typeof (this.fShow) == "function") this.fShow.apply(this.context, arguments);
            this._showDivPost.apply(this, arguments);
        }
    },
    _showDivPre: function() { // returns true if the provided "show" function should be called (this.fShow)
        var bShow = true;
        if (this.showHideDiv) {
            var o_src = $(arguments[0]), p_id = arguments[1];
            var div = $(p_id);
            if (div) {
                if (this.current && this.current != div) this.hideNow();
                if (this.current && this.current == div) bShow = false; // already showing the current one
                this.current = div;
                this.currentSrc = o_src;
                // setup listeners on the popup div
                if (!div.isFeaturedSetup) {
                    div.isFeaturedSetup = true;
                    Event.observe(div, "mouseover", this.show.bind(this));
                    Event.observe(div, "mouseout", this.hide.bind(this));
                }
            } else {
                bShow = false; // being called from an event listener that we created (no parameters) so it must be showing already
            }
        }
        return bShow;
    },
    _showDivPost: function() {
        if (this.showHideDiv) {
            var div = $(arguments[1]);
            if (div) div.show();
        }
    },
    hide: function() {
        this.hideArgs = arguments;
        this.clearTimer();
        this.t = setTimeout(this.hideNow.bind(this), this.nTimer);
    },
    hideNow: function() {
        this.clearTimer();
        if (this.zIndexFix && this.currentSrc) {
			this.currentSrc.setStyle({ zIndex: 0 });
			var shell = this.currentSrc.up(".toolbox_shell");
			if (shell) shell.setStyle({ zIndex: 9 });
		}
        if (this.showHideDiv) {
            if (this.current) this.current.hide();
            this.current = null;
            this.currentSrc = null;
        }
        if (typeof (this.fHide) == "function") this.fHide.apply(this.context, this.hideArgs || []);
    },
    clearTimer: function() {
        if (this.t >= 0) clearTimeout(this.t);
        this.t = -1;
    }
};

var MSRPHover = new VisualStateManager({ timer: 800, showHideDiv: true, zIndexFix: true });
var ToolTip = new VisualStateManager({ timer: 800, showHideDiv:true });
var ActionsMenu = new VisualStateManager({ timer: 400, showHideDiv: true, zIndexFix: true });
var FeaturedEditor = new VisualStateManager({
    timer: 400,
    showHideDiv: true, // shows and hides the div automatically, just need to position horizontally
    show: function(o_src, p_id) {
        var div = $(p_id);
        if (!div) return;
        // position horizontally
        var pos = $(o_src).positionedOffset();
        var posRel = o_src.up("UL").positionedOffset();
        var offset = 400;
        div.setStyle({ left: (pos.left + posRel.left + offset) + "px" });
    }
});

TopNav = {
    menus: {
        products: "#ddm_products_top, #ddm_products_mid, #ddm_products_btm",
        selectiontools: "#ddm_selectiontools_top, #ddm_selectiontools_mid, #ddm_selectiontools_btm",
        dealer: "#ddm_findadealer_top, #ddm_findadealer_mid, #ddm_findadealer_btm",
        myaccount: "#ddm_myaccount_top, #ddm_myaccount_mid, #ddm_myaccount_btm",
        customercare: "#ddm_customercare_top, #ddm_customercare_mid, #ddm_customercare_btm",
        resources: "#ddm_resources_top, #ddm_resources_mid, #ddm_resources_btm",
        inspiration: "#ddm_inspiration_top, #ddm_inspiration_mid, #ddm_inspiration_btm"
    },
    open: null,
    noTimout: false,
    timer: -1,
    wired: {},
    wireTopNav: function(src, key) {

        //alert(src + "::::" + key);
        // store a reference to the wired menu trigger (once)
        if (this.wired[key] == undefined) {
            this.wired[key] = src;
            // set up local scoped functions to retain the key
            var f_over = function() { TopNav.over(key) };
            var f_out = function() { TopNav.out(key) };
            // add mouseover and mouseout event listeners

            //note: the next line was commented out and was allowing menus to stay dropped if the
            //cursor never actually entered the drop-down; just stayed in the parent. Does this cause problems on non-fireside sites?
            $j(src).hover(f_over, f_out);

            if (this.menus[key] != undefined)
                $j(this.menus[key]).hover(f_over, f_out);
        }
        this.over(key);
    },
    over: function(key) {
        TopNav.cancel();
        TopNav.close();
        TopNav.open = $j(TopNav.menus[key]).css("display", "block");
    },
    out: function() {
        if (!this.noTimout) {
            TopNav.cancel();
            TopNav.timer = window.setTimeout(TopNav.close, 600);
        }
    },
    close: function() {
        if (TopNav.open) TopNav.open.css("display", "none");
        TopNav.open = null;
    },
    cancel: function() {
        if (TopNav.timer >= 0) window.clearTimeout(TopNav.timer);
        TopNav.timer = -1;
    },
    disableTimeout: function(val) {
        //alert(val);
        this.noTimout = val;
    },
    toggleTimeout: function() {
        //alert(val);
        this.noTimout = !this.noTimout;
    }
};
//$j(document).ready(TopNav.startup());

var ProductFiltering = {
    getSubProductInfo: function() {
        //var value = p_select.options[p_select.selectedIndex].value;                
        ProductFiltering.enableFormPart(function(paramsObj) {
            //var div = $('div' + $("cboOptions").selectedIndex);
            //var checks = div.select('input[type=checkbox]');
            //var guids = [];
            //for (var i = 0; i < checks.length; i++) if (checks[i].checked) guids.push(checks[i].value);
            //if (guids.length == checks.length) guids = [];
            //paramsObj.SubProductType = (guids.length > 0) ? guids : null;

            var div = $('divUnitType' + $("cboOptions").selectedIndex);
            var checks = div.select('input[type=checkbox]');
            var guids = [];
            for (var i = 0; i < checks.length; i++) if (checks[i].checked) guids.push(checks[i].value);
            if (guids.length == checks.length) guids = [];
            paramsObj.UnitType = (guids.length > 0) ? guids : null;

            div = $('divCategoryType' + $("cboOptions").selectedIndex);
            checks = div.select('input[type=checkbox]');
            guids = [];
            for (var i = 0; i < checks.length; i++) if (checks[i].checked) guids.push(checks[i].value);
            if (guids.length == checks.length) guids = [];
            paramsObj.CategoryType = (guids.length > 0) ? guids : null;

            //2 lines removed 11/29/10 to correct Product Finder (unused Product Width was overriding Width)
            //var selects = div.select('select');
            //paramsObj.Width = (selects.length > 0) ? selects[0].options[selects[0].selectedIndex].value : "";
        });
    },
    prestart: function() {
        if (!$("my_container")) return;
        WaitPopup.show();
    },
    startup: function() { // initial load
        if (!$("my_container")) return;
        Event.observe(window, "resize", this.onResize.bind(this));
        $$("#my_container>DIV").each(function(elm, i) {
            elm.setStyle({ position: 'absolute', zIndex: 10 });
        });
        this.exploreSpace();
        // get initial products list
        this.filter();
    },
    onResize: function() {
        var lastCols = this.cols;
        this.exploreSpace();
        if (this.cols == lastCols) return;
        //console.log("onResize passed, changing from ", lastCols, " to ", this.cols);
        var showCount = 0;
        $$("#my_container>DIV").each(function(elm, i) {
            if (elm.visible()) {
                // just move, animating while resizing is very jumpy
                elm.setStyle({ top: Math.floor(showCount / this.cols) * this.size.height + "px", left: (showCount % this.cols) * this.size.width + "px" });
                showCount++;
            }
        } .bind(this));
    },
    loadProducts: function() {
        //var value = p_select.options[p_select.selectedIndex].value;
        this.filter();
    },
    exploreSpace: function() { // find out how much space we have to move the images
        // ie7 width hack
        /*if (CompareBar.instance.brandedSite && navigator.userAgent.indexOf('MSIE 7.')) {
        var w = document.viewport.getWidth() - 300; // left and right edging (incl. left nav)
        $j(".products").css({width:w+"px"}); // may not be on all sites (e.g. not on fp)
        this.hspace = w-24; // scrollbar
        } else {
        // image box = 173x130
        this.hspace = $("my_container").getWidth();
        }*/
        this.hspace = $("my_container").getWidth();

        this.size = { width: 173, height: 170 };
        this.cols = Math.max(1, Math.floor(this.hspace / this.size.width));
        //console.log("hspace=", this.hspace, " cols=", this.cols);
    },
    filterTimer: -1,
    filter: function() {
        WaitPopup.show();
        if (this.filterTimer >= 0) clearTimeout(this.filterTimer);
        this.filterTimer = setTimeout(this.filterGo.bind(this), 200);
    },
    filterGo: function() {
        this.filterTimer = -1;
        var filterParms = {
            Keyword: "",
            ProductType: "",
            SubProductType: [],
            Width: "",
            DecorStyle: "",
            FuelType: [],
            MaxHeatOutput: "0",
            MinHeatOutput: "0",
            Brands: [],
            MSRPMaxNumber: "0",
            MSRPMinNumber: "0",
            RoomSettings: "",
            CategoryType: [],
            UnitType: []
        };
        this.formParts.each(function(f) {
            f(filterParms);
        });
        // debug output
        //this.getSubProductInfo();
        //var t="";for (var a in filterParms) t += a + ":" + filterParms[a] + "\n";alert(t);
        //HHTSitecore.services.ProductFinder.Filter("", null, "", "", null, null, null, null, filterParms.RoomSettings,this.fSuccess.bind(this), this.fFail.bind(this), null);
        filterParms.HeatOutput = [filterParms.MinHeatOutput, filterParms.MaxHeatOutput];
        filterParms.MSRPNumber = [filterParms.MSRPMinNumber, filterParms.MSRPMaxNumber];
        (["HeatOutput", "MSRPNumber", "SubProductType", "FuelType", "Brands", "CategoryType", "UnitType"]).each(function(key) {
            if (!(filterParms[key] instanceof Array)) filterParms[key] = [];
        });
        (["HeatOutput", "MSRPNumber"]).each(function(key) {
            var n = $A(filterParms[key]).max();
            if (isNaN(n) || n == 0) filterParms[key] = [];
        });
        //filterParms.SubProductType = (filterParms.SubProductType.length > 0) ? filterParms.SubProductType : null;
        //        alert("filterParms.SubProductType: " + filterParms.SubProductType);
        //        alert("filterParms.CategoryType: " + filterParms.CategoryType);
        //        alert("filterParms.UnitType: " + filterParms.UnitType);
        HHTSitecore.services.ProductFinder.Filter(filterParms.Keyword, filterParms.ProductType, filterParms.SubProductType, filterParms.Width, filterParms.DecorStyle, filterParms.FuelType, filterParms.HeatOutput, filterParms.Brands, filterParms.MSRPNumber, filterParms.RoomSettings, filterParms.CategoryType, filterParms.UnitType, this.fSuccess.bind(this), this.fFail.bind(this), null);
    },
    formParts: [],
    enableFormPart: function(f_code) {
        this.formParts.push(f_code);
    },
    formDivs: [],
    enableFormDivs: function(divId) {
        this.formDivs.push(divId);
    },
    fSuccess: function(result, context) {
        //alert(context.enableFormPart);
        //alert(result.length);
        var showCount = 0;
        $$("#my_container>DIV").each(function(elm) {
            if (result.indexOf(elm.id) >= 0) {
                //console.log("showing image:", elm, this.cols, this.size);
                //elm.setStyle({ top: Math.floor(showCount / this.cols) * this.size.height + "px", left: (showCount % this.cols) * this.size.width + "px" });
                new Effect.Move(elm, { duration: 1.0, mode: 'absolute', y: Math.floor(showCount / this.cols) * this.size.height, x: (showCount % this.cols) * this.size.width });
                if (!elm.visible())
                    new Effect.Appear(elm, { duration: 0.5 });
                //elm.show();
                showCount++;
            } else {
                if (elm.visible())
                    new Effect.Fade(elm, { duration: 0.5 });
                //elm.hide();
            }
        } .bind(this));
        //$("lblResult").update(result.length);
        $("lblResult").update(showCount);
        //console.log("my_container height ", this.size.height, result.length, this.cols);
        $("my_container").setStyle({ height: (this.size.height * Math.ceil(result.length / this.cols)) + "px" });
        //new Effect.Morph("my_container", { height: (this.size.height * Math.max(result.length / this.cols)) + "px" });
        WaitPopup.hide();
    },
    fFail: function(result, context) {
        WaitPopup.hide();
        alert("Unable to load the filter results from the server. Please try refreshing your browser window.");
        if (typeof (console) != "undefined")
            console.info("fFail", arguments);
    },
    updateIntro: function(text) {
        HHTSitecore.services.ProductFinder.UpdateIntro(text, this.iSuccess.bind(this), null);
    },
    iSuccess: function(result) {
        $("lblIntro").update(result.intro);
        $("lblIntroTitle").update(result.title);
    },
    enableFuelType: function() {
        //hide fuel type if product type is Stoves, Fireplaces, Inserts
        var opt = $("cboOptions");
        if (opt) {
            var text = $("cboOptions").options[$("cboOptions").selectedIndex].text;
            if (text.toLowerCase() == "stoves" || text.toLowerCase() == "fireplaces" || text.toLowerCase() == "inserts") {
                $("cblFuelTypes").setStyle({ display: "none" })
            }
            else {
                $("cblFuelTypes").setStyle({ display: "block" })
            }
            //alert($("cboOptions").selectedIndex);
            var unitDiv = $("divUnitType" + $("cboOptions").selectedIndex);
            unitDiv.setStyle({ display: "block" })
        }
    }
}
Event.observe(document, "dom:loaded", function() { ProductFiltering.prestart() }); // just to start up the loading animation
Event.observe(window, "load", function() { ProductFiltering.startup(); });  // has to run after CompareBar.instance now (dependency)
Event.observe(document, "dom:loaded", function() {
    var intro = $("lblIntro");
    if (intro) {
        var qs = window.location.search.replace('?', '');
        var bid = "";
        if (qs.length != 0) {
            qs = qs.replace(/\+/g, ' ');
            var args = qs.split('&');
            for (var i = 0; i < args.length; i++) {
                var pair = args[i].split('=');
                var name = decodeURIComponent(pair[0]);
                var value = (pair.length == 2) ? decodeURIComponent(pair[1]) : name;
                if (name == 'bid') { bid = value; }
            }
        }
        ProductFiltering.updateIntro(bid);
    }
    ProductFiltering.getSubProductInfo();
    ProductFiltering.enableFuelType();
});

// NOTE: converted to Prototype from jQuery
BrandedTopNav = {
    showTimer: -1,
    hideTimer: -1,
    noTimout: false,
    wireBrandedTopNav: function(src, key) {
        this.off = $("divTopNavNoDDM");
        this.on = $("divTopNavWDDM");
        this.off.observe("mouseover", this.mouseover.bind(this));
        this.off.observe("mouseout", this.mouseout.bind(this));
        this.on.observe("mouseover", this.mouseover.bind(this));
        this.on.observe("mouseout", this.mouseout.bind(this));
        this.wireBrandedTopNav = Prototype.emptyFunction;
    },
    show: function() {
        this.off.hide();
        this.on.show();
    },
    hide: function() {
        if (!this.noTimout) {
            this.off.show();
            this.on.hide();
        }
    },
    mouseover: function() {
        this.stopHide();
        this.showTimer = setTimeout(this.show.bind(this), 600);
    },
    mouseout: function() {
        this.stopShow();
        this.hideTimer = setTimeout(this.hide.bind(this), 600);
    },
    stopHide: function() {
        if (this.hideTimer >= 0) {
            clearTimeout(this.hideTimer);
            this.hideTimer = -1;
        }
    },
    stopShow: function() {
        if (this.showTimer >= 0) {
            clearTimeout(this.showTimer);
            this.showTimer = -1;
        }
    },
    disableTimeout: function(val) {
        //alert(val);
        this.noTimout = val;
    },
    toggleTimeout: function() {
        //alert(val);
        this.noTimout = !this.noTimout;
    }



};


// NOTE: converted to Prototype from jQuery
var BrandedProductHover = {
    menus: {},
    open: null,
    timer: -1,
    //firstTime: true,
    wired: {},
    wire: function(src, key) {
        src = $(src).select("IMG").first();
        if (!src) return;
        // store a reference to the wired menu trigger (once)
        if (this.wired[key] == undefined) {
            this.wired[key] = src;
            // set up local scoped functions to retain the key
            var f_over = this.over.bind(this, key);
            var f_out = this.out.bind(this, key);
            // add mouseover and mouseout event listeners
            Event.observe(src, "mouseout", f_out);
            Event.observe(key, "mouseover", f_over);
            Event.observe(key, "mouseout", f_out);
        }
        this.over(null, key, true);
    },
    over: function(event, key, firstTime) { // firstTime = the mouse just entered the main image (firstTime=false when the event is coming from the hover itself)
        this.cancel();
        if (firstTime) {
            this.close();
            // Do positioning
            this.extractHover(key);
            var pos = this.wired[key].viewportOffset();
            //var pos = this.wired[key].positionedOffset(); // Source (trigger) position
            pos.left -= 145;
            pos.top -= 55;
            this.open = $(key);
            this.open.setStyle({ position: "absolute", top: pos.top + "px", left: pos.left + "px", zIndex: 1000 }); // zIndex: 2 bazillion
            var that = this;
            //setTimeout(function() { try { that.open.setStyle({ display: "block" }) } catch (err) { } }, 500);

            setTimeout(function() { try{that.open.setStyle({ display: "block" }) }catch(err){}}, 500);
            
            //this.open.setStyle({ display: "block" });
            //that.currentEffect = new Effect.Grow(this.open, { direction: 'center', duration: 0.5, afterFinish: function() { that.currentEffect = null } });
        } else {
            this.open.setStyle({ display: "block" });
        }
    },
    extractHover: function(key) {
        // create a fixed container for our hovers
        if ($("branded_product_hover_cont") == null) {
            $(document.body).insert('<div id="branded_product_hover_cont" style="position:fixed;top:0px;left:0px;z-index:1000;"></div>');
        }
        // extract the hover and place outside the positioned images
        var elm = $(key);
        if (elm.wasExtracted != true) {
            elm.wasExtracted = true;
            $("branded_product_hover_cont").insert(elm.remove());
        }
    },
    out: function(event, key) {
        this.cancel();
        this.timer = window.setTimeout(this.close.bind(this), 400);
    },
    close: function() {
        if (this.open) this.open.setStyle({ display: "none" });
        this.open = null;
    },
    cancel: function() {
        if (this.currentEffect) this.currentEffect.cancel();
        if (this.timer >= 0) window.clearTimeout(this.timer);
        this.timer = -1;
    }
};

var SaveProduct = {
	showFromSave : function(productID) { // Marketing Product ID
		HHTSitecore.services.ProductService.ShowFromSave(productID, this.onShowSuccess.bind(this), this.onShowFailure.bind(this), null);
	},
	onShowSuccess : function(result, context) {
		$j('#ProductNameOnSavePopup').text(result.productName);
		$j('#SaveProductDimmer').show();
	},
	onShowFailure: function(result, context) {
	}
};

var SaveBuyersGuide = {
    showFromSave: function() {
        HHTSitecore.services.ProductService.ShowFromSaveBuyersGuide(this.onShowSuccess.bind(this), this.onShowFailure.bind(this), null);
    },
    onShowSuccess: function(result, context) {
        $j('#SaveBuyerGuideDimmer').show();
    },
    onShowFailure: function(result, context) {
    }
};

var SimpleRotator = Class.create();
SimpleRotator.prototype = {
    /*div: null,
    slides: null,
    slidescont: null,
    data: [],
    id: null,*/
    index: 0,
    nextTimer: -1,
    initialize: function(p_id, p_data, p_auto) { // p_data = array of HeaderSlide, p_auto = auto-progress
        this.auto = (p_auto == true || p_auto == undefined);
        this.data = (p_data != null && p_data instanceof Array) ? p_data : [];
        this.id = p_id;
        Event.observe(document, "dom:loaded", this.wire.bind(this)); // dom:loaded fires as soon as the dom is available
        Event.observe(window, "load", this.onload.bind(this)); // window.load fires when the entire page is loaded (including built-in media)
        Event.observe(window, "resize", this.resize.bind(this)); // window.resize fires when, well, the window is resized (IE fires more rapidly than FF, since we're on the topic...)
    },
    wire: Prototype.emptyFunction,
    onload: function() {
        this.onloadImpl();
        this.resize();
        this.waitForNext();
    },
    onloadImpl: Prototype.emptyFunction,
    resize: function(event) {
        if (this.pendingresizetimer >= 0) clearTimeout(this.pendingresizetimer);
        this.pendingresizetimer = setTimeout(function() {
            if (this.moving) {
                //console.info("resize on hold; moving");
                this.pendingresize = true;
            } else {
                //console.info("resize");
                this.pendingresizetimer = -1;
                this.pendingresize = false;
                this.resizeImpl();
            }
        } .bind(this), 300);
    },
    resizeImpl: Prototype.emptyFunction,
    // set up a timer for auto-scrolling (clears any currently pending timer)
    waitForNext: function() {
        this.cancelWaitForNext();
        if (this.auto)
            this.nextTimer = setTimeout(this.next.bind(this), this.pause);
    },
    // stop the timer
    cancelWaitForNext: function() {
        if (this.nextTimer >= 0) clearTimeout(this.nextTimer);
    },
    // actually move to the next image (sets up and plays a few animations)
    next: function() {
        this.navTo((this.index >= this.data.length - 1) ? 0 : this.index + 1);
    },
    previous: function() {
        this.navTo((this.index <= 0) ? this.data.length - 1 : this.index - 1);
    },
    // when the slide animation is done, do some cleanup and start the timeout for the next slide
    navDone: function() {
        this.moving = false;
        this.navDoneImpl();
        if (this.pendingresize) this.resize();
        this.waitForNext();
    },
    navDoneImpl: Prototype.emptyFunction,
    // slide to the specified index
    navTo: function(p_idx) {
        if (this.moving || p_idx == this.index) return;
        this.cancelWaitForNext();
        var last = this.index;
        this.index = p_idx;
        this.moving = true;
        this.onmove(p_idx, last);
    }
};

var HeaderRotator = Class.create(SimpleRotator, {
    menu: null,
    text: null,
    duration: 2500, // animation duration
    pause: 5000,
    // wire up the assigned DIVs from the generated page
    wire: function() {
        this.div = $(this.id);
        this.slides = this.div.select(".fp_home_image").first();
        this.slidescont = this.div.select(".fp_home_mover").first();
        this.menu = this.div.select(".image_switcher_toggle").first();
        this.text = this.div.select(".fp_home_image_switcher_text").first();
        //console.info("data: " + this.data.length);
    },
    // when the browser window resizes, we gotta resize all the divs involved in the sliding
    resizeImpl: function() {
        var w = document.viewport.getWidth();
        var divs = this.slidescont.select(".fp_home_image_div");
        this.slides.setStyle({ width: w + "px" });
        this.slidescont.setStyle({ width: (w * this.data.length) + "px", left: (-w * this.index) + "px" });
        divs.each(function(elm, idx) {
            elm.setStyle({ width: w + "px", left: (idx * w) + "px" });
        });
    },
    // The generated page always contains HTML for the first image and related text; This function adds the rest, and some other bits.
    onloadImpl: function() {
        //console.info("drawExtras");
        this.data.each(function(obj, index) {
            // add the nav button for this index
            var elm = new Element("LI", { "class": (index == 0) ? "on" : "off" });
            var a = new Element("A");
            a.observe("click", this.navTo.bind(this, index));
            this.menu.insert(elm.insert(a));
            // add the HeaderSlide objects (this uses the toElement() method)
            if (index == 0) this.slidescont.update("");
            this.slidescont.insert(obj);
            //console.info("adding ", obj, " to images list, list now contains: ", this.slidescont.select(".fp_home_image_div"));
        } .bind(this));
    },
    onmove: function(p_idx, p_last) {
        this.menu.select("LI").each(function(elm, idx) {
            elm.className = (p_idx == idx) ? "on" : "off";
        });
        this.text.update(this.data[p_idx].title);
        var width = document.viewport.getWidth();
        //console.info("moving from " + p_last + " to " + p_idx);
        new Effect.Move(this.slidescont, { x: -width * p_idx, mode: "absolute", duration: this.duration / 1000, afterFinish: this.navDone.bind(this) });
    }
});
/*if (typeof(console)=="undefined") {
	var console = {
		pending: "",
		log: function() {
			this.pending += $A(arguments).join(" ") + "\n";
		},
		info: function() {
			this.pending += $A(arguments).join(" ") + "\n";
		},
		warn: function() {
			this.pending += "WARNING: " + $A(arguments).join(" ") + "\n";
		},
		error: function() {
			this.pending += "ERROR: " + $A(arguments).join(" ") + "\n";
		},
		print: function() {
			alert(this.pending);
			this.pending = "";
		}
	}
}*/
var BrHomeRotator = Class.create(SimpleRotator, {
	// NOTE: the contents of this.data are rotated along with the divs to make a continuous cycle
	duration: 2000, // animation duration
	pause: 7000,
	// wire up the assigned DIVs from the generated page
	wire: function() {
		this.div = $(this.id);
		//this.slides = this.div.select(".home_bg").first();
		this.slidescont = this.div.select(".home_bg_mover").first();
		var that = this;
		var images = this.div.select("IMG.home_bg_actual_img");
		if (this.data.length == images.length && this.data.length > 0) {
			// set up the function to load the rest
			var fLoadRemaining = function() {
				images.each(function(img, i) {
					if (i == 0) return;
					$(img).observe("load", that.imgLoad.bind(that, i)); // must listen prior to setting 'src'
					img.src = that.data[i].photo; // if (i > 0)
					//console.log("adding img.onload", img, i);
				});
			};
			// set up the first div and hide the subsequent divs
			images.each(function(img, i) {
				img.up().setStyle({ zIndex: (i == 0) ? 3 : 1 });
				if (i > 0) $(img).up().hide();
			});
			var firstImg = $(images[0]);
			firstImg.up().setStyle({ zIndex: 3 });
			// ensure the first image is available(requires it to NOT be display:none)
			var cInt = setInterval(function() {
				if (firstImg.getWidth() > 0 && firstImg.getHeight() > 0) {
					clearInterval(cInt);
					that.imgLoad(0, null, firstImg);
					setTimeout(function() { fLoadRemaining() }, 500);
				}
			}, 500);
		}
		this.resizeImpl();
	},
	onloadImpl: function() {
		//this.position();
	},
	imgLoad: function(i, e, directImg) {
		//console.info("imgLoad");
		var img = (directImg) ? directImg : Event.element(e);
		img.up().show();
		img.__origW = img.getWidth();
		img.__origH = img.getHeight();
		if (i > 0) img.up().hide();
		//console.log("imgLoad", img, i, img.__origW, img.__origH);
		//setTimeout(this.positionOne.bind(this,null, img, i), 5000);
		this.positionOne(null, img, i);
	},
	// when the browser window resizes, we gotta resize all the divs involved in the sliding
	resizeImpl: function() {
		//console.info("resizeImpl");
		//console.log("resizeImpl");
		var vp = document.viewport.getDimensions();
		//this.slidescont.setStyle({ left: (-vp.width * this.index) + "px" });
		var images = this.div.select("IMG.home_bg_actual_img");
		images.each(this.positionOne.bind(this, vp));
		this.positionBadges(vp);
	},
	positionOne: function(vp, img, i) {
		//console.info("positionOne", vp, img, i);
		if (!vp) var vp = document.viewport.getDimensions();
		if (img.__origW && img.__origH) {
			//console.log("positionOne", img, i);
			//img.up().setStyle( {height:vp.height+"px", display: "block", left: (i * vp.width) + "px"} ); // position and show remaining slides
			img.up().setStyle({ height: vp.height + "px" }); // just set height with Fading effect
			var bStretchHeight = (img.__origH / vp.height < img.__origW / vp.width); // stretch to height
			var nScale = (bStretchHeight) ? vp.height / img.__origH : vp.width / img.__origW;
			img.setStyle({
				width: (bStretchHeight) ? "" : vp.width + "px",
				height: (bStretchHeight) ? vp.height + "px" : "",
				marginLeft: (bStretchHeight) ? Math.round((vp.width - img.__origW * nScale) / 2) + "px" : 0,
				marginTop: (bStretchHeight) ? 0 : Math.round((vp.height - img.__origH * nScale) / 2) + "px"
			});
		} else {
			//console.log("positionOne: no origW/origH");
		}
	},
	positionBadges: function(vp) {
		//console.info("positionBadges");
		// position the badge inside the available space
		var tables = this.slidescont.select(".home_bg_img>TABLE");
		if (tables.length == this.data.length) {
			var h = document.viewport.getHeight();
			var head = $("divTopNavNoDDM").getHeight(); // subtract the header height
			var foot = $$(".footer_left").first().getHeight(); // subtract the footer height
			var lmarg = 14, rmarg = 14;
			for (var i = 0, len = this.data.length; i < len; i++) {
				// calculate the position based on the percentage stored in each HomeSlide
				var top = head + Math.round((h - (head + foot + tables[i].getHeight())) * this.data[i].vpercent / 100);
				var left = lmarg + Math.round((vp.width - (lmarg + rmarg + tables[i].getWidth())) * this.data[i].hpercent / 100);
				tables[i].setStyle({ top: top + "px", left: left + "px" });
			}
		}
	},
	onmove: function(p_idx, p_last) {
		var width = document.viewport.getWidth();
		//console.info("onmove from " + p_last + " to " + p_idx);
		//new Effect.Move(this.slidescont, { x: -width * p_idx, mode: "absolute", duration: this.duration / 1000, afterFinish: this.navDone.bind(this) });
		var all = this.slidescont.select(".home_bg_img");
		// put the previous one above the new current one, and fade out the previous one
		all.each(function(div, i) {
			if (i == p_idx) div.setStyle({ zIndex: 2, display: 'block' });
			else if (i == p_last) div.setStyle({ zIndex: 3, display: 'block' });
			else div.setStyle({ zIndex: 1, display: 'none' });
		});
		new Effect.Fade(all[p_last], { duration: this.duration / 1000, afterFinish: this.navDone.bind(this) });
		this.updateExternals(p_idx);
	},
	updateExternals: function(p_idx) {
		// be careful here, home page doesn't have all the same elements available
		var pagenum = $("bg_img_current");
		if (pagenum) pagenum.update(p_idx + 1);
		var pager = $("bg_img_pager");
		if (pager) {
			pager.select("LI").each(function(elm, i) {
				elm.className = (p_idx == i) ? "on" : "off";
			});
		}
		var thumbs = $("bg_img_thumbs");
		if (thumbs) {
			thumbs.select("IMG").each(function(elm, i) {
				(p_idx == i) ? elm.show() : elm.hide();
			});
		}
	},
	navDoneImpl: function() {
		var all = this.slidescont.select(".home_bg_img");
		// show all, but ensure the current one is on top (need all visible for positioning the badges)
		all.each(function(div, i) {
			if (i == this.index) div.setStyle({ zIndex: 3, display: 'block' });
			else div.setStyle({ zIndex: 1, display: 'block' });
		} .bind(this));
	}
	/*navDoneImpl: function() {
	// reorder the children elements to obtain a constant right-to-left motion
	var all = this.slidescont.select(".home_bg_img");
	var first = all[0], current = all[1];
	var parent = first.parentNode;
	first.remove();
	parent.insert(first);
	this.index = 0;
	this.pendingresize = true; // trigger resize next
	// reorder the this.data array
	first = this.data.splice(0, 1);
	this.data.splice(this.data.length, 0, first[0]);
	//console.info("pos: " + this.data[0].hpercent + "x" + this.data[0].vpercent);
	}*/
});
var BrDetailRotator = Class.create(SimpleRotator, {
	// NOTE: the contents of this.data are rotated along with the divs to make a continuous cycle
	duration: 2000, // animation duration
	pause: 7000,
	// wire up the assigned DIVs from the generated page
	wire: function() {
		this.div = $(this.id);
		//this.slides = this.div.select(".home_bg").first();
		this.slidescont = this.div.select(".home_bg_mover").first();
		var that = this;
		var images = this.div.select("IMG.home_bg_actual_img");
		if (this.data.length == images.length && this.data.length > 0) {
			// set up the function to load the rest
			var fLoadRemaining = function() {
				images.each(function(img, i) {
					if (i == 0) return;
					//$(img).setStyle({ backgroundImage: "url(" + that.esc(that.data[i].photo) + ")" });
					$(img).observe("load", that.imgLoad.bind(that, i)); // must listen prior to setting 'src'
					img.src = that.data[i].photo; // if (i > 0)
					//console.log("adding img.onload", img, i);
				});
			};
			// set up the first div and hide the subsequent divs
			images.each(function(img, i) {
				img.up().setStyle({ zIndex: (i == 0) ? 3 : 1 });
				//if (i > 0) $(img).up().hide();
			});
			var firstImg = $(images[0]);
			firstImg.up().setStyle({ zIndex: 3 });
			// ensure the first image is available(requires it to NOT be display:none)
			var cInt = setInterval(function() {
				if (firstImg.getWidth() > 0 && firstImg.getHeight() > 0) {
					clearInterval(cInt);
					that.imgLoad(0, null, firstImg);
					setTimeout(function() { fLoadRemaining() }, 500);
				}
			}, 500);
		}
		this.resizeImpl();
	},
	onloadImpl: function() {
		//this.position();
	},
	imgLoad: function(i, e, directImg) {
		//console.info("imgLoad");
		var img = (directImg) ? directImg : Event.element(e);
		//		if (this.data[i].flash != null && this.data[i].flash.length > 0) { // add play indicator, event listener
		//			var play = new Element("DIV", { "class": "play_indicator" });
		//			play.observe("click", this.data[i].onClick.bind(this));
		//			img.up().insert(play);
		//		}
		//		} else {
		//			this.element.observe("click", this.data[i].onClickNav.bind(this));
		//		}
		img.up().show();
		img.__origW = img.getWidth();
		img.__origH = img.getHeight();
		//if (i > 0) img.up().hide();
		//console.log("imgLoad", img, i, img.__origW, img.__origH);
		//setTimeout(this.positionOne.bind(this,null, img, i), 5000);
		this.positionOne(null, img, i);
	},
	// when the browser window resizes, we gotta resize all the divs involved in the sliding
	resizeImpl: function() {
		//console.info("resizeImpl");
		//console.log("resizeImpl");
		var vp = document.viewport.getDimensions();
		//this.slidescont.setStyle({ left: (-vp.width * this.index) + "px" });
		var images = this.div.select("IMG.home_bg_actual_img");
		images.each(this.positionOne.bind(this, vp));
		var images = this.div.select("IMG.branded_product_detail_play_indicator");
		images.each(this.centerOne.bind(this, vp));
		//		this.positionBadges(vp);
	},
	positionOne: function(vp, img, i) {
		//console.info("positionOne", vp, img, i);
		if (!vp) var vp = document.viewport.getDimensions();
		if (img.__origW && img.__origH) {
			//console.log("positionOne", img, i);
			//img.up().setStyle( {height:vp.height+"px", display: "block", left: (i * vp.width) + "px"} ); // position and show remaining slides
			img.up().setStyle({ height: vp.height + "px" }); // just set height with Fading effect
			var bStretchHeight = (img.__origH / vp.height < img.__origW / vp.width); // stretch to height
			var nScale = (bStretchHeight) ? vp.height / img.__origH : vp.width / img.__origW;
			img.setStyle({
				width: (bStretchHeight) ? "" : vp.width + "px",
				height: (bStretchHeight) ? vp.height + "px" : "",
				marginLeft: (bStretchHeight) ? Math.round((vp.width - img.__origW * nScale) / 2) + "px" : 0,
				marginTop: (bStretchHeight) ? 0 : Math.round((vp.height - img.__origH * nScale) / 2) + "px"
			});
		} else {
			//console.log("positionOne: no origW/origH");
		}
	},
	centerOne: function(vp, img, i) {
		if (!vp) var vp = document.viewport.getDimensions();
		var h = img.getHeight();
		var w = img.getWidth();
		var top = (vp.height - h) / 2;
		var left = (vp.width - w) / 2;
		img.setStyle({ left: left + "px", top: top + "px" });
	},
	onmove: function(p_idx, p_last) {
		var width = document.viewport.getWidth();
		//console.info("onmove from " + p_last + " to " + p_idx);
		//new Effect.Move(this.slidescont, { x: -width * p_idx, mode: "absolute", duration: this.duration / 1000, afterFinish: this.navDone.bind(this) });
		var all = this.slidescont.select(".home_bg_img");
		// put the previous one above the new current one, and fade out the previous one
		all.each(function(div, i) {
			if (div.tagName == 'DIV') {
				if (i == p_idx) {
					div.setStyle({ zIndex: 2, display: 'block' });
				}
				else if (i == p_last) {
					div.setStyle({ zIndex: 3, display: 'block' });
				}
				else {
					div.setStyle({ zIndex: 1, display: 'none' });
				}
			}
		});
		new Effect.Fade(all[p_last], { duration: this.duration / 1000, afterFinish: this.navDone.bind(this) });
		this.updateExternals(p_idx);
	},
	updateExternals: function(p_idx) {
		// be careful here, home page doesn't have all the same elements available
		var pagenum = $("bg_img_current");
		if (pagenum) pagenum.update(p_idx + 1);
		var pager = $("bg_img_pager");
		if (pager) {
			pager.select("LI").each(function(elm, i) {
				elm.className = (p_idx == i) ? "on" : "off";
			});
		}
		var thumbs = $("bg_img_thumbs");
		if (thumbs) {
			thumbs.select("IMG").each(function(elm, i) {
				(p_idx == i) ? elm.show() : elm.hide();
			});
		}
	},
	navDoneImpl: function() {
		var all = this.slidescont.select(".home_bg_img");
		// show all, but ensure the current one is on top (need all visible for positioning the badges)
		all.each(function(div, i) {
			if (i == this.index) {
				div.setStyle({ zIndex: 3, display: 'block' });
			}
			else {
				div.setStyle({ zIndex: 1, display: 'block' });
			}
		} .bind(this));
	}
	/*navDoneImpl: function() {
	// reorder the children elements to obtain a constant right-to-left motion
	var all = this.slidescont.select(".home_bg_img");
	var first = all[0], current = all[1];
	var parent = first.parentNode;
	first.remove();
	parent.insert(first);
	this.index = 0;
	this.pendingresize = true; // trigger resize next
	// reorder the this.data array
	first = this.data.splice(0, 1);
	this.data.splice(this.data.length, 0, first[0]);
	//console.info("pos: " + this.data[0].hpercent + "x" + this.data[0].vpercent);
	}*/
});
var FiresideHomeBlurbRotator = Class.create(SimpleRotator, {
	menu: null,
	text: null,
	duration: 2500, // animation duration
	pause: 5500,
	// wire up the assigned DIVs from the generated page
	wire: function() {
		this.div = $(this.id);
		this.slides = this.div.select(".fsd_home_mover").first();
		this.slidescont = this.div.select(".fsd_home_image_div").first();
		//this.slideImage = this.div.select(".home_image_shell").first();
		//this.rightCol = this.div.select(".home_image_text").first();
		this.menu = this.div.select(".fsd_image_switcher_toggle").first();
		//console.info("data: " + this.data.length);
	},
	// when the browser window resizes, we gotta resize all the divs involved in the sliding
	resizeImpl: function() {
		var docViewport = document.viewport.getWidth();
		var w = 960;
		var shellMargin = (docViewport - w) / 2;
		var divs = this.slidescont.select(".home_image_shell");
		//this.slides.setStyle({ width: w + "px" });
		this.slidescont.setStyle({ width: (docViewport * this.data.length) + "px", left: ((-w - shellMargin) * this.index) + "px" });
		divs.each(function(elm, idx) {
			var imageDiv = elm.select(".home_image_main").first();
			imageDiv.setStyle({ width: w - 224 + "px", left: (idx * w) + "px", height: "499px" });
			elm.setStyle({ width: docViewport + "px", left: (idx * docViewport + shellMargin) + "px" });
		});
	},
	// The generated page always contains HTML for the first image and related text; This function adds the rest, and some other bits.
	onloadImpl: function() {
		//console.info("drawExtras");
		this.data.each(function(obj, index) {
			// add the nav button for this index
			var elm = new Element("LI", { "class": (index == 0) ? "on" : "off" });
			var a = new Element("A", { "class": obj.tabClass });
			a.insert(obj.heading);
			a.observe("click", this.navTo.bind(this, index));
			this.menu.insert(elm.insert(a));
			// add the HeaderSlide objects (this uses the toElement() method)
			if (index == 0) this.slidescont.update("");
			this.slidescont.insert(obj);
			//console.info("adding ", obj, " to images list, list now contains: ", this.slidescont.select(".home_image_shell"));
		} .bind(this));
	},
	onmove: function(p_idx, p_last) {
		//return;
		this.menu.select("LI").each(function(elm, idx) {
			elm.className = (p_idx == idx) ? "on" : "off";
		});
		//this.text.update(this.data[p_idx].title);
		var width = document.viewport.getWidth();
		//var width = 960;
		//console.info("moving from " + p_last + " to " + p_idx);
		new Effect.Move(this.slidescont, { x: -width * p_idx, mode: "absolute", duration: this.duration / 1000, afterFinish: this.navDone.bind(this) });
	}
});
var FiresideHomeFeatureRotator = Class.create(SimpleRotator, {
    menu: null,
    text: null,
    duration: 1000, // animation duration
    pause: 4500,
    // wire up the assigned DIVs from the generated page
    wire: function() {

        this.div = $(this.id);
        //this.slides = this.div.select(".home_body").first();
        this.slidescont = this.div.select(".fsd_home_feature_mover").first();
        //this.slideImage = this.div.select(".home_image_shell").first();
        //this.rightCol = this.div.select(".home_image_text").first();
        this.menu = this.div.select(".home_features_slider").first();
        //console.info("data: " + this.data.length);
    },
    // when the browser window resizes, we gotta resize all the divs involved in the sliding
    resizeImpl: function() {
        var docViewport = document.viewport.getWidth();
        var w = 960;
        //var shellMargin = (docViewport - w) / 2;
        var divs = this.slidescont.select(".fsd_home_feature_div");
        this.div.setStyle({ width: w + "px" });
        this.slidescont.setStyle({ width: (w * this.data.length) + "px", left: (-w * this.index) + "px" });
        divs.each(function(elm, idx) {
            elm.setStyle({ width: w + "px", left: (idx * w) + "px" });
        });
    },
    // The generated page always contains HTML for the first image and related text; This function adds the rest, and some other bits.
    onloadImpl: function() {
        //console.info("drawExtras");
        this.data.each(function(obj, index) {
            // add the nav button for this index
            var elm = new Element("LI");
            var a = new Element("A", { "class": (index == 0) ? "on" : "off" });
            a.insert(index + 1);
            a.observe("click", this.navToo.bind(this, index));
            this.menu.insert(elm.insert(a));
            // add the HeaderSlide objects (this uses the toElement() method)
            //if (index == 0) this.slidescont.update("");
            //this.slidescont.insert(obj);
            //console.info("adding ", obj, " to images list, list now contains: ", this.slidescont.select(".home_image_shell"));
        } .bind(this));
    },
    onmove: function(p_idx, p_last) {

        this.menu.select("A").each(function(elm, idx) {
            elm.className = (p_idx == idx) ? "on" : "off";
        });

        var width = 960;
        new Effect.Move(this.slidescont, { x: -width * p_idx, mode: "absolute", duration: this.duration / 1000, afterFinish: this.navDone.bind(this) });
    },
    navToo: function(p_idx,src) {
        this.onmove(p_idx, 0);
    }
});



var HomeSlide = Class.create();
HomeSlide.prototype = {
	element: null,
	initialize: function(p_photo, p_hpercent, p_vpercent, p_flash, p_title, p_guid, p_url) {
		this.photo = p_photo;
		this.hpercent = p_hpercent;
		this.vpercent = p_vpercent;
		this.flash = p_flash;
		this.title = p_title;
		this.guid = p_guid;
		this.url = p_url;
	},
	onClick: function(event) {
		MediaPopup.show(this.guid, this.guid, "Photo", "Flash Video", "Title", "Home", "Thumbnail");
	},
	onClickNav: function(event) {
		if (this.url != null && this.url.length > 0)
			document.location.href = this.url;
	},
	toElement: function() {
		if (!this.element) {
			this.element = new Element("DIV", { "class": "fp_home_image_div" });
			this.element.setStyle({ backgroundImage: "url(" + this.esc(this.photo) + ")" });
			//console.info("backgroundImage:", this, this.photo);
			if (this.flash != null && this.flash.length > 0) { // add play indicator, event listener
				var play = new Element("DIV", { "class": "fp_home_play_indicator" });
				play.observe("click", this.onClick.bind(this));
				this.element.insert(play);
			} else {
				this.element.observe("click", this.onClickNav.bind(this));
			}
		}
		return this.element;
	},
	esc: function(p_txt) {
		// %3F%3D%26
		return escape(p_txt).replace(/%3F/i, "?").replace(/%3D/i, "=").replace(/%26/i, "&");
	}
};
var HeaderSlide = Class.create();
HeaderSlide.prototype = {
    element: null,
    initialize: function(p_photo, p_flash, p_title, p_guid, p_url) {
        this.photo = p_photo;
        this.flash = p_flash;
        this.title = p_title;
        this.guid = p_guid;
        this.url = p_url;
    },
    onClick: function(event) {
        MediaPopup.show(this.guid, this.guid, "Photo", "Flash Video", "Title", "Home", "Thumbnail");
    },
    onClickNav: function(event) {
        if (this.url != null && this.url.length > 0)
            document.location.href = this.url;
    },
    toElement: function() {
        if (!this.element) {
            this.element = new Element("DIV", { "class": "fp_home_image_div" });
            this.element.setStyle({ backgroundImage: "url(" + this.esc(this.photo) + ")" });
            //console.info("backgroundImage:", this, this.photo);
            if (this.flash != null && this.flash.length > 0) { // add play indicator, event listener
                var play = new Element("DIV", { "class": "fp_home_play_indicator" });
                play.observe("click", this.onClick.bind(this));
                this.element.insert(play);
            } else {
                this.element.observe("click", this.onClickNav.bind(this));
            }
        }
        return this.element;
    },
    esc: function(p_txt) {
        // %3F%3D%26
        return escape(p_txt).replace(/%3F/i, "?").replace(/%3D/i, "=").replace(/%26/i, "&");
    }
};
var FiresideHomeBlurbSlide = Class.create();
FiresideHomeBlurbSlide.prototype = {
	element: null,
	elementImage: null,
	elementText: null,
	initialize: function(p_photo, p_rightContent, p_heading, p_tabClass, p_guid, p_url) {
		this.photo = p_photo;
		this.guid = p_guid;
		this.url = p_url;
		this.rightContent = p_rightContent;
		this.heading = p_heading;
		this.tabClass = p_tabClass;
	},
	onClickNav: function(event) {
		if (this.url != null && this.url.length > 0)
			document.location.href = this.url;
	},
	toElement: function() {
		if (!this.element) {
			this.element = new Element("DIV", { "class": "home_image_shell" });
			this.elementImage = new Element("DIV", { "class": "home_image_main" });
			this.elementImage.setStyle({ backgroundImage: "url(" + this.esc(this.photo) + ")" });
			//console.info("backgroundImage:", this, this.photo);
			this.elementText = new Element("DIV", { "class": "home_image_text" });
			this.elementText.insert(this.rightContent);
			this.element.insert(this.elementImage);
			this.element.insert(this.elementText);
			this.element.observe("click", this.onClickNav.bind(this));
		}
		return this.element;
	},
	esc: function(p_txt) {
		// %3F%3D%26
		return escape(p_txt).replace(/%3F/i, "?").replace(/%3D/i, "=").replace(/%26/i, "&");
	}
};
var FiresideHomeFeatureSlide = Class.create();
FiresideHomeFeatureSlide.prototype = {
	initialize: function() {
	},
	toElement: function() {
		return null;
	}
};
var StaticBrandedHeaderRotator = Class.create(SimpleRotator, {
	menu: null,
	text: null,
	duration: 2500, // animation duration
	pause: 5000,
	indexDiv: null,
	// wire up the assigned DIVs from the generated page
	wire: function() {
		this.div = $(this.id);
		this.slides = this.div.select(".fp_home_image").first();
		this.slidescont = this.div.select(".fp_home_mover").first();
		this.indexDiv = $$('.home_btm_bar_content').first();
		this.menu = this.indexDiv.select(".image_switcher_toggle").first();
		this.text = this.indexDiv.select(".fp_home_image_switcher_text").first();
		//console.info("data: " + this.data.length);
	},
	// when the browser window resizes, we gotta resize all the divs involved in the sliding
	resizeImpl: function() {
		var w = document.viewport.getWidth();
		var divs = this.slidescont.select(".fp_home_image_div");
		this.slides.setStyle({ width: w + "px" });
		this.slidescont.setStyle({ width: (w * this.data.length) + "px", left: (-w * this.index) + "px" });
		divs.each(function(elm, idx) {
			elm.setStyle({ width: w + "px", left: (idx * w) + "px" });
		});
	},
	// The generated page always contains HTML for the first image and related text; This function adds the rest, and some other bits.
	onloadImpl: function() {
		//console.info("drawExtras");
		this.data.each(function(obj, index) {
			// add the nav button for this index
			var elm = new Element("LI", { "class": (index == 0) ? "on" : "off" });
			var a = new Element("A");
			// Set displayed number index
			$j(a).text(index + 1);
			a.observe("click", this.navTo.bind(this, index));
			this.menu.insert(elm.insert(a));
			// add the HeaderSlide objects (this uses the toElement() method)
			if (index == 0) this.slidescont.update("");
			this.slidescont.insert(obj);
			//console.info("adding ", obj, " to images list, list now contains: ", this.slidescont.select(".fp_home_image_div"));
		} .bind(this));
	},
	onmove: function(p_idx, p_last) {
		this.menu.select("LI").each(function(elm, idx) {
			elm.className = (p_idx == idx) ? "on" : "off";
		});
		this.text.update(this.data[p_idx].title);
		var width = document.viewport.getWidth();
		//console.info("moving from " + p_last + " to " + p_idx);
		new Effect.Move(this.slidescont, { x: -width * p_idx, mode: "absolute", duration: this.duration / 1000, afterFinish: this.navDone.bind(this) });
	}
});

var CompareBar = Class.create();
CompareBar.prototype = {
	currentHover: null,
	autoHideTime: 1500,
	comparisonHTML: null,
	initialize: function(brandedSite, showImmediately) {
		this.brandedSite = (brandedSite == true);
		this.footer = $("footer_main");
		this.tray = $("footer_compare_tray");
		this.selections = $("footer_compare_selections");
		this.prod = $("footer_compare_product_info");
		this.prodAddNote = $("productAddedDiv");
		this.prodDesc = $("productDescriptionDiv");
		this.createVSMs();
		(showImmediately == true) ? this.show() : this.hide();
	},
	launchComparisons: function(comparisonID) {
		HHTSitecore.services.ComparisonList.LoadComparisonList(comparisonID || null, this.onLoadComparisonSuccess.bind(this), this.onLoadComparisonFailure.bind(this), null);
	},
	// This saveComparisons gets the product name html to display in the Save Comparison popup.  The actual save is done in the ProjectFolder class
	saveComparisons: function() {
		HHTSitecore.services.ComparisonList.SaveComparison(this.onSaveComparisonSuccess.bind(this), this.onSaveComparisonFailure.bind(this), null);
	},
	clearComparison: function(shouldInitialize) {
		HHTSitecore.services.ComparisonList.ClearComparison(shouldInitialize, this.onClearComparisonSuccess.bind(this));
	},
	launchComparisonFromEmail: function(comparisonIDs) {
		HHTSitecore.services.ComparisonList.LaunchComparisonFromEmail(comparisonIDs, this.onLaunchFromEmailSuccess.bind(this), this.onLoadComparisonFailure.bind(this), null);
	},
	createVSMs: function() {
		this.infoVSM = new VisualStateManager({
			timer: 800,
			show: function(product) {
				//console.log("info::show:", product);
				if (product == null) return;
				else if (product === true) {
					this.niceUpdate("compare_product_name", product);
					if (this.prod) this.prod.show();
					this.prodAddNote.show();
					this.prodDesc.hide();
				} else {
					this.currentHover = product.prodId;
					this.niceUpdate("compare_product_name", product.prodName);
					this.niceUpdate("compare_product_blurb", product.prodBlurb);
					this.niceUpdate("compare_product_msrp", product.prodMsrp);
					this.niceUpdate("compare_product_brand", product.brand);
					if (this.prod) this.prod.show();
					this.prodAddNote.hide();
					this.prodDesc.show();
				}
				//this.fireplacesCompareBarToggle(true);
			},
			hide: function() {
				//console.log("info::hide:");
				if (this.prod) this.prod.hide();
				this.prodAddNote.hide();
				this.prodDesc.hide();
				//this.fireplacesCompareBarToggle(false);
			}
		}, this);
		this.VSM = new VisualStateManager({
			timer: 800,
			show: function() {
				this.tray.show();
				if (this.brandedSite) this.brandedCompareBarToggle(true);
				else this.fireplacesCompareBarToggle(true);
				if (this.footer) this.footer.addClassName("compare_bg");
			},
			hide: function() {
				this.hideBecauseEmpty = false;
				this.tray.hide();
				this.infoVSM.hideNow();
				if (this.brandedSite) this.brandedCompareBarToggle(false);
				else this.fireplacesCompareBarToggle(false);
				if (this.footer) this.footer.removeClassName("compare_bg");
			}
		}, this);
		this.selectionsVSM = new VisualStateManager({
			timer: 1100,
			show: function() {
				if (this.brandedSite) this.brandedCompareBarSelectionsToggle(true);
				this.selections.className = "compare_bar_max";
				this.showingSelections = true;
			},
			hide: function() {
				if (this.brandedSite) this.brandedCompareBarSelectionsToggle(false);
				this.selections.className = "compare_bar_min";
				this.infoVSM.hideNow();
				this.showingSelections = false;
			}
		}, this);
	},
	show: function() {
		if (this.showSelections == true) this.selectionsVSM.show();
		if (this.hideBecauseEmpty == false) this.VSM.show(); // see hide() - may be forcing closed
	},
	hide: function(bEmpty) {
		this.hideBecauseEmpty = (bEmpty == true); // if bEmpty, we have no more comparisons, so force closed even if user has mouse-over
		this.VSM.hide();
	},
	hideTable: function() {
		Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this.completeLoadComparisons);
		$j('#ProductComparisonDimmer').hide();
	},
	hideBecauseEmpty: false,
	showingSelections: false,
	toggleSelections: function(bNow) {
		(this.showingSelections) ? (bNow) ? this.selectionsVSM.hideNow() : this.hideSelections() : this.showSelections(true);
	},
	showSelections: function(bForceOpen) {
		if (bForceOpen || this.showingSelections)
			this.selectionsVSM.show();
	},
	hideSelections: function() {
		this.selectionsVSM.hide();
	},
	showInfo: function(product) {
		this.infoVSM.show(product);
	},
	hideInfo: function() {
		this.infoVSM.hide();
	},
	niceUpdate: function(p_id, html) {
		var elm = $(p_id);
		if (elm) elm.update(html);
		//else if (typeof (console) != "undefined") console.warn("CompareBar.niceUpdate:", p_id, " is null");
	},
	addProduct: function(productId) {
		HHTSitecore.services.ComparisonList.AddComparedProduct(productId, this.onSuccess.bind(this), this.onFault.bind(this), null);
	},
	removeProduct: function(productId) {
		HHTSitecore.services.ComparisonList.RemoveComparedProduct(productId, this.onSuccess.bind(this), this.onFault.bind(this), null);
	},
	removeCurrent: function() {
		this.infoVSM.hideNow();
		if (this.currentHover) HHTSitecore.services.ComparisonList.RemoveComparedProduct(this.currentHover, this.onSuccess.bind(this), this.onFault.bind(this), null);
	},
	removeProduct: function(productId) {
		HHTSitecore.services.ComparisonList.RemoveComparedProduct(productId, this.onSuccess.bind(this), this.onFault.bind(this), null);
	},
	onSuccess: function(result, context) {
		if (result.status != true) {
			alert(result.errorMessage);
			return;
		}
		this.barUpdate(result);
		if ($j('#ProductComparisonDimmer').is(':visible') == true) {
			var comparisonsPanel = $j("[id$='ComparisonsCTAUpdatePanel']").get(0);
			__doPostBack(comparisonsPanel.id, '');

			this.comparisonHTML = result.comparisonHTML;
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeLoadComparisons);
		}
		else {
			if (result.action == 'remove') {
				var productHoverID = '#product_base' + result.removedProductID;

				var productHover = $j(productHoverID).get(0);
				if (productHover) {
					$j(productHoverID).find('input:checkbox').attr('checked', false);
				}
			}
		}
	},
	barUpdate: function(result) {
		$("productCountSpan").update("(" + result.count + ")");
		$$(".compare_bar_list").first().update(result.html);
		if (result.count == 0) {
			this.hide(true);
			//setTimeout(this.hide.bind(this), this.autoHideTime);
		} else if (result.action == "add") {
			this.show();
			//this.showSelections(true);
			//this.showSelections();
			this.showInfo(true);
			this.selectionsVSM.hide();
			//setTimeout(this.hideSelections.bind(this), this.autoHideTime);
		}
	},
	onFault: function(result, context) {
		alert("An error occured while adding a comparison.");
		if (typeof (console) != "undefined") console.error("ComparisonList.onfault:", result);
	},
	// This function sets the cookie with the currently hovered over product for the remove on the info popup
	//setComparedHoveredProduct: function(productID) {
	//    createCookie('comparedProductID', productID);
	//},
	// All the div and class changes necessary to toggle the branded compare bar
	brandedCompareBarToggle: function(bShow) {
		$j('#footer_main').toggleClass('compare_bg', bShow);
	},
	brandedCompareBarSelectionsToggle: function(bShow) {
		$j('#tray_toggle').toggleClass('expand', !bShow);
		$j('#tray_toggle').toggleClass('expanded', bShow);
		$j('#tray_toggle').text((bShow) ? 'Close' : 'Expand');
	},
	// All the div and class changes necessary to toggle the fp compare bar
	fireplacesCompareBarToggle: function(bShow) {
		$j(".footer_push").toggleClass("footer_push_compare", bShow);
		$j(".page_wrapper").toggleClass("page_wrapper_compare", bShow);
		$j(".footer").toggleClass("footer_compare", bShow);
	},
	completeLoadComparisons: function() {
		$j('#ComparisonContainerDiv').html(CompareBar.instance.comparisonHTML);
		//if (!CompareBar.instance.brandedSite) {
		//$j('#ProductComparisonDimmer').css({height:$(document.body).getHeight()+'px'});
		//$j('#ProductComparisonDimmer').attr('style', 'width:1020px; height:550px; overflow:auto; margin:0 auto;');
		//}
		$j("#ProductComparisonDimmer").show();
		if (!this.brandedSite) {
			$j("#ProductComparisonDimmer").css({ height: Math.max($j("BODY>FORM").height(), $j("#ComparisonContainerDiv").height() + 300) + 'px' });
		}

		// match row heights
		var t = $$("#SpecificationsDiv>UL");
		var heights = [];
		t.each(function(ul, i) {
			ul.select("LI").each(function(li, j) {
				heights[j] = Math.max(heights[j] || 0, li.getHeight());
			});
		});
		t.each(function(ul, i) {
			ul.select("LI").each(function(li, j) {
				li.setStyle({ height: heights[j] - 20 + "px" });
			});
		});

		// match top button row heights
		var b = $$("div.compare_scroll_th>div.compare_th_wrapper>UL");
		var buttonTops = [];
		b.each(function(ul, i) {
			ul.select("LI").each(function(li, j) {
				buttonTops[j] = Math.max(buttonTops[j] || 0, li.getHeight());
			});
		});
		b.each(function(ul, i) {
			ul.select("LI").each(function(li, j) {
				li.setStyle({ height: buttonTops[j] + "px" });
			});
		});
	},
	onLoadComparisonSuccess: function(result, context) {
		if (result.status) {
			var comparisonsPanel = $j("[id$='ComparisonsCTAUpdatePanel']").get(0);
			__doPostBack(comparisonsPanel.id, '');

			this.comparisonHTML = result.comparisonHTML;
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeLoadComparisons);
		}
		else {
			alert(result.errorMessage);
			return;
		}
	},
	onLoadComparisonFailure: function(result, context) {
	},
	onLaunchFromEmailSuccess: function(result) {
		if (result.status) {
			var comparisonsPanel = $j("[id$='ComparisonsCTAUpdatePanel']").get(0);
			__doPostBack(comparisonsPanel.id, '');

			this.comparisonHTML = result.comparisonHTML;
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeLoadComparisons);
			this.barUpdate(result);
		}
		else {
			alert(result.errorMessage);
			return;
		}
	},
	onSaveComparisonSuccess: function(result, context) {
		$j('#ComparedProductsToSave').html(result.comparedProductsHTML);
		$j('#SaveComparisonDimmer').show();
	},
	onSaveComparisonFailure: function(result, context) {
	},
	onClearComparisonSuccess: function(result) {
		$j('#ProductComparisonDimmer').hide();
		if (result.shouldInitialize) {
			var productListPanel = $j("[id$='ProductListUpdatePanel']").get(0);
			if (productListPanel) {
				__doPostBack(productListPanel.id, '');
			}
			this.initialize(this.brandedSite, false);
		}
	},
	findADealer: function() {
		var findADealerButton = $j("[id$='CompareFindADealer']").get(0);
		findADealerButton.click();
	}
};

var FormDefault = {
    init: function(o_src, p_default, b_passField) {
        this.blur(o_src, p_default, b_passField);
    },
    focus: function(o_src, p_default, b_passField) {
        o_src = $(o_src);
        if (o_src.value == p_default) {
            o_src.value = "";
            if (b_passField && !Prototype.Browser.IE) o_src.type = "password";
        }
    },
    blur: function(o_src, p_default, b_passField) {
        o_src = $(o_src);
        if (o_src.value == "") {
            if (b_passField && !Prototype.Browser.IE) o_src.type = "text";
            o_src.value = p_default;
        }
    }
};

var Popup = {
    open: function(options) {
        this.options = {
            url: '#',
            width: 600,
            height: 500,
            name: "_blank",
            location: "no",
            menubar: "no",
            toolbar: "no",
            status: "yes",
            scrollbars: "yes",
            resizable: "yes",
            left: "",
            top: "",
            normal: false,
            onclick: false
        }
        Object.extend(this.options, options || {});

        if (this.options.normal) {
            this.options.menubar = "yes";
            this.options.status = "yes";
            this.options.toolbar = "yes";
            this.options.location = "yes";
        }

        this.options.width = this.options.width < screen.availWidth ? this.options.width : screen.availWidth;
        this.options.height = this.options.height < screen.availHeight ? this.options.height : screen.availHeight;
        var openoptions = 'width=' + this.options.width + ',height=' + this.options.height + ',location=' + this.options.location + ',menubar=' + this.options.menubar + ',toolbar=' + this.options.toolbar + ',scrollbars=' + this.options.scrollbars + ',resizable=' + this.options.resizable + ',status=' + this.options.status
        if (this.options.top != "") openoptions += ",top=" + this.options.top;
        if (this.options.left != "") openoptions += ",left=" + this.options.left;
        window.open(this.options.url, this.options.name, openoptions);
        if (this.options.onclick) return false;
    }
}

var UpdHighlightData = {
    fieldId: null,
    buttonId: null,
    currentSectionId: null,
    sectionId: null,

    wire: function(p_field, p_btn) {
        this.fieldId = p_field;
        this.buttonId = p_btn;
        // add an event listener on MS' Ajax code
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.onAfterUpdate.bind(this));
    },
    getID: function(o_src, key) {
        this.selectThumb(o_src);
        this.sectionId = key;
        if (this.sectionId != this.currentSectionId) {
            $(this.fieldId).value = key;
            //console.info("__doPostBack('" + this.buttonId + "','')");
            __doPostBack(this.buttonId, '');
        } else {
            this.switchToItem(this.showIdx); // if no load required, the same section as last time was clicked
        }
    },
    switchToItem: function(p_idx) {
        //console.info("switchToItem: " + this.showIdx);        
        $("HighlightPopup").select(".popup_thumbnail_rotator .arrow_top").each(function(elm, i) { elm.setStyle({ visibility: (i == p_idx) ? "visible" : "hidden" }) });
    },
    onAfterUpdate: function(sender, args) {
        if (args.get_error() == undefined) {
            this.currentSectionId = this.sectionId;
        } else {
            if (typeof (console) != "undefined") console.error("There was an error" + args.get_error().message);
        }
    },
    selectThumb: function(o_idx) { // index or element
        if (typeof (o_idx) == "object" && o_idx.tagName.toLowerCase() != "li") o_idx = $(o_idx).up("li");
        $$("#highlight_thumbs_rotator .popup_thumbnail_rotator_body UL.popup_thumbs_list LI").each(function(elm, i) {
            elm.className = (i == o_idx || elm == o_idx) ? "on" : "";
        });
    }
};

var prodprice = {
    show: function() {
        $("ProdPriceWindow").show();
        MSRPHover.hideNow();
    },
    hide: function() {
        $("ProdPriceWindow").hide();
    }
};
var BrandedInfoPopup = {
    currentSelectItem: null,
    newSelectItem: null,
    fieldId: null,
    buttonId: null,
      
    wire: function(p_field, p_btn) {
        this.fieldId = p_field;
        this.buttonId = p_btn;
        // add an event listener on MS' Ajax code
       Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.onAfterUpdate.bind(this));
    },
    show: function(event, p_src) {
    this.newSelectItem = p_src;
        if(this.newSelectItem != this.currentSelectItem)
        {
             $(this.fieldId).value = this.newSelectItem;   
           // alert($(this.fieldId).value);
            
            __doPostBack(this.buttonId, '');
            $("BrandedInfoPopup").show();
            
        }
    
//    //this.atag_o.className = "some new class name";
//    this.currentSelectItem = p_src;        
//    $("CategoryNav" + p_src).className = "on";
//    $("descriptionDesign" + p_src).setStyle({ display: "block"});
//    this.setup(p_src);
    }, 
//    setup: function(p_src) {
//    if (p_src["isSetup"] == undefined) {
//        p_src.isSetup = true;
//        Event.observe(p_src, "click", this.onclick.bind(this));        
//        }    
//    },
//    onclick: function(event,p_src){ 
//    if(p_src != null)
//        {    
//            this.newSelectItem = p_src;            
//            if (this.newSelectItem != this.currentSelectItem) {
//            $("CategoryNav" + this.newSelectItem).className = "on";
//            $("descriptionDesign" + this.newSelectItem).setStyle({ display: "block"});
//            $("CategoryNav" + this.currentSelectItem).className = "off";
//            $("descriptionDesign" + this.currentSelectItem).setStyle({ display: "none"});
//            this.currentSelectItem = this.newSelectItem;    
//        }
//    }     

//    },
    hide: function() {
//    $("CategoryNav" + this.currentSelectItem).className = "off";
//    $("descriptionDesign" + this.currentSelectItem).setStyle({ display: "none"});
    $("BrandedInfoPopup").hide();
    },
    onAfterUpdate: function(sender, args) {
        if (args.get_error() == undefined) {        
        this.currentSectionId = this.sectionId;
            
            //console.info("updated!");
            //this.switchToItem(this.showIdx);
        } else {
            if (typeof (console) != "undefined") console.error("There was an error" + args.get_error().message);
        }
    }
    
};


var InfoPopup = {
    currentSelectItem: null,
    newSelectItem: null,
       
    show: function(event, p_src) {      
    $("InfoPopup").show();
    //this.atag_o.className = "some new class name";
    this.currentSelectItem = p_src;        
    $("CategoryNav" + p_src).className = "on";
    $("descriptionDesign" + p_src).setStyle({ display: "block"});
    this.setup(p_src);
    }, 
    setup: function(p_src) {
    if (p_src["isSetup"] == undefined) {
        p_src.isSetup = true;
        Event.observe(p_src, "click", this.onclick.bind(this));        
        }    
    },
    onclick: function(event,p_src){ 
    if(p_src != null)
        {    
            this.newSelectItem = p_src;            
            if (this.newSelectItem != this.currentSelectItem) {
            $("CategoryNav" + this.newSelectItem).className = "on";
            $("descriptionDesign" + this.newSelectItem).setStyle({ display: "block"});
            $("CategoryNav" + this.currentSelectItem).className = "off";
            $("descriptionDesign" + this.currentSelectItem).setStyle({ display: "none"});
            this.currentSelectItem = this.newSelectItem;    
        }
    }     

    },
    hide: function() {
    $("CategoryNav" + this.currentSelectItem).className = "off";
    $("descriptionDesign" + this.currentSelectItem).setStyle({ display: "none"});
    $("InfoPopup").hide();
    }
};

var HighlightPopup = {
    currentSectionId: null,
    sectionId: null,
    showIdx: null,
    fieldId: null,
    buttonId: null,
    popupId: "HighlightPopup",

    wire: function(p_field, p_btn) {
        this.fieldId = p_field;
        this.buttonId = p_btn;
        // add an event listener on MS' Ajax code
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.onAfterUpdate.bind(this));
    },

    show: function(event, p_src) {
        //alert(this.currentSectionId);        
        this.sectionId = p_src;
        if (this.sectionId != this.currentSectionId) { // only reload if the current panel isn't showing what was requested
            $(this.fieldId).value = this.sectionId;
            //alert(this.buttonId);
            __doPostBack(this.buttonId, '');
            $(this.popupId).show();
            Tracking.submit(p_src);
        } else {
            $(this.popupId).show();
        }

        
    },
    hide: function() {
        $(this.popupId).hide();
    },
    onAfterUpdate: function(sender, args) {
        if (args.get_error() == undefined) {
            this.currentSectionId = this.sectionId;

            //console.info("updated!");
            //this.switchToItem(this.showIdx);
        } else {
            if (typeof (console) != "undefined") console.error("There was an error" + args.get_error().message);
        }
    }
};

//Function for navigating through top menu.
var TopNavSubNav = {
    showTimer: -1,
    hideTimer: -1,
    div: null,

	show: function(p_src, div_id, matchTop) {

        //console.info("show:", p_src);//gives value of p_src
        //console.log(this.div, $(div_id));//gives value of div_id on events.

        if (this.div != $(div_id) && this.div != null) {
            //this.wait(100);
            this.hideNow();
        }
        this.stopHideNow();
        this.atag_o = $(p_src);
		if (this.atag_o.up().className == 'bottom_off') {
			this.atag_o.up().className = 'bottom_on';
		}
		else if (this.atag_o.up().className == 'all_prods') {
			this.atag_o.up().className = 'all_prods';
		}
		else {
			//this.atag_o.up().setStyle({ backgroundImage: '' });
        this.atag_o.up().className = "on";
		}
        this.toggleNext(true);
        //this.atag_o.className = "some new class name";
        this.div = $(div_id);
		if (this.div == null) return;
        //console.info("show:", this.div);
		// Set top
		//if (matchTop == true) {
		//	var parentOffset = $j(p_src).position();
		//	$j(div_id).css('top', parentOffset.top+"px");
		//}
        this.setup(this.div, this.atag_o);
        this.div.setStyle({ display: "block" });
    },
    toggleNext: function(bShow) {
    if (navigator.userAgent.indexOf('MSIE 7.') >= 0) {
			var px = (this.atag_o.up().next()) ? "-3px" : "-3px";
            this.atag_o.up().setStyle({ marginBottom: (bShow) ? px : "" });
        }
    },
    setup: function(div_o, p_src) {
        if (div_o["isSetup"] == undefined) {
            div_o.isSetup = true;
            Event.observe(div_o, "mouseout", this.onmouseout.bind(this));
            Event.observe(p_src, "mouseout", this.onmouseout.bind(this));
            Event.observe(div_o, "mouseover", this.onmouseover.bind(this));
        }
    },
    stopHideNow: function() {
        if (this.hideTimer >= 0) {
            clearTimeout(this.hideTimer);
            this.hideTimer = -1;
        }
    },
    hide: function() {
        this.hideTimer = setTimeout(this.hideNow.bind(this), 100);
    },
    hideNow: function(a_id) {
        if (this.atag_o) {
			if (this.atag_o.up().className == 'bottom_on') {
				this.atag_o.up().className = 'bottom_off';
			}
			else if (this.atag_o.up().className == 'all_prods') {
				this.atag_o.up().className = 'all_prods';
			}
			else {
            this.atag_o.up().className = "";
			}
            this.toggleNext(false);
        }
        if (this.div != null) {
            this.div.setStyle({ display: "none" });
            //this.atag_o.className = "";
        }
        this.div = null;
    },
    onmouseout: function(event) {
        //console.info("onmouseout:", Event.element(event));//gives the element name for the event.
        this.hide();
    },
    onmouseover: function(event) {
        //console.info("onmouseover:", Event.element(event));
        this.stopHideNow();

    }
};

var ImgZoomOverlay = {
    hideTimer: -1,
    popupObj: null,
    div: null,
    currentSrc: null,
    wire: function(o_popup) {
        this.popupObj = o_popup;
    },
    show: function(p_src, p_sect, p_idx) {
        this.popupObj.prepareLoad(p_sect, p_idx);
        if (p_src == this.currentSrc) {
            this.stopHideNow();
        } else {
            this.hideNow();
            this.currentSrc = p_src;
        }
        // <div class="img_zoom_overlay"></div>
        this.setupSrc(p_src);
        var p_sizeSource = (p_src.tagName.toLowerCase() == "div") ? $(p_src).select("IMG").first() : p_src;
        this.setupDiv(p_sizeSource);
    },
    hide: function() {
        this.hideTimer = setTimeout(this.hideNow.bind(this), 100);
    },
    hideNow: function() {
        //$("img_zoom_overlay").setStyle({ display: "none" });
        if (this.div != null) {
            this.div.remove();
            this.div = null;
        }
    },
    stopHideNow: function() {
        if (this.hideTimer >= 0) {
            clearTimeout(this.hideTimer);
            this.hideTimer = -1;
        }
    },
    setupSrc: function(p_src) {
        if (p_src["isSetup"] == undefined) {
            p_src.isSetup = true;
            Event.observe(p_src, "mouseout", this.onmouseout.bind(this));
        }
    },
    setupDiv: function(p_sizeSource) {
        if (this.div == null) {
            var size = p_sizeSource.getDimensions();
            this.div = new Element("DIV");
            this.div.className = "img_zoom_overlay";
            this.div.setStyle({ width: size.width + "px", height: size.height + "px" });
            p_sizeSource.insert({before: this.div});
            Event.observe(this.div, "click", this.onclick.bind(this));
            Event.observe(this.div, "mouseout", this.onmouseout.bind(this));
            Event.observe(this.div, "mouseover", this.onmouseover.bind(this));
        }
    },
    onclick: function(event) {
        this.popupObj.show();
    },
    onmouseout: function(event) {
        this.hide();
    },
    onmouseover: function(event) {
        this.stopHideNow();
    }
};


var FeaturesOptionsPopup = {
	currentSectionId: null,
	sectionId: null,
	showIdx: null,
	fieldId: null,
	buttonId: null,
	popupId: "PopupDiv",
	wire: function(p_field, p_btn) {
		this.fieldId = p_field;
		this.buttonId = p_btn;
		// add an event listener on MS' Ajax code
		//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.onAfterUpdate.bind(this));
	},
	prepareLoad: function(p_sect, p_idx) {
		this.sectionId = p_sect;
		this.showIdx = p_idx;
	},
	show: function() {
		if (this.sectionId != this.currentSectionId || $j('#FeaturesOptionsContent').html() == '') {
			//$(this.fieldId).value = this.sectionId;
			this.currentSectionId = this.sectionId;
			//if (console) {
			//	console.info("__doPostBack('" + this.buttonId + "','')");
			//}
			//__doPostBack(this.buttonId, '');
			// Reload outer container
			HHTSitecore.services.ProductService.CreateFeaturesPopupContent(this.currentSectionId, this.onPopupContentSuccess.bind(this));
		} else {
			var api = $j('#popupProductFeatureDiv .popup_thumbnail_rotator_body').scrollable({ api: true, size: ((MyAccount.brandedSite) ? 4 : 5), clickable: false, items: '.popup_thumbs_list', nextPage: '.arrow_right', prevPage: '.arrow_left', disabledClass: 'disabled_rotator_btns' });
			this.switchToItem(this.showIdx); // if no load required, the same section as last time was clicked
			$(this.popupId).show();
			var lis = $$('.popup_thumbnail_rotator .popup_thumbnail_rotator_body ul.popup_thumbs_list li');
			if (lis.length > 0) lis[this.showIdx].className = 'on';
			api.setPage(Math.floor(this.showIdx / ((MyAccount.brandedSite) ? 4 : 5)));
		}
	},
	onPopupContentSuccess: function(result) {
		$j('#FeaturesOptionsContent').html(result.html);
		var api = $j('#popupProductFeatureDiv .popup_thumbnail_rotator_body').scrollable({ api: true, size: ((MyAccount.brandedSite) ? 4 : 5), clickable: false, items: '.popup_thumbs_list', nextPage: '.arrow_right', prevPage: '.arrow_left', disabledClass: 'disabled_rotator_btns' });
		this.switchToItem(this.showIdx); // if no load required, the same section as last time was clicked
		$(this.popupId).show();
		var lis = $$('.popup_thumbnail_rotator .popup_thumbnail_rotator_body ul.popup_thumbs_list li');
//		if (console && console.log) {
//			console.log('lis length', lis.length);
//		}
		if (lis.length > 0) lis[this.showIdx].className = 'on';
		api.setPage(Math.floor(this.showIdx / ((MyAccount.brandedSite) ? 4 : 5)));
	},
	switchToItem: function(p_idx) {
		//console.info("switchToItem: " + this.showIdx);
		// big image
		$(this.popupId).select(".image_container .big_acc_image").each(function(elm, i) { elm.setStyle({ display: (i == p_idx) ? "block" : "none" }) });
		$(this.popupId).select(".popup_features_title_thumbs .white_22").each(function(elm, i) { elm.setStyle({ display: (i == p_idx) ? "block" : "none" }) });
		$(this.popupId).select(".popup_thumbnail_rotator .arrow_top").each(function(elm, i) { elm.setStyle({ visibility: (i == p_idx) ? "visible" : "hidden" }) });
		$(this.popupId).select(".popup_features_rightcol").each(function(elm, i) {
			elm.setStyle({ display: (i == p_idx) ? "block" : "none" });
			var f_show_opt = function(p_opt) {
//				if (console && console.log) {
//					//console.log("args", arguments.length, arguments);
//				}
				elm.select(".popup_info_container_bottom .finish_hover_showhide").each(function(opt, j) {
//					if (console && console.log) {
//						//console.log("j", j.length, j);
//						//console.log("p_opt", p_opt.length, p_opt);
//					}
					opt.setStyle({ display: (j == p_opt) ? "block" : "none" });
				});
				elm.select(".popup_info_container_bottom .finishTitle").each(function(opt, j) {
					opt.setStyle({ display: (j == p_opt) ? "block" : "none" });
				});
			};
			f_show_opt(0);
			elm.select(".popup_options_list LI A").each(function(atag, j) {
				atag.observe("mouseover", f_show_opt.bind(this, j));
			});
		});
	},
	hide: function() {
		$(this.popupId).hide();
	},
	onAfterUpdate: function(sender, args) {
		if (args.get_error() == undefined) {
			this.currentSectionId = this.sectionId;

//			if (console && console.log) console.info("updated!");
			this.switchToItem(this.showIdx);
			$(this.popupId).show();
		}
	}
};


var CollapserController = {
    inuse: false,
    catalog: {}, // each section calls CollapserController.add(id) which populates this struct
    wire: function() {
        for (var key in this.catalog) {
            var div = this.catalog[key] = $(key);
            Event.observe(div.select(".collapser_closed").first(), "click", this.show.bind(this, key));
            Event.observe(div.select(".collapser_open").first(), "click", this.hide.bind(this, key));
        }
    },
    add: function(p_key) {
        if (!this.inuse) {
            // if any collapsible sections are added, wire them up when the dom is fully available
            Event.observe(document, "dom:loaded", this.wire.bind(this));
            this.inuse = true;
        }
        this.catalog[p_key] = null;
    },
    show: function(p_key) {
        this.catalog[p_key].select(".collapser_closed").first().hide();
        this.catalog[p_key].select(".collapser_open").first().show();
        this.catalog[p_key].select(".features_bar_content").first().show();
    },
    hide: function(p_key) {
        this.catalog[p_key].select(".collapser_closed").first().show();
        this.catalog[p_key].select(".collapser_open").first().hide();
        this.catalog[p_key].select(".features_bar_content").first().hide();
    },
    showOnly: function(o_src) {
        var value = o_src.options[o_src.selectedIndex].value;
        for (var a in this.catalog) {
            if (value.length == 0 || value == a) this.show(a);
            else this.hide(a);
        }
    }
};


var WidgetGroup = Class.create();
WidgetGroup.prototype = {
	initialize: function(p_id) {
		this.id = p_id;
		Event.observe(document, "dom:loaded", this.onload.bind(this));
	},
	onload: function() {
		this.div = $(this.id);
		this.links = this.div.select(".widget_group_tabs_cont A");
		this.bodies = this.div.select(".widget_group_body_cont>.widget_toggle_list");
		if (this.links.length == this.bodies.length) {
			for (var i=0, len=this.links.length; i<len; i++) {
				this.links[i].setStyle({cursor:"pointer"});
				Event.observe(this.links[i], "click", this.show.bind(this,i));
			}
		}
		if (this.links.length > 0)
			this.show(0);
	},
	show: function(p_idx) {
		for (var i=0, len=this.links.length; i<len; i++) {
			this.bodies[i].setStyle({display:(i==p_idx)?"block":"none"});
		}
	}
};

var BrandPageResizer = Class.create();
BrandPageResizer.prototype = {
    initialize: function(fgOffset, bgOffset) {
        this.fgOffset = (fgOffset != undefined) ? fgOffset : 312;
        this.bgOffset = (bgOffset != undefined) ? bgOffset : 175;
        Event.observe(document, "dom:loaded", this.load.bind(this));
    },
    load: function() {
        this.bg = $("product_bg");
        this.fg = $$("#overview_tab, #features_tab, #specifications_tab, #accessories_tab").first();
        if (this.bg && this.fg) {
            Event.observe(window, "resize", this.resize.bind(this));
            this.resize();
        } else {
            alert("BrandPageResizer: fg=" + this.fg + ", bg=" + this.bg);
        }
    },
    resize: function() {
        var h = document.viewport.getHeight();
        this.bg.setStyle({ minHeight: (h - this.bgOffset) + "px" });
        this.fg.setStyle({ height: (h - this.fgOffset) + "px" });
    }
};

var DealerLocator = {
    dealerListPins: [],
    init: function() {
        //Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(this.onload.bind(this));
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.onResponse.bind(this));
    },
    onResponse: function(sender, args) {
        // check for specific postback buttons to redraw the map (not all postbacks are dealer-locator related)
        if (ajaxUpdateIncludesTrigger(sender, ["lnkFindaDealer", "btnFindaDealer", "SearchDealers", "btnSearch", "lnkBackToLocator", "btnFindADealer", "btnLocatorMoreSearchOptions", "lnkForProfessionals", "HeaderChangeLocation", "btnChangeLocation", "DDMChangeLocation", "DDMFindDealers", "DDMForProfessionals"])) {
            //console.info("onResponse:SearchDealers");
            HHTSitecore.services.DealerLocatorMapData.GetDealers(this.onDealers.bind(this), this.onFault.bind(this), null);
        }
        // TODO: ALSO check for postbacks specific to the dealer locator footer update panel
        //        if (ajaxUpdateIncludesTrigger(sender, ["lnkFindaDealer", "btnFindaDealer", "SearchDealers", "btnSearch", "lnkBackToLocator", "DealerFooterUpdateButton", "DealerFooterUpdateButtonTab2", "btnFindADealer", "btnLocatorMoreSearchOptions", "lnkForProfessionals", "HeaderChangeLocation", "btnChangeLocation"])) {
        //            this.wireRotators();
        //        }
        if (ajaxUpdateIncludesTrigger(sender, ["btnInfoHelp", "btnInfoDrawer"])) {
            $j("[id$='udInfoDrawer']").css({ position: 'static' });
            //called from footer list or button, default to brands tab
        }
        if (ajaxUpdateIncludesTrigger(sender, ["btnAwardInfo"])) {
            $j("[id$='udInfoDrawer']").css({ position: 'static' });
            //called from dealerlist default to awards tab
        }

        //        if (ajaxUpdateIncludesTrigger(sender, ["btnSubmitServiceRequest"])) {
        //            var success = $j("[id$='hdnServiceRequestSuccessful']").val();
        //            alert("Service Request Check: " + success);
        //            if (success == "1") {
        //                alert("success");
        //                $j("[id$='hdnServiceRequestSuccessful']").val("0")
        //                $j("#serviceRequestPopup").hide();

        //                var msg = "Thank you for contacting Fireside Hearth & Home. Someone will be responding within two business days of your request.";
        //                GenericMessagePopup.show('Service Request', msg);
        //            }
        //        }

    },
    wireRotators: function() {
        /*var size = 4, id = "#dealer_detail_rotator", itemsSlider = ".brand_list";
        $j(id + "_1," + id + "_2").scrollable({ size: size, clickable: false, items: itemsSlider, prevPage: ".related_products_arrow_left", nextPage: ".related_products_arrow_right", disabledClass: "disabled_rotator_btns" });
        // some cleanup for extra right-arrow when count == page size
        for (var i = 1; i <= 2; i++) {
        if ($j(id + "_" + i + ">" + itemsSlider).children().size() <= size) {
        $j(id + "_" + i).children(".related_products_arrow_right").hide();
        }
        }*/
    },
    onDealers: function(result, context) {

        var LatLngList = new Array(); //(new google.maps.LatLng(52.537, -2.061), new google.maps.LatLng(52.564, -2.017));

        //console.info("onDealers:", result);
        if (result.length > 0) {
            // center map on first result
            this.loadMap(new google.maps.LatLng(result[0].Latitude, result[0].Longitude));
            this.wireDealerList(result);
        }
        var firstDealer = null;
        (result.length).times(function(i) {
            var dealer = result[i];
            var pos = new google.maps.LatLng(dealer.Latitude, dealer.Longitude);
            //console.info("adding marker: ", dealer, pos);
            var icon = new google.maps.MarkerImage(dealer.PinImage);
            dealer.tmpMarker = new google.maps.Marker({ position: pos, map: this.map, title: dealer.DealerName, icon: icon });
            google.maps.event.addListener(dealer.tmpMarker, "click", function() {
                this.goToDealer(dealer);
                //alert("You clicked on " + dealer.DealerName);
                //this.map.panTo(new google.maps.LatLng(dealer.Latitude, dealer.Longitude));
            } .bind(this));
            if (i == 0)
                firstDealer = dealer;

            LatLngList[i] = pos;

        }, this);

        if (firstDealer != null)
            this.goToDealer(firstDealer);


        //MAP AUTO ZOOM FUNCTIONALITY - Also uncomment array above.
        //alert(LatLngList.length);

        if (LatLngList.length != 1) { //only fitBounds if more than one dealer, else default
            //Create a new viewpoint bound
            var bounds = new google.maps.LatLngBounds();

            //Go through each...
            for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {

                //And increase the bounds to take this point
                bounds.extend(LatLngList[i]);
            }

            //Fit these bounds to the map
            this.map.fitBounds(bounds);
        }
        
    },
    goToAward: function(tabIdx) {
        //defaultTabIdx = 0 for awards, 1 for brands 
        //- fireplaces shows both brand and award
        //- fireside shows only brand
        //- brand sites show only awards
        var btnId = (tabIdx == 1) ? "btnShowBrandDrawer" : "btnShowAwardDrawer";
        var btn = $j("[id$='" + btnId + "']").get(0);
        $j("[id$='udInfoDrawer']").css({ position: 'static' });
        __doPostBack(btn.name, '');
    },
    closeDrawer: function() {
        $('divInfoDrawer').hide();
        $j("[id$='udInfoDrawer']").css({ position: 'absolute' });
    },
    CloseCurrent: function() {
        // google-style pin info
        if (this.currentInfo) {
            this.currentInfo.close();
            this.currentInfo = null;
        }
    },
    setMyFireside: function() {
        var selectedDealerID = $j("[id$='hdnDealerDetailDealerID']").val();
        var myFiresideDealerID = $j("[id$='hdnMyFiresideDealerID']").val();
        if (selectedDealerID == myFiresideDealerID) {
            $j('#btnMakeMyFiresideLocation').hide();
            $j("#lblThisIsMyFireside").show();
        }
        else {
            $j('#btnMakeMyFiresideLocation').show();
            $j("#lblThisIsMyFireside").hide();
        }
    },
    goToDealer: function(dealer) {

        this.currentDealer = dealer;

        //update bottom panel
        var btn = $j("[id$='DealerFooterUpdateButton']").get(0);
        $j("[id$='hdnDealerDetailDealerID']").val(dealer.DealerID);
        __doPostBack(btn.name, '');

        this.CloseCurrent();

        // custom pin info
        var info = new HHTMapPinInfo({ content: dealer.InfoContents });
        info.open(this.map, dealer.tmpMarker);

        google.maps.event.addListener(info, "closeclick", function() { this.currentInfo = null } .bind(this));
        this.currentInfo = info;

        // simply pan to location
        //this.map.panTo(new google.maps.LatLng(dealer.Latitude, dealer.Longitude));
    },
    wireDealerList: function(result) {
        this.dealerListPins = $$(".dealer_pin");
        //if (this.dealerListPins.length != result.length) console.warn(this.dealerListPins, "<>", result.length);
        this.dealerListPins.each(function(elm, i) {
            elm.observe("click", this.goToDealer.bind(this, result[i]));
        }, this);
    },
    loadMap: function(p_center) { // reloaded after each search, since the entire locator is reloaded from the updatepanel

        var myOptions = {
            zoom: 11,
            center: p_center,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false,
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.DEFAULT
            }
        };
        this.map = new google.maps.Map($("google_map"), myOptions);


    },

    contactDealer: function() {
        var button = $j("[id$='btnSendToDealer']").eq(0);
        var h = button.attr('href');
        if (h.substring(0, 11) == "javascript:") {
            eval(h.substring(11));
        } else {
            window.location = h;
        }
    },
    onFault: function(result, context) {
        if (typeof (console) != "undefined") console.error("DealerLocator.onfault:", result);
    },
    onSearchDefault: function(cntrl) {
        var findADealerButton = $j("[id$='" + cntrl + "']").get(0);
        findADealerButton.click();
    },
    launchDefault: function() {
        var findADealerButton = $j("[id$='btnLaunchDefaultLocator']").get(0);
        findADealerButton.click();
    },
    launchDefaultProfessional: function() {
        var findADealerButton = $j("[id$='btnLaunchDefaultProfessionalLocator']").get(0);
        findADealerButton.click();
    },
    onSaveMyFiresideSuccess: function() {
        this.updateFiresideHeaderAndFooter();
    },
    onSaveMyFiresideFailure: function() {

    },
    saveMyFireside: function() {

        //set hidden values on dealer detail control
        var selectedDealerID = $j("[id$='hdnDealerDetailDealerID']").val();
        $j("[id$='hdnMyFiresideDealerID']").val(selectedDealerID);

        HHTSitecore.services.DealerLocatorMapData.SaveMyFireside(selectedDealerID, this.onSaveMyFiresideSuccess.bind(this), this.onSaveMyFiresideFailure.bind(this));

        //show hide buttons on map dealer popup window
        $j('#btnMakeMyFiresideLocation').hide();
        $j("#lblThisIsMyFireside").show();

    },

    updateFiresideHeaderAndFooter: function() {
        // Fireside My Fireside DDM update panel
        var myFiresideDDM = $j("[id$='FiresideMyLocationDDMPanel']").get(0);
        __doPostBack(myFiresideDDM.id, '');

        //var myFiresideHeaderSearch = $j("[id$='firesideHeaderSearchUpdatePanel']").get(0);
        //__doPostBack(myFiresideHeaderSearch.id, '');

        //var myFiresideFooterLocator = $j("[id$='StaticBrandedFADPanel']").get(0);
        //__doPostBack(myFiresideFooterLocator.id, '');
    }


    //    ,

    //    onSearch: function(src) {
    //        var geocoder = new google.maps.Geocoder();
    //        var userEntry = $j("#" + src).val();

    //        if (geocoder) {
    //            geocoder.geocode({ 'address': userEntry }, function(results, status) {

    //                var theResults = results[0];
    //                var vals = theResults.geometry.location;
    //                var coords = vals.split(",");

    //                $j("[id$='hdnGLat']").val(theResults.geometry.location);
    //                $j("[id$='hdnGLon']").val(theResults.geometry.location);
    //            });
    //        }
    //    }




};
Event.observe(document, "dom:loaded", function() { DealerLocator.init() });

// non-Prototype class that extends google's OverlayView
var HHTMapPinInfo = (function() {
    if (typeof (google) == "undefined") return;
    var f = function(options) {
        //console.log("HHTMapPinInfo.initialize:", arguments); //Causing scripts to abort in IE
        this.options = options;
    };
    f.prototype = Object.extend(google.maps.OverlayView.prototype, {
        // control functions
        open: function(map, marker) {
            //console.log("HHTMapPinInfo.open:", arguments);//Causing scripts to abort in IE
            this.setMap(map);
            this.marker = marker;
            this.map = map;
        },
        close: function() {
            //console.log("HHTMapPinInfo.close:", arguments);//Causing scripts to abort in IE
            this.setMap(null);

        },
        // functions expected by the google map api
        onAdd: function() {
            this.div = new Element("div");
            this.div.addClassName = "popup hover226";
            this.div.style.position = "absolute";
            this.div.update("<div class=\" dealer_info hover_top\">" + this.options.content + "</div><div class=\"dealer_info hover_btm\"></div>");
            this.getPanes().floatPane.appendChild(this.div);
            //console.log("HHTMapPinInfo.onAdd:", arguments, this.options.content);//Causing scripts to abort in IE
        },
        onRemove: function() {
            if (this.div.parentNode != null) {
                this.div.parentNode.removeChild(this.div)
                this.div = null;
                //console.log("HHTMapPinInfo.onRemove:", arguments);//Causing scripts to abort in IE
            }
        },
        draw: function() {
            //alert('draw');
            var overlayProjection = this.getProjection();
            var sw = overlayProjection.fromLatLngToDivPixel(this.marker.getPosition());


            this.div.style.left = sw.x + 20 + 'px'; this.div.style.top = sw.y - 82 + 'px';
            //console.log("HHTMapPinInfo.draw:", arguments, " div:", this.div);//Causing scripts to abort in IE

            if (this.alreadyMoved == undefined) {
                this.alreadyMoved = true;

                var newpoint = new google.maps.Point(sw.x + 40, sw.y + 100)

                this.map.panTo(overlayProjection.fromDivPixelToLatLng(newpoint));
            }

            //alert("Magic?");
            DealerLocator.setMyFireside();

        }
    });
    return f;
})();

OptionBrowse = {
    open: null,
    timer: -1,
    wired: {},
    wireOptionBrowse: function(src, key) {
        // store a reference to the wired menu trigger (once)
        if (this.wired[key] == undefined) {
            this.wired[key] = src;
            // set up local scoped functions to retain the key
            var f_over = function() { OptionBrowse.over(key) };
            var f_out = function() { OptionBrowse.out(key) };
            // add mouseover and mouseout event listeners
            $j(src).hover(f_over, f_out);
        }
        this.over(key);
    },
    over: function(key) {
        this.cancel();
        this.close();
        this.open = $j(key).css("display", "block");
        this.openKey = key;
        $j(this.wired[key]).addClass("finish_on");
    },
    out: function(key) {
        this.cancel();
        //this.timer = window.setTimeout(this.close, 400);
    },
    close: function() {
        if (this.open) {
            this.open.css("display", "none");
            $j(this.wired[this.openKey]).removeClass("finish_on");
        }
        this.open = null;
    },
    cancel: function() {
        if (this.timer >= 0) window.clearTimeout(this.timer);
        this.timer = -1;
    }
};

var DontAddThis = {
    init: function() {
        //if (document.location.href.indexOf("quadrafire") >= 0) $j(".toolbox_tab_1_off, .toolbox_tab_2_on").remove();
        setInterval(this.remove.bind(this), 1000);
    },
    remove: function() {
        $j("ul.share_list li a span").remove();
    }
};
Event.observe(document, "dom:loaded", function() { DontAddThis.init(); });

   SpecNav = {
       open: null,
       timer: -1,
       wired: {},
       wireSpecNav: function(src, key) {
           if (this.wired[key] == undefined) {
               this.wired[key] = src;
               var f_over = function() { SpecNav.over(key) };
               var f_out = function() { SpecNav.out(key) };
               $j(src).hover(f_over, f_out);
           }
       },
       over: function(key) {
           $j("#divPreviews div").hide();
           $j(key).show();
       },
       out: function(key) {}

   };

   // Every navigation action should go thru setFolder if the action needs to reset the session folder, or showFolder if not
   var MyAccount = {
       isAuthenticated: false, // Is the current user authenticated
       pendingSection: null, // Tabs, sections in the Folders tab (Products, Articles, Idea Boards, Comparisons, Notes, People)
       pendingTab: null, // Overview, folders, Profile
       pendingAction: null,
       brandedSite: false, // Is the current site branded or not
       staticBrandedSite: false, // Is the current site in the static Branded site templates (Heatilator, Harman, Fireside)
       createProjectSource: null,
       init: function() { // Initializes isAuthenticated, On Success method sets the div content
           if (document.URL.indexOf('Syndicated') < 0 && document.URL.indexOf('?s=1') < 0 && document.URL.indexOf('&s=1') < 0) {
               if (HHTSitecore.services.MyAccountService != null) {
                   HHTSitecore.services.MyAccountService.IsAuthenticated(this.onMyAccountInitSuccess.bind(this), this.onMyAccountInitFailure.bind(this), null);
               }
           }
       },
       onMyAccountInitSuccess: function(result, context) {
           var signInPopupBlurb;
           this.isAuthenticated = result.isAuthenticated;
           if (!this.isAuthenticated) {
               if (document.URL.indexOf('My-Account.aspx') >= 0) {
                   if (!this.brandedSite) {
                       if (document.URL.indexOf('sharedfolder') >= 0) {
                           var sharedPosition = document.URL.indexOf('sharedfolder');
                           var folderIDPosition = document.URL.indexOf('=', sharedPosition) + 1;
                           var folderID = document.URL.substring(folderIDPosition);
                           this.showMyAccountFoldersTab(folderID, 'products');
                           this.pendingAction = "Shared Registration";
                           signInPopupBlurb = 'You\'ll need to sign in before you can view this shared folder.';
                       }
                       else {
                           window.location = window.location.href.replace(window.location.search, '').replace(window.location.pathname, '');
                       }
                   }
                   else {
                       if (document.URL.indexOf('sharedfolder') >= 0) {
                           var sharedPosition = document.URL.indexOf('sharedfolder');
                           var folderIDPosition = document.URL.indexOf('=', sharedPosition) + 1;
                           var folderID = document.URL.substring(folderIDPosition);
                           this.showBrandedMyAccountFoldersTab(folderID, 'products');
                           this.pendingAction = "Shared Registration";
                           signInPopupBlurb = 'You\'ll need to sign in before you can view this shared folder.';
                       }
                       else {
                           window.location = window.location.href.replace(window.location.search, '').replace(window.location.pathname, '');
                       }
                   }
                   MyAccount.showSignInPopup(signInPopupBlurb);
               } // document.url.indexOf('MyAccount') >= 0
               else { // Quad or Heatnglo
                   //if (document.URL.indexOf('My') >= 0) {
                   if (document.URL.indexOf('My-Heat-n-Glo') >= 0 || document.URL.indexOf('My-QuadraFire') >= 0) {
                       if (document.URL.indexOf('sharedfolder') >= 0) {
                           var sharedPosition = document.URL.indexOf('sharedfolder');
                           var folderIDPosition = document.URL.indexOf('=', sharedPosition) + 1;
                           var folderID = document.URL.substring(folderIDPosition);
                           this.showBrandedMyAccountFoldersTab(folderID, 'products');
                           this.pendingAction = "Shared Registration";
                           MyAccount.showSignInPopup('You\'ll need to sign in before you can view this shared folder.');
                       }
                       else {
                           window.location = window.location.href.replace(window.location.search, '').replace(window.location.pathname, '');
                       }
                   }
               }
           }
           else {
               if (!this.brandedSite) {
                   if (document.URL.indexOf('sharedfolder') >= 0) {
                       var sharedPosition = document.URL.indexOf('sharedfolder');
                       var folderIDPosition = document.URL.indexOf('=', sharedPosition) + 1;
                       var folderID = document.URL.substring(folderIDPosition);
                       this.showMyAccountFoldersTab(folderID, 'products');
                   }
               }
               else {
                   if (document.URL.indexOf('sharedfolder') >= 0) {
                       var sharedPosition = document.URL.indexOf('sharedfolder');
                       var folderIDPosition = document.URL.indexOf('=', sharedPosition) + 1;
                       var folderID = document.URL.substring(folderIDPosition);
                       this.showBrandedMyAccountFoldersTab(folderID, 'products');
                   }
               }
           }
       },
       onMyAccountInitFailure: function(result, context) {
           this.isAuthenticated = false;
       },
       authenticationCheck: function() {
           HHTSitecore.services.MyAccountService.IsAuthenticated(this.onAuthCheckSuccess.bind(this));
       },
       onAuthCheckSuccess: function(result) {
           this.isAuthenticated = result.isAuthenticated;
           if (this.isAuthenticated == false) {
               this.logout();
           }
       },
       createAccount: function(firstName, lastName, userName, password, reenteredPassword, emailAddress, postalCode, country, rememberMe, signUpForNewsletter) {
           // Creates a new account, On Success method sets div content
           WaitPopup.show();
           HHTSitecore.services.MyAccountService.CreateAccount(firstName, lastName, userName, password, reenteredPassword, emailAddress, postalCode, country, rememberMe, signUpForNewsletter, this.onCreateSuccess.bind(this), this.onCreateFailure.bind(this), null);
       },
       onCreateSuccess: function(result, context) {
           if (result.status) {
               this.isAuthenticated = true;
               $j(result.welcomeDiv).html("");
               $j(result.welcomeDiv).html(result.welcomeHTML);
               $j('#registrationDimmer').hide();
               if (result.menuHTML != "") {
                   if (this.brandedSite == true) {
                       $j('.user_info').show();
                       $j('#MyAccountMenu').html(result.menuHTML);
                   }
                   else if (this.staticBrandedSite == true) {
                       $j('#myAccountDMMContainer').html(result.menuHTML);
                   }
                   this.completeSignIn();
               }
               else {
                   /****** IMPORTANT *******/
                   // You can use this 2 - 3 line pattern to update a specific UpdatePanel.
                   // The first line gets a reference to the panel
                   // The 2nd line does a postback just on that panel using the ID
                   // The 3rd line registers an endRequest handler on the ending of that postback
                   var myAccountLinksPanel = $j("[id$='TopNavSignInUpdatePanel']").get(0);
                   __doPostBack(myAccountLinksPanel.id, '');
                   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeSignIn);
                   TopNav.wired['myaccount'] = null;
               }
               if (result.footerDLHTML != "") {
                   $j('#footerDealerLocatorWrapper').html(result.footerDLHTML);
               }
               if (result.footerMAHTML != "") {
                   $j('#MyAccountFooterContainer').html(result.footerMAHTML);
               }
           }
           else {
               WaitPopup.hide();
               if (result.isAlreadyRegistered == true) {
                   $j('#registrationDimmer').hide();
                   $j('#AlreadyRegisteredDimmer').show();
               }
               else {
                   $j('#CreateErrorMessageDiv').text(result.errorMessage);
                   this.isAuthenticated = false;
               }
           }
           //_gaq.push(['_trackEvent', 'Leads', 'Submit', 'My Account']);
           EventTracking.trackEvent('Leads', 'Submit', 'My Account', '');
       },
       onCreateFailure: function(result, context) {
           WaitPopup.hide();
           this.isAuthenticated = false;
       },
       showSignInPopup: function(blurbText) {
           $j('#SignInPopupBlurbText').text(blurbText);
           $j('#SigninPopupDimmer').show();
       },
       signIn: function(userName, password, autoSignIn, callingDiv) {
           //alert('test');
           // Authenticates the user, On Success method sets div content
           $j('#ForgotPasswordP').show();
           $j('#ErrorMessageP').hide();
           WaitPopup.show();
           HHTSitecore.services.MyAccountService.SignIn(userName, password, autoSignIn, callingDiv, this.onSignInSuccess.bind(this), this.onSignInFailure.bind(this), null);

       },
       onSignInSuccess: function(result, context) {
           if (result.status) {
               this.isAuthenticated = true;
               $j(result.signInDiv).hide();
               $j(result.welcomeDiv).html("");
               $j(result.welcomeDiv).html(result.welcomeHTML);
               if (result.menuHTML != null && result.menuHTML != "") {
                   if (this.brandedSite == true) {
                       $j('.user_info').show();
                       $j('#MyAccountMenu').html(result.menuHTML);
                       this.completeSignIn();
                   }
                   else if (this.staticBrandedSite == true) {

                       $j('#myAccountDDMContainer').html(result.menuHTML);

                       if (GetCurrentSite() == "fireside") {
                           var myAccountLinksPanel = $j("[id$='FiresideMyAccountDDMPanel']").get(0);
                           if (myAccountLinksPanel) {
                               __doPostBack(myAccountLinksPanel.id, '');
                               Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeSignIn);
                               TopNav.wired['myaccount'] = null;
                           }
                       }
                       else {
                           this.completeSignIn();
                       }
                   }
                   else if (window.location.href.indexOf('IdeaGallery') >= 0) {
                       this.completeSignIn();
                   }
                   //this.completeSignIn();
               }
               else {
                   var myAccountLinksPanel = (GetCurrentSite() == "fireside") ? $j("[id$='FiresideMyAccountDDMPanel']").get(0) : $j("[id$='TopNavSignInUpdatePanel']").get(0);
                   if (myAccountLinksPanel) {
                       __doPostBack(myAccountLinksPanel.id, '');
                       Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeSignIn);
                       TopNav.wired['myaccount'] = null;
                   }
                   else {
                       this.completeSignIn();
                   }
               }
               if (result.footerDLHTML != "") {
                   $j('#footerDealerLocatorWrapper').html(result.footerDLHTML);
               }
               if (result.footerMAHTML != "") {
                   $j('#MyAccountFooterContainer').html(result.footerMAHTML);
               }
           }
           else {
               WaitPopup.hide();
               if (result.isAlreadyRegistered == true) {
                   $j(result.signInDiv).hide();
                   $j('#AlreadyRegisteredDimmer').show();
               }
               else {
                   if ($j('#SigninPopupDimmer').is(':visible')) {
                       $j('#PopupErrorMessageP').show();
                       $j('#PopupErrorMessageDiv').text(result.errorMessage);
                   }
                   else {
                       $j('#ErrorMessageP').show();
                       $j('#ErrorMessageDiv').text(result.errorMessage);
                   }
                   this.isAuthenticated = false;
               }
           }
       },
       onSignInFailure: function(result, context) {
           //alert('fail');
           WaitPopup.hide();
           this.isAuthenticated = false;
       },
       completeSignIn: function() {
           if (PopupAuthenticationHandler.pendingType) {
               WaitPopup.hide();
               PopupAuthenticationHandler.pendingType();
           }
           if (window.location.pathname == '/' && window.location.search.indexOf('sharedfolder') < 0) {
               var myAccountPage;

               if (MyAccount.brandedSite) {
                   if (window.location.href.indexOf('heatnglo') >= 0) {
                       myAccountPage = 'My-Heat-n-Glo.aspx';
                   }
                   else if (window.location.href.indexOf('quadrafire') >= 0) {
                       myAccountPage = 'My-QuadraFire.aspx';
                   }
               }
               else if (MyAccount.staticBrandedSite) {
                   myAccountPage = 'Header-Toolbox/My-Account.aspx';
               }
               else {
                   myAccountPage = 'Header-Toolbox/My-Account.aspx';
               }
               var newLocation;
               if (window.location.search == '' || window.location.search == '?') {
                   newLocation = window.location.href.substr(0, window.location.href.length - window.location.search.length) + myAccountPage;
               }
               else if (window.location.search.length > 1) {
                   newLocation = window.location.href.replace(window.location.search, myAccountPage + window.location.search);
               }
               window.location = newLocation;
           }
           else {
               WaitPopup.hide();
           }
       },
       logout: function() {
           // Logs out the current user, On Success method sets div content
           WaitPopup.show();
           HHTSitecore.services.MyAccountService.Logout(this.onLogoutSuccess.bind(this), this.onLogoutFailure.bind(this), null);
       },
       logoutOnClose: function() {
           HHTSitecore.services.MyAccountService.Logout();
       },
       onLogoutSuccess: function(result, context) {
           if (window.location.href.indexOf('IdeaGallery') >= 0) {
               this.completeLogout();
           }
           else if (result.menuHTML != "") {
               this.isAuthenticated = false;
               if (this.brandedSite == true) {
                   $j('.user_info').show();
                   $j('.user_info').html(result.logoutStateHTML);
                   $j('#MyAccountMenu').html(result.menuHTML);
                   this.completeLogout();
               }
               else if (this.staticBrandedSite == true) {
                   $j('#welcome_panel').html(result.logoutStateHTML);
                   $j('#myAccountDDMContainer').html(result.menuHTML);

                   if (GetCurrentSite() == "fireside") {
                       var myAccountLinksPanel = $j("[id$='FiresideMyAccountDDMPanel']").get(0);
                       if (myAccountLinksPanel) {
                           __doPostBack(myAccountLinksPanel.id, '');
                           Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeLogout);
                           TopNav.wired['myaccount'] = null;
                       }
                   }
                   else {
                       this.completeLogout();
                   }

               }
           }
           else {
               this.isAuthenticated = false;
               $j('#welcome_panel').html(result.logoutStateHTML);
               var myAccountLinksPanel = $j("[id$='TopNavSignInUpdatePanel']").get(0);
               if (myAccountLinksPanel) {
                   __doPostBack(myAccountLinksPanel.id, '');
                   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeLogout);
                   TopNav.wired['myaccount'] = null;
               }
           }
           if (result.footerDLHTML != "") {
               $j('#footerDealerLocatorWrapper').html(result.footerDLHTML);
           }
           if (result.footerMAHTML != "") {
               $j('#MyAccountFooterContainer').html(result.footerMAHTML);
           }
       },
       onLogoutFailure: function(result, context) {
           WaitPopup.hide();
           alert('Failure, message: ' + result.errorMessage);
       },
       completeLogout: function() {
           if (window.location.pathname.indexOf('My-') >= 0) {
               var newLocation = window.location.href.substring(0, window.location.href.indexOf(window.location.pathname));
               window.location = newLocation;
           }
           else {
               WaitPopup.hide();
           }
       },
       sendPassword: function(email) {
           // Sends the user a temporary password
           HHTSitecore.services.MyAccountService.SendPassword(email, this.onForgotPasswordSuccess.bind(this), this.onForgotPasswordFailure.bind(this), null);
       },
       onForgotPasswordSuccess: function(result, context) {
           if (result.status) {
               alert('A temporary random password has been sent.  Please signin with that password and change it if you need to.');
               $j('#ForgotPasswordDimmer').hide();
           }
           else {
               alert(result.errorMessage);
           }
       },
       onForgotPasswordFailure: function(result, context) {
           alert(result.errorMessage);
       },
       setFolder: function(brandedSite, folderID, tab, section, action, fRunOnSuccess) {
           this.authenticationCheck();
           // Sets the Session FolderID
           this.brandedSite = brandedSite;
           if (!folderID) { return; }
           if (tab) { this.pendingTab = tab; }
           if (section) { this.pendingSection = section; }
           if (action) { this.pendingAction = action; }

           HHTSitecore.services.MyAccountService.SetSelectedFolder(folderID, function() {
               this.onSetFolderSuccess.apply(this, arguments);
               if (typeof (fRunOnSuccess) == "function") fRunOnSuccess();
           } .bind(this), this.onSetFolderFailure.bind(this), null);
       },
       completeShowFolder: function() {
           if (PopupAuthenticationHandler.pendingType) {
               PopupAuthenticationHandler.pendingType();
           }
           else if (MyAccount.pendingAction == "Show Folder") {
               MyAccount.showFolder();
           }
           else if (MyAccount.pendingAction == "Share Folder") {
               MyAccount.showFolder();
               MyAccount.shareFolder();
           }
           else if (MyAccount.pendingAction == "Send Folder To Dealer") {
               MyAccount.showFolder();
               MyAccount.sendFolderToDealer();
           }
           else if (MyAccount.pendingAction == "Shared Registration") {
               $j('#registrationDimmer').show();
           }
           else if (MyAccount.pendingAction == "Readonly Folder") {
               MyAccount.showFolder();
           }
           WaitPopup.hide();
       },
       onSetFolderSuccess: function(result, context) {
           if (result.status) {
               ProjectFolder.isMyFolder = result.isMyFolder;

               var foldersPanel = $j("[id$='FoldersUpdatePanel']").get(0);
               if (foldersPanel) {
                   __doPostBack(foldersPanel.id, this.pendingSection);
                   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeShowFolder);
               }
           }
           else {
               alert(result);
           }
       },
       onSetFolderFailure: function(result, context) {
           alert(result);
       },
       showFolder: function(brandedSite, tab, section, action) {
           if (tab) { this.pendingTab = tab; }
           if (section) { this.pendingSection = section; }
           if (action) { this.pendingAction = action; }
           if (brandedSite) { this.brandedSite = brandedSite; }

           if (this.pendingTab == 'folders') {
               $j('#MyAccountTabTitle').html('&nbsp');
               if (this.brandedSite) {
                   this.showBrandedMyAccountFoldersTab();
               }
               else {
                   this.showMyAccountFoldersTab();
               }
               if (this.pendingSection) {
                   if (this.pendingSection == 'products') {
                       this.showFoldersSavedContentTab();
                   }
                   else if (this.pendingSection == 'ideaBoards') {
                       this.showFoldersSavedContentTab();
                   }
                   else if (this.pendingSection == 'comparisons') {
                       this.showFoldersSavedContentTab();
                   }
                   else if (this.pendingSection == 'articles') {
                       this.showFoldersSavedContentTab();
                   }
                   else if (this.pendingSection == 'notes') {
                       this.showFoldersNotesTab();
                   }
                   else if (this.pendingSection == 'people') {
                       if (ProjectFolder.isMyFolder) {
                           this.showFoldersPeopleTab();
                       }
                       else {
                           this.pendingSection = 'products';
                           this.showFoldersSavedContentTab();
                       }
                   }
               }
               if (!ProjectFolder.isMyFolder) {
                   MyAccount.showReadOnlyFolder();
               }
           }
           else if (this.pendingTab == 'overview' && !ProjectFolder.isDealer) {
               $j('#MyAccountTabTitle').html('&nbsp;');
               if (this.brandedSite) {
                   this.showBrandedMyAccountOverviewTab();
               }
               else {
                   this.showMyAccountOverviewTab();
               }
           }
           else if (this.pendingTab == 'profile') {
               $j('#MyAccountTabTitle').show().text(': Profile');
               if (this.brandedSite) {
                   this.showBrandedMyAccountProfileTab();
               }
               else {
                   this.showMyAccountProfileTab();
               }
           }
       },
       showReadOnlyFolder: function() {
           $j('#foldersNewProjectLink').hide();
           $j('#EditNotes').hide();
           $j('#myAccountProductSectionAddProduct').hide();
           $j('.people').hide();
           var folderTabName = $j("[id$='FolderTabFolderName']").get(0);
           if (folderTabName) {
               $j(folderTabName.id).text('&nbsp;');
           }
           //   		if ($j('.current_folder')) {
           //   			$j('.current_folder .grey_light_subnav .subnav_grey_light_send').hide();
           //   			$j('.current_folder .grey_light_subnav .subnav_grey_light_delete').hide();
           //   		}

       },
       showBrandedMyAccountFoldersTab: function() {
           $j('#MyAccountWrapperDiv').removeClass('my_account').addClass('my_account_folders');
           $j('#FoldersLI').removeClass('off');
           if (!$j('#FoldersLI').hasClass('on')) {
               $j('#FoldersLI').addClass('on');
           }
           $j('#OverviewLI').removeClass('on');
           if (!$j('#OverviewLI').hasClass('off')) {
               $j('#OverviewLI').addClass('off');
           }
           $j('#ProfileLI').removeClass('on');
           if (!$j('#ProfileLI').hasClass('off')) {
               $j('#ProfileLI').addClass('off');
           }
           $j('#brandedMyAccountOverviewDiv').hide();
           $j('#brandedMyAccountFolderDiv').show();
           $j('#brandedMyAccountProfileDiv').hide();
           $j('#RightColDiv').show();
           $j('#WelcomeTextBlurb').hide();
       },
       showBrandedMyAccountProfileTab: function() {
           $j('#MyAccountWrapperDiv').removeClass('my_account').addClass('my_account_folders');
           $j('#ProfileLI').removeClass('off');
           if (!$j('#ProfileLI').hasClass('on')) {
               $j('#ProfileLI').addClass('on');
           }
           $j('#FoldersLI').removeClass('on');
           if (!$j('#FoldersLI').hasClass('off')) {
               $j('#FoldersLI').addClass('off');
           }
           $j('#OverviewLI').removeClass('on');
           if (!$j('#OverviewLI').hasClass('off')) {
               $j('#OverviewLI').addClass('off');
           }
           $j('#brandedMyAccountOverviewDiv').hide();
           $j('#brandedMyAccountFolderDiv').hide();
           $j('#brandedMyAccountProfileDiv').show();
           $j('#RightColDiv').hide();
           $j('#WelcomeTextBlurb').hide();
       },
       showBrandedMyAccountOverviewTab: function() {
           $j('#MyAccountWrapperDiv').removeClass('my_account_folders').addClass('my_account');
           $j('#OverviewLI').removeClass('off');
           if (!$j('#OverviewLI').hasClass('on')) {
               $j('#OverviewLI').addClass('on');
           }
           $j('#FoldersLI').removeClass('on');
           if (!$j('#FoldersLI').hasClass('off')) {
               $j('#FoldersLI').addClass('off');
           }
           $j('#ProfileLI').removeClass('on');
           if (!$j('#ProfileLI').hasClass('off')) {
               $j('#ProfileLI').addClass('off');
           }
           $j('#brandedMyAccountOverviewDiv').show();
           $j('#brandedMyAccountFolderDiv').hide();
           $j('#brandedMyAccountProfileDiv').hide();
           $j('#RightColDiv').show();
           $j('#WelcomeTextBlurb').show();
       },
       showMyAccountOverviewTab: function() {
           $j('#OverviewTabContentDiv').show();
           $j('#FolderTabContentDiv').hide();
           $j('#ProfileTabContentDiv').hide();
           $j('#foldersli').removeClass('folders_on');
           $j('#foldersli').addClass('folders_off');
           $j('#firstli').removeClass('first_off');
           $j('#firstli').addClass('first_on');
           $j('#overviewli').removeClass('overview_off');
           $j('#overviewli').addClass('overview_on');
           $j('#midfoldersli').removeClass('mid_off_on');
           $j('#midfoldersli').addClass('mid_off_off');
           $j('#midfoldersli').removeClass('mid_on_off');
           $j('#midoverviewli').removeClass('mid_off_off');
           $j('#midoverviewli').addClass('mid_on_off');
           $j('#midoverviewli').removeClass('mid_off_on');
           $j('#profileli').removeClass('profile_on');
           $j('#profileli').addClass('profile_off');
           $j('#lastli').removeClass('last_on');
           $j('#lastli').addClass('last_off');
           $j('#MyAccountRightColumnDiv').show();
           $j('#WelcomeTextBlurb').show();
       },
       showMyAccountFoldersTab: function() {
           $j('#OverviewTabContentDiv').hide();
           $j('#FolderTabContentDiv').show();
           $j('#ProfileTabContentDiv').hide();
           $j('#foldersli').addClass('folders_on');
           $j('#foldersli').removeClass('folders_off');
           $j('#firstli').addClass('first_off');
           $j('#firstli').removeClass('first_on');
           $j('#overviewli').addClass('overview_off');
           $j('#overviewli').removeClass('overview_on');
           $j('#midfoldersli').removeClass('mid_off_on');
           $j('#midfoldersli').removeClass('mid_off_off');
           $j('#midfoldersli').addClass('mid_on_off');
           $j('#midoverviewli').removeClass('mid_off_off');
           $j('#midoverviewli').removeClass('mid_on_off');
           $j('#midoverviewli').addClass('mid_off_on');
           $j('#profileli').removeClass('profile_on');
           $j('#profileli').addClass('profile_off');
           $j('#lastli').removeClass('last_on');
           $j('#lastli').addClass('last_off');
           $j('#MyAccountRightColumnDiv').show();
           $j('#WelcomeTextBlurb').hide();
       },
       showMyAccountProfileTab: function() {
           $j('#OverviewTabContentDiv').hide();
           $j('#FolderTabContentDiv').hide();
           $j('#ProfileTabContentDiv').show();
           $j('#foldersli').removeClass('folders_on');
           $j('#foldersli').addClass('folders_off');
           $j('#firstli').addClass('first_off');
           $j('#firstli').removeClass('first_on');
           $j('#overviewli').addClass('overview_off');
           $j('#overviewli').removeClass('overview_on');
           $j('#midfoldersli').addClass('mid_off_on');
           $j('#midfoldersli').removeClass('mid_off_off');
           $j('#midfoldersli').removeClass('mid_on_off');
           $j('#midoverviewli').addClass('mid_off_off');
           $j('#midoverviewli').removeClass('mid_on_off');
           $j('#midoverviewli').removeClass('mid_off_on');
           $j('#profileli').addClass('profile_on');
           $j('#profileli').removeClass('profile_off');
           $j('#lastli').addClass('last_on');
           $j('#lastli').removeClass('last_off');
           $j('#MyAccountRightColumnDiv').hide();
           $j('#WelcomeTextBlurb').hide();
       },
       showFoldersSavedContentTab: function() {
           $j('#SavedContentDiv').show();
           if (!$j('#SavedTab').hasClass('current')) {
               $j('#SavedTab').toggleClass('current');
           }
           $j('#NotesTab').removeClass('current');
           $j('#PeopleTab').removeClass('current');
           $j('#NotesDiv').hide();
           $j('#PeopleDiv').hide();

           if (this.pendingSection == 'products') {
               if ($j('#ProductProjectFolderSectionDiv').hasClass('close')) {
                   $j('#ProductProjectFolderSectionDiv').toggleClass('close').toggleClass('open');
               }
               $j('#IdeaBoardsProjectFolderSection').addClass('close').removeClass('open');
               $j('#ArticlesProjectFolderSection').addClass('close').removeClass('open');
               $j('#ComparisonsProjectFolderSection').addClass('close').removeClass('open');
           }
           else if (this.pendingSection == 'ideaBoards') {
               if ($j('#IdeaBoardsProjectFolderSection').hasClass('close')) {
                   $j('#IdeaBoardsProjectFolderSection').toggleClass('close').toggleClass('open');
               }
               $j('#ComparisonsProjectFolderSection').addClass('close').removeClass('open');
               $j('#ArticlesProjectFolderSection').addClass('close').removeClass('open');
               $j('#ProductProjectFolderSectionDiv').addClass('close').removeClass('open');
           }
           else if (this.pendingSection == 'articles') {
               if ($j('#ArticlesProjectFolderSection').hasClass('close')) {
                   $j('#ArticlesProjectFolderSection').toggleClass('close').toggleClass('open');
               }
               $j('#IdeaBoardsProjectFolderSection').addClass('close').removeClass('open');
               $j('#ComparisonsProjectFolderSection').addClass('close').removeClass('open');
               $j('#ProductProjectFolderSectionDiv').addClass('close').removeClass('open');
           }
           else if (this.pendingSection == 'comparisons') {
               if ($j('#ComparisonsProjectFolderSection').hasClass('close')) {
                   $j('#ComparisonsProjectFolderSection').toggleClass('close').toggleClass('open');
               }
               $j('#IdeaBoardsProjectFolderSection').addClass('close').removeClass('open');
               $j('#ArticlesProjectFolderSection').addClass('close').removeClass('open');
               $j('#ProductProjectFolderSectionDiv').addClass('close').removeClass('open');
           }
       },
       showFoldersNotesTab: function() {
           $j('#NotesDiv').show();
           if (!$j('#NotesTab').hasClass('current')) {
               $j('#NotesTab').toggleClass('current');
           }
           $j('#SavedTab').removeClass('current');
           $j('#PeopleTab').removeClass('current');
           $j('#SavedContentDiv').hide();
           $j('#PeopleDiv').hide();
       },
       showFoldersPeopleTab: function() {
           $j('#PeopleDiv').show();
           if (!$j('#PeopleTab').hasClass('current')) {
               $j('#PeopleTab').toggleClass('current');
           }
           $j('#SavedTab').removeClass('current');
           $j('#NotesTab').removeClass('current');
           $j('#NotesDiv').hide();
           $j('#SavedContentDiv').hide();
       },
       completeEditNotesTab: function() {
           $j('#NotesDiv').show();
           if (!$j('#NotesTab').hasClass('current')) {
               $j('#NotesTab').toggleClass('current');
           }
           $j('#SavedTab').removeClass('current');
           $j('#PeopleTab').removeClass('current');
           $j('#SavedContentDiv').hide();
           $j('#PeopleDiv').hide();
       },
       editNotesTab: function() {
           var notesPanel = $j("[id$='ProjectNotesUpdatePanel']").get(0);
           if (notesPanel) {
               __doPostBack(notesPanel.id, 'edit');
               Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeEditNotesTab);
           }
       },
       shareFolder: function() {
           //this.sendFolderToDealer();
           this.authenticationCheck();
           this.pendingAction = "Show Folder";
           //Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this.completeShowFolder);
           var typeOfContactPanel = $j("[id$='TypeOfContactUpdatePanel']").get(0);
           if (typeOfContactPanel) {
               __doPostBack(typeOfContactPanel.id, '');
           }
           $j('#ShareProjectDimmer').show();
           $j('#ShareProjectContactDiv').show();
           $j('#ShareProjectFindADealerDiv').hide();
           $j('#ShareFolderTitle').text('Share this folder');
       },
       sendFolderToDealer: function() {
           this.authenticationCheck();
           Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(this.completeShowFolder);
           var typeOfContactPanel = $j("[id$='TypeOfContactUpdatePanel']").get(0);
           if (typeOfContactPanel) {
               __doPostBack(typeOfContactPanel.id, 'Dealer');
           }
           $j('#ShareProjectDimmer').show();
           $j('#ShareProjectFindADealerDiv').show();
           $j('#ShareProjectContactDiv').hide();
           $j('#ShareFolderTitle').text('Send this folder to a dealer');
       },
       createProjectFolder: function(name, typeOfProject, fuelType, productType, roomLocation) {
           WaitPopup.show();
           this.authenticationCheck();
           if (ValidateName(name)) {
               HHTSitecore.services.MyAccountService.CreateProjectFolder(name, typeOfProject, fuelType, productType, roomLocation, this.onCreateFolderSuccess.bind(this), this.onCreateFolderFailure.bind(this));
           }
           else {
               alert('The project folder name is not valid.  Please make sure that the name doesn\'t contain any special characters such as colons, quotation marks, or asterisks.');
               WaitPopup.hide();
           }
       },
       showCreateProjectFolder: function(createProjectSource) {
           this.authenticationCheck();
           if (createProjectSource && typeof (createProjectSource) == 'function') {
               PopupAuthenticationHandler.pendingType = createProjectSource;
           }
           else if (createProjectSource == 'No Folder') {
               //PopupAuthenticationHandler.pendingType = MyAccount.showFolder;
               MyAccount.pendingTab = 'folders';
               MyAccount.pendingSection = 'products';
           }
           $j('#CreateProjectFolderDimmer').show();
       },
       onCreateFolderSuccess: function(result) {
           $j('#CreateProjectFolderDimmer').hide();
           if (PopupAuthenticationHandler.pendingType) {
               PopupAuthenticationHandler.pendingType();
               WaitPopup.hide();
           }
           else {
               MyAccount.pendingAction = "Show Folder";
               var foldersPanel = $j("[id$='FoldersUpdatePanel']").get(0);
               if (foldersPanel) {
                   WaitPopup.show();
                   __doPostBack(foldersPanel.id, this.pendingSection);
                   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeShowFolder);
               }
           }
       },
       onCreateFolderFailure: function(result) {
           alert('The project folder name is not valid.  Please make sure that the name doesn\'t contain any special characters such as colons, quotation marks, or asterisks.');
           WaitPopup.hide();
       },
       removeProjectFolder: function(folderID) {
           this.authenticationCheck();
           if (confirm("Are you sure you want to remove this Project Folder?")) {
               HHTSitecore.services.MyAccountService.RemoveProjectFolder(folderID, this.onRemoveProjectFolderSuccess.bind(this), this.onRemoveProjectFolderFailure.bind(this));
           }
       },
       onRemoveProjectFolderSuccess: function(result) {
           if (result == '') {
               this.pendingSection = "";
               this.pendingTab = "overview";
               var foldersPanel = $j("[id$='FoldersUpdatePanel']").get(0);
               __doPostBack(foldersPanel.id, this.pendingSection);
               Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeShowFolder);
           }
           else {
               alert(result);
           }
       },
       onRemoveProjectFolderFailure: function(result) {
       },
       scrollToComment: function(nameToScrollTo) {
           this.showFolder(this.brandedSite, 'folders', 'products');
           $(nameToScrollTo).scrollTo();
       },
       ProcessHomeURL: function() {
           if (window.location.search.indexOf('sharedfolder') >= 0 && window.location.toString().indexOf('/My') == -1) {
               var qs = new Querystring(window.location.search.replace('?', ''));
               HHTSitecore.services.MyAccountService.CheckFolderExistance(qs.get('sharedfolder'), this.onCheckFolderExistanceSuccess.bind(this));
           }
       },
       onCheckFolderExistanceSuccess: function(result) {
           if (result.status == true) {
               var qs = new Querystring(window.location.search.replace('?', ''));
               if (qs.contains('d')) {
                   ProjectFolder.isDealer = true;
               }
               if (!MyAccount.isAuthenticated) {
                   MyAccount.brandedSite = false;
                   ProjectFolder.isMyFolder = false;
                   PopupAuthenticationHandler.pendingType = PopupAuthenticationHandler.ShowSharedFolder;
                   PopupAuthenticationHandler.pendingData = result.myAccountDestination + (ProjectFolder.isDealer == true ? '&d=' + qs.get('d') : '');
                   $j('#registrationDimmer').show();
               }
               else {
                   window.location = result.myAccountDestination + (ProjectFolder.isDealer == true ? '&d=' + qs.get('d') : '');
               }
           }
           else {
               alert('The shared project folder no longer exists');
           }
       },
       checkBlogContent: function(blogID, articleID) {
           HHTSitecore.services.MyAccountService.CheckBlogContent(blogID, articleID || null, this.oncheckBlogContentSuccess.bind(this));
       },
       oncheckBlogContentSuccess: function(result) {
           if (result.status == false) {
               alert(result.errorMessage);
               window.location = window.location.href.replace(window.location.search, '');
           }
       },
       HideProfileSave: function() {
           if ($j('#SavedProfile').is(':visible') == false) {
               $j('#SavedProfile').show();
           }
           setTimeout("$j('#SavedProfile').hide();", 10000);
           return true;
       }
   };
   Event.observe(document, "dom:loaded", function() { MyAccount.init(); });
//   Event.observe(window, "beforeunload", function() { MyAccount.logoutOnClose(); });

   var ProjectFolder = {
       associatedItemID: null,
       isMyFolder: false,
       isDealer: false,
       RemoveProduct: function(projectProductID) {
           MyAccount.authenticationCheck();
           MyAccount.pendingSection = "products";
           MyAccount.pendingTab = "folders";
           if (confirm("Are you sure you want to remove this Product from your Project Folder?")) {
               HHTSitecore.services.ProjectFolderService.RemoveProjectProduct(projectProductID, this.onSuccess.bind(this), this.onFailure.bind(this), null);
           }
       },
       RemoveArticle: function(articleID) {
           MyAccount.authenticationCheck();
           MyAccount.pendingSection = "articles";
           MyAccount.pendingTab = "folders";
           if (confirm("Are you sure you want to remove this Article from your Project Folder?")) {
               HHTSitecore.services.ProjectFolderService.RemoveArticle(articleID, this.onSuccess.bind(this), this.onFailure.bind(this), null);
           }
       },
       RemoveComparison: function(comparisonName) {
           MyAccount.authenticationCheck();
           MyAccount.pendingSection = "comparisons";
           MyAccount.pendingTab = "folders";
           if (confirm("Are you sure you want to remove this Comparison from your Project Folder?")) {
               HHTSitecore.services.ProjectFolderService.RemoveComparison(comparisonName, this.onSuccess.bind(this), this.onFailure.bind(this), null);
           }
       },
       RemoveIdeaBoard: function(ideaBoardID) {
           MyAccount.authenticationCheck();
           MyAccount.pendingSection = "ideaBoards";
           MyAccount.pendingTab = "folders";
           if (confirm("Are you sure you want to remove this Idea Board from your Project Folder?")) {
               HHTSitecore.services.ProjectFolderService.RemoveIdeaBoard(ideaBoardID, this.onSuccess.bind(this), this.onFailure.bind(this), null);
           }
       },
       RemovePerson: function(personID) {
           MyAccount.authenticationCheck();
           MyAccount.pendingSection = "people";
           MyAccount.pendingTab = "folders";
           if (confirm("Are you sure you want to remove this Contact from your Project Folder?")) {
               HHTSitecore.services.ProjectFolderService.RemovePerson(personID, this.onSuccess.bind(this), this.onFailure.bind(this), null);
           }
       },
       RemoveComment: function(commentID) {
           MyAccount.authenticationCheck();
           if (confirm("Are you sure you want to remove this Comment from your Project Folder?")) {
               HHTSitecore.services.ProjectFolderService.RemoveComment(commentID, this.onSaveCommentSuccess.bind(this), this.onFailure.bind(this), null);
           }
       },
       ProductHasAssociations: function(projectProductID) {
           MyAccount.authenticationCheck();
           if (confirm("The product you have selected to remove is associated with this Project Folder and one or more Comparisons in this Project Folder as well.  Are you sure you want to remove the Product?")) {
               MyAccount.pendingSection = "products";
               MyAccount.pendingTab = "folders";
               HHTSitecore.services.ProjectFolderService.RemoveProjectProduct(projectProductID, this.onSuccess.bind(this), this.onFailure.bind(this), null);
           }
       },
       RenameComparison: function(oldName, newName) {
           MyAccount.authenticationCheck();
           if (ValidateName(newName)) {
               HHTSitecore.services.ProjectFolderService.RenameComparison(oldName, newName, this.onSuccess.bind(this), this.onFailure.bind(this), null);
               $j('#RenameComparisonDimmer').hide();
           }
           else {
               alert('Please enter a valid name for the comparison.  Colons, quotes, question marks, less than and greater than signs, square brackets, and pipe (|) characters are invalid for a comparison name.');
           }
       },
       RenameGallery: function(oldName, ideaGalleryID, newName) {
           MyAccount.authenticationCheck();
           if (ValidateName(newName)) {
               HHTSitecore.services.ProjectFolderService.RenameGallery(oldName, ideaGalleryID, newName, this.onSuccess.bind(this), this.onFailure.bind(this), null);
               $j('#RenameComparisonDimmer').hide();
           }
           else {
               alert('Please enter a valid name for the idea gallery.  Colons, quotes, question marks, less than and greater than signs, square brackets, and pipe (|) characters are invalid for an idea gallery name.');
           }
       },
       LoadRenameGallery: function(oldName, ideaGalleryID) {
           MyAccount.authenticationCheck();
           var renamePanel = $j("[id$='SaveRenameUpdatePanel']").get(0);
           __doPostBack(renamePanel.id, "ProjectFolder.RenameGallery('" + oldName + "', '" + ideaGalleryID + "', $j('#NewName').val());");
           $j('#RenameComparisonDimmer').show();
           $j('#RenameTitle').text('Idea Board');
       },
       LoadRenameComparison: function(oldName) {
           MyAccount.authenticationCheck();
           var renamePanel = $j("[id$='SaveRenameUpdatePanel']").get(0);
           __doPostBack(renamePanel.id, "ProjectFolder.RenameComparison('" + oldName + "', $j('#NewName').val());");
           $j('#RenameComparisonDimmer').show();
           $j('#RenameTitle').text('Comparison');
       },
       ShareFolder: function(emailAddress, emailSubject, emailBody, typeOfContact, ccMe) {
           WaitPopup.show();
           MyAccount.authenticationCheck();
           HHTSitecore.services.ProjectFolderService.ShareFolder(emailAddress, emailSubject, emailBody, typeOfContact, ccMe, this.onShareFolderSuccess.bind(this), this.onFailure.bind(this), null);
           $j('#ShareFolderEmailAddress').val('');
           $j('#ShareFolderEmailSubject').val('');
           $j('#ShareFolderEmailBody').val('');
       },
       CheckContactType: function(contactType) {
           if (contactType.toString().indexOf('search for a dealer') >= 0) {
               $j('#ShareProjectContactDiv').hide();
               $j('#ShareProjectFindADealerDiv').show();
           }
           else if (contactType.toString().indexOf('New Friend') >= 0) {
               $j('#ShareProjectContactDiv').show();
               $j('#ShareProjectFindADealerDiv').hide();
               $j('#ShareFolderEmailAddress').val('');
           }
           else {
               $j('#ShareProjectContactDiv').show();
               $j('#ShareProjectFindADealerDiv').hide();
               if ($j('#ShareFolderEmailAddress')) {
                   $j('#ShareFolderEmailAddress').val(contactType);
               }
               else {
                   alert("Share Project Email Address field not found");
               }
           }
       },
       SaveNote: function(notesFieldID) {
           MyAccount.authenticationCheck();
           var notesField = $j("[id$='" + notesFieldID + "']").get(0);
           if ($j(notesField).val().length > 70) {
               alert('Please limit the note to 70 characters or less.');
               return;
           }
           $j('#AddNoteDimmer').hide();
           $j('#EditNoteDimmer').hide();
           HHTSitecore.services.ProjectFolderService.SaveNote($j(notesField).val(), this.associatedItemID, this.onSuccess.bind(this), this.onFailure.bind(this), null);
           this.associatedItemID = "";
       },
       addNote: function(associatedItemID) {
           MyAccount.authenticationCheck();
           $j('#AddNoteDimmer').show();
           this.associatedItemID = associatedItemID;
       },
       editNote: function(associatedItemID) {
           MyAccount.authenticationCheck();
           var editNotePanel = $j("[id$='EditNoteUpdatePanel']").get(0);
           __doPostBack(editNotePanel.id, associatedItemID);
           $j('#EditNoteDimmer').show();
           this.associatedItemID = associatedItemID;
       },
       saveArticle: function() {
           MyAccount.authenticationCheck();
           var selectedFolderIDs = '';

           var articleID = $j("[id$='hdnArticleIDToSave']").val();

           var folderList = $j("[id$='SaveArticleFolderUpdatePanel']").get(0);

           selectedFolderIDs = this.getCheckedFolders(folderList);

           if (selectedFolderIDs.length > 0) {
               HHTSitecore.services.ProjectFolderService.SaveArticle(articleID, selectedFolderIDs, this.onSaveContentSuccess.bind(this));
           }
           else {
               alert('Please select at least one folder to save the article to.');
           }
       },
       saveProduct: function() {
           MyAccount.authenticationCheck();
           var selectedFolderIDs = '';

           var folderList = $j("[id$='SaveProductFolderUpdatePanel']").get(0);

           selectedFolderIDs = this.getCheckedFolders(folderList);

           if (selectedFolderIDs.length > 0) {
               HHTSitecore.services.ProjectFolderService.SaveProduct(selectedFolderIDs, this.onSaveContentSuccess.bind(this));
           }
           else {
               alert('Please select at least one folder to save the product to.');
           }
       },
       saveBuyerGuide: function() {
           MyAccount.authenticationCheck();

           var currentKey = getQuerystring('rid', 'default');
           //alert('current key: ' + currentKey);

           var selectedFolderIDs = '';
           var folderList = $j("[id$='SaveBuyersGuideUpdatePanel']").get(0);
           selectedFolderIDs = this.getCheckedFolders(folderList);
           if (selectedFolderIDs.length > 0) {
               HHTSitecore.services.BuyersGuideService.SaveGuideToMyAccount(currentKey, selectedFolderIDs, this.onSaveBuyerGuideSuccess.bind(this));
           }
           else {
               alert('Please select at least one folder to save the buyer guide to.');
           }
       },
       saveComparison: function(comparisonName) {
           MyAccount.authenticationCheck();
           if (ValidateName(comparisonName) || comparisonName.toString.length == 0) {
               var selectedFolderIDs = '';

               var folderList = $j("[id$='SaveComparisonFolderUpdatePanel']").get(0);

               selectedFolderIDs = this.getCheckedFolders(folderList);

               if (selectedFolderIDs.length > 0) {
                   HHTSitecore.services.ProjectFolderService.SaveComparison(comparisonName, selectedFolderIDs, this.onSaveContentSuccess.bind(this));
               }
               else {
                   alert('Please select at least one folder to save the comparison to.');
               }
           }
           else {
               alert('Please enter a valid name for the comparison.  Colons, quotes, question marks, less than and greater than signs, square brackets, and pipe (|) characters are invalid for a comparison name.');
           }
       },
       saveComment: function(commentor, comment) {
           MyAccount.authenticationCheck();
           HHTSitecore.services.ProjectFolderService.SaveComment(commentor, comment, this.onSaveCommentSuccess.bind(this));
       },

       //saveIdeaGallery: function(galleryName) {}, - look in IdeaGallery.ascx

       getCheckedFolders: function(folder) {
           var selectedFolderIDs = '';

           labels = $j(folder).children('label');
           for (index = 0; index < labels.length; index++) {
               label = labels[index];
               var folderCheck = $j(label).children('input[type=checkbox]').get(0);
               if (folderCheck.checked) {
                   var folderID = $j(folder).children("input[type=hidden]").get(index);
                   //var folderID = $j(label + 'input[type=hidden]').get(0);
                   if (selectedFolderIDs.length == 0) {
                       selectedFolderIDs += $j(folderID).val();
                   }
                   else {
                       selectedFolderIDs += '&' + $j(folderID).val();
                   }
               }
           }
           return selectedFolderIDs;
       },
       completeFolderUpdate: function() {
           MyAccount.showFolder(null, null, null, 'Show Folder');
       },
       onSuccess: function(result, context) {
           Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeFolderUpdate);
           var foldersPanel = $j("[id$='FoldersUpdatePanel']").get(0);
           __doPostBack(foldersPanel.id, MyAccount.pendingSection);
       },
       onFailure: function(result, context) {
           alert('We’re sorry, for some reason your e-mail did not send. Please try again later. We apologize for the inconvenience.');
           WaitPopup.hide();
       },
       onShareFolderSuccess: function(result, context) {
           $j('#ShareProjectDimmer').hide();
           MyAccount.pendingSection = "people";
           MyAccount.pendingTab = "folders";
           Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeFolderUpdate);
           var foldersPanel = $j("[id$='FoldersUpdatePanel']").get(0);
           __doPostBack(foldersPanel.id, MyAccount.pendingSection);
           WaitPopup.hide();
       },
       onSaveContentSuccess: function(result) {
           $j(result).hide();
       },
       onSaveBuyerGuideSuccess: function(result) {
           $j(result.dimmerid).hide();
           window.location = result.redirectUrl;
       },
       onSaveCommentSuccess: function(result) {
           Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeFolderUpdate);
           var recentCommentPanel = $j("[id$='RecentCommentUpdatePanel']").get(0);
           if (recentCommentPanel) {
               __doPostBack(recentCommentPanel.id, '');
           }
       }
   };
   var EmailContent = {
   	contentURL: null,
   	emailContent: function(emailAddress, emailSubject, emailBody, ccMe) {
   		HHTSitecore.services.MyAccountService.EmailContent(emailAddress, emailSubject, emailBody, ccMe, this.contentURL, this.onEmailContentSuccess.bind(this), this.onEmailContentFailure.bind(this));
   	},
   	showEmailContent: function(contentDescription, contentURL) {
   		$j('#EmailContentTitle').text(contentDescription);
   		this.contentURL = contentURL;
   		$j('#EmailContentDimmer').show();
   	},
   	onEmailContentSuccess: function(result) {
   		if (result == "") {
   			$j('#EmailContentDimmer').hide();
   			this.contentID = "";
   		}
   		else {
   			alert(result);
   		}
   	},
   	onEmailContentFailure: function() {
   	}
   };
   
   $j(document).ready(function() {
       //default the first spec diagram to visible
       $j('#divPreviews div:first').show();
   });

   var PopupAuthenticationHandler = {
       pendingData: null,
       pendingType: null,
       ShowSaveProduct: function() {
           WaitPopup.show();
           var saveProductPanel = $j("[id$='SaveProductFolderUpdatePanel']").get(0);
           __doPostBack(saveProductPanel.id, '');          
           SaveProduct.showFromSave(this.pendingData);
           this.pendingData = null;
           this.pendingType = null;
           WaitPopup.hide();
       },
       ShowSaveBuyersGuide: function() {
           WaitPopup.show();
           var saveProductPanel = $j("[id$='SaveBuyersGuideUpdatePanel']").get(0);
           __doPostBack(saveProductPanel.id, '');
           SaveBuyersGuide.showFromSave();
           this.pendingData = null;
           this.pendingType = null;
           WaitPopup.hide();
       },
       ShowSaveArticle: function() {
           WaitPopup.show();
           var saveArticlePanel = $j("[id$='SaveArticleFolderUpdatePanel']").get(0);
           __doPostBack(saveArticlePanel.id, '');
           $j('#SaveArticleDimmer').show();
           this.pendingData = null;
           this.pendingType = null;
           WaitPopup.hide();
       },
       ShowSaveComparison: function() {
           WaitPopup.show();
           var saveComparisonPanel = $j("[id$='SaveComparisonFolderUpdatePanel']").get(0);
           __doPostBack(saveComparisonPanel.id, '');
           CompareBar.instance.saveComparisons();
           this.pendingData = null;
           this.pendingType = null;
           WaitPopup.hide();
       },
       ShowSaveIdeaBoard: function() {
           WaitPopup.show();
           var saveGalleryPanel = $j("[id$='SaveGalleryFolderUpdatePanel']").get(0);
           __doPostBack(saveGalleryPanel.id, '');
           $j('#SaveIdeaGalleryDimmer').show();
           $j('#SaveIdeaGalleryDimmer').css({ width: document.viewport.getWidth() + "px", height: document.viewport.getHeight() + "px" });
           this.pendingData = null;
           this.pendingType = null;
           WaitPopup.hide();
       },
       ShowSharedFolder: function() {
           var destination = this.pendingData;
           this.pendingData = null;
           this.pendingType = null;
           var qs = new Querystring(window.location.search.replace('?', ''));
           var fDone = function() { window.location = destination; };
           MyAccount.setFolder(MyAccount.brandedSite, qs.get('sharedfolder'), 'folders', 'products', 'Just Set', fDone);
       },
       ShowBrandedSharedFolder: function() {

           MyAccount.showBrandedMyAccountFoldersTab();
           this.pendingData = null;
           this.pendingType = null;
       },
       showForgotPassword: function() {
           if ($j('#SigninPopupDimmer')) {
               $j('#SigninPopupDimmer').hide();
           }
           $j('#ForgotPasswordDimmer').show();
       },
       ShowJoinNewsletter: function() {
           JoinNewsletterWidget.click(this, $j('#sendNewsLetterEmail').val());
       },
       ShowWriteReview: function() {
           $j('#WriteReviewDiv').toggle();
       },
       StartSaveArticle: function() {
           if (MyAccount.isAuthenticated) {
               PopupAuthenticationHandler.ShowSaveArticle();
           }
           else {
               PopupAuthenticationHandler.pendingType = PopupAuthenticationHandler.ShowSaveArticle;
               MyAccount.showSignInPopup('You\'ll need to sign in before you can save this article to your personal page.  ');
           }
       },
       StartSaveProduct: function(productID) {
           if (MyAccount.isAuthenticated) {
               PopupAuthenticationHandler.pendingData = productID;
               PopupAuthenticationHandler.ShowSaveProduct();
           }
           else {
               PopupAuthenticationHandler.pendingData = productID;
               PopupAuthenticationHandler.pendingType = PopupAuthenticationHandler.ShowSaveProduct;
               MyAccount.showSignInPopup('You\'ll need to sign in before you can save this product to your personal page.  ');
           }
       },
       StartSaveComparison: function() {
           if (MyAccount.isAuthenticated) {
               PopupAuthenticationHandler.ShowSaveComparison();
           }
           else {
               PopupAuthenticationHandler.pendingType = PopupAuthenticationHandler.ShowSaveComparison;
               MyAccount.showSignInPopup('You\'ll need to sign in before you can save this comparison to your personal page.  ');
           }
       },
       StartSaveIdeaBoard: function() {
           if (MyAccount.isAuthenticated) {
               PopupAuthenticationHandler.ShowSaveIdeaBoard();
           }
           else {
               PopupAuthenticationHandler.pendingType = PopupAuthenticationHandler.ShowSaveIdeaBoard;
               MyAccount.showSignInPopup('You\'ll need to sign in before you can save this idea gallery to your personal page.  ');
           }
       },
       StartJoinNewsletter: function() {
           if (MyAccount.isAuthenticated) {
               WaitPopup.show();
               HHTSitecore.services.MyAccountService.JoinNewsletter();
               WaitPopup.hide();
               //GenericMessagePopup.show('Newsletter Signup', 'Thank you!  You have been signed up to receive our e-newsletter.');
               ThankYouMessageBox.show('Newsletter', '');
           }
           else {
               $j('#NewsletterRegistrationDimmer').toggle();
           }
       },
       StartSaveBuyersGuide: function() {
           if (MyAccount.isAuthenticated) {

               var key = getQuerystring('rid', '');

               if (key != '') {
                   //alert('current key: ' + key);
                   HHTSitecore.services.BuyersGuideService.SaveGuideToMyAccount(key,key);
               }
               else {
                   PopupAuthenticationHandler.pendingData = "";
                   PopupAuthenticationHandler.ShowSaveBuyersGuide();
               }

           }
           else {
               PopupAuthenticationHandler.pendingData = "";
               PopupAuthenticationHandler.pendingType = PopupAuthenticationHandler.ShowSaveBuyersGuide;
               MyAccount.showSignInPopup('You\'ll need to sign in before you can save your Hearth Planner to your personal page.  ');
           }
       },
       ShowMyAccount: function() {
           if (!MyAccount.isAuthenticated) {
               MyAccount.showSignInPopup('You\'ll need to sign in before you can go to your personal page.  ');
           }
           return MyAccount.isAuthenticated;
       },
       StartWriteReview: function() {
           if (MyAccount.isAuthenticated) {
               PopupAuthenticationHandler.ShowWriteReview();
           }
           else {
               PopupAuthenticationHandler.pendingType = PopupAuthenticationHandler.ShowWriteReview;
               MyAccount.showSignInPopup('To write a review, please sign in to your account.  ');
           }
       }
   };
      function ClearSearch() {
      	$j("[id$='LocatorQuickEntryTextbox1']").val("");
      }

      DealerAwardDrawer = {
         
          SelectBrandDrawer: function(isDistSearch) {
              $j("[id$='brandInfoTab']").show();
              $j("[id$='dealerLevelsTab']").hide();
              $j('#imgBrandInfo').removeClass().addClass('left greybtn_brand_info_active');

              if (isDistSearch == "True")
                  $j('#imgDealerLevels').removeClass().addClass('left greybtn_distributor_levels');
              else
                  $j('#imgDealerLevels').removeClass().addClass('left greybtn_dealer_levels');
          },

          SelectDealerLevelDrawer: function(locatorType) {
              $j("[id$='brandInfoTab']").hide();
              $j("[id$='dealerLevelsTab']").show();
              $j('#imgBrandInfo').removeClass().addClass('left greybtn_brand_info');

              if (locatorType == "Distributor")
                  $j('#imgDealerLevels').removeClass().addClass('left greybtn_distributor_levels_active');
              else
                  $j('#imgDealerLevels').removeClass().addClass('left greybtn_dealer_levels_active');

          }

      };


      InternationalSearch = {
          toggleResults: function() {
              $j("#divDealerResultsOpen").toggle();
              $j("#divDealerResultsClosed").toggle();
          },
          toggleContacts: function() {
              $j("#divContactsOpen").toggle();
              $j("#divContactsClosed").toggle();
          }
      };

      InternationalPricing = {
          show: function() {
              $j("#ProdPriceWindow").show();
          }
      };

    PromoSearch = {
        toggle: function(keyOpen, keyClosed, state) {
            if (state == "open") {
                $j(keyOpen).show();
                $j(keyClosed).hide();
            }
            else {
                $j(keyOpen).hide();
                $j(keyClosed).show();
            }
        }
    };




    $j(document).ready(function() {
        $j("#ecoHelp").hover(function() {
            $j(this).next(".hover270").animate({ opacity: "show", bottom: "20" }, "slow");
        }, function() {
            $j(this).next(".hover270").animate({ opacity: "hide", bottom: "15" }, "fast");
        });
    });

    PromotionPager = {
    click: function(src, key) {
            //src = ul li #
        //this may need to be refactored to allow multiple uses of the promotion pager on one page
            $j("[id$='ulPager'] li").removeClass().addClass('off'); //turn off all pager li's
            $j(src).parent().removeClass().addClass('on'); //turn the paging number that was clicked on
            $j("[id$='ulPromoSlots'] li").hide(); //hide all the promoslot li's
        $j(key).show();
        }
    };
    
    
   
    JoinNewsletterWidget = {
        click: function(src) {
            email = $j(src).parent().children('#sendNewsLetterEmail').val();
            if (email == "Enter your email")
                email = "";

            $j('#registrationDimmer').toggle();
            $j('#createAccountTitle').text("Join Our Newsletter");
            $j('#EmailAddress').val(email);
            $j('#SignupForNewsletter').attr('checked', true);
        }
    };
    
    
    
    
    //SURVEY SERVICE CALLS
//    var CreateSurvey = {
//        surveyCode: null,
//        surveyResponse: null,
//        surveyCookie: null,
//        getSurvey: function(page) {
//            //get active survey cookie string - but only if not on landing page
//            if (page.indexOf("LANDING-PAGE") < 1) {
//                HHTSitecore.services.SurveyService.GetSurveyCookie(this.onSurveyCookieSuccess.bind(this));
//            }
//        },
//        onSurveyCookieSuccess: function(result) {
//            //if survey cookie is on user's machine, bail - else load survey
//            if (result.status) {
//                HHTSitecore.services.SurveyService.LoadSurvey(this.onSurveySuccess.bind(this));
//            }
//        },
//        onSurveySuccess: function(result) {
//            if (result.status) {
//                $j('#SurveyText').html(result.surveyHTML);
//                $j('#SurveyPopupDimmer').show();
//            }
//        },
//        setSurveyValues: function(surveyResponse, surveyCode) {
//            this.surveyResponse = surveyResponse;
//            this.surveyCode = surveyCode;
//        },
//        saveSurvey: function(surveyEmail) {
//            HHTSitecore.services.SurveyService.SaveSurvey(this.surveyCode, this.surveyResponse, surveyEmail, this.onSaveSurveySuccess.bind(this));
//        },
//        onSaveSurveySuccess: function(result) {
//            if (!result.status) {
//                alert("Error - Your survey was not saved.  Please try again later.  ERROR: " + result.surveyHTML);
//            }
//            $j('#SurveyPopupDimmer').hide();
//        },
//        closeSurvey: function(surveyCode, cookieDuration) {
//            HHTSitecore.services.SurveyService.CloseSurvey(surveyCode, cookieDuration, this.onCloseSurveySuccess.bind(this));
//        },
//        onCloseSurveySuccess: function(result) {
//            $j('#SurveyPopupDimmer').hide();
//        }
//    };


   	
   	

    /*
        Thank you, http://beardscratchers.com/journal/fixing-the-enter-keypress-event-in-aspnet-with-jquery
        Altered to allow any parent tag (not just fieldset tags) and expanded the class name it
        looks for to contain "submit-form-" instead of starting with "submit-".
        Also fixed an issue with executing javascript inside an href attribute.
        Usage:
            1) Find a div (or other tag) that contains, at any child depth, both the text field that should
               submit the form, and the button/link that you want it to invoke.
            2) Make up a new UNIQUE CSS class name that starts with "submit-form-", and add it to both the
               containing div and the button/link you want to invoke.
            3) Smile.
        
    */
    $j(document).ready(function() {
        $j('FORM').bind('keypress', function(e) {
            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
            var target = e.target.tagName.toLowerCase();
            if (key === 13 && target === 'input') {
                e.preventDefault();

                var parentFieldset = $j(e.target).parents('[class*="submit-form-"]');
                //parentFieldset = parentFieldset.filter('class^="submit-"').eq(0);

                if (parentFieldset.length > 0) {
                    var classnames = parentFieldset.attr('class').split(' ');

                    for (var i = 0; i < classnames.length; i++) {
                        if (classnames[i].substring(0, 12) == 'submit-form-') {
                            var button = $j('a.' + classnames[i] + ', button.' + classnames[i], $j(this)).eq(0);
                            if (button.length > 0) {
                                if (typeof (button.get(0).onclick) == 'function') {
                                    button.trigger('click');
                                } else if (button.attr('href')) {
                                    var h = button.attr('href');
                                    if (h.substring(0, 11) == "javascript:") {
                                        eval(h.substring(11));
                                    } else {
                                        window.location = h;
                                    }
                                } else {
                                    button.trigger('click');
                                }
                            }
                            break;
                        }
                    }
                }
            }
        });
    });



    ModelComparison = {
        show: function(productid) {
            //alert(productid);
            HHTSitecore.services.Generic.LoadModelComparison(productid,this.onLoad.bind(this), this.onFail.bind(this), null);
        },
        hide: function(){
            $j('#ProductModelComparisonDimmer').hide();
        },
        onLoad: function(result) {
            $j('#ProductModelComparisonDimmer').html(result);
            $j('#ProductModelComparisonDimmer').show();
        },
        onFail: function(result) {
            alert('FAIL' + result.valueOf());
        }
    };


    FeaturePopup = {
        show: function(featureID) {
            //alert(featureID);
            HHTSitecore.services.Generic.LoadFeaturePopup(featureID, this.onLoad.bind(this), this.onFail.bind(this), null);
        },
        hide: function() {
            $j('#model_compare_popup').hide();
        },
        onLoad: function(result) {
            $j('#model_compare_popup').html(result);
            $j('#model_compare_popup').show();
        },
        onFail: function(result) {
            alert('FAIL' + result.valueOf());
        }
    };

    AccessoryPopup = {
        show: function(accessoryID) {
            //alert(accessoryID);
            HHTSitecore.services.Generic.LoadAccessoryPopup(accessoryID, this.onLoad.bind(this), this.onFail.bind(this), null);
        },
        hide: function() {
            $j('#model_compare_popup').hide();
        },
        onLoad: function(result) {
            $j('#model_compare_popup').html(result);
            $j('#model_compare_popup').show();
        },
        onFail: function(result) {
            alert('FAIL' + result.valueOf());
        }
    };


    QuickQuote = {
        showQuickQuoteHBD: function() {
            var url = $j("#hbdImageURL").val();
            $j(".imgname").html($j("#hbdProductName").val());
            $j(".imghbdproductimage").attr("src", url);
            $j('#divQuickQuotePanel').show();
            $j("[id$='divQuickQuoteHBD']").show();
            $j('#divQuickQuoteRotator').html("");

            $j("[id$='divRequestTop']").show()
            $j("[id$='divRequestLower']").show()

            $j("[id$='divThanksTop']").hide()
            $j("[id$='divThanksLower']").hide()

            this.checkFireside();
        },
        showQuickQuote: function(productID) {

            var isHBD = $j("#hbdImageURL").val() != "" && $j("#hbdImageURL").val() != null;

            if (isHBD) {
                this.showQuickQuoteHBD();
            }
            else {

                //load single product or product rotator...
                $j("[id$='hdnSelectedProductID']").val(productID); //sits on quick quote main sublayout
                HHTSitecore.services.QuickQuoteService.LoadQuickQuoteProducts(productID, this.onQuickQuoteLoad.bind(this), this.onQuickQuoteFail.bind(this), null);

                $j('#divQuickQuotePanel').show(); //primary panel

                $j("[id$='divRequestTop']").show()
                $j("[id$='divRequestLower']").show()

                $j("[id$='divThanksTop']").hide()
                $j("[id$='divThanksLower']").hide()

                $j("[id$='divQuickQuoteHBD']").hide();
            }

            this.checkFireside();

        },
        checkFireside: function() {
            HHTSitecore.services.Generic.HasSelectedFireside(this.onCheckFireside.bind(this));
        },
        onCheckFireside: function(result) {
            //alert("on check fireside, has fireside=" + result);
            if (result) {
                $j("[id$='divQuickQuoteDealerLocator']").hide();
            }
        },
        show: function() {
            $j("#quickQuote").show();
            //this.checkFireside();
        },
        hide: function() {
            $j("#quickQuote").hide();
        },
        onQuickQuoteLoad: function(result) {

            var defaultProductID = result.productid;
            $j('#divQuickQuoteRotator').html(result.html);
            $j("[id$='hdnSelectedProductID']").val(defaultProductID);
            $j(".divCurrentQuickQuoteProductID").hide();

            if (result.isSingle == true) {
                $j("[id$='QuoteProductsForward']").hide();
            }
            else {
                $j("[id$='QuoteProductsForward']").show();
            }
        },
        setRotatorFirstProduct: function() {
            //set the first item as selected..
            var defaultProductID = $j(".divCurrentQuickQuoteProductID:eq(0)").text();
            $j("[id$='hdnSelectedProductID']").val(defaultProductID);
        },
        onQuickQuoteFail: function(result) {
            //alert('FAIL' + result.valueOf());
        },
        incrementRotator: function(productId, direction) {
            //alert(productId);
            HHTSitecore.services.QuickQuoteService.IncrementRotator(productId, direction, this.onIncrement.bind(this));
        },
        onIncrement: function(result) {
            //alert(result.productid);
            $j('.div_quick_quote_product').html(result.html);
            $j("[id$='hdnSelectedProductID']").val(result.productid);
        }
    };

    MiniLocator = {
        selectDealer: function(btn) {
            var selectDealerBtn = $j("[id$='" + btn + "']").get(0);
            selectDealerBtn.click();
            $j("[id$='txtSelectedDealer']").val("1");
        },
        clearDealer: function() {
            $j("[id$='txtSelectedDealer']").val("");
        }
       };

	Folders = {
		toggle: function(name) {
			var elm = $(name);
			if (elm.hasClassName("open")) {
				$(name + "_inner").hide();
				elm.removeClassName("open");
			} else {
				$(name + "_inner").show();
				elm.addClassName("open");
			}
		}
	};
	
	/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008
	
	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
	*/
       function Querystring(qs) { // optionally pass a querystring to parse
       	this.params = {};
       	
       	if (qs == null) qs = location.search.substring(1, location.search.length);
       	if (qs.length == 0) return;
       	
       	// Turn <plus> back to <space>
       	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
       	qs = qs.replace(/\+/g, ' ');
       	var args = qs.split('&'); // parse out name/value pairs separated via &

       	// split out each name=value pair
       	for (var i = 0; i < args.length; i++) {
       		var pair = args[i].split('=');
       		var name = decodeURIComponent(pair[0]);

       		var value = (pair.length == 2)
			? decodeURIComponent(pair[1])
			: name;

       		this.params[name] = value;
       	}
       };

       Querystring.prototype.get = function(key, default_) {
       	var value = this.params[key];
       	return (value != null) ? value : default_;
       };

       Querystring.prototype.contains = function(key) {
       	var value = this.params[key];
       	return (value != null);
       };

NewsletterRegistration =
{
    isFromNewsletterSignup: true,
    SignUp: function(registrantName, registrantEmail, isConsumer, isBuilder, isFromNewsletterSignup) {
        WaitPopup.show();
        this.isFromNewsletterSignup = isFromNewsletterSignup;
        //convertedIsConsumer = isConsumer == 'on';
        //convertedIsBuilder = isBuilder == 'on';
        HHTSitecore.services.MyAccountService.NewsletterSignUp(registrantName, registrantEmail, isConsumer, isBuilder, this.onSignUpSuccess.bind(this), this.onSignUpFailure.bind(this));
    },

    onSignUpSuccess: function() {
        WaitPopup.hide();
        if (this.isFromNewsletterSignup == true) {
            $j('#NewsletterRegistrationDimmer').toggle();
            //GenericMessagePopup.show('Newsletter Signup', 'Thank you!  You have been signed up to receive our e-newsletter.');
            ThankYouMessageBox.show('Newsletter', '');
        }
    },

    onSignUpFailure: function() {
        WaitPopup.hide();
    },

    JoinNewsletter: function(firstname, lastname, fullname, email, company, postal, isBuilder) {
        WaitPopup.show();
        HHTSitecore.services.Generic.JoinNewsletter(firstname, lastname, fullname, email, company, postal, isBuilder, this.onJoinNewsletterSuccess.bind(this), this.onJoinNewsletterFailure.bind(this));
    },
    onJoinNewsletterSuccess: function() {
        WaitPopup.hide();
        //_gaq.push(['_trackEvent', 'Leads', 'Submit', 'Newsletter']);
        EventTracking.trackEvent('Leads', 'Submit', 'Newsletter', '');
        $j("[id$='divNewsletterThanks']").show();
        //ThankYouMessageBox.show('Newsletter', '');
    },
    onJoinNewsletterFailure: function() {
        WaitPopup.hide();
    }
};

RatingStars =
{
	currentRating: 0,
	onmouseover: function(star) {
		if ($j(star).selector.indexOf('1') > 0) {
			this.setRating(star);
			$j('#RatingTranslation').text('Poor');
			this.removeRating($j('#RatingStar2'));
			this.removeRating($j('#RatingStar3'));
			this.removeRating($j('#RatingStar4'));
			this.removeRating($j('#RatingStar5'));
		}
		else if ($j(star).selector.indexOf('2') > 0) {
			this.setRating(star);
			this.setRating($j('#RatingStar1'));
			$j('#RatingTranslation').text('Fair');
			this.removeRating($j('#RatingStar3'));
			this.removeRating($j('#RatingStar4'));
			this.removeRating($j('#RatingStar5'));
		}
		else if ($j(star).selector.indexOf('3') > 0) {
			this.setRating(star);
			this.setRating($j('#RatingStar1'));
			this.setRating($j('#RatingStar2'));
			$j('#RatingTranslation').text('Average');
			this.removeRating($j('#RatingStar4'));
			this.removeRating($j('#RatingStar5'));
		}
		else if ($j(star).selector.indexOf('4') > 0) {
			this.setRating(star);
			this.setRating($j('#RatingStar1'));
			this.setRating($j('#RatingStar2'));
			this.setRating($j('#RatingStar3'));
			$j('#RatingTranslation').text('Good');
			this.removeRating($j('#RatingStar5'));
		}
		else if ($j(star).selector.indexOf('5') > 0) {
			this.setRating(star);
			this.setRating($j('#RatingStar1'));
			this.setRating($j('#RatingStar2'));
			this.setRating($j('#RatingStar3'));
			this.setRating($j('#RatingStar4'));
			$j('#RatingTranslation').text('Excellent');
		}
	},
	onmouseout: function() {
		if (this.currentRating > 0) {
			if (this.currentRating == 1) {
				this.setRating($j('#RatingStar1'));
				this.removeRating($j('#RatingStar2'));
				this.removeRating($j('#RatingStar3'));
				this.removeRating($j('#RatingStar4'));
				this.removeRating($j('#RatingStar5'));
				$j('#RatingTranslation').text('Poor');
			}
			else if (this.currentRating == 2) {
				this.setRating($j('#RatingStar1'));
				this.setRating($j('#RatingStar2'));
				this.removeRating($j('#RatingStar3'));
				this.removeRating($j('#RatingStar4'));
				this.removeRating($j('#RatingStar5'));
				$j('#RatingTranslation').text('Fair');
			}
			else if (this.currentRating == 3) {
				this.setRating($j('#RatingStar1'));
				this.setRating($j('#RatingStar2'));
				this.setRating($j('#RatingStar3'));
				this.removeRating($j('#RatingStar4'));
				this.removeRating($j('#RatingStar5'));
				$j('#RatingTranslation').text('Average');
			}
			else if (this.currentRating == 4) {
				this.setRating($j('#RatingStar1'));
				this.setRating($j('#RatingStar2'));
				this.setRating($j('#RatingStar3'));
				this.setRating($j('#RatingStar4'));
				this.removeRating($j('#RatingStar5'));
				$j('#RatingTranslation').text('Good');
			}
			else if (this.currentRating == 5) {
				this.setRating($j('#RatingStar1'));
				this.setRating($j('#RatingStar2'));
				this.setRating($j('#RatingStar3'));
				this.setRating($j('#RatingStar4'));
				this.setRating($j('#RatingStar5'));
				$j('#RatingTranslation').text('Excellent');
			}
		}
		else {
			this.currentRating = 0;
			this.removeRating($j('#RatingStar1'));
			this.removeRating($j('#RatingStar2'));
			this.removeRating($j('#RatingStar3'));
			this.removeRating($j('#RatingStar4'));
			this.removeRating($j('#RatingStar5'));
			$j('#RatingTranslation').text('');
		}
	},
	onclick: function(star) {
		if ($j(star).selector.indexOf('1') > 0) {
			this.currentRating = 1;
			this.setRating($j('#RatingStar1'));
			$j('#RatingTranslation').text('Poor');
		}
		else if ($j(star).selector.indexOf('2') > 0) {
			this.currentRating = 2;
			this.setRating($j('#RatingStar1'));
			this.setRating($j('#RatingStar2'));
			$j('#RatingTranslation').text('Fair');
		}
		else if ($j(star).selector.indexOf('3') > 0) {
			this.currentRating = 3;
			this.setRating($j('#RatingStar1'));
			this.setRating($j('#RatingStar2'));
			this.setRating($j('#RatingStar3'));
			$j('#RatingTranslation').text('Average');
		}
		else if ($j(star).selector.indexOf('4') > 0) {
			this.currentRating = 4;
			this.setRating($j('#RatingStar1'));
			this.setRating($j('#RatingStar2'));
			this.setRating($j('#RatingStar3'));
			this.setRating($j('#RatingStar4'));
			$j('#RatingTranslation').text('Good');
		}
		else if ($j(star).selector.indexOf('5') > 0) {
			this.currentRating = 5;
			this.setRating($j('#RatingStar1'));
			this.setRating($j('#RatingStar2'));
			this.setRating($j('#RatingStar3'));
			this.setRating($j('#RatingStar4'));
			this.setRating($j('#RatingStar5'));
			$j('#RatingTranslation').text('Excellent');
		}
	},
	setRating: function(star) {
		$j(star).attr('src', GetSiteImageDirectory() + 'rating_full.png');
	},
	removeRating: function(star) {
		$j(star).attr('src', GetSiteImageDirectory() + 'rating_empty.png');
	}
};

var CustomerRating = {
	reviewID: '',
	Preview: function(rating, title, text) {
		WaitPopup.show();
		var baseProductID = $j("[id$='BaseProductID']").val();
		HHTSitecore.services.ProductService.SaveReview(this.reviewID, baseProductID, rating, title, text, 0, this.onPreviewSuccess.bind(this), this.onPreviewFailure.bind(this));
	},
	onPreviewSuccess: function(result) {
		if (result.status == true) {
			this.reviewID = result.reviewID;
			$j('#previewTitle').text($j('#txtTitle').val());
			$j('#previewText').text($j('#txtText').val());
			$j('#previewRater').text(result.rater);
			if (RatingStars.currentRating >= 1) {
				RatingStars.setRating($j('#PreviewStar1'));
			}
			if (RatingStars.currentRating >= 2) {
				RatingStars.setRating($j('#PreviewStar2'));
			}
			if (RatingStars.currentRating >= 3) {
				RatingStars.setRating($j('#PreviewStar3'));
			}
			if (RatingStars.currentRating >= 4) {
				RatingStars.setRating($j('#PreviewStar4'));
			}
			if (RatingStars.currentRating == 5) {
				RatingStars.setRating($j('#PreviewStar5'));
			}
			$j('#PreviewHeader').toggle();
			$j('#WriteReviewSubmitErrorDiv').hide();
			$j('#EditReviewLower').toggle();
			$j('#PreviewReviewLower').toggle();
		}
		else {
			$j('#WriteReviewPreviewErrorDiv').toggle();
			if (result.message == 'You have already rated this product.') {
				$j('#WriteReviewPreviewErrorText').text(result.message);
			}
			else {
				$j('#WriteReviewPreviewErrorText').text('A system error occurred: ' + result.message + '  Please refresh the page and try again.');
			}
		}
		WaitPopup.hide();
	},
	onPreviewFailure: function() {
		$j('#WriteReviewPreviewErrorDiv').toggle();
		$j('#WriteReviewPreviewErrorText').text('A system error occurred.  Please refresh the page and try again.');
		WaitPopup.hide();
	},
	Edit: function() {
		$j('#PreviewHeader').toggle();
		$j('#PreviewReviewLower').toggle();
		$j('#EditReviewLower').toggle();
	},
	Submit: function(rating, title, text) {
		WaitPopup.show();
		var baseProductID = $j("[id$='BaseProductID']").val();
		HHTSitecore.services.ProductService.SaveReview(this.reviewID, baseProductID, rating, title, text, 1, this.onSubmitSuccess.bind(this), this.onSubmitFailure.bind(this));
	},
	onSubmitSuccess: function(result) {
		if (result.status == true) {
			$j('#WriteReviewDiv').toggle();
			productName = $j("[id$='WriteProductName']").text();
			this.CleanUpWriteFields();
			WaitPopup.hide();
			GenericMessagePopup.show('THANK YOU', 'We appreciate you taking the time to review the ' + productName + '. A confirmation e-mail has been sent to the address associated with your account.  To activate your review, click the activation link in that e-mail.','', 'generic_message_reviews_thankyou');
		}
		else {
			$j('#WriteReviewSubmitErrorDiv').toggle();
			if (result.message == 'You have already rated this product.') {
				$j('#WriteReviewSubmitErrorText').text(result.message);
			}
			else {
				$j('#WriteReviewSubmitErrorText').text('A system error occurred: ' + result.message + '  Please refresh the page and try again.');
			}
			WaitPopup.hide();
		}
	},
	onSubmitFailure: function() {
		$j('#WriteReviewSubmitErrorDiv').toggle();
		$j('#WriteReviewSubmitErrorText').text('A system error occurred: ' + result.message + '.   Please refresh the page and try again.');
		WaitPopup.hide();
	},
	Cancel: function() {
		if (this.reviewID != '' && this.reviewID != null) {
			WaitPopup.show();
			HHTSitecore.services.ProductService.RemoveReview(this.reviewID, this.onCancelSuccess.bind(this), this.onCancelFailure.bind(this));
		}
		else {
			$j('#WriteReviewDiv').toggle();
			this.CleanUpWriteFields();
		}
	},
	onCancelSuccess: function(result) {
		WaitPopup.hide();
		$j('#WriteReviewDiv').toggle();
		this.CleanUpWriteFields();
	},
	onCancelFailure: function() {
		WaitPopup.hide();
	},
	CheckForReviewActivation: function() {
		var qs = new Querystring(window.location.search.replace('?', ''));
		if (qs.contains('pra') == true) {
			HHTSitecore.services.ProductService.ActivateReview(qs.get('pra'), this.onCheckForReviewActivationSuccess.bind(this));
		}
	},
	onCheckForReviewActivationSuccess: function(result) {
		if (result.status == true) {
			GenericMessagePopup.show('THANK YOU', 'Your product review has been activated.', '', 'generic_message_reviews_thankyou');
		}
	},
	CleanUpWriteFields: function() {
		$j('#WriteReviewSubmitErrorDiv').hide();
		$j('#WriteReviewPreviewErrorDiv').hide();
		this.reviewID = '';
		$j('#txtTitle').val('');
		$j('#txtText').val('');
		RatingStars.removeRating($j('#RatingStar1'));
		RatingStars.removeRating($j('#RatingStar2'));
		RatingStars.removeRating($j('#RatingStar3'));
		RatingStars.removeRating($j('#RatingStar4'));
		RatingStars.removeRating($j('#RatingStar5'));
		$j('#RatingTranslation').text('');
	}
};




var Survey = {
    typeLocation: '',
    popupID: '',
    textID: '',
    complete: false,
    surveyID: '',
    loadPopupSurvey: function(page) { //retrieve active popup survey if not on a survey page or landing page
        if (page != "landing-page" && this.surveyID == '') {
            HHTSitecore.services.SurveyService.LoadSurvey('', this.onSurveyPopupLoad.bind(this));
        }
    },
    onSurveyPopupLoad: function(result) {
        if (result.html != '') {
            $j('#divSurveyPopupText').html(result.html);
            $j('#divSurveyPopup').show();
            this.loadSlide(0);
        }
    },
    loadPageSurvey: function(page, surveyID) { //retrieve specific survey for survey page
        this.surveyID = surveyID;
        if (page != "landing-page") {
            HHTSitecore.services.SurveyService.LoadSurvey(surveyID, this.onSurveyPageLoad.bind(this));
        }
    },
    onSurveyPageLoad: function(result) {
        if (result.html != '') {
            $j('#divSurveyPageText').html(result.html);
            $j('#divSurveyPage').show();
            this.loadSlide(0);
        }
    },
    loadSlide: function(idx) {
        var surveyID = $j('.current_survey_id').html();
        HHTSitecore.services.SurveyService.LoadSlide(surveyID, idx, this.onSlide.bind(this));
    },
    onSlide: function(result) {
        if (result.html != '') {
            $j('#survey_slide').html(result.html);
        }
    },
    saveAnswer: function(questionItemID, questionValue, answerItemID, answerValue, selected, removeOthers) {
        //surveyItemID,questionItemID,questionValue,answerItemID,answerValue,selected,removeOthers
        //alert(questionItemID + "," + questionValue + "," + answerItemID + "," + answerValue + "," + selected + "," + removeOthers);
        var surveyID = $j('.current_survey_id').html();
        HHTSitecore.services.SurveyService.SaveResponse(surveyID, questionItemID, questionValue, answerItemID, answerValue, selected, removeOthers, this.onSaveAnswer.bind(this));
    },
    onSaveAnswer: function(result) {
        //...
    },
    submitSurvey: function() {
        var surveyID = $j('.current_survey_id').html();
        HHTSitecore.services.SurveyService.SubmitSurvey(surveyID, this.onSubmitSurvey.bind(this));
    },
    onSubmitSurvey: function(result) {
        //alert('Thank you for taking the survey');
        //... (return thank you?)
        $('divSurveyContent').setStyle({ display: "none" });
        $('divSurveyThanks').setStyle({ display: "block" });
    },
    closeSurvey: function() {
        $j('#divSurveyPopup').hide();
    }
};





var Coupon = {
    typeLocation: '',
    popupID: '',
    textID: '',
    complete: false,
    getCoupon: function(type) {

        this.typeLocation = type;
        this.popupID = '#CouponPopup';
        this.textID = '#CouponText';

        if (window.location.href.toLowerCase().indexOf('landing-pages') < 0) {
            HHTSitecore.services.CouponService.LoadCoupon(this.typeLocation, this.onResult.bind(this), this.onResult.bind(this));
        }
    },
    closeCoupon: function() {
        $j('#CouponPopup').hide();
    },
    saveCouponRequest: function(couponid, coupontype, leadsource, firstname, lastname, fullname, email, phone, join, postalcode, city, state, country, dealerid) {
        //alert(dealerid);
        var isValid = this.validate(fullname, email, phone)
        if (isValid) {
            HHTSitecore.services.CouponService.SaveCouponRequest(couponid, coupontype, leadsource, firstname, lastname, fullname, email, phone, join, postalcode, city, state, country, dealerid, this.onResult.bind(this), this.onResult.bind(this));
        }
    },
    onResult: function(result) {

        if (result.isThankYou) {
            //_gaq.push(['_trackEvent', 'Leads', 'Submit', 'Coupon']);
            EventTracking.trackEvent('Leads', 'Submit', 'Coupon', '');
        }

        if (result.html != '') {
            $j('#CouponText').html(result.html);
            $j('#CouponPopup').show();
            $j('#ResultUserCouponID').html(result.usercouponid);
        }

    },
    validate: function(name, email, phone) {

        var error = "";

        if (name == "") { error = "Please complete the Name field"; }
        else if (email == "") { error = "Please enter a valid email address"; }
        else if (!Validate.email(email)) { error = "Please enter a valid email address"; }
        else if (phone == "") { error = "Please complete the Phone field"; }
        else { error = ""; }

        if (error != "") {
            alert(error);
            return false;
        }
        return true;

    }
};



//TRACK EVENT
var EventTracking = {
    trackEvent: function(category, action, label, page) {
        var act = action;
        var pg = page.toLowerCase();
        //alter action if on landing page
        if (pg.indexOf("landing-pages") > 0) {
            act = "LP_" + action;
        }
        _gaq.push(['_trackEvent', category, act, label]);
    }
};


var HomeFeatures = Class.create();
HomeFeatures.prototype = {
	initialize: function() {
	},
	matchButtonPosition: function() {
		// match row heights
		var t = $$("div.columns4");
		var height = t[0].getHeight() - 10;
		var heights = [];
		//		t.each(function(ul, i) {
		//			ul.select("DIV.heightcolumn").each(function(li, j) {
		//				heights[j] = Math.max(heights[j] || 0, li.getHeight());
		//			});
		//		});
		t.each(function(ul, i) {
			ul.select("DIV.heightcolumn").each(function(li, j) {
				li.setStyle({ height: height + "px" });
			});
		});

		// match top button row heights
		var b = $$("div.columns4>div.heightcolumn");
		var buttonTops = [];
		b.each(function(ul, i) {
			var header = ul.select("h1.heightheader");
			buttonTops[i] = Math.max(buttonTops[i] || 0, header[0].getHeight());
		});
		var slots = $$("div.columns4>div.heightcolumn>div.heightrow");
		slots.each(function(ul, i) {
			heights[i] = Math.max(heights[i] || 0, ul.getHeight());
		});
		var maxHeight = heights[0];
		for (index = 1; index < heights.length; index++) {
			maxHeight = Math.max(maxHeight, heights[index]);
		}
		var maxButtonHeight = buttonTops[0];
		for (index = 1; index < buttonTops.length; index++) {
			maxButtonHeight = Math.max(maxButtonHeight, buttonTops[index]);
		}
		b.each(function(ul, i) {
			//b[i].select("div.heightrow")[0].setStyle({ height: height - (height - heights[i]) - buttonTops[i] + "px" });
			b[i].select("div.heightrow")[0].setStyle({ height: maxHeight + (maxButtonHeight - buttonTops[i]) + "px" });
		});
	}
};

var StoreLocationMap = Class.create();
StoreLocationMap.prototype = {
	map: null,
	geocoder: null,
	initialize: function(p_data) { // p_data = location address
		this.data = p_data
		Event.observe(document, "dom:loaded", this.wire.bind(this)); // dom:loaded fires as soon as the dom is available
	},
	wire: function() {
		var mapOptions = {
			zoom: 13,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			disableDefaultUI: true
		}
		var mapContainer = $$('div.location_map_shell');
		map = new google.maps.Map($$('.location_map_shell')[0], mapOptions);
		//console.log('Got map: ' + map);
		geocoder = new google.maps.Geocoder();
		//console.log('Got geocoder: ' + geocoder);
		var address = this.data;
		//console.log('address: ' + address);
		if (geocoder.geocode != undefined) {
			geocoder.geocode({ 'address': address }, function(results, status) {
				//console.log('in function of geocode, status: ' + status);
				if (status == google.maps.GeocoderStatus.OK) {
					//console.log('Geocoder OK: results: ' + results);
					map.setCenter(results[0].geometry.location);
					//console.log('Set Center: location:' + results[0].geometry.location);
					var marker = new google.maps.Marker({
						map: map,
						position: results[0].geometry.location
					});
				} else {
					alert('Geocode was not successful for the following reason: ' + status);
				}
			});
		} else {
			alert('Geocoder.geocode is undefined');
		}
	}
};


var ServiceRequest = {
    show: function(dealerID, dealerName, phone) {
        var msg = "Use the form below to contact service, or call " + phone + ".";
        $j("[id$='hdnServiceRequestID']").val(dealerID);
        $j("[id$='requestDealerName']").text(dealerName);
        $j("[id$='requestServiceMessage']").text(msg);
        $j("[id$='serviceRequestPopup']").show();
    },
    hide: function() {
        $j("[id$='serviceRequestPopup']").hide();
    },
    hideMessage: function() {
        $j("[id$='serviceRequestMessage']").hide();
    }
};


ThankYouMessageBox = {
    show: function(messageType, messageSection) {
        HHTSitecore.services.Generic.LoadThankYouMessage(messageType, messageSection, this.onLoad.bind(this), this.onFail.bind(this), null);
    },
    hide: function() {
        $j('#ThankYouMessageBoxDimmer').hide();
    },
    onLoad: function(result) {
        $j('#ThankYouMessageBoxDimmer').html(result);
        $j('#ThankYouMessageBoxDimmer').show();
    },
    onFail: function(result) {
        //alert('FAIL: ' + result.message);
    }
};


    function twitterCallback(twitters) {
        //alert("callback");
        //displays all the tweets in the twitters array..
        var statusHTML = [];
        for (var i = 0; i < twitters.length; i++) {
            var username = twitters[i].user.screen_name;

            var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
                return '<a href="' + url + '">' + url + '</a>';
            }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
                return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
            });

            statusHTML.push('<li><div id="retweetid" style="display:none;">' + twitters[i].id_str + '</div><span>' + status + '</span> <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id_str + '">' + relative_time(twitters[i].created_at) + '</a></li>');
        }
        document.getElementById('twitter_update_list').innerHTML = statusHTML.join('') + '<span class="twitter_quote_right">”</span>';

        //hide all tweets...
        $j("#twitter_update_list").find("li").each(function(i) {
            $j(this).hide();
        });

        twitterUpdate();


    }


    function twitterUpdate(){

        var selected = -1;
        
        $j("#twitter_update_list").find("li").each(function(i) {
            if ($j(this).is(':visible')) {
                selected = i;
                $j(this).hide();
            }
        });

        $j("#twitter_update_list").find("li").each(function(i) {
            if ((selected == -1 && i == 0) || selected == 2 && i == 0) {
                $j(this).show();
            }
            else {
                if (selected + 1 == i)
                    $j(this).show();
            }
        });

        //retweet
        $j("#twitter_update_list").find("li").each(function(i) {
            if ($j(this).is(':visible')) {
                document.getElementById('retweet').setAttribute('href', 'http://twitter.com/intent/retweet?tweet_id=' + $j(this).find("#retweetid").html());
            }
        });

        //reset the update...  
        var t = setTimeout("twitterUpdate();", 10000)
    }

    function twitterLoad(twitters) {
        this.twitterCallback(twitters);
    }

    function relative_time(time_value) {
        var values = time_value.split(" ");
        time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
        var parsed_date = Date.parse(time_value);
        var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
        var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
        delta = delta + (relative_to.getTimezoneOffset() * 60);

        if (delta < 60) {
            return 'less than a minute ago';
        } else if (delta < 120) {
            return 'about a minute ago';
        } else if (delta < (60 * 60)) {
            return (parseInt(delta / 60)).toString() + ' minutes ago';
        } else if (delta < (120 * 60)) {
            return 'about an hour ago';
        } else if (delta < (24 * 60 * 60)) {
            return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
        } else if (delta < (48 * 60 * 60)) {
            return '1 day ago';
        } else {
            return (parseInt(delta / 86400)).toString() + ' days ago';
        }
    }








YouTube = {
    loadVideo: function(videoID) {
        //alert('test');
        HHTSitecore.services.Generic.LoadYouTubeVideo(videoID, this.onLoad.bind(this), this.onFail.bind(this), null);
    },
    onLoad: function(result) {
        $j("[id$='youtube_video']").html(result);
        //$j('#youtube_video').html(result);
    },
    onFail: function(result) {
        alert('Failed to load video.');
    }
};


var BuyersGuide = {

    updateResponses: function(answerID, rbl) {

        //key is the folderid or default for a non-logged in user
        var folderID = getQuerystring('rid', 'default');

        //note: first answer in array must be the selected answer.
        var answers = new Array();
        answers[0] = $j("#" + rbl + ' input:checked').val();

        var x = 1;
        $j("#" + rbl + ' input').each(function() {
            var answerID = $j(this).val();
            var checked = $j(this).is(':checked')
            if (!checked) {
                answers[x] = answerID;
            }
            x++;
        });

        HHTSitecore.services.BuyersGuideService.UpdateUserResponses(folderID, answers);

    },

    fieldId: null,
    buttonId: null,
    popupId: "AnswerPopup",
    wirePopup: function(p_field, p_btn) {
        this.fieldId = p_field;
        this.buttonId = p_btn;
    },
    showPopup: function(event, p_src) {
        $(this.fieldId).value = p_src;
        __doPostBack(this.buttonId, '');
        $(this.popupId).show();
    },
    hidePopup: function() {
        $(this.popupId).hide();
    },

    toggleHeader: function(link) {
        var cls = $j(link).attr("class");
        $j("[id$='SectionPageLink']").attr("class", "close");
        if (cls != "open") { $j(link).attr("class", "open"); }

        BuyersGuide.resetSections();
    },

    recommendationsSection: null,
    goToSection: function(fromIndex, toIndex) {
        $j("[id$='SectionID_" + fromIndex + "']" + " .accordionButton").removeClass('on'); //remove class from this slide
        $j("[id$='SectionID_" + fromIndex + "']" + " .accordionContent").slideUp('normal'); //close slide
        $j("[id$='SectionID_" + fromIndex + "'] [id$='SectionPageLink']").attr("class", "close"); //close header

        $j("[id$='SectionID_" + toIndex + "']" + " .accordionButton").addClass('on'); //add class to slide
        $j("[id$='SectionID_" + toIndex + "']" + " .accordionContent").slideDown('normal'); //open slide
        $j("[id$='SectionID_" + toIndex + "'] [id$='SectionPageLink']").attr("class", "open"); //open header

        //if this is the last section, show recommendations
        var ifRec = ($j("[id$='SectionID_" + (toIndex + 1) + "']" + " .accordionButton").attr("class"));
        if (ifRec == null) { BuyersGuide.showProductRecommendations(); };

        //reset section
        BuyersGuide.resetSections();
    },
    resetSections: function() {
        for (var i = 1; i > 0; i++) {
            var reset = $j("[id$='SectionID_" + i + "'] .ResetSection").get(0);
            if (reset != null) { reset.click(); } else { i = -1; }
        }
    },

    showProductRecommendations: function() {
        HHTSitecore.services.BuyersGuideService.LoadProductRecommendations(this.onProductRecommendationsLoad.bind(this), this.onProductRecommendationsFail.bind(this));
    },
    onProductRecommendationsLoad: function(result) {
        $j('#product_recommendation_step').html(result);
        //populate steps for first product...
        var firstProductID = $j('.hidden_product_id:first').text();
        if (firstProductID != '' && firstProductID != null) {
            BuyersGuide.showRelatedRecommendations(firstProductID);
        }
    },
    onProductRecommendationsFail: function(result) {
        alert('FAIL: ' + result.message);
    },

    productId: null,
    showRelatedRecommendations: function(productid) {
        this.productId = productid;
        $j('#BuyersGuideProductID').val(productid);
        HHTSitecore.services.BuyersGuideService.LoadRelatedRecommendations(productid, this.onRelatedRecommendationsLoad.bind(this), this.onRelatedRecommendationsFail.bind(this));
    },
    onRelatedRecommendationsLoad: function(result) {
        $j('.project_recommendations').html(result);
    },
    onRelatedRecommendationsFail: function(result) {
        alert('FAIL: ' + result.message);
    },
    showRecommendedModel: function(productid) {
        HHTSitecore.services.BuyersGuideService.LoadRecommendedProduct(productid, this.onRecommendedModelLoad.bind(this), this.onRecommendedModelFail.bind(this));
    },
    onRecommendedModelLoad: function(result) {
        $j('.product_recommended').html(result);
    },
    onRecommendedModelFail: function(result) {
        alert('FAIL: ' + result.message);
    },
    selectModel: function(selected) {
        $j("[id$='RecommendedModel']").attr("class", "");
        $j(selected).attr("class", "selected");
    },
    launchQuickQuote: function() {
        QuickQuote.showQuickQuote(this.productId);
    }

};

var BuyersGuideSectionRotator = Class.create(SimpleRotator, {
    menu: null,
    text: null,
    duration: 1000, // animation duration
    pause: 10000000,
    stepback: null,
    stepnext: null,
    sectionback: null,
    sectionnext: null,
    sectionreset: null,
    // wire up the assigned DIVs from the generated page
    wire: function() {
        this.div = $(this.id);
        this.slidescont = this.div.select(".section_mover").first();
        this.menu = this.div.select(".section_slider").first();
        this.stepback = this.div.select(".StepBack").first();
        this.stepnext = this.div.select(".StepNext").first();
        this.sectionback = this.div.select(".SectionBack").first();
        this.sectionnext = this.div.select(".SectionNext").first();
        this.sectionreset = this.div.select(".SectionReset").first();
    },
    // when the browser window resizes, we gotta resize all the divs involved in the sliding
    resizeImpl: function() {
        var docViewport = document.viewport.getWidth();
        var w = 960;
        var divs = this.slidescont.select(".section_div");
        this.div.setStyle({ width: w + "px" });
        this.slidescont.setStyle({ width: (w * this.data.length) + "px", left: (-w * this.index) + "px" });
        divs.each(function(elm, idx) {
            elm.setStyle({ width: w + "px", left: (idx * w) + "px" });
        });
    },
    // The generated page always contains HTML for the first image and related text; This function adds the rest, and some other bits.
    onloadImpl: function() {
        var iMax = 0;
        this.data.each(function(obj, index) {
            iMax = index;
        });
        if (iMax != 0) {
            this.data.each(function(obj, index) {
                // add the nav button for this index
                if (index == 0) {
                    this.menu.insert("QUESTIONS: ");
                }
                var elm = new Element("LI");
                var a = new Element("A", { "class": (index == 0) ? "on" : "off" });
                a.insert(index + 1);
                a.observe("click", this.navToo.bind(this, index));
                this.menu.insert(elm.insert(a));

                // add the slide back/next buttons for sections with multiple questions
                a = new Element("A", { "class": "back_off" });
                a.observe("click", this.navToo.bind(this, index));
                this.stepback.insert(a);
                a = new Element("A", { "class": (index == 1) ? "next_on" : "next_off" });
                a.observe("click", this.navToo.bind(this, index));
                this.stepnext.insert(a);


            } .bind(this));
            //hide section next button on load if multiple questions
            this.sectionnext.select("A").each(function(elm, idx) {
                elm.className = (idx == 0) ? "next_off" : "next_on";
            });

            //add hidden reset button
            a = new Element("A", { "class": "ResetSection" });
            a.observe("click", this.navToo.bind(this, 0));
            this.sectionreset.insert(a);
        }
    },
    onmove: function(p_idx, p_last) {
        //alert(this.menu.className);
        this.menu.select("A").each(function(elm, idx) {
            elm.className = (p_idx == idx) ? "on" : "off";
        });
        this.stepback.select("A").each(function(elm, idx) {
            elm.className = ((idx == p_idx - 1) && (p_idx != 0)) ? "back_on" : "back_off";
        });
        this.sectionback.select("A").each(function(elm, idx) {
            elm.className = ((p_idx == 0 && idx == 0)) ? "back_on" : "back_off";
        });
        var iMax = 0;
        this.stepnext.select("A").each(function(elm, idx) { iMax = idx; });
        this.stepnext.select("A").each(function(elm, idx) {
            elm.className = ((idx == p_idx + 1) && (p_idx != iMax)) ? "next_on" : "next_off";
        });
        this.sectionnext.select("A").each(function(elm, idx) {
            elm.className = ((p_idx == iMax)) ? "next_on" : "next_off";
        });
        var width = 960;
        new Effect.Move(this.slidescont, { x: -width * p_idx, mode: "absolute", duration: this.duration / 1000, afterFinish: this.navDone.bind(this) });
    },
    navToo: function(p_idx, src) {
        this.onmove(p_idx, 0);
    }
});
var BuyersGuideSectionSlide = Class.create();
BuyersGuideSectionSlide.prototype = {
    initialize: function() {
    },
    toElement: function() {
        return null;
    }
};


var Validate = {
    //TODO: Add more methods for validating. Name? Phone? Numeric?
    email: function(email) {
        filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (filter.test(email)) { return true; }
        else { return false; }
    },
    isUSPostal: function(postal) {
        //validate us or canadian postal code
        filter = /^\d{5}(-\d{4})?$/;
        if (filter.test(postal)) { return true; }
        else { return false; }
    },
    isCanadianPostal: function(postal) {
        //validate us or canadian postal code
        filter = /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/;
        if (filter.test(postal)) { return true; }
        else { return false; }
    },
    isPostal: function(postal) {
        //validate us or canadian postal code
        filter = /(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/;
        if (filter.test(postal)) { return true; }
        else { return false; }
    }



}



//**PLEASE SAVE**//

//var AjaxTest = {
//    show: function(val1, val2) {

//        //TODO: Explore $j.getJSON
//        //TODO: Class that appends this at runtime?
//    
//        var webMethod = 'http://fireplaces.localhost.com/services/generic.asmx/JeffServiceMethod';
//        var resultDiv = '#JeffAjaxTest';
//        var parameters = "{'val':'" + val1 + "','val1':'" + val2 + "'}";

//        $j.ajax({ type: "POST", url: webMethod, data: parameters, contentType: "application/json; charset=utf-8", dataType: "json",
//            success: function(msg) {
//                alert(msg.d.HTML);
//                $j(resultDiv).html(msg.d.HTML);
//            },
//            error: function(e) {
//                $j(resultDiv).html("Unavailable");
//            }
//        });
//    }
//}



//    var test = function(val1, val2) {

//        //TODO: Explore $j.getJSON
//        //TODO: Class that appends this at runtime?

//        var webMethod = 'http://fireplaces.localhost.com/services/generic.asmx/JeffServiceMethod';
//        var resultDiv = '#JeffAjaxTest';
//        var parameters = "{'val':'" + val1 + "','val1':'" + val2 + "'}";

//        $j.ajax({ type: "POST", url: webMethod, data: parameters, contentType: "application/json; charset=utf-8", dataType: "json",
//            success: function(msg) {
//                alert(msg.d.HTML);
//                $j(resultDiv).html(msg.d.HTML);
//            },
//            error: function(e) {
//                $j(resultDiv).html("Unavailable");
//            }
//        });
//    }


var SendAProject = {
    validate: function(name, email, phone) {

        var error = "";

        if (name == "") { error = "Please complete the Name field"; }
        else if (email == "") { error = "Please enter a valid email address"; }
        else if (!Validate.email(email)) { error = "Please enter a valid email address"; }
        else if (phone == "") { error = "Please complete the Phone field"; }
        else { error = ""; }

        if (error != "") {
            alert(error);
            return false;
        }
        return true;

    }

}


var Tracking = {

    submit: function(productID) {
        HHTSitecore.services.ProductFinder.LoadTrackingBug(productID, this.onTrackSuccess.bind(this), null);
    },

    onTrackSuccess: function(result) {
        $j('#tracking_result').html(result);
    }

};


