/**
 * @author sfrederick
 */

var sizes = new Array();
var colors = new Array();
var prices = new Array();

var magsettings = {lensWidth: 60, lensHeight: 60, lensCss: {opacity: 0.3}};

jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 

jQuery.fn.fadeOut = function(speed, callback) { 
    return this.animate({opacity: 'hide'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeTo = function(speed,to,callback) { 
    return this.animate({opacity: to}, speed, function() { 
        if (to == 1 && jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
};

jQuery.fn.magnify = function( options ) {
    
	var settings = {
		lensWidth: 100,
		lensHeight: 100,
		showEvent: 'mouseover',
		hideEvent: 'mouseout',
		stagePlacement: 'right',
		preload: true,
		loadingImage: '',
		stageCss: {},
		lensCss: {},
		onBeforeShow: function() {},
		onAfterShow: function() {},
		onBeforeHide: function() {},
		onAfterHide: function() {}
	};
	
	options ? jQuery.extend( settings, options ) : null;
	
	return this.each(function() {
            
        if (this.attributes.zoomed) {
            // do nothing, already zoomed
        } else {
            
            $(this).attr('zoomed', 'z');
            
            var img = jQuery("img:first", this), smallimage = new Smallimage(img), a = jQuery(this), lens = new Lens(), largeimage = new Largeimage(a[0].href), largeimageloaded = false, smallimagedata = {}, stage = null, scale = 1, running = false, loader = null, noimage = false, self = this;
            
            smallimage.loadimage();
            
            img.bind(settings.showEvent, activate);
            
        }
            
            function activate(e){
                if (!running) {
                    running = true;
                    settings.onBeforeShow.apply(smallimage, [settings]);
                    if (!largeimage) { // a re-show
                        largeimage = new Largeimage(a[0].href);
                    }
                    lens.activate(e);
                    lens.setposition(e);
                    jQuery(lens.node).bind('mousemove', lens.setposition).bind(settings.hideEvent, deactivate);
                    if (largeimageloaded) { // preload true
                        stage = new Stage();
                        stage.activate();
                    }
                    else {
                        // preload false or re-show
                        largeimage.loadimage();
                    }
                    settings.onAfterShow.apply(smallimage, [settings]);
                    a[0].blur();
                    return false;
                }
                else 
                    deactivate(e);
            }
            
            function deactivate(e){
                settings.onBeforeHide.apply(self, [settings]);
                jQuery(lens.node).unbind('mousemove').unbind('mouseover').remove();
                if (stage.node) {
                    jQuery(stage.node).remove();
                }
                if (largeimage.node) {
                    jQuery(largeimage.node).remove();
                }
                largeimage = null;
                largeimageloaded = false;
                settings.onAfterHide.apply(self, [settings]);
                running = false;
                
                // a brutal hack to prevent the annoying re-firing of mouseover 
                // when mouseout over top of small image.
                // unbind and rebind show event after 50ms.
                img.unbind(settings.showEvent);
                var s = setTimeout(function(){
                    img.bind(settings.showEvent, activate);
                }, 50);
            }
            
            /********* classes: Smallimage, Largeimage, Lens, Stage, Loader ***********/
            
            function Smallimage(image){
                this.node = image[0];
                
                this.loadimage = function(){
                    this.node.src = img[0].src;
                };
                
                this.node.onload = function(){
                    smallimagedata.w = jQuery(this).width();
                    smallimagedata.h = jQuery(this).height();
                    smallimagedata.pos = jQuery(this).offset();
                    smallimagedata.pos.r = smallimagedata.w + smallimagedata.pos.left;
                    smallimagedata.pos.b = smallimagedata.h + smallimagedata.pos.top;
                    
                    if (settings.preload) {
                        largeimage.loadimage();
                    }
                };
                
                return this;
            }
            
            function Largeimage(url){
            
                this.url = url;
                this.node = new Image();
                
                
                this.loadimage = function(){
                    if (!this.node) 
                        this.node = new Image();
                    this.node.style.position = 'absolute';
                    this.node.style.display = 'none';
                    this.node.style.left = '-5000px';
                    loader = new Loader();
                    document.body.appendChild(this.node);
                    
                    this.node.src = this.url; // fires off async
                };
                
                this.node.onload = function(){
                    // context is largeimage.node
                    
                    largeimageloaded = true;
                    // set to block, get width & height, then hide again
                    this.style.display = 'block';
                    var w = jQuery(this).width(), h = jQuery(this).height();
                    this.style.display = 'none';
                    scale = (w / smallimagedata.w + h / smallimagedata.h) / 2;
                    
                    jQuery(loader.node).remove();
                    
                    if (running) { // loaded on show event, so must activate stage
                        stage = new Stage();
                        stage.activate();
                    }
                };
                
                this.node.onerror = function(){
                    jQuery(loader.node).remove();
                    noimage = true;
                    if (running) {
                        stage = new Stage();
                        stage.activate();
                    }
                };
                return this;
            }
            
            Largeimage.prototype.setposition = function(){
                this.node.style.left = Math.ceil(-scale * parseInt(lens.getoffset().left)) + 'px';
                this.node.style.top = Math.ceil(-scale * parseInt(lens.getoffset().top)) + 'px';
            };
            
            function Lens(){
                this.node = document.createElement("div");
                jQuery(this.node).css({
                    width: settings.lensWidth + 'px',
                    height: settings.lensHeight + 'px',
                    backgroundColor: 'white',
                    opacity: 0.6,
                    position: 'absolute',
                    border: '1px dashed #bbbbbb',
                    zIndex: 1000,
                    cursor: 'crosshair'
                }).css(settings.lensCss);
                
                return this;
            }
            
            Lens.prototype.activate = function(){
                document.body.appendChild(this.node);
                this.node.style.display = 'block';
            };
            
            Lens.prototype.setposition = function(e){
            
                var self = e.type == 'mousemove' ? this : this.node, lensleft = e.pageX - settings.lensWidth / 2, lenstop = e.pageY - settings.lensHeight / 2, realwidth = parseInt(self.style.width) +
                parseInt(self.style.borderLeftWidth) +
                parseInt(self.style.borderRightWidth), realheight = parseInt(self.style.height) +
                parseInt(self.style.borderTopWidth) +
                parseInt(self.style.borderBottomWidth), incorner = incorner();
                
                if (!incorner) {
                    // use 'self' so the context is right whether setting mouseover or on mousemove
                    if (againstleft()) {
                        self.style.top = lenstop + 'px';
                        self.style.left = smallimagedata.pos.left + 'px';
                    }
                    else 
                        if (againstright()) {
                            //console.log(self.style.width);
                            self.style.top = lenstop + 'px';
                            self.style.left = smallimagedata.pos.r - realwidth + 'px';
                        }
                        else 
                            if (againsttop()) {
                                self.style.left = lensleft + 'px';
                                self.style.top = smallimagedata.pos.top + 'px';
                            }
                            else 
                                if (againstbottom()) {
                                    self.style.left = lensleft + 'px';
                                    self.style.top = smallimagedata.pos.b - realheight + 'px';
                                }
                                else {
                                    self.style.top = lenstop + 'px';
                                    self.style.left = lensleft + 'px';
                                }
                }
                else {
                    self.style.top = incorner == 'topleft' || incorner == 'topright' ? smallimagedata.pos.top + 'px' : smallimagedata.pos.b - realheight + 'px';
                    self.style.left = incorner == 'topleft' || incorner == 'bottomleft' ? smallimagedata.pos.left + 'px' : smallimagedata.pos.r - realwidth + 'px';
                }
                
                largeimage.setposition();
                
                function againstleft(){
                    return lensleft < smallimagedata.pos.left;
                }
                
                function againstright(){
                    return lensleft + realwidth > smallimagedata.pos.r;
                }
                
                function againsttop(){
                    return lenstop < smallimagedata.pos.top;
                }
                
                function againstbottom(){
                    return lenstop + realheight > smallimagedata.pos.b;
                }
                
                function incorner(){
                    if (againstbottom() && againstright()) 
                        return 'bottomright';
                    else 
                        if (againstbottom() && againstleft()) 
                            return 'bottomleft';
                        else 
                            if (againsttop() && againstright()) 
                                return 'topright';
                            else 
                                if (againsttop() && againstleft()) 
                                    return 'topleft';
                                else 
                                    return false;
                }
            };
            
            Lens.prototype.getoffset = function(){
                var o = {};
                o.left = parseInt(this.node.style.left) - parseInt(smallimagedata.pos.left) + 'px';
                o.top = parseInt(this.node.style.top) - parseInt(smallimagedata.pos.top) + 'px';
                return o;
            };
            
            function Stage(){
                this.node = document.createElement("div");
                jQuery(this.node).css({
                    position: 'absolute',
                    width: Math.round(settings.lensWidth * scale) + 'px',
                    height: Math.round(settings.lensHeight * scale) + 'px',
                    
                    zIndex: 2000,
                    overflow: 'hidden',
                    border: '1px solid #999999',
                    display: 'none',
                    backgroundColor: 'white'
                }).css(settings.stageCss);
                jQuery(this.node).attr('id','stage');
                this.realheight = parseInt(this.node.style.height) +
                parseInt(this.node.style.borderTopWidth) +
                parseInt(this.node.style.borderBottomWidth);
                this.realwidth = parseInt(this.node.style.width) +
                parseInt(this.node.style.borderLeftWidth) +
                parseInt(this.node.style.borderRightWidth);
                var st = jQuery.browser.safari ? document.body.scrollTop : document.documentElement.scrollTop;
                var screenbottom = document.documentElement.clientHeight + st;
                this.node.style.top = smallimagedata.pos.top + this.realheight > screenbottom ? screenbottom - this.realheight - 10 + 'px' : smallimagedata.pos.top + 'px';
                this.node.style.left = settings.stagePlacement == 'right' ? smallimagedata.pos.r + 10 + 'px' : smallimagedata.pos.left - this.realwidth - 10 + 'px';
                return this;
            }
            
            Stage.prototype.activate = function(){
                if (noimage) 
                    this.node.appendChild(document.createTextNode('Large Image Not Found.'));
                else {
                    if (!this.node.firstChild) 
                        this.node.appendChild(largeimage.node);
                    largeimage.node.style.display = 'block';
                    largeimage.setposition();
                }
                document.body.appendChild(this.node);
                jQuery(this.node).fadeIn(300);
            };
            
            function Loader(){
                this.node = settings.loadingImage ? new Image() : document.createElement("div");
                jQuery(this.node).appendTo("body").css({
                    top: smallimagedata.pos.top + 10 + 'px',
                    left: smallimagedata.pos.left + 10 + 'px',
                    position: 'absolute'
                });
                return this;
            }	
	});
};

$.fn.droppy = function(options) {
    
  options = $.extend({speed: 20}, options || {});
  
  this.each(function() {
    
    var root = this, zIndex = 1000;
    
    function getSubnav(ele) {
      if (ele.nodeName.toLowerCase() == 'li') {
        var subnav = $('> ul', ele);
        return subnav.length ? subnav[0] : null;
      } else {
        return ele;
      }
    }
    
    function getActuator(ele) {
      if (ele.nodeName.toLowerCase() == 'ul') {
        return $(ele).parents('li')[0];
      } else {
        return ele;
      }
    }
	
    function hide() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', false);
      setTimeout(function() {
        if (!$.data(subnav, 'cancelHide')) {
          $(subnav).slideUp(options.speed);
        }
      }, 100);
    }
  
    function show() {
      var subnav = getSubnav(this);
      if (!subnav) return;
      $.data(subnav, 'cancelHide', true);
      $(subnav).css({zIndex: zIndex++}).fadeIn(options.speed);
      if (this.nodeName.toLowerCase() == 'ul') {
        var li = getActuator(this);
        $(li).addClass('hover');
        $('> a', li).addClass('hover');
      }
    }
    
    $('ul, li', this).hover(show, hide);
    $('li', this).hover(
      function() { 
	  	$(this).addClass('hover'); 
		$('> a', this).addClass('hover');
		var e = $(this).find('a.main img')[0];
		if (e) {
			var f = e.attributes.src.nodeValue;
			$(e).attr('src', f.substring(0, (f.length - 4)) + '_on' + f.substring((f.length - 4)));
		}
	  },
      function() { 
	  	$(this).removeClass('hover'); 
		$('> a', this).removeClass('hover'); 
		var e = $(this).find('a.main img')[0];
		if (e) {
			var f = e.attributes.src.nodeValue;
			$(e).attr('src', f.substring(0, (f.length - 7)) + f.substring((f.length - 4)));
		}
	  }
    );
    
  });
  
};

jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results);
	$results.hide().addClass(options.resultsClass).css("position", "absolute");
	if( options.width > 0 ) $results.css("width", options.width);

	// Add to body element
	$("body").append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var cache = {};
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache(){
		cache = {};
		cache.data = {};
		cache.length = 0;
	};

	// flush cache
	flushCache();

	// if there is a data array supplied
	if( options.data != null ){
		var sFirstChar = "", stMatchSets = {}, row = [];

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( typeof options.url != "string" ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ ){
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 ){
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}

		// add the data items to the cache
		for( var k in stMatchSets ){
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}

	$input
	.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if( selectCurrent() ){
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){onChange();}, options.delay);
				break;
		}
	})
	.focus(function(){
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	})
	.blur(function() {
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	});

	hideResultsNow();

	function onChange() {
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$(lis[active]).addClass("ac_over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $("li.ac_over", results)[0];
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];
			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
		if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
		input.lastSelected = v;
		prev = v;
		$results.html("");
		$input.val(v);
		hideResultsNow();
		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange ){
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		} else if( field.setSelectionRange ){
			field.setSelectionRange(start, end);
		} else {
			if( field.selectionStart ){
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue){
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 ){
			// fill in the value (keep the case the user has typed)
			//$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			//createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
		$results.css({
			width: parseInt(iWidth) + "px",
			top: (pos.y + input.offsetHeight) + "px",
			left: pos.x + "px"
		}).show();
	};

	function hideResults() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(":visible")) {
			$results.hide();
		}
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
	};

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;

		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement("li");
			if (options.formatItem) {
				li.innerHTML = options.formatItem(row, i, num);
				li.selectValue = row[0];
			} else {
				li.innerHTML = row[0];
				li.selectValue = row[0];
			}
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$(li).hover(
				function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
		}
		return ul;
	};

	function requestData(q) {
		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		// recieve the cached data
		if (data) {
			receiveData(q, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data);
				addToCache(q, data);
				receiveData(q, data);
			});
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};

	function makeUrl(q) {
		var url = options.url + "?q=" + encodeURI(q);
		for (var i in options.extraParams) {
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
		return url;
	};

	function loadFromCache(q) {
		if (!q) return null;
		if (cache.data[q]) return cache.data[q];
		if (options.matchSubset) {
			for (var i = q.length - 1; i >= options.minChars; i--) {
				var qs = q.substr(0, i);
				var c = cache.data[qs];
				if (c) {
					var csub = [];
					for (var j = 0; j < c.length; j++) {
						var x = c[j];
						var x0 = x[0];
						if (matchSubset(x0, q)) {
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	function matchSubset(s, sub) {
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.flushCache = function() {
		flushCache();
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function(){
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		if (data) {
			findValueCallback(q, data);
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data)
				addToCache(q, data);
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data){
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() ){
				li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 ){
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
	}

	function addToCache(q, data) {
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength) {
			flushCache();
			cache.length++;
		} else if (!cache[q]) {
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
}

jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 1;
	options.matchContains = options.matchContains || 0;
	options.cacheLength = options.cacheLength || 1;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.autoFill = options.autoFill || false;
	options.width = parseInt(options.width, 10) || 0;

	this.each(function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};

/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license and MIT:
 *   http://www.opensource.org/licenses/GPL-license.php
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
 * Revision: $Id$
 * Version: 0.5
 * 
 * Changelog :
 *  Version 0.5 
 *  - separate css style for current selected element and hover element which solve the highlight issue 
 *  Version 0.4
 *  - Fix width when the select is in a hidden div   @Pawel Maziarz
 *  - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
 */
jQuery.fn.extend({
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	}
});


/* pawel maziarz: work around for ie logging */
if (!window.console) {
	var console = {
		log: function(msg) { 
	 }
	}
}
/* */

jQuery.SelectBox = function(selectobj, options) {
	
	var opt = options || {};
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "current";
	opt.currentClass = opt.selectedClass || "selected"
	opt.debug = opt.debug || false;
	
	var elm_id = selectobj.id;
	var active = -1;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var $select = $(selectobj);
	// jquery container object
	var $container = setupContainer(opt);
	//jquery input object 
	var $input = setupInput(opt);
	var br = document.createElement("br");
	var $br = $(br);
	// hide select and append newly created elements
	$select.hide().before($input).before($br).before($container);
	
	
	init();
	
	$input
	.click(function(){
	    if (!inFocus) {
			if ($container.not(':visible')) {
				$container.slideDown(100);
			}else{
				$container.slideUp(100);
			}
		}
	})
	.focus(function(){
	   if ($container.not(':visible')) {
	       inFocus = true;
		   //$container.toggle();
	       $container.slideDown(100);
	   }
	})
	.keydown(function(event) {
		switch(event.keyCode) {
			case 38: // up
				event.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				event.preventDefault();
				moveSelect(1);
				break;
			//case 9:  // tab 
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				$('li.'+opt.hoverClass).trigger('click');
				break;
			case 27: //escape
			  hideMe();
			  break;
		}
	})
	.blur(function() {
		if ($container.is(':visible') && hasfocus > 0 ) {
			if(opt.debug) console.log('container visible and has focus')
		} else {
			hideMe();	
		}
	});


	function hideMe() { 
		hasfocus = 0;
		$container.slideUp(100); 
	}
	
	function init() {
		$container.append(getSelectOptions($input.attr('id'))).hide();
		var width = parseInt($input.css('width'));
		$container.width((width)+6);
    }
	
	function setupContainer(options) {
		var container = document.createElement("div");
		$container = $(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
		
		return $container;
	}
	
	function setupInput(options) {
		var input = document.createElement("input");
		var $input = $(input);
		$input.attr("id", elm_id+"_input");
		$input.attr("type", "text");
		$input.addClass(options.inputClass+' clear');
		$input.attr("autocomplete", "off");
		$input.attr("readonly", "readonly");
		$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
		
		return $input;	
	}

	function moveSelect(step) {
		var lis = $("li", $container);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass(opt.hoverClass);

		$(lis[active]).addClass(opt.hoverClass);
	}
	
	function setCurrent() {	
		var li = $("li."+opt.currentClass, $container).get(0);
		var ar = (''+li.id).split('_');
		var el = ar[ar.length-1];
		$select.val(el);
		$input.val($(li).html());
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return $select.val();
	}
	
	// input value
	function getCurrentValue() {
		return $input.val();
	}
	
	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		$select.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '_' + $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).html());
				$(li).addClass(opt.currentClass);
			}
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('over on : '+this.id);
				jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				if (opt.debug) console.log('out on : '+this.id);
				jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
			  var fl = $('li.'+opt.hoverClass, $container).get(0);
				if (opt.debug) console.log('click on :'+this.id);
				$('li.'+opt.currentClass).removeClass(opt.currentClass); 
				$(this).addClass(opt.currentClass);
				setCurrent();
				hideMe();
				if (opt.clickUrl){
					document.location.href=opt.clickUrl+getCurrentValue();
				}
			});
		});
		return ul;
	}
	
};

jQuery.fn.multiImgSetup = function( options ) {
	var i = 0;
	return this.each(function() {
		$(this).parent().css({
			'z-index': String(i + 2000),
			'list-style': 'none',
			'padding': '0px',
			'margin': '0px'
		});
		if (i != 0){
			$(this).parent().hide();
		}
		i++;
	});
};

jQuery.fn.multiImgNext = function( options ) {
	var i = 0;
	$("#img-colors").hide();
	$(options.grp).show();
	var foundVisible = false;
	var setNext = false;
	this.each(function() {
		if (foundVisible){
			$(this).parent().show();
			$(this).magnify(magsettings);
			foundVisible = false;
			setNext = true;
		}
		if ($(this).parent().is(':visible') && !setNext){
			$(this).parent().hide();
			foundVisible = true;
			if ($(options.grp+" .prodimg").length == (i+1)){
				$(options.grp+" .mainimg").parent().show();
				$(options.grp+" .mainimg").magnify(magsettings);
			}
		}
		i++;
	});
};

jQuery.fn.multiImgPrev = function( options ) {
	var i = 0;
	$("#img-colors").hide();
	$(options.grp).show();
    var t = $(options.grp).length;
    if (t > 2) {
        this.each(function(){
            if ($(this).parent().is(':visible')) {
                $(this).parent().hide();
                if (i == 0) {
                    $(options.grp + " .prodimg:last").each(function(){
                        $(this).parent().show()
                    });
                }
                else {
                    $(this).parent().prev().show();
                }
                $(this).magnify(magsettings);
            }
            i++;
        });
    }else{
        $(options.grp+" .mainimg").each(function(){
            if ($(this).parent().is(':visible')) {
                $(this).parent().hide();
                $(options.grp + " .prodimg:last").each(function(){
                    $(this).parent().show();
                    $(this).magnify(magsettings);
                });
            }else{
                $(this).parent().show();
                $(this).magnify(magsettings);
                $(options.grp + " .prodimg:last").each(function(){
                    $(this).parent().hide();
                });
            }
        });
    }
};

$(document).ready(function(){

	$('#emcomplmsg').hide();

	$('.cformselect').selectbox();
	$('#sort_by_menu').selectbox();
    
    $('#sort_by_menu').change(function(v){
       console.log(v); 
    });
    
	// preload rollover images
	$('#nav a.main img').each(function(){
	  	var f = this.attributes.src.nodeValue;
	    $("<img>").attr("src", f.substring(0, (f.length - 4)) + '_on' + f.substring((f.length - 4)));
	});

	$('.preload').each(function(){
	  	var f = this.attributes.href.nodeValue;
	    $("<img>").attr("src", f);
	});

	// turn off the mask after the page has loaded
	$('#ajmask').toggle();
	$('#ajmsg').toggle();
	
    /*$("#sameAsPhysical").change(function(event) {
        if (event.target.checked) {
            $("#physical input").each(function() {
                $("#billing input[name='" + $(this).attr("name").replace(/physical/, "billing") + "']").val($(this).val());
            });
        }
    });*/

	// email field
	$('#email_list_field').focus(function(f){
		if (f.target.value == 'Enter Email Address') {
			f.target.value = '';
		}
	});

	$('#email_list_field').blur(function(f){
		if (f.target.value == ''){
			f.target.value = 'Enter Email Address';
		}
	});
	
	// static email field
	$('#email_static_list_field').focus(function(f){
		if (f.target.value == 'Enter Email Address') {
			f.target.value = '';
		}
	});

	$('#email_static_list_field').blur(function(f){
		if (f.target.value == ''){
			f.target.value = 'Enter Email Address';
		}
	});

	// search field
	$('#search_field').focus(function(f){
		if (f.target.value == 'Enter Keyword') {
			f.target.value = '';
		}
	});

	$('#search_field').autocomplete(
		'/products/aj/search_suggest.php',
		{
			delay:10,
			minChars:2,
			matchSubset:1,
			matchContains:1,
			maxItemsToShow:10,
			autoFill:true,
			width: 126
		}
	);

	$('#search_field').blur(function(f){
		if (f.target.value == ''){
			f.target.value = 'Enter Keyword';
		}
	});
	
	$('#search_button input').click(function(b){
		//console.log(b);
	});
	
	$('#email_list_submit').click(function(b){
		var f = $('#email_list_field').val();
		if (f.match(new RegExp(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/))){
			$('#ajmask').fadeTo(100,0.3);
			$('#ajmsg').toggle();
			$.ajax({
				url: "/products/aj/email_join.php",
				method: 'POST',
				data: "e=" + f,
				dataType: "json",
				error: function (xhr, desc, exceptionobj) {
					//console.log(xhr.responseText);
					$('#ajmask').fadeOut();
					$('#ajmsg').fadeOut();
				},
				success : function (json) {
					if (json.error) { alert(json.error); return; }
					var output = "";
					for (p in json) {
						output += p + " : " + json[p] + "\n";
					}
					//console.log("Results: \n\n" + output);
					$('#ajmsg').fadeOut();
					$('#emcomplmsg').show();
					$('#media_pixels').html("<img src='https://cts.vresp.com/s.gif?h=6969974626\' height='1' width='1'/><iframe src=\"http://view.atdmt.com/iaction/siqsmp_SimpsonEmailSignup_3\" width=\"1\" height=\"1\" frameborder=\"0\" scrolling=\"No\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\"></iframe><iframe src=\"http://view.atdmt.com/iaction/EmailSignup2\" width=\"1\" height=\"1\" frameborder=\"0\" scrolling=\"No\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\"></iframe>");
					$('#emcomplmsg').click(function(){
						$('#ajmsg').fadeOut();
						$('#emcomplmsg').hide();		
					});
				}
			});
		}else{
			//console.log('no match');
		}
	});
	
	// static page submit
	$('#email_static_list_submit').click(function(b){
		var f = $('#email_static_list_field').val();
		if (f.match(new RegExp(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/))){
			$('#ajmask').fadeTo(100,0.3);
			$('#ajmsg').toggle();
			$.ajax({
				url: "/products/aj/email_join.php",
				method: 'POST',
				data: "e=" + f,
				dataType: "json",
				error: function (xhr, desc, exceptionobj) {
					//console.log(xhr.responseText);
					$('#ajmask').fadeOut();
					$('#ajmsg').fadeOut();
				},
				success : function (json) {
					if (json.error) { alert(json.error); return; }
					var output = "";
					for (p in json) {
						output += p + " : " + json[p] + "\n";
					}
					//console.log("Results: \n\n" + output);
					$('#ajmsg').fadeOut();
					$('#emcomplmsg').show();
					$('#media_pixels').html("<img src='https://cts.vresp.com/s.gif?h=6969974626\' height='1' width='1'/><iframe src=\"http://view.atdmt.com/iaction/siqsmp_SimpsonEmailSignup_3\" width=\"1\" height=\"1\" frameborder=\"0\" scrolling=\"No\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\"></iframe><iframe src=\"http://view.atdmt.com/iaction/EmailSignup2\" width=\"1\" height=\"1\" frameborder=\"0\" scrolling=\"No\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\"></iframe>");
					$('#emcomplmsg').click(function(){
						$('#ajmsg').fadeOut();
						$('#emcomplmsg').hide();
						window.location = "http://simpsonraceproducts.com";
					});
				}
			});
		}else{
			//console.log('no match');
		}
	});
	
	$('#nav').droppy();
	
	/*$(".prodimg").flyout();*/
	
	$(".prodimg").multiImgSetup();
	$("#prev-h").click(function(){
		$("#h-images .prodimg").multiImgNext({grp: '#h-images'});
        $("#stage").remove();
	});
	$("#next-h").click(function(){
		$("#h-images .prodimg").multiImgNext({grp: '#h-images'});
        $("#stage").remove();
	});
    function strstr( haystack, needle, bool ) {
     
        var pos = 0;
     
        haystack += '';
        pos = haystack.indexOf( needle );
        if( pos == -1 ){
            return false;
        } else{
            if( bool ){
                return haystack.substr( 0, pos );
            } else{
                return haystack.slice( pos );
            }
        }
    }
    $(".general-ctot").mouseover(function(){
        $("#stage").remove();
    });
    $("#stage").mouseover(function(){
        $("#stage").remove();
    });
	$(".thm-colors").click(function(){
        $("#stage").remove();
		var t = this.attributes.src.nodeValue;
		t = t.replace(/\/s\//, '/l/');
        t = t.replace(/\.\./, '');
		$("#h-images").hide();
		$("#img-colors").show();
		$("#img-colors").css('visibility', 'visible');
		$("#img-colors .prodimg").parent().hide();
		$("#img-colors .prodimg img").each(function(){
			if (strstr(this.attributes.src.nodeValue, t)){
				$(this).parent().parent().show();
				$(this).parent().magnify(magsettings);
			}
		});
	});
	$("#h-images .mainimg").magnify(magsettings);

	$('#sizing_chart').click(function(){
		$('#ajmask').toggle();
		$('#sizing_chart_info').show();
		$('#sizing_chart_info').css('visibility', 'visible');
	});

	$('#shoe_sizing_chart').click(function(){
		$('#ajmask').toggle();
		$('#shoe_sizing_chart_info').show();
		$('#shoe_sizing_chart_info').css('visibility', 'visible');
	});

	$('#glove_sizing_chart').click(function(){
		$('#ajmask').toggle();
		$('#glove_sizing_chart_info').show();
		$('#glove_sizing_chart_info').css('visibility', 'visible');
	});

	$('#firesuit_sizing_chart').click(function(){
		$('#ajmask').toggle();
		$('#firesuit_sizing_chart_info').show();
		$('#firesuit_sizing_chart_info').css('visibility', 'visible');
	});
	
	$('#firesuitjr_sizing_chart').click(function(){
		$('#ajmask').toggle();
		$('#firesuitjr_sizing_chart_info').show();
		$('#firesuitjr_sizing_chart_info').css('visibility', 'visible');
	});
	
	$('a.tozoom').fancyZoom({overlay:0.10});
	
	$('a.prodimg').click(function(){ return false; }); //do nothing for product image clicks
	
	$('#zoom_click').click(function(){
       $('#h-images .prodimg').each(function(){
            if ($(this).parent().is(':visible')) {
				$(this).parent().each(function(){
					$(this).find('a').each(function(){
						$(this).fancyzoom({shownow: true});
					});
				});
			}
		});
	});
	
});

function methodSelect(v){
	
}

function submitonce(){
	
}

if (typeof swfobject == 'object') {
	var flashvars = {};
	var params = {};
	params.wmode = "opaque";
	var attributes = {};
	
	swfobject.embedSWF("images/main.swf", "content_home_image_1", "550", "260", "9.0.0", "lib/swfobject/expressInstall.swf", flashvars, params, attributes);
}