function body_onload () {
  // Runs onload functions. Will return immediately if run more than once.
  // Set up below. The reason for all this complication is that sometimes IE 6
  // does not fire window.onload, so we can call this again just in case.
  
  if ( body_onload.already_run ) {
    return;
  }
  
  // Do this before running functions in case one calls body_onload.
  body_onload.already_run = true;
  
  for ( var i = 0 ; i < body_onload.functions.length ; i++ ) {
    body_onload.functions[i].apply(window, arguments);
  }
}
body_onload.functions = [];
if ( window.onload ) {
  body_onload.functions.push(window.onload);
}
window.onload = body_onload;

function addLoadEvent(func) {
  body_onload.functions.push(func);
}
function addClass(element,value) {
  if (!element.className) {
    element.className = value;
  } else {
    newClassName = element.className;
    newClassName+= " ";
    newClassName+= value;
    element.className = newClassName;
  }
}
function stripeTables() {
  if (!document.getElementsByTagName) return false;
  var tables = document.getElementsByTagName("table");
  for (var i=0; i<tables.length; i++) {
    var odd = false;
    var rows = tables[i].getElementsByTagName("tr");
    for (var j=0; j<rows.length; j++) {
      if (odd == true) {
        addClass(rows[j],"odd");
        odd = false;
      } else {
        odd = true;
      }
    }
  }
}

function highlightRows() {
  if(!document.getElementsByTagName) return false;
  var rows = document.getElementsByTagName("tr");
  for (var i=0; i<rows.length; i++) {
    rows[i].oldClassName = rows[i].className
    rows[i].onmouseover = function() {
      addClass(this,"highlight");
    }
    rows[i].onmouseout = function() {
      this.className = this.oldClassName
    }
  }
}

function emulateHover(root) {
	var node, i;
	
	if ( ! root ) {
		return;
	}
	
	for (i=0; i<root.childNodes.length; i++) {
		node = root.childNodes[i];
		if (node.nodeName=="LI") {
			node.onmouseover=function() {
				this.className+=" over";
			}
			node.onmouseout=function() {
				this.className=this.className.replace(" over", "");
			}
		}
	}
}

startList = function() {
	if (document.all&&document.getElementById) {
		emulateHover(document.getElementById("nav"));
		emulateHover(document.getElementById("subnav"));
	}
}

function disable_nav() {
	$('nav').addClassName("disable");
	$('subnav').addClassName("disable");
}

function enable_nav() {
	$('nav').removeClassName("disable");
	$('subnav').removeClassName("disable");
}


if(typeof(Control) == "undefined")
	var Control = {};
