var $ = jQuery;

// There is a lot of legacy code that tests for `$.browser.msie`. This property has been removed from jQuery since
// v1.9.1. It is super old and should not be used anymore.
if ('undefined' === typeof $.browser) {
	$.browser = {
		msie: false,
		version: '',
	};
}

if ('function' !== typeof $.fn.live) {
	$.fn.extend({
		live: function(event, callback) {
			if (this.selector) {
				$(document).on(event, this.selector, callback);
			}
		}
	});
}


// jQuery plugins; just paste them here
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 * @author Ariel Flesler
 * @version 1.4
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

// Custom jQuery plugin for viking
(function($) {


	$.fn.ident = function(id) {
		if (id) {
			this.attr('id', id);
			return this;
		} else {
			return this.attr('id');
		}
	};
	$.fn.exists = function(func) {
		if (this.length > 0 && typeof func == "function") {
			func(this);
			return this;
		}
		return this.length > 0;
	};
	$.fn.enable = function() {
		return this.each(function() {
			this.disabled = false;
		});
	};
	$.fn.disable = function() {
		return this.each(function() {
			this.disabled = true;
		});
	};
	$.fn.check = function() {
		return this.each(function() {
			this.checked = true;
		});
	};
	$.fn.uncheck = function() {
		return this.each(function() {
			this.checked = false;
		});
	};
    $.fn.toggleCheck = function() {
        return this.each(function() {
           this.checked = !this.checked;
        });
    };
   	$.fn.array_initialize = function(arr) {
		var alen = arr.length;
		for (var i = 0; i < alen; i++) {
			arr[i] = $(['#', arr[i]].pack());
		}
		return arr;
	};
	$.extend({
        ie6: function() {
            return ($.browser.msie && $.browser.version < 7);
        },
		addStylesheet: function(sheet) {
			var link = $(['<link rel="stylesheet" type="text/css" href="/consumer/stylesheets/', sheet, '.css" />'].pack());
			$('head').append(link);
			return link;
		},
        addCSS: function(sheet) { // for the directory structure change where stylesheets are in /css now
			var link = $(['<link rel="stylesheet" type="text/css" href="/consumer/css/', sheet, '.css" />'].pack());
			$('head').append(link);
			return link;
		},
        pause: function(timeout) {
			timeout = timeout || 1000;
			var b = $('body');
			b.addClass('pause');
			setTimeout(function() {
				b.removeClass('pause');
			}, timeout);
		},
		spreadItems: function(list) {
			var width = list.width();
			var items = list.find('li');
			var w = 0;
			items.each(function() {
				w += $(this).width();
			});
			var padding = width - w
			padding = padding / items.length
			var incremental_padding = padding / items.length;
			padding = padding + incremental_padding;
			items.each(function(i) {
				if (i > 0) {
					$(this).css('padding-left', padding.pixelate());
				}
			});
		},


		// <select> boxes will show through any dynamic layers on a page in IE.
		// This attempts to find any that have a corner within the boundaries
		// of a flyout. If so, then they're hidden until the layer goes away.
		hideSelects: function(node) {
			if ($.browser.msie) {
				var box = {
					top: node.offset().top,
					right: node.offset().left + node.outerWidth(true),
					bottom: node.offset().top + node.outerHeight(true),
					left: node.offset().left
				}
				$('select').each(function(i) {
					var select = $(this);
					var coords = {
						top: select.offset().top,
						right: select.offset().left + select.outerWidth(true),
						bottom: select.offset().top + select.outerHeight(true),
						left: select.offset().left
					};
					if (coords.top >= box.top && coords.bottom <= box.bottom) {
						if (coords.left >= box.left || coords.right >= box.right) {
							select.addClass('ie-hidden').css('visibility', 'hidden');
						}
					}
				})
			}
		},

		// This should work with $.hideSelects
		showSelects: function(node) {
			if ($.browser.msie) {
				$('select.ie-hidden').each(function() {
					$(this).removeClass('ie-hidden').css('visibility', 'visible');
				});
			}
		},

		spreadItemsEvenly: function(list) {
            if (!list) {
			    list = $('#nav-footer');
            }

			var width = list.width();
			var items = list.find('li:visible');
			var w = 0;
			items.each(function() {
				w += $(this).width();
			});
			var padding = width - w
			padding = padding / items.length
			var incremental_padding = padding / items.length;
			padding = padding + incremental_padding;
            padding = (padding / width) * 100;

			items.each(function(i) {
				if (i > 0) {
					$(this).css('padding-left', [padding, '%'].pack());
				}
			});
		},
        spreadItemsEqually: function(list) {
            var width = list.width();
            var items = list.find('li');
            var itemWidth = width / items.length;
            items.each(function() {
                $(this).width(itemWidth);
            });

        }
	});

	$.fn.carousel = function(o) {
        var list = $(this);
		var div = $('<div class="carousel"><div class="carousel-up"></div><div class="carousel-body"></div><div class="carousel-down"></div></div>');
		var top;
		o = o || {};
		var wait = false;
		var visible;
		var scrollBy;
		var index = 0;

		var fadeButton = function(button) {
			button.fadeTo(500, 0.5, function() {
				button.fadeTo(1000, 1);
			});
		};


		var listen = function() {
            var delay = 1;
            var interval;
            div.find('.carousel-down').click(function() {
                var next = top.next();
                if (next.exists()) {
                    list.scrollTo(next, 1000);
                    top = next;
                } else {
                    fadeButton($(this));
                }
            });
            div.find('.carousel-up').click(function() {
                var prev = top.prev();
                if (prev.exists()) {
                    list.scrollTo(prev, 1000);
                    top = prev;
                } else {
                    fadeButton($(this));
                }
            });


		};
		var init = function() {
            visible = o.visible || 2;
            scrollBy = o.scrollBy || 1;
            var height = 0;
            var heights = [];
            list.find('li').each(function() {
                heights.push($(this).height());
            });
            heights.sort(function(a, b) {
                return a - b;
            });
            height = heights.pop();
            height += heights.pop();
            if ($.ie6()) {
                // For some reason ie6 claims that each <li> is about 50px taller than it actually is.
                height -= 100;
            }
            list.height(height);
            top = list.find('li:first');
            list.parents(':first').append(div);
            div.find('.carousel-body').append(list.remove());
            listen();

		};

		init();
	};


})(jQuery);

// Based on public domain code by Tyler Akins <http://rumkin.com/>
// Original code at http://rumkin.com/tools/compression/base64.php

var Base64 = (function() {
  function encode_base64(data) {
    var out = "", c1, c2, c3, e1, e2, e3, e4;
    for (var i = 0; i < data.length; ) {
       c1 = data.charCodeAt(i++);
       c2 = data.charCodeAt(i++);
       c3 = data.charCodeAt(i++);
       e1 = c1 >> 2;
       e2 = ((c1 & 3) << 4) + (c2 >> 4);
       e3 = ((c2 & 15) << 2) + (c3 >> 6);
       e4 = c3 & 63;
       if (isNaN(c2))
         e3 = e4 = 64;
       else if (isNaN(c3))
         e4 = 64;
       out += tab.charAt(e1) + tab.charAt(e2) + tab.charAt(e3) + tab.charAt(e4);
    }
    return out;
  }

  function decode_base64(data) {
    var out = "", c1, c2, c3, e1, e2, e3, e4;
    for (var i = 0; i < data.length; ) {
      e1 = tab.indexOf(data.charAt(i++));
      e2 = tab.indexOf(data.charAt(i++));
      e3 = tab.indexOf(data.charAt(i++));
      e4 = tab.indexOf(data.charAt(i++));
      c1 = (e1 << 2) + (e2 >> 4);
      c2 = ((e2 & 15) << 4) + (e3 >> 2);
      c3 = ((e3 & 3) << 6) + e4;
      out += String.fromCharCode(c1);
      if (e3 != 64)
        out += String.fromCharCode(c2);
      if (e4 != 64)
        out += String.fromCharCode(c3);
    }
    return out;
  }

  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  return { encode:encode_base64, decode:decode_base64 };
})();

var IEOnly = function() {
    var maxZIndex = 1;
    return {
        zIndex: function(node, zindex, context_id) {
            if (zindex > maxZIndex) {
                maxZIndex = zindex;
            }
            if (jQuery.browser.msie && (jQuery.browser.version < 8)) {

                try {
                    var iaz_preserved_elements = [];
                    var iaz_preserved_zindexes = [];

                    // default values
                    if (undefined == zindex) {
                        zindex = 1;
                    }

                    var context = (!context_id) ? jQuery('body') : jQuery(['#', context_id].join(''));

                    var element = node;

                    // undo past ie_apply_zindex()
                    for (var i = iaz_preserved_elements.length - 1; i >= 0; i--) {
                        iaz_preserved_elements[i].css({'z-index': iaz_preserved_zindexes[i]});
                    }
                    iaz_preserved_elements = [];
                    iaz_preserved_zindexes = [];

                    // find relative-positioned ancestors of element within context
                    element.parents().each(function(i) {
                        var ancestor = jQuery(this);
                        if ('relative' === ancestor.css('position')) {
                            // preserve ancestor's current z-index
                            iaz_preserved_elements.push(ancestor);
                            iaz_preserved_zindexes.push(ancestor.css('z-index'));

                            // apply z-index to ancestor
                            ancestor.css({'z-index': zindex});
                        }
                        if (ancestor == context) {

                            throw $break;
                        }
                    });
                } catch(e) {
                    // Let it go. This too shall pass.
                }
            }
        }
    };
}();


// Function to add a class to the nav04 layout style.
// Mostly used to add a divider to the page using a background.
// If no addRemove function passed in, then default to add.
function Nav04BackgroundToggler(className, addRemove) {
	if ((!addRemove) || (addRemove == "add")) {
		$('div.nav04').addClass(className);
	}
	if (addRemove == "remove") {
		$('div.nav04').removeClass("nav04-divider-product-accs");
	}
};

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

var Browser = function() {
    return {
        ie: function() {
            return (window.ActiveXObject) ? true : false;
        },
        ie6: function() {
            if (window.ActiveXObject) {
                var v = $.browser.version;
                if (v >= 6 && v < 7) {
                    return true;
                }
            }
            return false;
        }
    }
}();


