autoSelectMenu = false; 
var prevEl;


function init(){
	
	// quit if this function has already been called
	if (arguments.callee.done) return;
	
	// flag this function so we don't do the same thing twice
	arguments.callee.done = true;
	
	// kill the timer
	if (_timer) {
		clearInterval(_timer);
		_timer = null;
	}
	
	nav = navigator.userAgent.toLowerCase();
	if (/WebKit/i.test(navigator.userAgent)) { // sniff
		document.body.className += ' safari';
	}	
	
	/* Add class="selected" to any link with id="btn_sectionName", 
	   where sectionName is the BODY element's id.*/
	links = document.getElementsBySelector('a');
	for (var i=0, t=links.length; i<t ;i++){
		if (linkHasBodyId(links[i].id)){
			links[i].className += ' selected';	
		}
	}
		
	/* Mark as selected any link that targets the current file */
	if (autoSelectMenu){
		fileName = getFileName(location.href);
		linksProdMenu = document.getElementsBySelector('a');

		for (var i=0, t=linksProdMenu.length; i<t; i++){
			if (fileName == getFileName(linksProdMenu[i].href)){
				linksProdMenu[i].className += ' selected';
			}
		}
	}	

	// Attach main menu script and PNG fix.
	// These are only for IE (other browsers use CSS only). 
	if (typeof supersleight != 'undefined' && typeof sfHover != 'undefined'){
		sfHover();
		// Running the following right now this halts IE6 page loading for a second. 
		// The option is to have it onload, but we get the ugly gray boxes blink.
		supersleight.run(); 
	}


	// The Techniques pulldowns.
	var pulldowns = document.getElementsBySelector('select.redirectOnChange');
	for (var i=0, t=pulldowns.length; i<t ;i++){
		addEvent(pulldowns[i], 'change', redirectOnChange);
	}
	
	// The Additional Info pulldown for Product Detail pages.
	if (document.getElementById('additionalInfo')){
		var swatches = document.getElementsBySelector('#additionalInfo .swatches');
		if (swatches[0]){
			var ul = swatches[0].getElementsByTagName("UL");
			if (ul){
				ul[0].style.display = 'none';
				var swalink = swatches[0].getElementsByTagName("A")[0];
				addEvent(swalink, 'click', function(){
					var ul = this.parentNode.parentNode.getElementsByTagName("UL")[0];						
					ul.style.display = (ul.style.display == 'none')?'':'none';
				});
			}
		}
	}

	// Store locator's States menu
	stateMenu = document.getElementById('state');
	if (stateMenu){
		addEvent(stateMenu, 'change', function(){document.getElementById('form1').submit();});
		document.getElementById('go').style.display = 'none';
	}
	
	// Add Print This Page functionality for users with JavaScript enabled
	btnPrint = document.getElementById('printThis');
	if (btnPrint){
		addEvent(btnPrint, 'click', function(e){window.print();e.preventDefault();});
		btnPrint.innerHTML = '<a href="#">Print this page</a>';
		btnPrint.style.display = 'block';
	}
	
	// Have View the Videos launch in a popup.
	
	btnVideos = document.getElementsBySelector('.video a');
		if (btnVideos[0]){
		
		for (var i=0, t=btnVideos.length; i<t ;i++){
			addEvent(btnVideos[i], 'click', popUpVideo);
		}
		
			
		}
	
	btnVideos = document.getElementsBySelector('.video_sm a');
		if (btnVideos[0]){
		for (var i=0, t=btnVideos.length; i<t ;i++){
			addEvent(btnVideos[i], 'click', popUpVideo);
		}
	}
	

	
	// Setup behavior for the registration/profile form
	if (document.getElementById('form_1')){ setupRegistrationForm(); };
	
	
	/*  Main menu's keyboard navigation 
		(FIXME This needs some more work, maybe replace it for http://users.tpg.com.au/j_birch/plugins/superfish/)
	var mainMenuDiv = document.getElementById('mainMenu');
	var menuItems = mainMenuDiv.getElementsByTagName('a');
	for (var i=0, t=menuItems.length; i<t ;i++){
		if (mainMenuDiv == menuItems[i].parentNode.parentNode.parentNode){
			addEvent(menuItems[i], 'focus', function(){fireEvent(this.parentNode,'mouseover')});
		}
	}*/
		
	// A class available to apply specific CSS rules for users with jsEnabled
	document.getElementsByTagName('BODY')[0].className += ' jsEnabled';
}


// DEAN EDWARDS ONLOAD FIX http://dean.edwards.name/weblog/2006/06/again/  
/* for Mozilla */
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on 
@if (@_win32 && @_jscript_version > 5.5)
	document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
	var script = document.getElementById("__ie_onload");
	script.onreadystatechange = function() {
		if (this.readyState == "complete") {
			init(); // call the onload handler
		}
	};
@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
	var _timer = setInterval(function() {
		if (/loaded|complete/.test(document.readyState)) {
			init(); // call the onload handler
		}
	}, 10);
}

/* for other browsers */
window.onload = init;

// Detect IE version http://dean.edwards.name/weblog/2007/03/sniff/#comment83590
var IEVersion=/*@cc_on function(){ switch(@_jscript_version){ case 1.0:return 3; case 3.0:return 4; case 5.0:return 5; case 5.1:return 5; case 5.5:return 5.5; case 5.6:return 6; case 5.7:return 7; }}()||@*/0;


