/***************
* These functions set up the skeleton for image rollovers and input onfocus changes.
***************/
function rolloverReplace(o, suffix) {
	var srcstring = o.getAttribute('src');
	var newsrcstring = srcstring.replace(/_((down)|(off)|(on))\./, suffix);
	o.setAttribute('src', newsrcstring);
}
function rolloverOn(ev) {
	var evtarget = YAHOO.util.Event.getTarget(ev);
	rolloverReplace(evtarget, '_on.');
}
function rolloverOff(ev) {
	var evtarget = YAHOO.util.Event.getTarget(ev);
	rolloverReplace(evtarget, '_off.');
}
function rolloverDown(ev) {
	var evtarget = YAHOO.util.Event.getTarget(ev);
	rolloverReplace(evtarget, '_down.');
}

function resetButtonNoId(el){
  try{
    if(!el){
      throw('element required');
    }
    el.setAttribute('src',old_button_src);
    el.style.height = old_button_height + 'px';
  }
  catch(e){
//    alert(e);
  }
}

function resetButton(button_id){
  try{
    if(!button_id){
      throw('button id required');
    }
    var button = document.getElementById(button_id);
    resetButtonNoId(button);
  }
  catch(e){
//    alert(e);
  }
}

//global variables for old button, to be reset in case of failure
var old_button_src = '';
var old_button_height = 0;
//keep this together with setLoader function

function doLoader(element){
  old_button_src = element.getAttribute('src').replace(/(_on|_off|_down)\.(.{2,3})/,'_off.$2');
  old_button_height = element.clientHeight;

  var old_width = element.clientWidth;

  if (!document.getElementById("loginSubmitButton") && (!document.getElementById("head_search_submit"))){
	  element.setAttribute('src', "/images/icons/loader.gif");
	  element.style.width = old_width + 'px';
	  element.style.height = '20px'; //current height of loader;
	}

}

function setLoader(element){
  //don't touch the render or cart checkout button or cart recalculate button
  //the form validation goes first, so we're going to fire this manually from there
  if(!element){
    return;
  }
  else if(element.id && (element.id == 'render_submit' || element.id=="cart_checkout_button" || element.id=="update")){
    return;
  }
  //comment this last condition list the file and the function + why
  //IS_VALID_NO_LOADER_IMG is a global boolean to prevent the loader image when the form isn't valid
  //else if(element.id == 'login' && defined(IS_VALID_NO_LOADER_IMG) && IS_VALID_NO_LOADER_IMG == false){ //false and 0 //(also do the isset on this)
	//return;
  //}

  doLoader(element);
}

function rolloverClick(ev) {
	var evtarget = YAHOO.util.Event.getTarget(ev);
	setLoader(evtarget);
}
function setupRolloverHandlers(el) {
	var rollbuttons = preloadRollovers(el);
	var container = el ? YAHOO.util.Dom.get(el) : document;
	YAHOO.util.Event.addListener(rollbuttons, "mouseover", rolloverOn);
	YAHOO.util.Event.addListener(rollbuttons, "mouseout", rolloverOff);
	YAHOO.util.Event.addListener(rollbuttons, "mousedown", rolloverDown);
	var theseneedloader = YAHOO.util.Dom.getElementsByClassName('image_button', '*', container);
	YAHOO.util.Event.addListener(theseneedloader, "click", rolloverClick);
}
function preloadRollovers(el){
  // If a container isn't passed, we run through everything
  if (!el) {
  	var loader = new Image();
	loader.src = "/images/icons/loader.gif";
  	var container = document;
  } else {
	var container = YAHOO.util.Dom.get(el);
  }
  // get image and input collections
  var imgcol = new Array();
  imgcol[imgcol.length]=container.getElementsByTagName('img');
  imgcol[imgcol.length]=container.getElementsByTagName('input');

  var pics = new Array();
  var rolloverEls = new Array();
  for(var j=0;j<imgcol.length;j++){
    for(var i=0;i<imgcol[j].length;i++){
        // preload images
		if (imgcol[j][i].src.match('_off.')){
			rolloverEls[rolloverEls.length] = imgcol[j][i];
			// Preload the _on state
			pics[pics.length]=new Image();
			pics[pics.length-1].src=imgcol[j][i].src.replace(/_(off)\./, '_on.');
			// Preload the _down state
			pics[pics.length]=new Image();
			pics[pics.length-1].src=imgcol[j][i].src.replace(/_(off)\./, '_down.');
		}
    }
  }
  return rolloverEls;
}
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
function initTypeNav(){
  var typeNav_img = null;
  if(typeNav_img = document.getElementById('typeNav_img')){
    typeNav_img.onmouseover = function(){
      try{
	this.src = '/images/typeNav/typeNav_on.gif';
      }
      catch(e){//alert(e);
      }
    };
    typeNav_img.onmouseout = function(){
      try{
      this.src = '/images/typeNav/typeNav_off.gif';
      }
      catch(e){//alert(e);
      }
    };
    typeNav_img.onmousedown = function(){
    try{
      this.src = '/images/typeNav/typeNav_down.gif';
    }
    catch(e){//alert(e);
    }

    };
  }

}
YAHOO.util.Event.addListener(window, "load", externalLinks);
YAHOO.util.Event.addListener(window, "load", initTypeNav);
// @name      The Fade Anything Technique
// @namespace http://www.axentric.com/aside/fat/
// @version   1.0-RC1
// @author    Adam Michela
// @license	  http://creativecommons.org/licenses/by-sa/2.0/