Array.prototype.pack = function() {
    return this.join('');
};

Array.prototype.edges = function() {
    return {
        first: this[0],
        last: this[this.length - 1]
    };
};

// Interface fixes

function Tags() {};
Tags.IMG = "img";
Tags.DIV = "div";
Tags.SPAN = "span";
Tags.UL = "ul";
Tags.A = "a";
Tags.OL = "ol";
Tags.LI = "li";

function Events() {};
Events.MOUSEOVER = "mouseover";
Events.MOUSEDOWN = "mousedown";
Events.MOUSEOUT = "mouseout";
Events.MOUSEUP = "mouseup";
Events.MOUSEMOVE = "mousemove";
Events.CLICK = "click";
Events.DOUBLE_CLICK = "dblclick";
Events.KEYDOWN = "keydown";
Events.KEYUP = "keyup";
Events.KEYPRESS = "keypress";
Events.LOAD = "load";
Events.ABORT = "abort";
Events.UNLOAD = "unload";
Events.normalize = function(evt) {
	var e = {};
	e.e = evt || window.event;
	e.target = evt.target || evt.srcElement;
	return e;
};

Events.pageXY = function(e) {
	var c = {};
	c.x = (e.pageX) ? e.pageX : e.clientX;
	c.y = (e.pageY) ? e.pageY : e.clientY;
	return c;
};


/**
*	If Node is undefined, then define some constants for IE.
*/
if (typeof Node == "undefined") {
	Node = function() {};
	Node.ELEMENT_NODE = 1;
    Node.ATTRIBUTE_NODE = 2;
    Node.TEXT_NODE = 3;
    Node.CDATA_SECTION_NODE = 4;
    Node.ENTITY_REFERENCE_NODE = 5;
    Node.ENTITY_NODE = 6;
    Node.PROCESSING_INSTRUCTION_NODE = 7;
    Node.COMMENT_NODE = 8;
    Node.DOCUMENT_NODE = 9;
    Node.DOCUMENT_TYPE_NODE = 10;
    Node.DOCUMENT_FRAGMENT_NODE = 11;
    Node.NOTATION_NODE = 12;
}

/**
*	Give IE a NodeFilter.
*/
if (typeof NodeFilter == "undefined") {
	NodeFilter = function() {
	};
	NodeFilter.FILTER_ACCEPT = 1;
	NodeFilter.FILTER_REJECT = 2;
	NodeFilter.FILTER_SKIP = 3;
	NodeFilter.SHOW_ALL = -1;
	NodeFilter.SHOW_ELEMENT = 1;
	NodeFilter.SHOW_ATTRIBUTE = 2;
	NodeFilter.SHOW_TEXT = 4;
	NodeFilter.SHOW_CDATA_SECTION = 8;
	NodeFilter.SHOW_ENTITY_REFERENCE = 16;
	NodeFilter.SHOW_ENTITY = 32;
	NodeFilter.SHOW_PROCESSING_INSTRUCTION = 64;
	NodeFilter.SHOW_COMMENT = 128;
	NodeFilter.SHOW_DOCUMENT = 256;
	NodeFilter.SHOW_DOCUMENT_TYPE = 512;
	NodeFilter.SHOW_DOCUMENT_FRAGMENT = 1024;
	NodeFilter.SHOW_NOTATION = 2048;
}

// Prototype (Javascript, not the library) additions.

/**
	Trim both sides of a string.
*/
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};

/**
	Trim left side of a string.
*/
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
};

/**
	Trim right side of a string.
*/
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
};

/**
	Parses a string into a JSONObject.
*/
String.prototype.parseJSON = function () {
    try {
    	 return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};

String.prototype.pixelate = function() {
	return [this, 'px'].join('');
};

String.prototype.idPack = function() {
    return ['#', this].join('');
};

String.prototype.classPack = function() {
    return ['.', this].join('');
};

String.prototype.camelCase = function() {
    if (this.length > 0) {
        var val = this.replace(/[^a-zA-Z0-9]/g, '');
        val = val.split('');
        val[0] = val[0].toLowerCase();
        val = val.join('');
        return val;
    }
    return null;
};

String.prototype.ucfirst = function() {
    if (this.length > 0) {
        var val = this.split('');
        val[0] = val[0].toUpperCase();
        return val.join('');
    }
    return null;
}

Number.prototype.pixelate = function() {
	return [this, 'px'].join('');
};

// Event listener wrappers

/**
	Returns an eventListener-style object for a particular browser. It'll either be W3C or MS.
*/
function addListener(node, event, funktion, bubble) {
	if (node.addEventListener) {
		node.addEventListener(event, funktion, bubble);
	} else if (node.attachEvent) {
		node.attachEvent(["on", event].join(""), funktion);
	}
};

/**
	Removes an eventListener-style object for a particular browser.
*/
function removeListener(node, event, func, bubble) {
	if (node.removeEventListener) {
		node.removeEventListener(event, func, bubble);
	} else if (node.detachEvent) {
		node.detachEvent(["on", event].join(""), func);
	}
};

/**
*	Force events to return false if they are handled in listeners.
*/
function stopEvent(e) {
	if (e.preventDefault) {
		e.preventDefault();
	} else if (e.cancelBubble) {
		e.cancelBubble = true;
	} else if (e.returnValue) {
		e.returnValue = false;
	} else if (e.stopPropagation) {
		e.stopPropagation();
	} else {
		e.returnValue = false;
		e.cancelBubble = true;
	}
	return false;
};

// DOM utilities

/**
	Finds the actual type of an object. For some reason, typeof [1, 2, 3] will return "object" instead of "array". This is true for all browsers.
*/
function typeOf(what) {
	var t = typeof what;
	if (t === "object") {
		if (what) {
			if (what instanceof Array) {
				t = "array";
			}
		} else {
			t = "null";
		}

	}
	return t;
};

/**
 * Returns whether or not an image has loaded. Pretty useful in intervals.
 * @param img
 */
function imageLoaded(img) {
	if (!img.complete) {
		return false;
	}
	if (img.naturalWidth && img.naturalWidth == 0) {
		return false;
	}
	return true;
};

/**
*	Is it a function?
*/
function isFunction(what) {
	if (typeOf(what) == "function") {
		return true;
	}
	return false;
};

/**
	Overwrites a node's class name.

	@param node The node to change.
	@param className The class name to apply to the node.
*/
function setClass(node, className) {
	node.className = className;
};

/**
	Adds a class to a node's existing set of class names.

	@param node The node to add the class name to.
	@param className The name of the class to add.
*/
function addClass(node, klassName) {
	if (!node.className) {
		node.className = klassName;
	} else {
		var classes = node.className.split(" ");
		classes.push(klassName);
		node.className = classes.join(" ");
	}
};

/**
	Removes a class name from a node's existing set of class names.

	@param node The node to remove the class name from.
	@param className The name of the class to remove.
*/
function removeClass(node, className) {
	var pattern = new RegExp(["(^|\\s)" , className , "(\\s|$)"].join(""));
	node.className = node.className.replace(pattern, " ");
};

/**
	Replaces a class name on a node's existing set of class names.

	@param node The node to remove the class name from.
	@param search The name of the class to remove.
	@param replace The name of the class to add.
*/
function replaceClass(node, search, replace) {
	removeClass(node, search);
	addClass(node, replace);
};

function kill(node) {
	if (node) {
		node = $(node);
	}
	if (node) {
		return node.parentNode.removeChild(node);
	}
};

function gut(node) {
	var cnodes = node.childNodes;
	for (var i = cnodes.length - 1; i > -1; i--) {
		cnodes[i].parentNode.removeChild(cnodes[i]);
	}
	return node;
};

function findPosition(node) {
	var nleft = 0;
	var ntop = 0;
	var width = node.offsetWidth;
	var height = node.offsetHeight;
	if (node.offsetParent) {
		do {
			nleft += node.offsetLeft;
			ntop += node.offsetTop;
		} while ((node = node.offsetParent) != null);
		return {
			'x': nleft,
			'y': ntop,
			'w': width,
			'h': height
		};
	}
};


/**
	Gets the style object for a node.

	@param node The node from which to extract the style.
*/
function getStyle(node) {
	if (node.style) {
		return node.style;
	} else if (node.currentStyle) {
		return node.currentStyle;
	}
	return false;
};

function style(node, styles) {
	var style = getStyle(node);
	for (var i in styles) {
		style[i] = styles[i];
	}
};

function addStyle(node, styles) {
	var style = getStyle(node);
	for (var i in styles) {
		style[i] = styles[i];
	}
};

var queryString = function(params) {
	var qs = [];
	for (var i in params) {
		qs.push([i, params[i]].join("="));
	}
	qs = qs.join("&");
	return qs;
};



/**
	Produces a collection of nodes based on their class name.

	@param node Reference to a root node to begin the search
	@param className The class name you're looking for
	@param tagName (Optional) The name of the tag you're looking for. Including this parameter will make this function run faster. This can either be an array of tags or a string.
*/
function getElementsByClassName(node, className, tagName) {
	var classes = [];
	var tags = (tagName != null) ? tagName : "*";

	if (typeOf(tags) !== "array") {
		tags = [tags];
	}
	for (var i in tags) {
		var tag = tags[i];
		var elements = node.getElementsByTagName(tag);
		var eLength = elements.length;
		var pattern = new RegExp(["(^|\\s)" , className , "(\\s|$)"].join(""));
		var i = 0;
		var j = 0;
		for (i = 0, j = 0; i < eLength; i++) {
			if (pattern.test(elements[i].className)) {
				classes.push(elements[i]);
			}
		}
	}
	return classes;
};


/**
	Produces a collection of nodes based on their class name.

	@param node Reference to a root node to begin the search
	@param classNames A collection of class names and their types

*/
function getElementsByManyClassNames(node, classNames) {

	var klasses = {};


	if (typeOf(classNames) !== "array") {
		classNames = [classNames];
	}

	for (var i in classNames) {
		var className = classNames[i].klass;
		var tags = classNames[i].tag;
		if (typeOf(tags) != "array") {
			tags = [tags];
		}

		for (var tag in tags) {
			var elements = node.getElementsByTagName(tags[tag]);
			var eLength = elements.length;

			var pattern = new RegExp(["(^|\\s)" , className , "(\\s|$)"].join(""));
			var i = 0;
			var j = 0;
			for (i = 0, j = 0; i < eLength; i++) {
				if (pattern.test(elements[i].className)) {
					if (!klasses[className]) {
						klasses[className] = [];
					}
					klasses[className].push(elements[i]);
				}
			}
		}
	}
	for (var i in klasses) {
		if (!klasses[i]) {
			klasses[i] = [];
		}
	}
	return klasses;
};

/**
	IE's implementation of document.getElementsByName is idiotic. This will slow things down for that
	browser, but should work correctly for others.<b>

	@param node The node to search for.
	@param name The name to search for.
*/
function getElementsByName(node, name) {
	if (webapp.isIE()) {
		var nodes = document.getElementsByTagName(node);
		var ie_nodes = [];
		var nlen = nodes.length;
		for (var i = 0; i < nlen; i++) {
			var n = nodes[i];
			if (n.name && n.name == name) {
				ie_nodes.push(n);
			}
		}
		return ie_nodes;
	} else {
		return document.getElementsByName(name);
	}
};

// Objects


/**
	Makes an ajax request object
*/
function XHR() {
	var xhr;
	try {
		xhr = new XMLHttpRequest();
	} catch (e) {
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				return false;
			}
		}
	}
	return xhr;
};
XHR.GET = "GET";
XHR.POST = "POST";

