// JavaScript Document
/* Author: Travis Cunningham */
/* Description: Basic Functions */
/* Date: June 2008 */

//Jump Nav
function MM_jumpMenu(targ,selObj,restore){ 
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
//AddLoad Event
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

//Toggle Object
// To call toggleObj(this,'triggerClass','activeClass','domain');
function toggleObj(obj,triggerClass,activeClass,objCont,ifSingle,domain){
	var sibling;
	var allActive = getElementsByClassName('active', 'a', objCont);
	
	if(ifSingle){
		for(i=0; i<allActive.length;i++){
			allActive[i].className = triggerClass;
			allActive[i].nextSibling.nextSibling.className='closed';
		}
	}
	// Set active state on toggle
	if(obj.className== triggerClass + ' ' + activeClass){
		obj.className= triggerClass;
	} else { obj.className= triggerClass + ' ' + activeClass; }
	
	if(obj.nextSibling.nodeType==3) {
		sibling=obj.nextSibling.nextSibling;
	} else { sibling=obj.nextSibling; }
	
	//Open Please
	sibling.className=(sibling.className=='open')? 'closed' : 'open';

	var thisRel = obj.getAttribute('rel');
	var open = false;
	if(sibling.className=='open'){open = true;}
	navUpdateCookie(thisRel, open, domain);	
	
}

// Setup Links
function expandLinks(objCont,action,ifSingle,domain){
	if ($(objCont)) {
		var expandCont = $(objCont);
		var expandLinks = getElementsByClassName('expTrig', 'a', expandCont);
		for(i=0; i<expandLinks.length; i++){
			if(action){
				expandLinks[i].onclick=function() {
					toggleObj(this,'expTrig','active',objCont,ifSingle,domain);
					return false;
				}
			} else {
				expandLinks[i].onmouseover=function() {
					toggleObj(this,'expTrig','active',objCont,ifSingle,domain);
					return false;
				}
				expandLinks[i].onclick=function() {
					return false;
				}
			}
		} 
	}
	balanceNav();
}
//addLoadEvent(function(){expandLinks('sideNav',true,false)});

//How to Call this function
//expandLinks((ContainerID),(True For onclick false for onmouseover),(true fo open just one false for open all));

// document.getElementById(); replacement.
function $() {
    var elements = new Array();
    // Find all the elements supplied as arguments
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];      
        // If the argument is a string assume it's an id
        if (typeof element == 'string') {
            element = document.getElementById(element);
        }      
        // If only one argument was supplied, return the element immediately
        if (arguments.length == 1) {
            return element;
        }     
        // Otherwise add it to the array
        elements.push(element);
    }
    // Return the array of multiple requested elements
    return elements;
};

// Retrieve an array of element base on a class name
function getElementsByClassName(className, tag, parent){
    parent = parent || document;
    if(!(parent = $(parent))) return false;
    // Locate all the matching tags
    var allTags = (tag == "*" && parent.all) ? parent.all : parent.getElementsByTagName(tag);
    var matchingElements = new Array();
    // Create a regular expression to determine if the className is correct
    className = className.replace(/\-/g, "\\-");
    var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
    var element;
    // Check each element
    for(var i=0; i<allTags.length; i++){
        element = allTags[i];
        if(regex.test(element.className)){
            matchingElements.push(element);
        }
    }
    // Return any matching elements
    return matchingElements;
};
// get ElementByAttribute function (container,tag,attribute,attribute value)
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
	var oCurrent;
	var oAttribute;
	for(var i=0; i<arrElements.length; i++){
		oCurrent = arrElements[i];
		oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
		if(typeof oAttribute == "string" && oAttribute.length > 0){
			if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
				arrReturnElements.push(oCurrent);
			}
		}
	}
	return arrReturnElements;
}