var Fat = {
	make_hex : function (r,g,b)
	{
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	},
	fade_all : function ()
	{
		var a = document.getElementsByTagName("*");
		for (var i = 0; i < a.length; i++)
		{
			var o = a[i];
			var r = /fade-?(\w{3,6})?/.exec(o.className);
			if (r)
			{
				if (!r[1]) r[1] = "";
				if (!o.id) o.id = YAHOO.util.Event.generateId(o);
				if (o.id) Fat.fade_element(o.id,null,null,"#"+r[1]);
			}
		}
	},
	fade_element : function (id, fps, duration, from, to)
	{
		if (!fps) fps = 30;
		if (!duration) duration = 3000;
		if (!from || from=="#") from = "#FFFF33";
		if (!to) to = this.get_bgcolor(id);

		var frames = Math.round(fps * (duration / 1000));
		var interval = duration / frames;
		var delay = interval;
		var frame = 0;

		if (from.length < 7) from += from.substr(1,3);
		if (to.length < 7) to += to.substr(1,3);

		var rf = parseInt(from.substr(1,2),16);
		var gf = parseInt(from.substr(3,2),16);
		var bf = parseInt(from.substr(5,2),16);
		var rt = parseInt(to.substr(1,2),16);
		var gt = parseInt(to.substr(3,2),16);
		var bt = parseInt(to.substr(5,2),16);

		var r,g,b,h;
		while (frame < frames)
		{
			r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames));
			g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames));
			b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames));
			h = this.make_hex(r,g,b);

			setTimeout("Fat.set_bgcolor('"+id+"','"+h+"')", delay);

			frame++;
			delay = interval * frame;
		}
		setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay);
	},
	set_bgcolor : function (id, c)
	{
	    try{
		var o = document.getElementById(id);
		o.style.backgroundColor = c;
	    }
	    catch(e){
	      //lots of places where this gets called and for
	      //some reason o is null
	      //so just ignore these errors
	    }
	},
	get_bgcolor : function (id)
	{
		var o = document.getElementById(id);
		while(o)
		{
			var c;
			if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color");
			if (o.currentStyle) c = o.currentStyle.backgroundColor;
			if ((c != "" && c != "transparent") || o.tagName == "BODY") { break; }
			o = o.parentNode;
		}
		if (c == undefined || c == "" || c == "transparent") c = "#FFFFFF";
		var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
		if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3]));
		return c;
	}
}
YAHOO.util.Event.addListener(window, "load", Fat.fade_all);
function isLocalLink(a_object){
  var href_pathname = a_object.href.match(/^http:\/\/([\w\.\-]*)(\/.*)#.*$/);
  if( (href_pathname) &&
      (href_pathname[2] == window.location.pathname) &&
      (a_object.href.indexOf('#top') == -1 ) ){

    return true;
  }
  else{
    return false;
  }
}

function getWrapperId(){
    if(document.getElementById('wide_container')){
      return 'wide_container';
    }
    else if(document.getElementById('container')){
      return 'container';
    }
    else{
      //error
    }

}

function linkClick(){
  var wrapper_id = getWrapperId();
  document.getElementById(wrapper_id).style.overflow = "visible";
}

function getHash(element){
  var re = /#(.*)$/;
  var href = element.getAttribute('href');
  if(href){
    var hash = href.match(re);
    if(hash){
      return hash[1];
    }
  }
  return null;
}

function getElementFromEvent(e_e, e_this){

  /************
    teh weirdness

    sometimes e is event, sometimes it's element

    seems to be a firefox bug where e is usually event, and this is element
    but when url has a hash, e is element and this is window

    so...

    the purpose of this function is to take e and this from a
    callback, and return the correct this

    ************/

  if(e_e.target || e_e.srcElement){
    //e is event, therfore this is element
    return e_this;
  }
  else{
    return e_e;
  }
}

function linkBlur(e){

  var element = getElementFromEvent(e, this);
  var wrapper_id = getWrapperId();

  if(needsRemedy){
    document.getElementById(wrapper_id).style.overflow = "hidden";
  }

  var hash = getHash(element);
  //only fade if that id exists
  if(hash && document.getElementById(hash)) {
    Fat.fade_element(hash);
  }
}

function initLinks(){
  var anchors = document.getElementsByTagName('a');
  var once = false;
  /* time for some jiggetty jiggety browser sniffing....
    safari likes mousedown/mouseup
    others are sweet on click/blur
  */
  if(window.navigator.userAgent.indexOf('Safari') != -1){
    var downEvt = "mousedown";
    var upEvt = "mouseup";
  }
  else{
    var downEvt = "click";
    var upEvt = "blur";
  }

  for(var i = 0; i < anchors.length; i++){
    if( isLocalLink(anchors[i]) ){
      if(needsRemedy){
	YAHOO.util.Event.addListener(anchors[i], downEvt, linkClick);
      }
      YAHOO.util.Event.addListener(anchors[i], upEvt, linkBlur);
    }
  }
}

function urlAnchor(){
  if(window.location.hash){
    return true;
  }
  else return false;
}

function getPixFromTop(element){
  if(element.offsetParent){
    return (element.offsetTop + getPixFromTop(element.offsetParent));
  }
  else{
    return element.offsetTop;
  }
}

function getPixFromLeft(element){
  if(element.offsetParent){
    return (element.offsetLeft + getPixFromLeft(element.offsetParent));
  }
  else{
    return element.offsetLeft;
  }
}

function setHashFocus(hash){
  var anchor = null;
  if(!(anchor = document.getElementById(hash))){
    var anchors = document.getElementsByTagName('a');
    for(var i = 0; i < anchors.length; i++){
      if(anchors[i].name == hash){
	var pix = getPixFromTop(anchors[i]) - (anchors[i].offsetHeight * 2);
	break;
      }
    }
  }
  else{
    var pix = getPixFromTop(anchor) - (anchor.offsetHeight * 2);
  }

  window.scrollTo(0,pix);
}

function scriptLinks(html){
  var r = new RegExp('<a (href="('+window.location.pathname+window.location.search+')?#.+") ?>','g');
  return html.replace(r,'<a $1 onclick="linkClick();" onblur="linkBlur(this);">');
}

function handleUrlAnchor(){
  var hash = window.location.hash.substr(1);
  var html = document.body.innerHTML;
  if(needsRemedy){
    document.body.innerHTML = '';
    document.body.innerHTML = scriptLinks(html);

    setHashFocus(hash);
  }

  try{
    if(document.getElementById(hash)){
      Fat.fade_element(hash);
    }
  }
  catch(e){
//    alert(e);
  }
}

function initWindow(){
try{
  initLinks();
  if(urlAnchor()){
    handleUrlAnchor();
  }
}
catch(e){
//    alert(e);
  }
}

//global
var needsRemedy = false;

try{
    if((window.navigator.userAgent.indexOf('Gecko') != -1 ||  // limit to gecko browsers (eg firefox)
       window.navigator.userAgent.indexOf('MSIE 7') != -1)  //and ie7
       && window.navigator.userAgent.indexOf('Safari') == -1){ //but not safari
	needsRemedy = true;
    }
      YAHOO.util.Event.addListener(window, "load", initWindow);
}

catch(e){
//  alert(e);
}

function swapRenderLoader(render_id, loader_id, param){
	if (param == 1){
		//alert("1: " +render_id);
		document.getElementById(render_id).style.display = "block";
		document.getElementById(loader_id).style.display = "none";
	} else if (param == 2){
		//alert("2: " +render_id);
		document.getElementById(render_id).style.display = "none";
		document.getElementById(loader_id).style.display = "block";
	}
}

function swapAllRenderLoaders(){
	var images = document.getElementsByTagName("img");
	var img_id = "";

	//set loaders
	for (var i = 0; i<images.length; i++){
		img_id = images[i].id;
		if (img_id.substring(0,13) == "render_loader")images[i].style.display = "block";
	}

	//set images
	for (var i = 0; i<images.length; i++){
		img_id = images[i].id;
		if (img_id.substring(0,10) == "render_img") images[i].style.display = "block";
		if (img_id.substring(0,13) == "render_loader") images[i].style.display = "none";
	}
}

function strpos(haystack,needle,offset){
    var i = (haystack+'').indexOf(needle,offset);
    if (i===-1) { return false; }

    return i;
}

function showHide( object, className ){
	if(object.className == 'hide'){
		object.className = 'show';
	}else{
		object.className = 'hide';
	}
}

function bgChange(object, color){
	if(object.style.backgroundColor == ''){
		object.style.backgroundColor = color;
	}else{
		object.style.backgroundColor = '';
	}
}

function arrowSwitch( object ){
	if(object.innerHTML.charCodeAt(0) == '9654'){
		object.innerHTML = '&#9660;';
	}else{
		object.innerHTML = '&#9654;';
	}
}

function validateEmailAddress(email) {
	emailStr = email;
	var checkTLD=1;

	/* The following is the list of known TLDs that an e-mail address must end with. */

	/* 11/14/08 JC: added .cat TLD. Not really a country TLD so fails two-letter country
	domain test later on in this function, so it needs to be added here. */

	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|cat)$/;

	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	var emailPat=/^(.+)@(.+)$/;

	/* The following string represents the pattern for matching all special
	characters such as ( ) < > @ , ; : \ " . [ ] */
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

	/* The following string represents the range of characters allowed in a 
	username or domainname.*/
	var validChars="\[^\\s" + specialChars + "\]";

	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";

	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

	/* The following string represents an atom */
	var atom=validChars + '+';

	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.*/
	var word="(" + atom + "|" + quotedUser + ")";

	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {
	/* Too many/few @'s or something; basically, this address doesn't
	even fit the general mould of a valid e-mail address. */
	
		return false;
	}

	var user=matchArray[1];
	var domain=matchArray[2];

	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			return false;
		}
	}

	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			return false;
		}
	}

	// See if "user" is valid 
	if (user.match(userPat)==null) { return false; }

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	
	var IPArray=domain.match(ipDomainPat);

	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				return false;
			}
		}

		return true;
	}
}