function InternetExplorer() {
	if (!InternetExplorer._I) {

		InternetExplorer.prototype.SELECT_CLASS_NAME = "ie-hide-select";

		InternetExplorer.prototype.init = function() {

		};

		InternetExplorer.prototype.forceFlyoutWidths = function(node) {
			if (!node) {
				return;
			}
			var style = getStyle(node);

		};

		InternetExplorer.prototype.unwreckSelects = function(node) {
			var coords = {};
			coords.top = { x : node.offsetLeft, y : node.offsetTop };
			coords.bottom = { x : node.offsetLeft, y : coords.y + node.offsetHeight };
			coords.width = node.offsetWidth;
			coords.height = node.offsetHeight;

			// now get all the selects and see where they are on the page
			var selects = document.getElementsByTagName("select");
			for (var i = selects.length - 1; i > -1; i -= 1) {
				var sel = selects[i];
				var parent = sel.offsetParent;
				var left = sel.offsetLeft;
				var top = sel.offsetTop;
				left += parent.offsetLeft;
				top += parent.offsetTop;
				while (parent = parent.offsetParent) {
					left += parent.offsetLeft;
					top += parent.offsetTop;
				}
				var bottom = top + sel.offsetHeight;
				if (left >= coords.top.x && left <= coords.top.x + coords.width) {

					if ((top >= coords.top.y && top <= coords.top.y + coords.height) || (bottom >= coords.top.y && bottom <= coords.top.y + coords.height)) {
						sel.className = this.SELECT_CLASS_NAME;
					}
				}


			}
		};

		InternetExplorer.prototype.wreckSelects = function(node) {
			var selects = document.getElementsByTagName("select");
			var pattern = /ie-hide-select/;
			for (var i = selects.length - 1; i > -1; i -= 1) {
				if (selects[i].className.match(pattern)) {
					selects[i].className = selects[i].className.replace(pattern, "");
				}
			}
		};

		InternetExplorer.prototype.fixFlyout = function(node) {
			if (!node) {
				return;
			}
			var width = node.offsetWidth;
			var style = getStyle(node);
			style.width = [width, "px"].join("");
		};

		InternetExplorer._I = 1;
	}
};

/**
	Convenience wrapper for getting/setting cookies.
*/
function Cookie() {
	if (!Cookie._i) {
		Cookie.prototype.set = function(key, value, a) {
			var today = new Date();
			var later = new Date(today.getTime() + 31536000000);
			document.cookie = [key, "=", escape(value), "; expires=", later.toGMTString(), "; path=/"].join("");
		};
		Cookie.prototype.get = function(key) {
			var keyLength = key.length;
			var cookie = document.cookie;
			var cookieLength = cookie.length;
			var cookieEnd = null;
			for (var i = 0; i < cookieLength; i++) {
				var j = i + keyLength;
				if (cookie.substring(i, j) == key) {
					cookieEnd = cookie.indexOf(";", j);
					if (cookieEnd == -1) {
						cookieEnd = cookie.length;
					}
					return unescape(cookie.substring(j + 1, cookieEnd));
				}
			}
			return false;
		};
		Cookie.prototype.expire = function(key) {
			var today = new Date();
			var before = new Date(today.getTime() - 31536000000);
			document.cookie = [key, "=; expires=", before.toGMTString(), "; path=/"].join("");
		};
		Cookie.prototype.dump = function() {
			alert(document.cookie);
		};
		Cookie._i = 1;
	}
};

/**
	Browser sniffer.
*/
function BrowserDetector() {

	this.browserName;
	this.browserVersion;
	this.ie = false;
	this.broken = false;

	if (!BrowserDetector._I) {
		BrowserDetector.prototype.init = function() {
			if (document.all) {
				this.ie = true;
			}
			var version = 0;
			if (navigator.appVersion.indexOf("MSIE") != -1) {
				version = navigator.appVersion.split("MSIE");
				this.browserName = "Internet Explorer";
				this.browserVersion = parseFloat(version[1]);
			} else if (navigator.userAgent.match(/applewebkit/i)) {
				var versions = navigator.userAgent.split("/");
				versions = versions[versions.length - 2].split(" ");
				this.browserName = "Safari";
				this.browserVersion = versions[0];
			} else if (navigator.userAgent.match(/gecko/i)) {
				var versions = navigator.userAgent.split("/");
				this.browserName = "Mozilla";
				this.browserVersion = versions[versions.length - 1];
			} else {
				this.browserName = "Unknown";
				this.browserVersion = 0;
			}
		};

		BrowserDetector.prototype.isIE = function() {
			return this.ie;
		};

		BrowserDetector.prototype.isBroken = function() {
			if (this.ie && this.browserVersion < 7) {
				return true;
			}
			return false;
		};

		BrowserDetector.prototype.getName = function() {
			return this.browserName;
		};

		BrowserDetector.prototype.getVersion = function() {
			return this.browserVersion;
		};

		BrowserDetector._I = 1;
	}
	this.init();
};

/**
*	Main interface to the web application.
*/
function Webapp() {

	this.debug = false;
	this.loggingEnabled = true;
	this.ieLoggingEnabled = false;
	this.URLPrefix = "/consumer";

	if (!Webapp._I) {
		Webapp.prototype.browserDetector = new BrowserDetector();
		Webapp.prototype.init = function() {

		};

		Webapp.prototype.getURL = function(path) {
			return [this.URLPrefix, path].join("");
		};

		/**
			Returns whether or not the webapp is in debug mode.
		*/
		Webapp.prototype.isDebug = function() {
			return this.debug;
		};

		Webapp.prototype.reload = function() {
			window.location.reload();
		};

		Webapp.prototype.isIE = function() {
			return this.browserDetector.isIE();
		};

		Webapp.prototype.isBroken = function() {
			return this.browserDetector.isBroken();
		};

		Webapp.prototype.log = function(message) {
			if (this.loggingEnabled && typeof console != "undefined" && console.log) {
				if (typeof message == "object") {
					console.log(message.join(" "));
				} else {
					console.log(message);
				}
			}
		};

		Webapp._I = 1;
	}
	this.init();
};

var webapp = new Webapp();

/**
*	Shortcut to Firebug's console log.
*/
function log(message) {
	webapp.log(message);
};

function addListener(node, event, funktion, bubble) {
	if (node.addEventListener) {
		node.addEventListener(event, funktion, bubble);
	} else if (node.attachEvent) {
		node.attachEvent(["on", event].join(""), funktion);
	}
};

function removeListener(node, event, func, bubble) {
	if (node.removeEventListener) {
		node.removeEventListener(event, func, bubble);
	} else if (node.detachEvent) {
		node.detachEvent(["on", event].join(""), func);
	}
};

function getStyle(node) {
	if (node.style) {
		return node.style;
	} else if (node.currentStyle) {
		return node.currentStyle;
	}
	return false;
};

function updateInnerHTML(node, innerHTML) {
	node.innerHTML = "";
	var div = document.createElement("div");
	div.innerHTML = innerHTML;
	node.appendChild(div);
};


String.prototype.parseJSON = function () {
    try {
    	 return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};

function XHR() {
	var xhr;
	try {
		xhr = new XMLHttpRequest();
	} catch (e) {
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				return false;
			}
		}
	}
	return xhr;
};

function materialize(node) {
	var style = getStyle(node);
	style.display = "block";
};

function spiritualize(node) {
	var style = getStyle(node);
	style.display = "none";
};

function getCoordinates(e) {
	var px;
	var py;
	if (e.pageX && e.pageY) {
		px = e.pageX;
		py = e.pageY;
	} else {
		px = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - document.body.clientLeft;
		py = e.clientY + document.body.scrollTop + document.documentElement.scrollTop - document.body.clientTop;
	}
	var coords = { x : px , y : py };
	return coords;
};