// Gallery Script
// Use as: showPic(this,'featured pic id','link list id');
function showPic(whichpic,featPic,galleryId) {
	//Set featPic Image
	if (!document.getElementById(featPic)) return true;
	var source = whichpic.getAttribute('href');
	var featPic = document.getElementById(featPic);
	if (featPic.nodeName != 'IMG') return true;
	featPic.setAttribute('src',source);
	if (!document.getElementById(galleryId)) return false;
	var gallery = document.getElementById(galleryId);
	//Set Link styles
	var setLinks = gallery.getElementsByTagName('a');
	for ( var i=0; i < setLinks.length; i++) {
		setLinks[i].className='';
		
	}
	whichpic.className='active';
	return false;
}
//Prepare Product Gallery
//Use as: prepareGallery(this,'featured pic id','link list id');
function prepareGallery(featPic,galleryId) {
  if (!document.getElementsByTagName) return false;
  if (!document.getElementById) return false;
  if (!document.getElementById('productGalImg')) return false;
  var gallery = document.getElementById('thumbList');
  var links = gallery.getElementsByTagName('a');
  for ( var i=0; i < links.length; i++) {
    links[i].onclick = function() {
      return showPic(this,'productGalImg','thumbList');
    }
  }
}

// Swatch Gallery Script
// Use as: showPic(this,'featured pic id','link list id');
function showSwatch(whichSwatch) {
	var placeholderSwatch = document.getElementById('productGalleryInner');
	var getSwatch = whichSwatch.getAttribute('rel');
	var id = whichSwatch.getAttribute('id');
	var newSwatch = document.getElementById(getSwatch).innerHTML;
//	
	placeholderSwatch.innerHTML = newSwatch;
	var swatchList = document.getElementById('swatchList');
	var swatchLinks = swatchList.getElementsByTagName('a');
	for ( var i=0; i < swatchLinks.length; i++) {
		swatchLinks[i].className='';
	}
	whichSwatch.className = 'active';
	myLightbox.updateImageList();
//	
	switchColorDrop(id);
	switchSizeDrop(id);
	return false;
}
//Prepare Swatch Gallery
//
//function prepareSwatchGallery() {
//		
//	var swatchList = document.getElementById('swatchList');
//	var swatchLinks = swatchList.getElementsByTagName('a');
//	if(document.getElementById('productGallery') && swatchLinks.length >= 1){
//		swatchLinks[0].className='active';
//		for ( var i=0; i < swatchLinks.length; i++) {
//			swatchLinks[i].onclick = function() {
//			  
//			  return showSwatch(this);
//			}
//		}
//	}
//}
//addLoadEvent(prepareSwatchGallery);

sfHover = function() {
	if(document.getElementById('brandLogoCont')){
		var sfEls = document.getElementById('brandLogoCont').getElementsByTagName("a");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				//this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
				this.className="";
			}
		}
	}
}
addLoadEvent(sfHover);

function changedColor(){
	var colormaster = document.getElementById('colormaster');
	var theIndex = colormaster.selectedIndex;
	switchSwatch('a' + theIndex);
	switchSizeDrop('a' + theIndex);
}
//switchSwatch('a' + this.selectedIndex);
function switchSwatch(id) {
	var swatchList = document.getElementById('swatchList');
	var whichSwatch = document.getElementById(id);
	showSwatch(whichSwatch);
}
function switchColorDrop(value) {
	var colormaster = document.getElementById('colormaster');
	//var whichColor = getElementsByAttribute(colormaster,'option','value',value);
	//switchColor
	var noA = value.substring(1);
	//alert(noA);
	colormaster.selectedIndex = noA;
}
function switchSizeDrop(theIndex){
	var prodSelect = document.getElementById('prodSelect');
	var sizeOutput = document.getElementById('sizeOutput');
	var currentSize = getElementsByClassName('shownSize', 'select', prodSelect)
	var noA = theIndex.substring(1);
	//Show size
	var showSize = document.getElementById('size'+noA).innerHTML;
	sizeOutput.innerHTML = showSize;
}

/* 
if open, close this nav and update the cookie
if closed, open this nav, close other navs and update the cookie
*/
function navToggle(navItem, url, domain){
	var navArray = Array('Guys', 'Girls', 'Media');
	
	document.location.href = url;	
	
	if(document.getElementById('subNav' + navItem).className == 'closed'){
		navUpdateState(navItem, true);
		navUpdateCookie(navItem, true, domain);
		for(var i=0; i < navArray.length; i++) {		
			if(navArray[i] != navItem){
				navUpdateCookie(navArray[i], false, domain);
				navUpdateState(navArray[i], false);
			}
		}		
	}
}


