﻿/**********************************************
                       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'
};
	
// 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 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 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_FP/loading_bg.png) no-repeat;"><img src="/images_FP/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) {
   		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);
   		}
   		else {
   			console.log('Didn\'t find message.');
   		}
   		$j('#GenericMessageBoxDiv').show();
   	}
   };

   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"
    },
    open: null,
    noTimout: false,
    timer: -1,
    wired: {},
    wireTopNav: 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() { TopNav.over(key) };
            var f_out = function() { TopNav.out(key) };
            // add mouseover and mouseout event listeners
            //$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 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 = 175x130
		this.hspace = $("my_container").getWidth();
		}*/
		this.hspace = $("my_container").getWidth();

		this.size = { width: 175, 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: ""
		};
		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"]).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;
		HHTSitecore.services.ProductFinder.Filter(filterParms.Keyword, filterParms.ProductType, filterParms.SubProductType, filterParms.Width, filterParms.DecorStyle, filterParms.FuelType, filterParms.HeatOutput, filterParms.Brands, filterParms.MSRPNumber, filterParms.RoomSettings, 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(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);
	}
}
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)

// 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), 300);
    },
    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() { that.open.setStyle({ display: "block" }) }, 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 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 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 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;
            __doPostBack(this.buttonId, '');
            $(this.popupId).show();
        } 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) {

        //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);
        this.atag_o.up().className = "on";
        this.toggleNext(true);
        //this.atag_o.className = "some new class name";
        this.div = $(div_id);
        //console.info("show:", this.div);
        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" : "1px";
            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) {
            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"])) {
            //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"])) {
            this.wireRotators();
        }
        if (ajaxUpdateIncludesTrigger(sender, ["btnInfoHelp", "btnInfoDrawer"])) {
            $j("[id$='udInfoDrawer']").css({ position: 'static' });
            //called from footer list or button, default to brands tab
            //this.goToAward(1);
        }
        if (ajaxUpdateIncludesTrigger(sender, ["btnAwardInfo"])) {
            $j("[id$='udInfoDrawer']").css({ position: 'static' });
            //called from dealerlist default to awards tab
            //this.goToAward(0);
        }




    },
    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) {

        //        alert($j("[id$='hdnGLat']").val());
        //        alert($j("[id$='hdnGLon']").val());

        //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;

        }, this);

        if (firstDealer != null)
            this.goToDealer(firstDealer);
    },
    goToAward: function(defaultTab) {
        var btnId = (defaultTab == 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;
        }
    },
    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();
    }

    //    ,

    //    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));
            }

        }
    });
    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
   	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) {
   			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%20Account.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('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) {
   		// 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, 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 != "") {
   				$j('.user_info').show();
   				$j('#MyAccountMenu').html(result.menuHTML);
   				this.completeSignIn();
   			}
   			else {
   				var myAccountLinksPanel = $j("[id$='TopNavSignInUpdatePanel']").get(0);
   				__doPostBack(myAccountLinksPanel.id, '');
   				Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.completeSignIn);
   				TopNav.wired['myaccount'] = null;
   			}
   		}
   		else {
   			WaitPopup.hide();
   			if (result.isAlreadyRegistered == true) {
   				$j('#registrationDimmer').hide();
   				$j('#AlreadyRegisteredDimmer').show();
   			}
   			else {
   				$j('#CreateErrorMessageDiv').text(result.errorMessage);
   				this.isAuthenticated = false;
   			}
   		}
   	},
   	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) {
   		// 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 != "") {
   				$j('.user_info').show();
   				$j('#MyAccountMenu').html(result.menuHTML);
   				this.completeSignIn();
   			}
   			else {
   				var myAccountLinksPanel = $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();
   				}
   			}
   		}
   		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) {
   		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%20Heat%20n%20Glo.aspx';
   				}
   				else if (window.location.href.indexOf('quadrafire') >= 0) {
   					myAccountPage = 'My%20QuadraFire.aspx';
   				}
   			}
   			else {
   				myAccountPage = 'Header%20Toolbox/My%20Account.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 (result.menuHTML != "") {
   			this.isAuthenticated = false;
   			$j('.user_info').show();
   			$j('.user_info').html(result.logoutStateHTML);
   			$j('#MyAccountMenu').html(result.menuHTML);
   			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;
   			}
   		}

   	},
   	onLogoutFailure: function(result, context) {
   		WaitPopup.hide();
   		alert('Failure, message: ' + result.errorMessage);
   	},
   	completeLogout: function() {
   		if (window.location.pathname.indexOf('My%20') >= 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 (|) charachters 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 (|) charachters 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(articleID) {
   		MyAccount.authenticationCheck();
   		var selectedFolderIDs = '';

   		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.');
   		}
   	},
   	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 (|) charachters 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();
   	},
   	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("spec_views_list").init(function() {
           $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();
   	},
   	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());
   	},
   	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.');
   		}
   		else {
   			PopupAuthenticationHandler.ShowJoinNewsletter();
   		}
   	},
   	ShowMyAccount: function() {
   		if (!MyAccount.isAuthenticated) {
   			MyAccount.showSignInPopup('You\'ll need to sign in before you can go to your personal page.  ');
   		}
   		return MyAccount.isAuthenticated;
   	}
   };
      function ClearSearch() {
      	$j("[id$='LocatorQuickEntryTextbox1']").val("");
      }

      DealerAwardDrawer = {
          ShowHideBrandDrawer: function() {
              //diable the brand drawer if on a branded site
              var showBrands = $j("[id$='hdnShowBrands']").val();
              if (showBrands == "Y")
                  $j('#imgBrandInfo').show();
              else
                  $j('#imgBrandInfo').hide();
          },
          SelectBrandDrawer: function() {
              $j("[id$='brandInfoTab']").show();
              $j("[id$='dealerLevelsTab']").hide();
              $j('#imgBrandInfo').removeClass().addClass('left greybtn_brand_info_active');
              $j('#imgDealerLevels').removeClass().addClass('left greybtn_dealer_levels');
              this.ShowHideBrandDrawer();
          },

          SelectDealerLevelDrawer: function() {
              $j("[id$='brandInfoTab']").hide();
              $j("[id$='dealerLevelsTab']").show();
              $j('#imgBrandInfo').removeClass().addClass('left greybtn_brand_info');
              $j('#imgDealerLevels').removeClass().addClass('left greybtn_dealer_levels_active');
              this.ShowHideBrandDrawer();
          }

      };


      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) {
        //this may need to be refactored to allow multiple uses of the promotion pager on one page
        $j("[id$='ulPager'] li").removeClass().addClass('off');
        $j(src).parent().removeClass().addClass('on');
        $j("#ulPromoSlots li").hide();
        $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() {
            //get active survey cookie string
            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) {
            HHTSitecore.services.SurveyService.CloseSurvey(surveyCode, 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;
                        }
                    }
                }
            }
        });
    });


    QuickQuote = {
        show: function() {
            $j("#quickQuote").show();
        },
        hide: function() {
            $j("#quickQuote").hide();
        },
        incrementRotator: function(src, direction) {

        var currentIdx = $j("[id$='hdnSelectedProductIdx']").val();
        
        //alert(currentIdx);
        var newIdx = 0;
        if (direction == "back")
            newIdx = parseInt(currentIdx) - 1;
        else
            newIdx = parseInt(currentIdx) + 1;

        $j("[id$='hdnSelectedProductIdx']").val(newIdx);
        //alert("currentIdx: " + currentIdx + " - newIdx: " + newIdx);

        }
    };

    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");
			}
		}
	};