function Flyout(e, func) {
	if (!e) {
		return false;
	}

	this.event = e;
	this.id = "flyout";
	this.headerId = "flyout-header";
	this.contentId = "flyout-content";
	this.imgSrc = "/images/search_button-close.gif";
	this.imgAlt = "[close]";
	this.imgId = "close-flyout";
	this.header = null;
	this.content = null;
	this.ieStyleSet = false;

	if (!Flyout._I) {
		Flyout.prototype.init = function() {
			kill($(this.id));
			this.build();
		};

		Flyout.prototype.setStyle = function(property, value) {
			var style = getStyle($(this.id));
			style[property] = value;
			log(style[property] + " " + value);
			this.ieStyleSet = true;
		};

		Flyout.prototype.setHeader = function(node) {
			var header = $(this.headerId);
			if (header) {
				this.header = header;
				header.appendChild(node);
				header.appendChild(this.getCloseButton());
			}
		};

		Flyout.prototype.fixIE = function() {

			var node = $(this.id);
			var style = getStyle(node);
			if (webapp.isIE() && this.ieStyleSet) {
				style.width = "auto";
				var dt = node.getElementsByTagName("dt")[0];
				var dd = node.getElementsByTagName("dd")[0];
				var dtStyle = getStyle(dt);
				var ddStyle = getStyle(dd);

				dtStyle.width = new Pixel().get(node.offsetWidth - 20);
				ddStyle.width = "auto";

			} else {
				style.width = "250px";
			}
			style.border = "0";
			style.zoom = "1.0";
			style.backgroundColor = "transparent";
			var ie = new InternetExplorer();
			ie.wreckSelects(node);
			ie.unwreckSelects(node);
			ie.fixFlyout(node);
		};

		Flyout.prototype.getCloseButton = function() {
			var img = document.createElement("img");
			img.id = this.imgId;
			img.src = webapp.getURL(this.imgSrc);
			img.alt = this.imgAlt;
			var me = this;
			img.onclick = function() {
				var node = $(me.id);
				if (webapp.isIE()) {
					var ie = new InternetExplorer();
					ie.wreckSelects();
				}
				kill(node);
				if (isFunction(func)) {
					func();
				}
			};
			return img;
		};

		Flyout.prototype.setStandardHeader = function() {
			this.setHeader(this.getCloseButton());
		};

		Flyout.prototype.setContent = function(dom) {
			var content = $(this.contentId);
			if (content) {
				content.appendChild(dom);
				if (webapp.isIE()) {
					var ie = new InternetExplorer();
					ie.fixFlyout($(this.id));
				}
			}
		};

		Flyout.prototype.clear = function() {
			var content = $(this.contentId);
			if (content) {
				clear(content);
			}
		};

		Flyout.prototype.build = function() {
			var div = document.createElement("div");
			div.id = "flyout";
			var content = document.createElement("div");
			content.appendChild(this.getCloseButton());

			content.id = "flyout-content";
			div.appendChild(content);
			document.body.appendChild(div);
			this.position();
		};

		Flyout.prototype.position = function() {
			var e = this.event || window.event;
			var node = e.target || e.srcElement;
			var xy = getCoordinates(e);
			var style = getStyle($(this.id));
			for (var i in xy) {
				xy[i] = [xy[i], "px"].join("");
			}
			style.top = xy.y;
			style.left = xy.x;
		};

		Flyout.prototype.cleanup = function() {
			var style = getStyle($(this.id));

		};

		Flyout.prototype.show = function(func) {
			var style = getStyle($(this.id));

			materialize($(this.id), func);

			if (webapp.isIE()) {
				this.fixIE();
			}
		};

		Flyout._I = 1;
	}
	this.init();
};

var followupper = function() {
	jQuery(".fup").each(function(i) {
		var fup = $(this);
    	var id = fup.ident().split(':')[1];
		$(['#', id].pack()).click(function(e) {
            var node = $(this);
            var name = $(this).attr('name');
            if (this.type && this.type === "radio") {
                $(['input[name=', name, ']'].pack()).each(function() {
                    if ($(this).ident() !== node.ident()) {
                        $(this).click(function() {
                            fup.slideUp('fast');
                        });
                    } else {
                        fup.slideDown('fast');
                    }
                });
            } else {
                var returnVal = false;
                if (node.hasClass('fup-override-show-check')) {
                    returnVal = !fup.is(":visible");
                    if (returnVal) {
                        node.attr('checked', 'checked');
                    } else {
                        node.removeAttr('checked');
                    }
                fup.slideToggle('fast');
                } else {
                    fup.slideToggle('fast');
                    return returnVal;
            }
            }
		});
	});
};

function Tag(tagName, params, func) {
	if (!Tag._I) {
		Tag.prototype.init = function(tagName, params) {
			if (params) {
                var node = document.createElement(tagName);

                switch (typeof params) {
                    case "object":
                        for (var i in params) {
                            if (i == "text") {
                                node.appendChild(document.createTextNode(params[i]));
                            } else {
                                node.setAttribute(i, params[i])
                            }
                        }
                        break;
                    case "string":
                        node.appendChild(document.createTextNode(params));
                        break;

                }

				return node;
			} else {
				return document.createElement(tagName);
			}
		};
		Tag._I = 1;
	}
	return this.init(tagName, params);
};

function Text(text) {
	if (!Text._I) {
		Text.prototype.init = function(text) {
			return document.createTextNode(text);
		};
		Text._I = 1;
	}
	return this.init(text);
};

function JSONObject(text) {
	if (!JSONObject._I) {
		JSONObject.prototype.init = function(text) {
			switch (typeof text) {
				case "string":
					return text.parseJSON();
					break;
				case "object":
					if (text.responseText) {
						return text.responseText.parseJSON();
					}
					break;
				default:
					return false;
			}
		};

		JSONObject._I = 1;
	}
	return this.init(text);
};

function QueryStringParser(link) {

    this.map = {};

    if (!QueryStringParser._I) {
        QueryStringParser.prototype.init = function() {
            var search;

            if (link) {
                search = link.split('?')[1];
            } else if (typeof translatedRequestURL !== "undefined" && translatedRequestURL !== "null") {
                search = translatedRequestURL.split("?")[1];
            } else if (window.location.search) {
                search = window.location.search.split('?')[1];
            }

            if (search) {
                var chunks = search.split("&");
                for (var i = chunks.length - 1; i > -1; i--) {
                    var chunk = chunks[i];
                    var split = chunk.split("=");
                    this.map[split[0]] = split[1];
                }
            }
        };

        QueryStringParser.prototype.get = function(key) {
            return this.map[key];
        };

        QueryStringParser.prototype.set = function(href, name, value) {
        	if (href.indexOf("?") == -1) {
        		return (href + "?" + name + "=" + value);
        	} else if (href.indexOf("?"+name+"=") == -1 && href.indexOf("&"+name+"=") == -1) {
        		return (href + "&" + name + "=" + value);
        	} else {
        		//add +1 at the end for the equal (=) sign since the format is name=value
        		var startIndex = href.indexOf(name) + name.length + 1;
        		var endIndex = href.indexOf("&", startIndex);
        		if (endIndex == -1) {
        			return (href.substring(0, startIndex) + value);
        		} else {
        			return (href.substring(0, startIndex) + value + href.substring(endIndex, href.length));
        		}
        	}
        }

        QueryStringParser._I = 1;
    }
    this.init();
};


/**
 * Auto-displays the dynamic login flyout if there were any errors.
 * ATG doesn't seem to use a list for errors, but rather lines separated by <BR> tags,
 * so this will look for a <div id="login_errors"> and count the <BR> tags.
 * If greater than or equal to 1, then it will automatically show
 * <div id="global_login_popup">.
 */
function LoginListener() {
    if (!LoginListener._I) {
        LoginListener.prototype.init = function() {
            // Fire a submit event if the enter key is pressed in IE.
            if (Browser.ie()) {
                var username = $("global_login_email_input");
                var password = $("global_login_password_input");
                var submit = function(e) {
                    e = e || window.event;
                    var my = e.target || e.srcElement;
                    if (e.keyCode == 13) {
                        // Add the x/y coordinates or else ATG won't accept the form.
                        var x = new Tag('input', {name: '/atg/userprofiling/ProfileFormHandler.login.x', type: 'hidden', value: '1'});
                        var y = new Tag('input', {name: '/atg/userprofiling/ProfileFormHandler.login.y', type: 'hidden', value: '1'});
                        my.form.appendChild(x);
                        my.form.appendChild(y);
                        my.form.submit();
                    }
                };
                addListener(password, "keyup", submit, false);
            }
            var qsp = new QueryStringParser();
            var loginFailed = qsp.get('loginFailed');
            alert(loginFailed);


        };
        LoginListener._I = 1;
    }
    this.init();
};

(function($) {
	var Load = function() {
		var functions = [
            followupper
		];

        $.each(functions, function(i, f) {
            f();
        });

        if (!!$.fn.browser && $.browser.msie) {
            $('.nav-primary ul').each(function() {
                IEOnly.zIndex($(this), 800);
            });
            var nodes = $('#global_cart_popup, #global_myaccount_popup_main_links, #global_login_popup');
            $.each(nodes, function(i, item) {
                IEOnly.zIndex($(this), 1000);
            });

        }
	};
    $(Load);
})(jQuery);

var PNG = function() {
    return {
        fix: function(node) {
            if (typeof pngfix === "function") {
                pngfix(node);
            }
        }
    };
}();


var ImageOverlay = function($) {
    var images = {};
    return {
        apply: function(url) {
            try {
		        var body = $('body');
		        var img = new Image();
		        img.src = url;

                var addToPage = function(image) {

                    $('#overlay').remove();
                    img = image;

			        var overlay = $('<div id="overlay">');
                    var content = $('<div id="overlay-content">');
			        var close = $('<span id="overlay-close">close <strong>x</strong></span>');
                    if (!$.browser.msie) {
                        overlay.css({opacity: 0});
                    }

			        body.append(overlay);
			        overlay.append(content);
			        content.append(close);
			        content.append(img);

                    overlay.width(body.width());
                    overlay.height(body.height());

                    var width = {
                        body:  body.width(),
                        content: content.width()
                    };
                    var left = (width.body - width.content) / 2;
                    content.css({
                        marginLeft: left,
                        marginRight: left,
                        marginTop: $('html').scrollTop()
                    });

			        PNG.fix();
                    if (!$.browser.msie) {
                        setTimeout(function() {
                            overlay.fadeTo(500, 1);
                        }, 100);
                    } else {
                        overlay.show();
                    }

			        overlay.click(function() {
                        if (!!$.fn.browser && $.browser.msie) {
                            overlay.remove();
                            $.showSelects();
                        } else {
                            overlay.fadeTo(500, 0, function() {
                                $(this).remove();
                            });
                        }
			        });
                };

                if (images[img.src]) {
                    addToPage(images[img.src]);
                } else {
                    img.onload = function() {
                        images[this.src] = this;
                        addToPage(images[this.src]);
                    };
                }
	        } catch(ex) {

	        }
        },
        remove: function() {
            $('#overlay').remove();
        }
    };
}(jQuery);