/* 
navItem = 'Guys' or 'Girls' or "media'
navOpen = true to open, false to close
*/
function navUpdateState(navItem, navOpen){
	if(navOpen){
		document.getElementById('trig' + navItem).className = 'expTrig active';
		document.getElementById('subNav' + navItem).className = 'open';
	}else{
		document.getElementById('trig' + navItem).className = 'expTrig active';
		document.getElementById('subNav' + navItem).className = 'closed';	
	}
}


function navOpenFromCookie(domain) {
	// colon seperated, eg. "guys:girls:media" for all navs open
	currentCookie = navReadCookie();
	if(currentCookie){
		var ca = currentCookie.split(':');
	
		for(var i = 0; i < ca.length; i++) {
			navUpdateState(ca[i], true);
		}	
	}else{
		navCreateCookie('',domain);
	}
}
//Push footer if left column expands
function balanceNav() {
	var content = document.getElementById('content');
	var contentHeight = content.scrollHeight - 120;
	var sidebar = getElementsByClassName('sidebar1', 'div', content);
	var sidebarHeight = sidebar[0].scrollHeight;
	
	if(contentHeight < sidebarHeight){
		content.style.height = sidebarHeight + 'px';
	}
}
//addLoadEvent(balanceNav);
/*
	navName: string example: 'guys'
	navOpen: boolean example: 'true' (if guys nav is open)
*/
function navUpdateCookie(navName, navOpen, domain) {
	// colon seperated, eg. "guys:girls:media" for all navs open
	currentCookie = navReadCookie();
	var ca = currentCookie.split(':');
	
	if(navOpen!=true){
		navOpen = false;
	}
	
	var foundNav = false;
	
	for(var i = 0; i < ca.length; i++) {
		if(navName==ca[i] && navOpen==true){
			foundNav = true;
		}
		if(navName==ca[i] && navOpen==false){
			foundNav = true;
			ca[i] = "";			
		}		
	}
	
	if(foundNav==false && navOpen==true){
		ca[ca.length] = navName;
	}
	
	newNav = '';
	
	for(var i = 0; i < ca.length; i++) {
		if(ca[i] != ''){
			if(newNav!=''){newNav += ':'}
			newNav += ca[i]
		}
	}
	navCreateCookie(newNav, domain);
	balanceNav();
}
function omnitureCreateCookie(cookieType,cookieValue,domain) {
	var cookie = cookieType + '=' + cookieValue + ';';
	
	// keep cookie for 30 days
	var date = new Date();
	var ndeMilliSecondsInDay = 86400000; // 24*60*60*1000
	date.setTime(date.getTime()+(30*ndeMilliSecondsInDay));
	cookie += ' expires=' + date.toGMTString() + ';';
	// this needs to be set to .sundiego.com to work across the search subdomain at omniture
	cookie += ' domain=' + domain + ';';
	
	cookie += ' path=/';

	document.cookie = cookie;
}

function navCreateCookie(openNavs, domain) {
    // are any navs open? (default is all closed)
	var cookie = 'openNavs=' + openNavs + ';';
	
	// keep cookie for 30 days
	var date = new Date();
	var ndeMilliSecondsInDay = 86400000; // 24*60*60*1000
	date.setTime(date.getTime()+(30*ndeMilliSecondsInDay));
	cookie += ' expires=' + date.toGMTString() + ';';
	// this needs to be set to .sundiego.com to work across the search subdomain at omniture
	cookie += ' domain=' + domain + ';';
	
	cookie += ' path=/';

	document.cookie = cookie;
}

function navReadCookie() {
  var nameEQ = 'openNavs=';
  var ca = document.cookie.split(';');

  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1, c.length);
    }
    if (c.indexOf(nameEQ) == 0) {
      return c.substring(nameEQ.length,c.length);
    }
  }
  return '';
}