function footerSubscribe(email) {
	if (validateEmailAddress(email)==false) {
		$('footer_email_error').update('&#9650; Invalid email address.');			
		Event.observe('iidlui-iidlui', 'keypress', function() { $('footer_email_error').update(''); });
		return false;
	} else {
		var url = '/fonts/footer_subscribe.php';
		var query_string = 'email=' + $F('iidlui-iidlui');
		
		doFade('footer_email_success', 0, 100, 1);
		$('footer_email_success').show();
		$('footer_email_success').update('<span style="color:black">Please wait...</span>');
		
		new Ajax.Request(url, {
			method:"post",
			parameters: query_string,
			onSuccess: function(transport) {
				
				$('footer_email_success').update(transport.responseText);
				$('iidlui-iidlui').value = 'Enter email address';
				doFade('footer_email_success', 0, 100, 1);
				$('footer_email_success').show();
				setTimeout("doFade('footer_email_success', 100, 0, 2000);", 1000);
				setTimeout("$('footer_email_success').hide();", 3000);
				
				return false;
			},
			
			onFailure: function() {
				$('footer_email_error').update('Problem adding ' + $F('iidlui-iidlui'));
				setTimeout("doFade('footer_email_error', 100, 0, 2000);", 1000);
				
				return false;
			}				
		})
		
		return false;
	}
}

function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(N) {
	if (N==null) return "00";
	N=parseInt(N); if (N==0 || isNaN(N)) return "00";
	N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
	return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}

//parseUri 1.2.2
//(c) Steven Levithan <stevenlevithan.com>
//MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

var addthis_config = {
	services_compact: 'email, twitter, facebook, wordpress, digg, delicious, stumbleupon, more',
	services_exclude: 'favorites, print',
	data_track_linkbacks: true,
	ui_delay: 500
}
var addthis_share = {
	templates: {
		twitter: 'Check this out: {{url}} (shared from @FontShop)'
	}
}