var DropShadow = function() {
    return {
        shade: function(node) {



        }
    }
}();

/*
	Note: if changes are made to the parameters of the form below, change them in global.js also.
	Dealer locator code is located in objects.js and global.js
*/
/*var request_brochure = function() {

    var show_popup = function() {
        var results_page = $('#request_brochure_results');
        if (!results_page) { return false; }
        var zip = new QueryStringParser().get('zip');
        if (zip) {
            var url = "http://direct.where2getit.com/cwc/apps/w2gi.php";
            var params = {
                client: 'vikingrange',
                template: 'locator_all',
                radius: '200',
                postalcode: zip
            };
            var qs = [];
            for (var i in params) {
                qs.push([i, params[i]].join('='));
            }
            qs = qs.join('&');
            url = [url, qs].join('?');
            var w = window.open(url,'locatorWindow', 'resizable=no,scrollbars=yes,directories=no,menubar=no,toolbar=no,titlebar=no,status=no,location=no,width=810,height=600');
            var div = $('#where_to_buy');
            if (div) {
                div.find('a').click(function(e) {
                    var w = window.open(url,'locatorWindow', 'resizable=no,scrollbars=yes,directories=no,menubar=no,toolbar=no,titlebar=no,status=no,location=no,width=810,height=600');
                    return false;
                });
            }
        }
    }();
    // Show the option to see resellers for US and Canadian customers
    var show_resellers = function() {
        var form = $('#request_brochure_form');
        if (!form) return false;
        $('#country').change(function() {
            var val = $(this).find('option:selected').val();
            if (val !== 'US' && val !== 'CA') {
                $('#show_dealers').slideUp('fast');
                $(this).blur();
            } else if (val === 'US' || val === 'CA') {
                $('#show_dealers').slideDown('fast');
            }
        });
        $('#zipcode').blur(function() {
            if ($('#country').find('option:selected').val() == 'CA') {
                var chars = $(this).val().split('');
                chars.splice(2, 1, [chars[2], ' '].pack())
                $(this).val(chars.pack())
            }
        });
    }();
};*/

var header_menu = function($) {
    var login_failed_listen = function() {
        if (window.location.search.match(/loginFailed=/)) {
            var popup = $('#global_login_popup');
            var opener = $('#global_login_opener');
			$('#header-nav-wrapper').find('.popped').fadeOut('fast');
            $('#header-nav-wrapper1').find('.popped').fadeOut('fast');
            if (!opener) {
                popup.css('top', $('#header-nav-wrapper').height());
				popup.css('top', $('#header-nav-wrapper1').height());
	            popup.fadeIn('fast', function() {
	                $(this).addClass('popped');
	                $(this).find('.closer').click(function() {
	                    popup.fadeOut('fast');
	                });
	                /*
	                var other_items = setTimeout(function() {
	                    popup.find('#cart-flyout-other-items').slideDown();
	                    var actions = setTimeout(function() {
	                        popup.find('#cart-actions').slideDown();
	                    }, 500);
	                }, 500);
	                */
	            });
            }
        }
    }();

    var main_menu = function() {
        // Remove empty submenus so that superfish won't show <ul> borders
        $('ul.nav-primary ul').each(function() {
            if ($(this).find('li').length == 0) {
                $(this).remove();
            }
        });
        // Adding a check for the existence of superfish. On the 2020 navigation it does not exist.
		// TODO: Remove this code after 2020 release.
        if (!!$.fn.superfish) {
			$('ul.nav-primary').superfish({
				autoArrows: false,
				dropShadows: true,
				disableHI:     false,              // set to true to disable hoverIntent detection
				animation: {height: 'show'},
				speed: 'fast'
			});
		}
	}();

    var top_right_menu = function($) {
        var wrapper = $('#header-nav-wrapper');
		var wrapper1 = $('#header-nav-wrapper1');
        //LOKVIK-1944 : adding delay to hover/mouseenter events
        var openerTimeout = null;
        var OPENER_DELAY = 350;
	    $('#global_myaccount_opener, #global_login_opener, #global_cart_opener').each(function() {
            $(this).bind('mouseenter', function() {
                var link = $(this);
                //LOKVIK-1944
                openerTimeout = setTimeout(function(){
	                if (link.ident() == 'global_cart_opener') {
	                    //link.css('background-image', 'url(/consumer/images/header/cart-blue.gif)');
	                }
	                var chunk = link.ident().split('_')[1];
	                var popup = $(['#global', chunk, 'popup'].join('_'));
	                if (popup) {
	                    popup.css('top', '50px');
	                    wrapper.find('.quicklinks_popup:visible').hide();
						wrapper1.find('.quicklinks_popup:visible').hide();
	                    popup.show(10, function() {
	                        IEOnly.zIndex($(this), 2000);
	                        var p = $(this);
	                        p.find('.closer').click(function() {
	                            p.hide();
	                        });
	                        popup.addClass('popped');
	                        var other_items = setTimeout(function() {
	                            p.find('#cart-flyout-other-items').slideDown();
	                            var actions = setTimeout(function() {
	                                p.find('#cart-actions').slideDown();
	                            }, 500);
	                        }, 500);
	                    });
	                }
            	}, OPENER_DELAY);
            });
        });
	    //LOKVIK-1944 : allows user to pass over quickly with NO events firing
        $('#global_myaccount_opener, #global_login_opener, #global_cart_opener').each(function() {
            $(this).bind('mouseleave', function() {
               clearTimeout(openerTimeout);
            });
        });

	    $('#global_login_form #global_login_email_input').blur(function() {
            $('#global_login_password_input').focus(function() {
				$(this).val('');
				if (!!$.fn.browser && $.browser.msie) {
                    // Internet explorer is very bad at handling this; it can't swap out the 'type' attribute
                    // of an input, so the only thing that can be done is swap the text element with a new
                    // password element. However, it renders password fields slightly differently than a text
                    // field, so this needs the additional steps of setting an explicit width and hieght
                    // so that it doesn't break the layout.
					var id = $(this).ident();
					var name = $(this).attr('name');
					var size = $(this).attr('size');
                    var width = $(this).width();
                    var height = $(this).height();
					var maxlength = $(this).attr('maxlength');
					var input = $(['<input class="login-fields" type="password" name="', name, '" id="', id, '2" size="', size, '" maxlength="', maxlength, '" />'].pack());

                    input.width(width);
                    input.height(height);
					$(this).replaceWith(input);
					setTimeout(function() {
						try {
							document.getElementById([id, '2'].pack()).focus();
						} catch(ex) {
							// As if IE wasn't already throwing enough of a fit...
						}
					}, 500);

				} else {
					$(this)[0].type = "password";
				}
		    }).focus();
	    });
	    //LOKVIK-1944 : add delay to popup fading
	    var poppedTimeout = null;
	    var FADE_DELAY = 750;
		$('#header-nav-wrapper').bind('mouseleave', function() {
			var thisEl = $(this);
			poppedTimeout = setTimeout(function(){
				//$(thisEl).find('#global_cart_opener').css('background-image', 'url(/consumer/images/header/cart-white-transparent.png)');
				$(thisEl).find('.popped').fadeOut('fast');
		    }, FADE_DELAY);
		});
		$('#header-nav-wrapper').bind('mouseenter', function() {
			clearTimeout(poppedTimeout);
		});
		$('#header-nav-wrapper1').bind('mouseleave', function() {
			var thisEl = $(this);
			poppedTimeout = setTimeout(function(){
				//$(thisEl).find('#global_cart_opener').css('background-image', 'url(/consumer/images/header/cart-white-transparent.png)');
				$(thisEl).find('.popped').fadeOut('fast');
		    }, FADE_DELAY);
		});
		$('#header-nav-wrapper1').bind('mouseenter', function() {
			clearTimeout(poppedTimeout);
		});
    }(jQuery);
};

var footer_menu = function() {
	var scale = function() {
		var list = $('#nav-footer');
		var width = list.width();
		var items = $('#nav-footer li');
		var w = 0;
		items.each(function() {
			w += $(this).width();
		});
		var padding = width - w
		padding = padding / items.length
		var incremental_padding = padding / items.length;
		padding = padding + incremental_padding;
		items.each(function(i) {
			if (i > 0) {
				$(this).css('padding-left', padding.pixelate());
			}
		});
	}();
};

// Functions to run on the home page.
var index = function() {
    var add_flash = function() {
/*
    	if(FlashDetect.versionAtLeast(9, 0)){
	    	var home = new SWFObject(
	      				"/content/index_flash/vik_story_main.swf",
			    			"home",
							"948",
							"383",
		  				"9",
							"#FFFFFF");
		  	home.addParam("quality", "best");
			home.addParam("wmode", "transparent");
			home.write("flashcontent-homepage-primary");
    		$('#flashcontent-homepage-primary').show();
    		$('#jscontent-homepage-primary').html('');
    	} else {
    		$('#jscontent-homepage-primary').show();
    	}
*/
        var promo = new SWFObject(
						"/consumer/media/homepage.swf",
						"home",
						"948",
						"383",
						"9",
						"#FFFFFF");
		promo.addParam("quality", "best");
		promo.addParam("wmode", "transparent");
		promo.write("flashcontent-homepage-range");
    }();
    var swap_flash = function() {
        var block = $('#content-homepage');
        if (!block) {
            return false;
        }
        var main = $('#flashcontent-homepage-primary');
        var promo = $('#flashcontent-homepage-range');
        block.find('a.homepage_flash_swap').click(function() {
            main.toggle();
            promo.toggle();
            return false;
        });
    }();
};