function getFileName(str){
	var arr = str.split("/");
	return arr[arr.length-1];
}

function redirectOnChange(e){
	var value = this[this.selectedIndex].value;
	if (value != '0'){
		location.href = location.href + value;
	}
}


function linkHasBodyId(linkId){
	if (!linkId){return false;}
	bodyId = document.getElementsByTagName("BODY")[0].id;
	linkSection = linkId.split("_");
	if (linkSection.length == 2){linkSection = linkSection[1];} else {linkSection = false;}
	return (linkSection && linkSection == bodyId);
}

function popUpVideo(e){
	videoWin = window.open(this.href, 'video', 'width=640,height=360,top=100,left=100');
	if (videoWin){videoWin.focus(); e.preventDefault();} else {return true};
}

function popUpVideo_small(e){
	videoWin = window.open(this.href, 'video', 'width=390,height=350,top=100,left=100');
	if (videoWin){videoWin.focus(); e.preventDefault();} else {return true};
}


function setupRegistrationForm(){
	
	/* So.
	This lists roles (option value) and what element ID they enable. 
	Roles and States are global. Sorry. */
	usrRole = [];
	usrRole['1'] = ['11', '53'];		/* Stylist */
	usrRole['2'] = usrRole['3'] = usrRole['4'] = usrRole['1'];/* Copies of stylist */
	usrRole['7'] = ['19', '20', '52'];	/* Student */
	usrRole['8'] = ['30'];				/* Member of the press */
	usrRole['9'] = ['31'];				/* Distributor */
	
	usrRoleFields = usrRole['1'].concat(
					usrRole['2'], 
					usrRole['4'], 
					usrRole['7'], 
					usrRole['8'], 
					usrRole['9']);
	
	setupRoles();
	// setupStates();
}


function setupStates(e){

	if (typeof this == 'object'){
		statesMenu = document.getElementById('element_14_2');
		addEvent(statesMenu, 'change', setupStates);
	} else {
		rolesMenu = this;	
	}
	
}



function setupRoles(e){

	if (typeof this == 'object'){
		rolesMenu = document.getElementById('element_15');
		addEvent(rolesMenu, 'change', setupRoles);
	} else {
		rolesMenu = this;	
	}
	
	for (var j=0, f=usrRoleFields.length; j<f; j++){
		field = document.getElementById('li_' + usrRoleFields[j]);
		field.style.display = 'none';
	}
	
	var li;
	var fields = usrRole[rolesMenu.options[rolesMenu.selectedIndex].value];
	if (fields){
		for (var i=0, f=fields.length; i<f; i++){
			field = document.getElementById('li_' + fields[i]);
			field.style.display = '';
		}
	}
	
	// This is an ugly hack that repositions the Model, for IE6. Enjoy.
	if (IEVersion != 0 && IEVersion < 7){
		document.getElementById('mainContent').style.position = 'static';
		document.getElementById('mainContent').style.position = 'relative';
	}
}


/*
addEvent(element, type, handler)
  ie: addEvent(window, "load", init);
  Includes removeEvent, preventDefault and stopPropagation.
  Source: http://therealcrisp.xs4all.nl/upload/addEvent_dean.html
*/
function addEvent(element, type, handler)
{
	if (element.addEventListener){
		element.addEventListener(type, handler, false);
	}else
	{
		if (!handler.$$guid) {handler.$$guid = addEvent.guid++;}
		if (!element.events) {element.events = {};}
		var handlers = element.events[type];
		if (!handlers)
		{
			handlers = element.events[type] = {};
			if (element['on' + type]){ handlers[0] = element['on' + type];}
			element['on' + type] = handleEvent;
		}
	
		handlers[handler.$$guid] = handler;
	}
}
addEvent.guid = 1;

function removeEvent(element, type, handler)
{
	if (element.removeEventListener){
		element.removeEventListener(type, handler, false);
	}else if (element.events && element.events[type] && handler.$$guid){
		delete element.events[type][handler.$$guid]; }

}

function handleEvent(event)
{
	event = event || fixEvent(window.event);
	var returnValue = true;
	if(this.events){
	var handlers = this.events[event.type];

	for (var i in handlers)
	{
		if (!Object.prototype[i])
		{
			this.$$handler = handlers[i];
			if (this.$$handler(event) === false){ returnValue = false;}
		}
	}

	if (this.$$handler) {this.$$handler = null;}
	}
	return returnValue;
}

function fixEvent(event)
{
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
}
fixEvent.preventDefault = function()
{
	this.returnValue = false;
}
fixEvent.stopPropagation = function()
{
	this.cancelBubble = true;
}

// This little snippet fixes the problem that the onload attribute on the body-element will overwrite
// previous attached events on the window object for the onload event
if (!window.addEventListener)
{
	document.onreadystatechange = function()
	{
		if (window.onload && window.onload != handleEvent)
		{
			addEvent(window, 'load', window.onload);
			window.onload = handleEvent;
		}
	}
}


function fireEvent(element, type){
    if (document.all){
        element.fireEvent("on" + type);
    } else {
        var clickEvent = window.document.createEvent("MouseEvent");
        clickEvent.initEvent(type, false, true);
        element.dispatchEvent(clickEvent);
    }
} 



/*
document.getElementsBySelector(selector) 
  ie: elements = document.getElementsBySelect('div#main p a.external')
  Source: http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
  Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
  Opera 7 fails 
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained 
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
   Tag
*/