Control.Tabs = Class.create();
Object.extend(Control.Tabs,{
	tabs: $A([]),
	responders: $A([]),
	addResponder: function(responder){
		Control.Tabs.responders.push(responder);
	},
	removeResponder: function(responder){
		Control.Tabs.responders = Control.Tabs.responders.without(responder);
	},
	notifyResponders: function(event_name,argument_one,argument_two){
		Control.Tabs.responders.each(function(responder){
			if(responder[event_name])
				responder[event_name](argument_one,argument_two);
		});
	},
	findByTabId: function(id){
		return this.tabs.find(function(tab){
			return tab.links.find(function(link){
				return link.key == id;
			});
		});
	}
});
Object.extend(Control.Tabs.prototype,{
	activeContainer: false,
	activeLink: false,
	initialize: function(tab_set,options){
		Control.Tabs.tabs.push(this);
		tab_set = $(tab_set);
		this.options = {
			beforeChange: Prototype.emptyFunction,
			afterChange: Prototype.emptyFunction,
			linkSelector: 'li a',
			activeClassName: 'active',
			defaultTab: 'first',
			autoLinkExternal: true
		};
		if(options)
			for(o in options)
				this.options[o] = options[o];
		this.containers = $H({});
		this.links = (typeof(this.options.linkSelector) == "string"
			? tab_set.getElementsBySelector(this.options.linkSelector)
			: this.options.linkSelector(tab_set)
		).findAll(function(link){return (/^#/).exec(link.href.replace(window.location.href.split('#')[0],''));});
		this.links.each(function(link){
			link.key = $A(link.getAttribute('href').replace(window.location.href.split('#')[0],'').split('/')).last().replace(/#/,'');
			this.containers.set(link.key, $(link.key));
			link.onclick = function(link){
				this.setActiveTab(link);
				return false;
			}.bind(this,link);
		}.bind(this));
		if(this.options.defaultTab == 'first')
			this.setActiveTab(this.links.first());
		else if(this.options.defaultTab == 'last')
			this.setActiveTab(this.links.last());
		else
			this.setActiveTab(this.options.defaultTab);
		target_regexp = /#(.+)$/;
		targets = target_regexp.exec(window.location);
		if(targets && targets[1]){
			$A(targets[1].split(',')).each(function(target){
				this.links.each(function(target,link){
					if(link.key == target){
						this.setActiveTab(link);
						throw $break;
					}
				}.bind(this,target));
			}.bind(this));
		}
		if(this.options.autoLinkExternal){
			$A(document.getElementsByTagName('a')).each(function(a){
				if(!this.links.include(a)){
					clean_href = a.href.replace(window.location.href.split('#')[0],'');
					if(clean_href.substring(0,1) == '#'){
						if(this.containers.keys().include(clean_href.substring(1))){
							$(a).observe('click',function(event,clean_href){
								this.setActiveTab(clean_href.substring(1));
							}.bindAsEventListener(this,clean_href));
						}
					}
				}
			}.bind(this));
		}
	},
	setActiveTab: function(link){
		if(typeof(link) == "undefined" || link == false)
			return;
		if(typeof(link) == "string"){
			this.links.each(function(_link){
				if(_link.key == link){
					this.setActiveTab(_link);
					throw $break;
				}
			}.bind(this));
		}else{
			this.containers.each(function(item){
				item[1].hide();
			});			
			this.links.each(function(item){
				item.removeClassName(this.options.activeClassName);
			}.bind(this));
			link.addClassName(this.options.activeClassName);
			this.options.beforeChange(this,this.activeContainer);
			Control.Tabs.notifyResponders('beforeChange',this,this.activeContainer);
			this.activeContainer = this.containers.get(link.key);
			this.activeLink = link;
			this.containers.get(link.key).show();
			this.options.afterChange(this,this.containers.get(link.key));
			Control.Tabs.notifyResponders('afterChange',this,this.containers.get(link.key));
		}
	},
	next: function(){
		this.links.each(function(link,i){
			if(this.activeLink == link && this.links[i + 1]){
				this.setActiveTab(this.links[i + 1]);
				throw $break;
			}
		}.bind(this));
	},
	previous: function(){
		this.links.each(function(link,i){
			if(this.activeLink == link && this.links[i - 1]){
				this.setActiveTab(this.links[i - 1]);
				throw $break;
			}
		}.bind(this));
	},
	first: function(){
		this.setActiveTab(this.links.first());
	},
	last: function(){
		this.setActiveTab(this.links.last());
	}
});


    Event.observe(window,'load',function(){
        $$('.tabs').each(function(tabs){
            new Control.Tabs(tabs);
        });
    });


/**
 * Update a city selection drop-down with reseller cities in the state
 * selected in a related drop-down.
 *
 * @param stateSel The state select element or id
 * @param citySel  The city select element or id to update
 */
function updateResellerCities(stateSel, citySel) {
  stateSel = $(stateSel);
  
  new Ajax.Request('/resellers/city_listing', {
                       method: 'get',
                       parameters: 'state='+escape(stateSel.options[stateSel.selectedIndex].value),
                       onSuccess: function(req) {
                         var json = null;
                         try { json = eval('(' + req.responseText + ')'); } catch (e) { json = null; }
                         replaceSelectOptions(citySel, json);
                       }
                       });    
}

function updateResellerIntlCities(countrySel, citySel) {
  countrySel = $(countrySel);

  new Ajax.Request('/resellers/intl_city_listing', {
                       method: 'get',
                       parameters: 'country='+escape(countrySel.options[countrySel.selectedIndex].value),
                       onSuccess: function(req) {
                         var json = null;
                         try { json = eval('(' + req.responseText + ')'); } catch (e) { json = null; }
                         replaceSelectOptions(citySel, json);
                       }
                       });    
}

/**
 * Replace all but the first option in a select with a new array of options
 *
 * @param sel      The select element or id to update
 * @param options  The new array of options
 */
function replaceSelectOptions(sel, options) {
  sel = $(sel);
  
  // remove everything but the first option
  sel.selectedIndex = 0;
  var i;
  for (i = sel.options.length - 1; i > 0; i--) {
    sel.remove(i);
  }
  
  // create and add new options
  for (i = 0; i < options.length; i++) {
    var opt = document.createElement('OPTION');
    var text = document.createTextNode(options[i].text);
    opt.appendChild(text);
    opt.value = options[i].value;
    sel.appendChild(opt);
  }

  // a selection has been made, so free the store menu
  unpinStoreMenu();
}

/**
 * 'Pin' down the store menu so that it won't hide itself while
 * selections are being made in the drop-down.
 */
function pinStoreMenu() {
  var stores = $('stores');
  if (stores.className.indexOf('pinned') == -1)
    stores.className += " pinned";
}

/**
 * Un-'pin' the store menu so that it can loose focus normally now
 * that selections have been completed
 */
function unpinStoreMenu() {
  var stores = $('stores');
  stores.className = stores.className.replace(" pinned", "").replace("pinned", "");
}

function update_item_select ( select, switch_image ) {
  new Ajax.Request('/products/select_item', {
      asynchronous : true,
      evalScripts : true,
      parameters : {
        id : select.value,
        switch_image : ( switch_image ? "1" : "" ) // 0 isn't blank
      }
    });
}

function shopping_cart_close () {
  var shopping_cart = $('shopping_cart');
  
  // We have to force the element to hide because it will be kept open while
  // the mouse is over it.
  
  shopping_cart.removeClassName('over');
  shopping_cart.style.display = "none";
  
  window.setTimeout(function () { shopping_cart.style.display = "" }, 1);
}

/**
 * Dynamically replace some h2 tags with swf objects using a non-standard font
 */
function update_swf_headings() {
	var hIdx = 1;
	$$('h2.swf_replace').each(function(h2) {
		txt = h2.innerHTML.stripTags();
		id = h2.id;
		if (!id) { id = 'swf_head_'+hIdx; h2.id = id; hIdx++; }
		var so = new SWFObject("/swf/vag_rounded_light.swf", id, h2.getWidth(),
		  Math.max(h2.getHeight(), 18), "8", "#ffffff");
		so.addVariable("txt", txt);
		so.addVariable("textcolor", "#68421A");
		so.addVariable("h", Math.max(h2.getHeight(), 18));
		so.addVariable("w", h2.getWidth());
		so.write(id);
	});
}


addLoadEvent(startList);
addLoadEvent(stripeTables);
addLoadEvent(highlightRows);
addLoadEvent(update_swf_headings);