var cart = function() {

	var rewrite_success_url = function() {

		var success = $('form.add-to-cart .success-url');
		success.val('/consumer/ajax/cart.jsp');

	}();

	var add_to_cart = function() {

		if (!$.fn.live) {
			return;
		}

		$('.add-to-cart .submit').live('click',


			function(event) {

				var form = $(this).parents('form:first');
				var action = $(this).parents('form:first').attr('action');

					console.log('action = ' + action);

				try {

					console.log('inside try');

					var data = {};

					// Add x/y hidden inputs for input type=image or else ATG won't accept the form
					form.find('input:image').each(

						function(i) {

							var name = $(this).attr('name');
							var x = [name, '.x'].pack();
							var y = [name, '.y'].pack();

							$.each([x, y],

								function(k, v) {

									var input = $(['<input type="hidden" name="', v, '" value="1" />'].pack());
									form.append(input)

								}

							);

						}

					);

					form.find('input, textarea').each(function(i) {

						var k = $(this).attr('name');
						var v = $(this).attr('value');

						if (k) {

							data[k] = v;

						}

					}

				);

				form.find('select').each(

					function(i) {

						var k = $(this).attr('name');
						var v = $(this).find('option:selected').val();

						if (k) {

							data[k] = v;

						}

					}

				);


			var post = function(response) {

				var id = $('#product-id').val();

				$.get('/consumer/popups/flyouts/cart/recently_added.jsp', {id: id}, get);

			};

			// This will run after the data has been posted to the server.
			var get = function(response) {

				// Scroll to the top of the page
				$.scrollTo('body:eq(0)', 500, { easing: 'linear'});

				// Make the cart icon turn blue.
				//$('#global_cart_opener').css('background-image', 'url(/consumer/images/header/cart-blue.gif)')
				// Hide all other popups.
				$('#header-nav-wrapper').find('.popped').fadeOut('fast');

				// Build the popup and position it correctly.
				var popup = $(response);

				var cartQuantity = popup.find("#cart-quantity-update").text().trim();
				if (!!cartQuantity) {
					$('.current-cart-quantity').each(function() {
						$(this).text(cartQuantity);
					});
				}

				$('#cart_dropdown_wrapper').append(popup);

				popup.css('top', $('#header-nav-wrapper').height());

				// Show the popup and update the quantity displayed on the page.
				popup.fadeIn('fast',

					function() {

						$(this).addClass('popped');
						$(this).find('.closer').click(

							function() {

								popup.fadeOut('fast');

							}

						);

						$('#current-cart-quantity').text($(this).find('.cart-quantity-update').text().trim());
						$('#global_cart_popup').empty().append(popup.children().clone(true));

						setTimeout(

							function() {

								popup.find('#cart-flyout-other-items').slideDown("fast");

								setTimeout(

									function() {

										popup.find('#cart-actions').slideDown();

									},

								500);

							},

							500

						);

					}

				);

				// Remove the popup
				var timeout = setTimeout(

					function() {

						popup.fadeOut('slow',

							function() {

								//$('#global_cart_opener').css('background-image', 'url(/consumer/images/header/cart-white-transparent.png)')
								popup.remove();

							}

						);

					},

					20000

				);

				// Halt the scheduled removal of the popup and remove it when the mouse leaves.
				popup.bind('mouseenter',

					function() {

						clearTimeout(timeout);

						$(this).bind('mouseleave',

							function() {

								return;

								$(this).fadeOut('fast',

									function() {

										//$('#global_cart_opener').css('background-image', 'url(/consumer/images/header/cart-white-transparent.png)');
										popup.remove();

									}

								);

							}

						)

					}

				);

			}

			// Submit the form in the background.
			$.post(action, data, post);

		} catch (e) {

			log(e);

		}

		// Do not let the form submit on its own.
		return false;

	}
)
}();


};

var flyouts = function() {
	$('a.flyout').click(function(e) {
		$.get($(this).attr('href'), {}, function(data) {
			var f = new Flyout(e);
			var div = $('<div></div>');
			div.html(data);
			f.setContent(div[0]);
			f.show();
		})
		return false;
	});
};

var FormListener = function() {
	var login_form = function() {

		var toggleBrowserCookiesDisabledLayer = function(shouldShow) {
			if ('undefined' === typeof shouldShow) {
				shouldShow = true;
			}
			var node = $('#ECflyout_cookieinformation');
			if (!!shouldShow) {
				node.removeClass('hide');
			} else {
				node.addClass('hide');
			}
		}

		$('#remember-me').click(function(e) {
		    var checkbox = $(this);
		    var checked = checkbox.is(':checked');
		    // This variable can be flipped to have the layer show regardless of whether browser cookies are enabled.
			// It should be set to false unless you are testing.
		    var shouldFail = false;
		    if (!!checked) {
		        if (!!shouldFail) {
		        	toggleBrowserCookiesDisabledLayer(true);
				} else if (navigator.cookieEnabled) {
					var cookie = new Cookie();
					var test = 'test';
					// Try to set and retrieve a cookie. If it  works, then there is no need to show the "browser cookies disabled" layer.
					cookie.set(test, test);
					if (!!cookie.get(test)) {
					    cookie.expire(test);
					    toggleBrowserCookiesDisabledLayer(false);
					} else {
						// Show the layer
						toggleBrowserCookiesDisabledLayer(true);
					}
				} else {
				    // Cookies are not enabled
					toggleBrowserCookiesDisabledLayer(true);
				}
			} else {
		    	toggleBrowserCookiesDisabledLayer(false);
			}
		});

		var checked = false;
		$('#login-form input:image').click(function(e) {
			var remember_me = $('#remember-me:checked').length;
			if (remember_me > 0) {
				var cookie = new Cookie();
				cookie.set("test", "test");
				var test = cookie.get("test");
				if (!test) {
					$.get('/consumer/popups/flyouts/login/cookies_disabled.jsp', {}, function(data) {
						var f = new Flyout(e);
						var div = $('<div></div>');
						div.html(data);
						f.setContent(div[0])
						var offset = $('#login-form').offset();
						f.show();
						f.setStyle('top', offset.top.pixelate());
						f.setStyle('left', offset.left.pixelate());

						div.find('button:first').click(function() {
							checked = true;
							$('#login-form input:image').click();
						})
						$('#close-flyout').click(function() {
							checked = true;
							$('#login-form input:image').click();
						})
					})
				} else {
					return true;
				}
			} else {
				return true;
			}

			return false;
		});
	}();
};

var Layer = function(node) {
	var div = node;
	if (node)
	var init = function() {
		$('#EC2').remove();
		div =  $('<div class="overlay-wrapper"><div id="EC2"></div></div>');
		// div.css({position: 'absolute', marginLeft: 0, top: node.offset().top, left: node.offset().left + node.width() + 10})
		$('body').append(div);
	}();
	return {
        getNode: function() {
            return $('#EC2');
        },
		addContent: function(text) {
			var clHeight = $(document).height();
			var clWidth = $(document).width();
			var winHeight = $(window).height();
			var winWidth = $(window).width();

            var layer = $('#EC2');
			if (typeof text === 'object') {
				layer.html(text);
				$('.overlay-wrapper').css('height',$(document).height());
				$('.overlay-wrapper').css('width',$(document).width());
				// $('#EC2').css('top', 'calc(' + window.scrollY + 'px + 15%)');
			} else {
				layer.text(text);
				$('.overlay-wrapper').css('height',$(document).height());
				$('.overlay-wrapper').css('width',$(document).width());
				// $('#EC2').css('top', 'calc(' + window.scrollY + 'px + 15%)');
			}
			// TODO
			// These lines have been removed as they error out and cause the buy online modals to fail on the for sale PDP items
            // Determine if the side edges go beyond #wrapper boundary
            // var wrapper = $('#wrapper');
			// if(wrapper) {
			// 	wrapper.left = wrapper.offset().left;
			// 	wrapper.right = wrapper.offset().left + wrapper.width();
			// }

            // layer.left = layer.offset().left;
            // layer.right = layer.left + layer.width();
            // layer.bottom = layer.offset().top + layer.height();

            // if (layer.left < wrapper.left) {
            //     layer.animate({
            //         left: wrapper.left
            //     }, 400);
            // } else if (layer.right > wrapper.right) {
            //     var newPosition = wrapper.right - layer.width();
            //     layer.animate({
            //         left: newPosition
            //     }, 400);
            // }
            return layer;
		},
        addCloseButton: function() {
            var img = $("<div class='header-close clearfix'><img id='close-button' src='/consumer/images/header/close_blue.gif' alt='close' /></div>")
            $('#EC2').prepend(img);
            img.click(function() {
				$('#EC2').remove();
				$('body').css('overflow','visible');
				$('.ui-widget-overlay, .overlay-wrapper').remove();
            });
        },
        addClass: function(klass) {
            var layer = $('#EC2');
            layer.addClass(klass);
            return layer;
        },
        moveUpHalfway: function() {
            var layer = $('#EC2');
            var top = layer.offset().top;
            top = top - (layer.height() / 2);
            layer.css('top', top);
        },
		remove: function() {
			$('#EC2').remove();
		},
		fadeOut: function() {
			$('#EC2').fadeOut(500, function() {
				$(this).remove();
			});
		}
	};
};

var Form = function($) {

	var clear = function() {
		$('form a.clear-form').click(function() {
			$(this).parents('form:first')[0].reset();
			return false;
		});
	}();

	return {
		canadianate_zip: function(node) {
			var f = function() {
				if (!node.val().match(/\s/)) {
					var chars = node.val().split('');
					chars.splice(2, 1, [chars[2], ' '].pack());
					node.val(chars.pack().toUpperCase());
				}
			};
			node.blur(f);
			node.blur();
		},
		americanize_zip: function(node) {
			var f = function() {
				if (node && node.val()) {
					node.val(node.val().replace(/\s/, ''));
				}
			};
			node.blur(f);
			f();
		},

		validate: function(form) {
			var valid = true;
			var add_error_class = function(node) {
				try {
					node.parents('label:first').addClass('required-failed');
				} catch(ex) {
					alert(ex);
				}

			};
			var remove_error_class = function(node) {
				node.parents('label.required').removeClass('required-failed');
			};


			form.find('label.required input:visible:enabled, label.required textarea:visible:enabled').each(function(i) {
				if ($(this).val().length < 1) {
					if (!$(this).hasClass('ignore-validation')) {
						add_error_class($(this));
						valid = false;
					}
				} else {
					remove_error_class($(this));
				}
			});
			form.find('label.required select:visible:enabled').each(function(i) {
				var option = $(this).find('option:selected');
				if (!option.attr('value')) {
					add_error_class($(this));
					valid = false;
				} else {
					remove_error_class($(this));
				}
			});

			return valid;
		},

		// This gives a class of "required" to a label. This is used by this object's validate() function,
		// as well as the location_aware_forms function in this file.
		require: function(node) {
			node.parents('label:first').addClass('required');
		},

		// This gives a class of "required-failed" to a label. Via CSS, this turns the <label>'s
		// background image into a red asterisk. This is used by the validate() function.
		unrequire: function(node) {
			node.parents('label:first').removeClass('required').removeClass('required-failed');
		},

		// Builds an object intended to be fed to $'s get, post, and ajax methods. It ignores all
		// disabled form elements.
		values: function(form) {
			var data = {};
			// Add x/y hidden inputs for input type=image or else ATG won't accept the form
			form.find('input:image').each(function(i) {
				if (!$(this).attr('disabled')) {
					var name = $(this).attr('name');
					var x = [name, '.x'].pack();
					var y = [name, '.y'].pack();
					$.each([x, y], function(k, v) {
						var input = $(['<input type="hidden" name="', v, '" value="1" />'].pack());
						form.append(input);
					});
				}
			});

			// Build the rest of the form.
			form.find(':input').each(function(i) {
				if (!$(this).attr('disabled')) {
					var k = $(this).attr('name');
					var v = $(this).attr('value');
					if (k) {
						if (!data[k]) {
							data[k] = [v];
						} else {
							data[k].push(v);
						}
					}
				}
			});
			return data;
		},

		// This simply adds more GET parameters to a URL.
		add_get_params: function(form, params) {
			var found = false;
			if (form.attr('action').indexOf('?') != -1) {
				found = true;
			}
			var qs = [];
			for (var i in params) {
				qs.push([i, params[i]].join('='));
			}
			qs = qs.join('&');
			var join_char = '?';
			if (found) {
				join_char = '&';
			}
			form.attr('action', [form.attr('action'), qs].join(join_char));
		},

		// This should be scrapped.
		add_ajax: function(form) {
			Form.add_get_params(form, {ajax: true});
		}
	};
}(jQuery);



//Initializes expand / collapse / flyouts.
var initializeEC = function(button) {
	var ecSection = $(button).parents(":first").children("#MainKitchenProfileSection");

	//Start Initialization
	ecSection.find(".ECflyout").hide().wrapInner("<div class=\"ECflyoutContent\"></div>").prepend("<div class=\"ECflyoutArrow\"></div>");
	ecSection.find(".ECflyoutreg").hide().wrapInner("<div class=\"ECflyoutContent\"></div>").prepend("<div class=\"ECflyoutArrowreg\"></div>");
	ecSection.find(".ECtrigger").addClass("plus");

	// Toggle the expand/collapse content
	ecSection.children(".EC").find(".ECtrigger a").toggle(
		function(){
			var ECtarget = this.hash;
			$(this).parent().next(".ECflyout").hide(); // this fixes a phantom div problem regarding adjacent .ECcontent divs
			$(this).parent().next(".ECflyoutreg").hide(); // this fixes a phantom div problem regarding adjacent .ECcontent divs
			$(this).blur().parent().addClass("minus").removeClass("plus");
			$(ECtarget).slideDown(50);
			$(this).parent().next(".ECcontent").show();
		},
		function(){
			var ECtarget = this.hash;
			$(this).blur().parent().removeClass("minus").addClass("plus");
			$(ECtarget).hide();
		}
	);

	// Flyout trigger
	ecSection.find(".ECtrigger a").hover(
		function(){
			$(this).parent().next(".ECflyout").show();
			$(this).parent().next(".ECflyoutreg").show();
			},function(){
			$(this).parent().next(".ECflyout").hide();
			$(this).parent().next(".ECflyoutreg").hide();
		}
	);

}

var ec = function() {
	/*
			For form expand / collapse / flyouts.
			HTML should be written as follows:

			<div class="EC">
				<div class="ECtrigger">
					<a href="#thistrigger">trigger text</a>
				</div>
				<div class="ECflyout">
					Content of the flyout
				</div>
				<div class="ECcontent" id="thistrigger">content</div>
			</div>

			Notes:
			1. .ECflyout is optional.
			2. the anchor tag identifier should match the ID of the content div
			   that it opens.

		*/

		// initialization
		$(".ECflyout").hide().wrapInner("<div class=\"ECflyoutContent\"></div>").prepend("<div class=\"ECflyoutArrow\"></div>");
		$(".ECflyoutreg").hide().wrapInner("<div class=\"ECflyoutContent\"></div>").prepend("<div class=\"ECflyoutArrowreg\"></div>");
		$(".ECtrigger").addClass("plus");

		// show triggers with a .show class on them
		$(".show .ECtrigger a").addClass("minus").removeClass("plus");
		$(".show .ECcontent").show();

		// toggle the expand/collapse content
		$(".EC > .ECtrigger a").toggle(function(){
			var ECtarget = this.hash;
			$(this).parent().next(".ECflyout").hide(); // this fixes a phantom div problem regarding adjacent .ECcontent divs
			$(this).parent().next(".ECflyoutreg").hide(); // this fixes a phantom div problem regarding adjacent .ECcontent divs
			$(this).blur().parent().addClass("minus").removeClass("plus");
			$(ECtarget).slideDown(50);
			$(this).parent().next(".ECcontent").show();

		},function(){
			var ECtarget = this.hash;
			$(this).blur().parent().removeClass("minus").addClass("plus");
			$(ECtarget).hide();
		});

		// flyout trigger
		$(".ECtrigger a").hover(function(){
		$(this).parent().next(".ECflyout").show();
		$(this).parent().next(".ECflyoutreg").show();
		},function(){
		$(this).parent().next(".ECflyout").hide();
		$(this).parent().next(".ECflyoutreg").hide();
		});

		// flyout trigger
		$(".ECLinktrigger a").hover(function(){
		$(this).parent().next(".ECflyout").show();
		$(this).parent().next(".ECflyoutreg").show();
		},function(){
		$(this).parent().next(".ECflyout").hide();
		$(this).parent().next(".ECflyoutreg").hide();
		});

}

var viewToggle = function() {
    // For View All / Close Toggle
	// This is repeated in product.js
    $(".view-all").click(
	    function() {
	     $(this).parent().find("ul li.toggle").show();
	     $(this).parent().find("span.current-count").hide();
	     $(this).parent().find("span.full-count").show();
	     $(this).parent().find(".view-close").show();
	     $(this).hide();
	     return false;
	    }
    );

    $(".view-close").click(
	    function() {
	     $(this).parent().find("ul li.toggle").hide();
	     $(this).parent().find("span.current-count").show();
	     $(this).parent().find("span.full-count").hide();
	     $(this).parent().find(".view-all").show();
	     $(this).hide();
	     return false;
	    }
    );
};
var bindBodyClickOnce = true;
var FancySelects = function(targetSelects) {
    if (!!$.fn.browser && $.browser.msie && $.browser.version < 7) {
        return false;
    }
    var zIndex = 1000;
    //if no specific target specified for fancy slects, then get them all
    if (targetSelects == null || targetSelects.length < 1) {
    	targetSelects = $('select.fancy-dropdown');
    }
    targetSelects.each(function() {
        var select = $(this);
        var div = $('<div class="fancy-dropdown-box">');
        var val = $.trim(select[0].options[select[0].selectedIndex].firstChild.data);
        var field = $('<div class="fancy-dropdown-display">');
        var selector = $('<div class="fancy-dropdown-selector">');
        var label = $('<div class="fancy-dropdown-label">');
        label.text(val);
        field.append(selector).append(label);
        div.append(field);
        var input = $('<input type="hidden" />');
        input.addClass('fancy-dropdown-value').attr('id', select.attr('id')).attr('value', val).attr('name', select.attr('name'));

        div.css({
            zIndex: zIndex--
        });
        select.hide();
        div.append(input);
        select.after(div);
        selector.height(label.height());

        var y = div.outerHeight();

        var ul = $('<ul class="fancy-dropdown-list">');
        ul.css({
            top: y,
            right: 0/*,
            minWidth: label.width()*/
        });
        // Create the fake <option>s
        select.find('option').each(function() {
            var li = $('<li>');
            li.attr('id', ['fancyDropdown-', $(this).attr('value')].pack());
            li.text($.trim($(this).text()));
            ul.append(li);
        });

        div.append(ul);
        /*ul.css('min-width',ul.width());*/
        var clear = $('<div class="clear"></div>');
        div.after(clear);


        ul.find('li').unbind('click').click(function() {
            var val = $(this).ident().split('fancyDropdown-')[1];
            input.val(val);
            select.val(val);
            select.change();
            label.text($.trim($(this).text()));
            ul.hide();
            selector.height(label.height());
        });

        field[0].clicked = false;

        field.unbind('click').click(function() {
			$('body').addClass('fancyDropDownClicked');
			var fieldList = $(this).parent().find('ul.fancy-dropdown-list');
			$(this).parent().addClass('field-list-active');
			$('div.fancy-dropdown-box:not(.field-list-active)').find('ul.fancy-dropdown-list').hide();
			$(this).parent().removeClass('field-list-active');
            if (fieldList.is(':hidden')) {
            	fieldList.fadeIn('fast', function() {
                    var list = $(this);
                    var width = list[0].w;
                    var height = list[0].h;

                    if (!list.hasClass('dimensions-set')) {
                        var maxw = (list.width()) ? list.width():0;
                        var maxh = 0;
                        list.find('li').each(function() {
                            var w = $(this).width();
                            maxw = (w > maxw) ? w : maxw;
                            maxh += $(this).height();
                        });
						width = maxw;
                        if (width > list.width()) {
                            list.width(width);
                        }
                        if (maxh < list.height()) {
                            // no scrollbars
                            list.height(maxh);
                            list.width(field.width()).css('padding-right', 7);
                        }
                        //add 18px to the min-width to prevent horizontal scrolling
                        list.css('min-width', width + 18).css('min-height', height);
                        list.css("left", 0);//Possible fix for IE horizontal scroll bars
                        list.addClass('dimensions-set');
                        //list.data('width', width + 18).data('height', height);
                        //list.addClass('open').data('width', width).data('height', height);
                    }
                    // var current
                    //("#mySelect option[value='3']").attr('selected', 'selected');

                });
            } else {
               // ul.hide();
               fieldList.fadeOut();
            }
        });
    });
    if (bindBodyClickOnce) {
    	$('body').unbind('click').click(function() {
        	if (!$('body').hasClass('fancyDropDownClicked')) {
        		$('ul.fancy-dropdown-list').fadeOut();
        	} else {
        		$('body').removeClass('fancyDropDownClicked');
        	}
        });
    	bindBodyClickOnce = false;
    }
};


var HeaderRoundCorners = function() {
    // IE7 and IE8 CSS3 PIE.js
    // PIE will only be included as a script for IE versions less than 9
    if (window.PIE) {

        var addPieCornersForIE = [];
        addPieCornersForIE.push('#header-nav-wrapper');
        addPieCornersForIE.push('#logo-and-site-search .nav-primary-search');
        addPieCornersForIE.push('#header-nav-wrapper ul.intl-contact-support');
        addPieCornersForIE.push('#header-nav-wrapper ul.user-quote-cart');


        $.each(addPieCornersForIE, function(i, val) {
            if ($(val).length > 0) {
                $(val).each(function() {
                    PIE.attach(this);
                });
            }
        });

        if (!!$.fn.browser && $.browser.msie) {

            var userQuotePIE = $('#header-nav-wrapper ul.user-quote-cart');
            var intlContactPIE = $('#header-nav-wrapper ul.intl-contact-support');
            var siteSearchPIE = $('#logo-and-site-search .nav-primary-search');

            if ($.browser.version > 6 && $.browser.version < 8) {

                if (intlContactPIE.length > 0 && userQuotePIE.length > 0) {
                    var before = userQuotePIE.prev().css('left');
                    before = before.replace(/px/,'');
                    userQuotePIE.prev().css('left', (Number(before) - 4) + 'px');

                    before = intlContactPIE.prev().css('left');
                    before = before.replace(/px/,'');
                    intlContactPIE.prev().css('left', (Number(before) + 3) + 'px');
                }

                if (siteSearchPIE.length > 0) {
                    before = siteSearchPIE.prev().css('left');
                    before = before.replace(/px/, '');
                    siteSearchPIE.prev().css('left', (Number(before) - 1));

                    before = siteSearchPIE.prev().css('top');
                    before = before.replace(/px/, '');
                    siteSearchPIE.prev().css('top', (Number(before) + 1));
                }
            } else if ($.browser.version > 7 && $.browser.version < 9) {

                if (userQuotePIE.length > 0) {
                    var before = userQuotePIE.prev().css('left');
                    before = before.replace(/px/,'');
                    userQuotePIE.prev().css('left', (Number(before) - 1) + 'px');
                }

                if (siteSearchPIE.length > 0) {
                    before = siteSearchPIE.prev().css('top');
                    before = before.replace(/px/, '');
                    siteSearchPIE.prev().css('top', (Number(before) + 1));
                }
            }
        }

    }
};

$(document).ready(function() {
    var functions = [
        /*HeaderRoundCorners,*/
        FormListener,
        header_menu,
        index,
        cart,
        /*request_brochure,*/
        flyouts,
        viewToggle,
        footer_menu
	];
	for (var i = 0; i < functions.length; i++) {
            functions[i](jQuery);
	}
	FancySelects(null);

   // for alternating row color on tables with class zebra
	$("table.zebra tr:nth-child(even)").not("[td]").addClass("even");
	$("table.zebra tr:nth-child(odd)").not("[td]").addClass("odd");

	// for removing the value from an input field on focus
	// used in global search.
	//LOKVIK-1590 : added IE6 workaround
	if (!!$.fn.browser && $.browser.msie && $.browser.version.substr(0,1)<7) {
	     $('input.clear-focus').click(function() {
	         if (this.value == this.defaultValue){
	             this.value = '';
	         }
	         if(this.value != this.defaultValue){
	             this.select();
	         }
	     });
	} else {
		$('input.clear-focus').focus(function() {
	         if (this.value == this.defaultValue){
	             this.value = '';
	         }
	         if(this.value != this.defaultValue){
	             this.select();
	         }
	     });
	}


	/*
		For form expand / collapse / flyouts.
		HTML should be written as follows:

		<div class="EC">
			<div class="ECtrigger">
				<a href="#thistrigger">trigger text</a>
			</div>
			<div class="ECflyout">
				Content of the flyout
			</div>
			<div class="ECcontent" id="thistrigger">content</div>
		</div>

		Notes:
		1. .ECflyout is optional.
		2. the anchor tag identifier should match the ID of the content div
		   that it opens.

	*/

	// initialization
	$(".ECflyout").hide().wrapInner("<div class=\"ECflyoutContent\"></div>").prepend("<div class=\"ECflyoutArrow\"></div>");
	$(".ECflyoutreg").hide().wrapInner("<div class=\"ECflyoutContent\"></div>").prepend("<div class=\"ECflyoutArrowreg\"></div>");
	$(".ECtrigger").addClass("plus");

	// show triggers with a .show class on them
	$(".show .ECtrigger").addClass("minus").removeClass("plus");
	$(".show .ECcontent").show();


	// New function to handle the expand/collapse content
	$(".EC > .ECtrigger a").click(function(){
		if($(this).blur().parent().hasClass("plus")){
			var ECtarget = this.hash;
			$(this).parent().next(".ECflyout").hide(); // this fixes a phantom div problem regarding adjacent .ECcontent divs
			$(this).parent().next(".ECflyoutreg").hide(); // this fixes a phantom div problem regarding adjacent .ECcontent divs
			$(this).blur().parent().addClass("minus").removeClass("plus");
			$(ECtarget).slideDown(50);
			$(this).parent().next(".ECcontent").show();
		}
		else{
			var ECtarget = this.hash;
			$(this).blur().parent().removeClass("minus").addClass("plus");
			$(ECtarget).hide();
		}
		return false;
	});

	// flyout trigger
	$(".ECtrigger a").hover(function(){
	$(this).parent().next(".ECflyout").show();
	$(this).parent().next(".ECflyoutreg").show();
	},function(){
	$(this).parent().next(".ECflyout").hide();
	$(this).parent().next(".ECflyoutreg").hide();
	});

	// flyout trigger
	$(".ECLinktrigger a").hover(function(){
	$(this).parent().next(".ECflyout").show();
	$(this).parent().next(".ECflyoutreg").show();
	},function(){
	$(this).parent().next(".ECflyout").hide();
	$(this).parent().next(".ECflyoutreg").hide();
	});

	$('.openAccordion .head').click(function() {
		$(this).next().slideToggle('slow');
		if($(this).hasClass('collapsed')) {
			$(this).removeClass('collapsed').addClass('expanded');
		} else {
			$(this).removeClass('expanded').addClass('collapsed');
		}
		return false;
	});


    $('.proceed-as-a-guest').click(function(e){
        e.preventDefault();
        $('.page-content.page-checkout form #checkoutButtonContainer input.submit.cart').click();
        return false;
    });

});


/**
 * Submits the global logout form, logging the user out of the site
 **/
function doLogout () {
	var form = jQuery('#logoutForm');
	document.getElementById('logoutForm').submit();
};

$('.logout-current-user').live('click', function(e){
	e.preventDefault();
	$('#logout-form-success-url').val(window.location.href);
	doLogout();
	return false;
});


var Ajax = function() {
    return {
        parse: function(str) {
            var ta = document.createElement("textarea");
            ta.innerHTML = str.replace(/</g, "&lt;").replace(/>/g, "&gt;");
            return ta.value;
        }
    };
}();

var Log = function($) {
    var s;
    if (typeof console === "object") {
        return {
            log: function(str) {
                s = str;
                return console.log(str);
            },
            info: function(str) {
                s = str;
                return console.info(str);
            },
            debug: function(str) {
                s = str;
                return console.debug(str);
            },
            dir: function(str) {
                s = str;
                return console.dir(str);
            },
            warn: function(str) {
                s = str;
                return console.warn(str);
            },
            error: function(str) {
                s = str;
                return console.error(str);
            }
        };
    } else {
        if (window.location.port == "f8080" && $.browser.msie && $.browser.version < 8) {
            $.ajax({
                type: 'GET',
                url: '/consumer/javascript/firebug-lite-compressed.js',
                dataType: 'script',
                cache: true,
                success: function() {
                    firebug.env.height = 300;
                }
            });

            return {
                log: function(str) {
                    return console.log(str);
                },
                debug: function(str) {
                    return console.log(str);
                },
                info: function(str) {
                    return console.log(str);
                },
                dir: function(str) {
                    return console.log(str);
                },
                warn: function(str) {
                    return console.log(str);
                },
                error: function(str) {
                    return console.log(str);
                }
            };
        } else {
            return {
                log: function() {},
                debug: function() {},
                info: function() {},
                dir: function() {},
                warn: function() {},
                error: function() {}
            };
        }
    }
}(jQuery);

// Now get rid of alert()
function alert(obj, force) {
    if (!force) {
        if (typeof obj === 'object') {
            Log.dir(obj);
        } else {
            Log.info(obj);
        }
    } else {
        alert(obj);
    }
}

/**
 * This object can be used to circumvent a lot of "clicking as fast as possible" bugs. Instantiate a new
 * ClickLocker and use it like this:
 *
 * var locker = new ClickLocker();
 * $('a').click(function() {
 *      if (locker.isLocked()) {
 *          // don't do anything
 *          return false;
 *      }
 *      locker.lock();
 *      // amazing code
 *      locker.unlock(50);
 * });
 *
 * unlock() has a timeout that defaults to 1 second but can be overridden as in the example above.
 */
var ClickLocker = function() {
    var locked = false;
    var defaultTimeout = 1000;
    return {
        lock: function() {
            locked = true;
        },
        unlock: function(t) {
            var timeout = t || defaultTimeout;
            setTimeout(function() {
                locked = false;
            }, timeout);
        },
        isLocked: function() {
            return locked;
        }
    };
};
