
/**
 * For IE version 5.5-6, fakes support of 32 bit PNG alpha
 * transparency by converting the image to span with a background
 * image (applied using a filter).
 *
 * @param img  The image element or id
 */
function png32Support(img) {
  // get the image
  if (!img) return;
  img = $(img);
  if ((img.tagName.toUpperCase() != 'IMG') && (img.tagName.toUpperCase() != 'INPUT')) return;
  
  // IE only
  if (!document.all) return;
  
  // versions 5.5 - 6 only
  var ieVersion = parseFloat(navigator.appVersion.split("MSIE")[1]);
  if ((ieVersion < 5.5) || (ieVersion >= 7.0)) return;
  
  if ((img.tagName.toUpperCase() == 'INPUT') || (img.useMap && img.useMap != '')) {
      img.style.cssText = "width: "+img.clientWidth+"px; height: "+img.clientHeight+"px;" + img.style.cssText +
          "; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+img.src+"', sizingMethod='scale');";
          img.src = '/skin/frontend/tgo/default/images/spacer.gif';
  } else {
      var opts = {};
      if (img.id)        opts['id'] = img.id;
      if (img.className) opts['class'] = img.className;
      if (img.title)     opts['id'] = img.title;
      opts['style'] = "width: "+img.width+"px; height: "+img.height+"px; display: inline-block;" + img.style.cssText +
          "; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+img.src+"', sizingMethod='scale');";
  
      var html = "<span";
      for (var attr in opts) {
          html += " "+attr+"=\""+opts[attr]+"\"";
      }
      html += "></span>";
  
      img.outerHTML = html;
  }
}

function toggle_subcategory ( toggle_link ) {
	var li = $(toggle_link).up("li");
	
	if ( li.hasClassName("disclosure_open") ) {
		li.removeClassName("disclosure_open");
	} else {
		li.addClassName("disclosure_open");
	}

        return false;
}

function toggle_all_subcategories ( toggle_link ) {
    var a = $(toggle_link);
    if (a.hasClassName("disclosure_open")) {
        a.up(".head").up().select("li").map(function (n) {
          n.removeClassName("disclosure_open");
        });
        a.removeClassName("disclosure_open");
    } else {
        a.up(".head").up().select("li").map(function (n) {
          n.addClassName("disclosure_open");
        });
        a.addClassName("disclosure_open");
    }
}

function toggle_featured_category ( toggle_link ) {
	var div = $(toggle_link).up(".category");
	
	if ( div.hasClassName("disclosure_open") ) {
		div.removeClassName("disclosure_open");
	} else {
		div.addClassName("disclosure_open");
	}
}

function set_main_image ( mask, url ) {
	$(mask).up("ul").select("li").each(function (n) {
		n.removeClassName("selected");
	});
	$(mask).up("li").addClassName("selected");
	$$("#product_view_greenscreen img")[0].src = url;
}

function product_tab_onclick ( tab ) {
	var matches = tab.className.match(/\b(tab_\w+)\b/);
	
	if ( matches ) {
		/* FIXME. This should really take other classes into account. */
		$("product_tabs").className = matches[1];
	}
}

function DatatableLoadingMessage ( element, message ) {
	if ( element ) {
		this.initialize(element);
		
		if ( message ) {
			this.set(message);
		}
	}
}

DatatableLoadingMessage.prototype.initialize = function ( element ) {
	this.element = $(element);
}

DatatableLoadingMessage.prototype.set = function ( message ) {
	var position, height, span;
	
	if ( this.div ) {
		span = this.div.down("span.message");
	} else {
		this.element.addClassName("disable_selects");
		
		position = this.element.cumulativeOffset();
		height = Math.max(this.element.offsetHeight, 20);
		
		this.div = $(document.createElement("DIV"));
		this.div.className = "datatable_loading";
		this.div.style.top = position.top + "px";
		this.div.style.left = position.left + "px";
		this.div.style.width = Math.max(this.element.offsetWidth, 50) + "px";
		this.div.style.height = height + "px";
		
		span = $(document.createElement("SPAN"));
		span.className = "message";
		span.style.lineHeight = .9*height + "px";
		this.div.appendChild(span);
		
		document.body.appendChild(this.div);
	}
	
	span.innerHTML = "";
	span.appendChild(document.createTextNode(message));
}

DatatableLoadingMessage.prototype.clear = function () {
	if ( this.div ) {
		this.div.remove();
		this.div = null;
		
		if ( this.element ) {
			this.element.removeClassName("disable_selects");
		}
	}
}

// Invoke JS specified in an attribute of an element. Parameters are named
// because there is no other way to pass a value in.
function invoke_action ( element, name, p_names, p_values ) {
	p_names = p_names || [];
	p_values = p_values || [];
	
	if ( typeof(element[name]) != "function" ) {
		var f;
		
		eval("f = function (" + p_names.join(",") + ") {"
			+ element.getAttribute(name) + "}");
		
		element[name] = f;
	}
	
	return element[name].apply(element, p_values);
}

function datatable_serialize_row ( row ) {
	var data;
	
	row = $(row);
	
	row.select("input.placeholder").each(clear_placeholder);
	data = row.select(["input", "select"]).invoke("serialize").join("&");
	row.select("input.placeholder").each(restore_placeholder);
	
	return data;
}

function datatable_new ( table ) {
	var tr_new, tr, separator;
	
	table = $(table);
	
	tr_new = table.select("tr.new")[0];
	tr = tr_new.cloneNode(true);
	
	tr.removeClassName("new");
	tr.setAttribute("not_saved", "1")
	_datatable_mark_edit(tr);
	invoke_action(table, "onedit");
	
	tr_new.parentNode.insertBefore(tr, tr_new);
	
	separator = tr.previous("tr");
	if ( separator && separator.hasClassName("row_seperator") ) {
		tr_new.parentNode.insertBefore(separator.cloneNode(true), tr_new);
	}
	
	tr.select("input.placeholder").each(setup_placeholder);
}

function datatable_edit ( button ) {
	var tr = $(button).up("tr");
	
	tr.select("input").each(function ( input ) {
		var p = input.previous(".noedit");
		if ( p ) {
			input.value = collapse_text_nodes(p.childNodes);
		}
	});
	
	tr.select("select").each(function ( select ) {
		var p = select.previous(".noedit");
		if ( p ) {
			select.select("option").find(
				function ( option ) {
					if ( option.innerHTML == p.innerHTML ) {
						select.value = option.value;
						return true;
					}
					
					return false;
				});
		}
	});
	
	_datatable_mark_edit(tr);
	invoke_action(tr.up("table"), "onedit");
}

function datatable_submit ( button ) {
	var tr, message;
	
	tr = $(button).up("tr");
	message = new DatatableLoadingMessage(tr, "Working...");
	
	invoke_action(tr.up("table"), "rowsubmit",
		["row", "onsuccess", "onfailure"],
		[tr,
			function () { _datatable_submit_success(tr, message) },
			function () { _datatable_submit_failure(tr, message) }]);

}

function _datatable_submit_success ( tr, message ) {
	message.clear();
	
	if ( ! tr.up("body") ) {
		return;
	}
	
	tr.select("input").each(function ( input ) {
		var value = input.value;
		
		if ( input.hasClassName("placeholder") && placeholder_is_empty(input) ) {
			value = "";
		}
		
		var p = input.previous(".noedit");
		if ( p ) {
			p.innerHTML = "";
			p.appendChild(document.createTextNode(value));
		}
	});
	
	tr.select("select").each(function ( select ) {
		var p = select.previous(".noedit");
		if ( p ) {
			select.select("option").find(
				function ( option ) {
					if ( select.value == option.value ) {
						p.innerHTML = option.innerHTML;
						return true;
					}
					
					return false;
				});
		}
	});
	
	tr.setAttribute("not_saved", "0")
	invoke_action(tr.up("table"), "onnoedit");
	_datatable_mark_noedit(tr);
}

function _datatable_submit_failure ( tr, message ) {
	message.clear();
	tr.select("input.placeholder").each(setup_placeholder);
}

function datatable_delete ( button ) {
	var tr, message;
	
	tr = $(button).up("tr");
	message = new DatatableLoadingMessage(tr, "Working...");
	
	invoke_action(tr.up("table"), "rowdelete",
		["row", "onsuccess", "onfailure"],
		[tr,
			function () { _datatable_delete_success(tr, message) },
			function () { _datatable_delete_failure(tr, message) }]);
}

function _datatable_delete_success ( tr, message ) {
	var separator;
	
	if ( tr.up("body") ) {
		separator = tr.next("tr");
		
		if ( separator && separator.hasClassName("row_seperator") ) {
			separator.remove();
		}
		
		tr.remove();
	}
	
	message.clear();
}

function _datatable_delete_failure ( tr, message ) {
	message.clear();
}

function collapse_text_nodes ( nodes ) {
	var i, str = [];
	
	for ( i = 0 ; i < nodes.length ; i++ ) {
		if ( nodes[i].nodeType == 3 ) {
			str.push(nodes[i].nodeValue);
		}
	}
	
	return str.join("");
}

function _datatable_mark_edit ( tr ) {
	tr.removeClassName("noedit");
	tr.addClassName("edit");
	
	var elements = tr.select([ "input", "select" ]);
	if ( elements.length ) {
		elements[0].activate()
	}
	
	tr.select("input.placeholder").each(setup_placeholder);
}

function _datatable_mark_noedit ( tr ) {
	tr.removeClassName("edit");
	tr.addClassName("noedit");
}


function datatable_cancel ( button ) {
	var tr = $(button).up('tr');
	var next_tr = tr.next('tr');
	
	if (next_tr && next_tr.hasClassName('row_seperator')) {
		next_tr.remove();
	}
	
	invoke_action(tr.up("table"), "onnoedit");
	
	if (tr.getAttribute('not_saved') == 1) {
		tr.remove();
	} else {
		_datatable_mark_noedit(tr);
	}
}



/**
 * Open an expandable/collapsable pair
 */
function expand_expandable_pair(button) {
    var parent = $($(button).up('.collapsed').parentNode);
    parent.down('.expanded').style.display = 'block';
    parent.down('.collapsed').style.display = 'none';
}

/**
 * Open an expandable/collapsable pair
 */
function collapse_expandable_pair(button) {
    var parent = $($(button).up('.expanded').parentNode);
    parent.down('.expanded').style.display = 'none';
    parent.down('.collapsed').style.display = 'block';
}

/**
 * viewportOffset is somehow broken for IE either in prototype or in
 * someplace else that redefines something
 */
function getViewportOffset(elem) {
    var valueT = 0, valueL = 0;

    var element = elem;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent == document.body &&
        Element.getStyle(element, 'position') == 'absolute') break;

    } while (element = element.offsetParent);

    element = elem;
    do {
      if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return Element._returnOffset(valueL, valueT);
}

/**
 * Determine the position of an element in absolute coordinates for
 * positioning a layer
 */
function getAbsolutePosition(elem, target) {
    // find page position of the element
    elem = $(elem);
    var p = elem.viewportOffset();

    // this is always in coordinates for absolute positioning
    var parent = $(target).getOffsetParent();
    var delta = getViewportOffset(parent);

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    return {left: (p[0] - delta[0]),
            top:  (p[1] - delta[1])}
}

/**
 * Display the login popup
 */
function loginPopup(trigger) {
    var popup = $('login_popup');
    popup.style.display='block';

    var loc = getAbsolutePosition(trigger, popup);
    popup.style.left = (loc.left - popup.clientWidth) + 'px';
    popup.style.top = (loc.top - 18) + 'px';
}


/**
 * Display the ratings popup
 */
function ratingsPopup(trigger, productId) {
    is_logged_in(
        // Logged in.
        function () {
            $('review_popup_form').action
                = '/review/product/post/id/'+productId+'/';
            var popup = $('review_popup');
            popup.style.display='block';
    
            var loc = getAbsolutePosition(trigger, popup);
            popup.style.left = (loc.left - popup.clientWidth) + 'px';
            popup.style.top = (loc.top - 18) + 'px';
        },
        // Not logged in.
        function () {
            loginPopup(trigger);
        });
}

/**
 * Sets the rating value for the ratings form
 */
function setRatingValue(value) {
    $('rating_value').value = value;

    for (var i = 1; i <= 5; i++) {
        if (i <= value) {
            $('rating_star_'+i).addClassName("on");
        } else {
            $('rating_star_'+i).removeClassName("on");
        }
    }
}

/** This function can be called in two ways:
 *  listPopup(this, 4) - give it a trigger (usually this) and a single product id.
 *  listPopup(this, null, 'class_name') - this will get product Ids from inputs with the specified classname
 *      and ignore any values given for productId.
 **/
function listPopup(trigger, productId, inputClass) {
  is_logged_in(
    // Logged in.
    function () {
      load_list_popup(function () {
      	$('list_popup').removeClassName("list_popup_b_on");
      	
        if (inputClass) {
          ids = $$('.'+inputClass).select(function(el) {
            return el.checked;
          }).pluck('value').join(',');
          $('list_popup_product_id').value = ids;
          if (ids == '') {
            alert('Please select some products to add.');
            return;
          }
        } else {
          $('list_popup_product_id').value = productId;      
        }
        
        var popup = $('list_popup');
        popup.style.display = 'block';
        var loc = getAbsolutePosition(trigger, popup);
        popup.style.left = (loc.left - popup.clientWidth) + 'px';
        popup.style.top = (loc.top - 18) + 'px';
        
        if ( $('list_popup_list_id').value == "new" ) {
          // Backward compatibility: condition can be removed after 2009/7/24
          if ( $('list_popup_list_name') ) {
            $('list_popup_list_name').focus();
            $('list_popup_list_name').select();
          }
        }
      });
    },
    // Not logged in.
    function () {
        loginPopup(trigger);
    });
}

function load_list_popup ( on_done ) {
  if ( $('list_popup') ) {
    on_done();
    return;
  }
  
  new Ajax.Request("/list/index/popupform/", {
    method: 'get', 
    onSuccess: function ( response ) {
      var div = document.createElement("DIV");
      div.innerHTML = response.responseText;
      document.body.appendChild(div);
      on_done();
    },
    onFailure: function ( response ) {
      alert("An error occurred.");
    }
  });
}

function submitListPopup() {
  // Backward compatibility: can be removed after 2009/7/24
  var new_list_name = $('list_popup_list_name');
  if ( new_list_name ) {
    new_list_name = new_list_name.value
  } else {
    new_list_name = "New list";
  }
  
  if ( $('list_popup_list_id').value == "new" && new_list_name == "" ) {
    alert("You must enter a list name.");
    return;
  }
  
  new Ajax.Request($('add_item_to_list_url').value,
    {
      method: 'post',
      evalJSON: true,
      parameters: {
        product_id: $('list_popup_product_id').value,
        list_id: $('list_popup_list_id').value,
        name : new_list_name
      },
      onSuccess: function(r) {
        if (r.responseJSON.new_list) {
          l = r.responseJSON.new_list;
          $('list_popup_list_id').appendChild(new Option(l.name, l.id));
        }
        
      	if ( r.responseJSON.message ) {
					$('list_popup').addClassName("list_popup_b_on");
					$('list_popup_message').innerHTML = "";
					$('list_popup_message').appendChild(
						document.createTextNode(r.responseJSON.message));
      	} else {
      		close_list_popup();
      	}
      },
      onFailure: function(r) {
        alert(r.responseJSON.error);
      }
    });
}

function list_popup_onchange ( select ) {
  if ( select.value == "new" ) {
    $('list_popup_list_name').show();
    $('list_popup_list_name').focus();
    $('list_popup_list_name').select();
  } else {
    $('list_popup_list_name').hide();
  }
}

function close_list_popup () {
	$('list_popup').hide();
	$('list_popup').removeClassName("list_popup_b_on");
}

/**
 * Change tables on home page featured products
 */
function switchRotatorTab(show) {
    var tabs = new Array('rotator_essentials', 'rotator_favorites', 'rotator_innovations');
    tabs.each(function (t) {
      if (t == show)
          $(t).addClassName('selected');
      else
          $(t).removeClassName('selected');
    });
}

/**
 * Popups for green icons
 */
function setupGreenIconPopups() {
    $$('.greenIcons li').each(function (i) {
      Event.observe(i, 'mouseover', function (event) {
        var li = $(event.target);
        if (li.nodeName.toUpperCase() != 'LI')
            li = li.up('li');
        var popup = li.down('.green_pop_up');
        if ( ! popup ) {
          // Popup is already open.
          return;
        }
        
        popup.style.display = 'block';
        var loc = getAbsolutePosition(li, popup);
        popup.style.left = (loc.left - 10) + 'px';
        popup.style.top = (loc.top + 18) + 'px';
      });

      Event.observe(i, 'mouseout', function (event) {
        var li = $(event.target);
        if (li.nodeName.toUpperCase() != 'LI')
            li = li.up('li');
        var popup = li.down('.green_pop_up');
        popup.style.display = 'none';
      });
    });

    $$('#greenness_icons li').each(function (i) {
      Event.observe(i, 'mouseover', function (event) {
        var li = $(event.target);
        if (li.nodeName.toUpperCase() != 'LI')
            li = li.up('li');
        var popup = li.down('.green_pop_up');
        if ( ! popup ) {
          // Popup is already open.
          return;
        }
        
        popup.style.display = 'block';
        var loc = getAbsolutePosition(li, popup);
        popup.style.left = (loc.left - 5) + 'px';
        popup.style.top = (loc.top + 18) + 'px';
      });

      Event.observe(i, 'mouseout', function (event) {
        var li = $(event.target);
        if (li.nodeName.toUpperCase() != 'LI')
            li = li.up('li');
        var popup = li.down('.green_pop_up');
        popup.style.display = 'none';
      });
    });

    $$('.greenness_ranking').each(function (i) {
      Event.observe(i, 'mouseover', function (event) {
        var div = $(event.target);
        if (!div.hasClassName('greenness_ranking'))
            div = div.up('.greenness_ranking');
        var popup = div.down('.green_pop_up');
        if ( ! popup ) {
          // Popup is already open.
          return;
        }
        
        popup.style.display = 'block';

        /* These often appear within overflow: hidden elements. */
        $('inside').appendChild(popup);
        div.popup = popup;

        var loc = getAbsolutePosition(div, popup);

        var leftOff = 0;
        if (div.up('#product_view_greenscreen'))
            leftOff = -4;

        if (div.hasClassName('dark_green_rank'))
            popup.style.left = (loc.left - 1 + leftOff) + 'px';
        else if (div.hasClassName('green_rank'))
            popup.style.left = (loc.left + 30 + leftOff) + 'px';
        else
            popup.style.left = (loc.left + 61 + leftOff) + 'px';
        popup.style.top = (loc.top + 28) + 'px';
      });

      Event.observe(i, 'mouseout', function (event) {
        var div = $(event.target);
        if (!div.hasClassName('greenness_ranking'))
            div = div.up('.greenness_ranking');

        var popup;
        if (div.popup) {
            popup = div.popup;
            var parent = popup.parentNode;
            parent.removeChild(popup);
            div.appendChild(popup);
            div.popup = null;
        } else {
            var popup = div.down('.green_pop_up');
        }
        popup.style.display = 'none';
      });
    });
}

/**
 * Popups for (i) icons
 */
function setupInfoPopups() {
    $$('.info_icon').each(function(i) {
      setupInfoPopup(i);
    });
}

function setupInfoPopup(i) {
	if (i.title) {
        i.hiddenTitle = i.title;
        i.title = '';

        Event.observe(i, 'mouseover', function (event) {
          var img = $(event.target);
          if (!img.hasClassName('info_icon'))
              img = img.up('info_icon');

          var popup;
          if (!img.popup) {
              var popup = document.createElement('div');
              popup.className = 'green_pop_up';
              popup.innerHTML = '<div class="body">'+img.hiddenTitle+'</div><div class="bottom"></div>';
              $('inside').appendChild(popup);
              img.popup = popup;
          } else {
              popup = img.popup;
          }

          popup.style.display = 'block';
          var loc = getAbsolutePosition(img, popup);
          popup.style.left = (loc.left - 10) + 'px';
          popup.style.top = (loc.top + 8) + 'px';
        });

        Event.observe(i, 'mouseout', function (event) {
          var img = $(event.target);
          if (!img.hasClassName('info_icon'))
              div = div.up('info_icon');

          if (img.popup) {
              var popup = img.popup;
              popup.style.display = 'none';
              var parent = popup.parentNode;
              parent.removeChild(popup);
              img.popup = null;
          }
        });
      }
}

function open_popup ( a ) {
	var w = window.open(a.href, a.target || "_blank",
		"width=700,height=500,toolbar=no,menubar=no,location=yes,"
		+ "scrollbars=yes,status=yes,resizable=yes");
	w.focus();
	return false;
}

function record_history ( name, url ) {
	if ( ! url ) {
		url = window.location.href;
	}
	
	document.cookie = "last_" + encodeURIComponent(name) + "="
		+ encodeURIComponent(url) + "; path=/";
}

// This will be updated by the code that updates that top tab. This is only a
// default for the case that the top tab is missing (shouldn't happen).
var is_logged_in = function ( yes, no ) {
  alert("An error occurred; couldn't determine if you are logged in.");
}

var restriction_checks = $H({});
// func takes the product id, and a boolean for whether it is restricted
var register_restriction_check = function ( product_id, func ) {
  var checks;
  var match = /\bhas_restricted_products=(\d+)/.exec(document.cookie);
  
  if ( match && match[1] == "1" ) {
    checks = restriction_checks.get(product_id);
    if ( ! checks ) {
      restriction_checks.set(product_id, $A([]));
      checks = restriction_checks.get(product_id);
    }
    
    checks.push(func);
  } else {
    // No restricted products.
    func(product_id, false);
  }
}

function set_restrictions ( product_ids ) {
  var missing = $A([]);
  
  // Deal with restricted products.
  $A(product_ids).each(function ( id ) {
    if ( restriction_checks.get(id) ) {
      restriction_checks.unset(id).each(function ( f ) { f(id, true); });
    } else {
      missing.push(id);
    }
  });
  
  // Deal with products that are not restricted.
  restriction_checks.each(function ( pair ) {
    pair.value.each(function ( f ) { f(pair.key, false); });
  });
  
  if ( missing.length ) {
    throw "Cannot find restriction_checks records for " + missing.join(", ");
  }
  
  restriction_checks = $H({});
}

function loadUtilityBox () {
  var error_message = "An error occured loading account details tab. <a href='javascript:loadUtilityBox();'>Click here</a> to try again.";
  var on_logged_in = $A([]);
  var on_not_logged_in = $A([]);
  
  is_logged_in = function ( yes, no ) {
    on_logged_in.push(yes);
    on_not_logged_in.push(no);
  };
  
  register_restriction_check = function () {
    throw "Cannot register a restriction check after dom:loaded";
  };
  
  new Ajax.Request("/utilitybox", {
    method : 'post',
    parameters : {
      restriction_checks : restriction_checks.keys().join(",")
    },
    onSuccess : function (res) {
      if ( res.responseJSON && res.responseJSON.html ) {
        $('top_tab').innerHTML = res.responseJSON.html;
        
        if ( res.responseJSON.logged_in ) {
          on_logged_in.each(function (f) { f(); });
          is_logged_in = function ( yes, no ) { yes(); };
        } else {
          on_not_logged_in.each(function (f) { f(); });
          is_logged_in = function ( yes, no ) { no(); };
        }
        
        set_restrictions(res.responseJSON.restricted_products);
      } else {
        $('top_tab').innerHTML = error_message;
      }
    },
    onFailure : function(res) {
      $('top_tab').innerHTML = error_message;
      
      is_logged_in = function ( yes, no ) {
        loadUtilityBox();
        on_logged_in.push(yes);
        on_not_logged_in.push(no);
      }
    }
  });
}

// dom:loaded is not reliable in IE in prototype.js < 1.6.1
if ( Prototype.Browser.IE ) {
  function check_ie_dom_loaded () {
    try {
      document.documentElement.doScroll('left');
    } catch ( e ) {
      // Only throws an exception before the DOM is loaded.
      check_ie_dom_loaded.defer();
      return;
    }
    
    loadUtilityBox();
  }
  
  if ( window == top ) {
    check_ie_dom_loaded();
  } else {
    document.observer("load", loadUtilityBox);
  }
} else {
  document.observe("dom:loaded", loadUtilityBox);
}

function set_price ( id, tiers, special_price ) {
  var match = /\bcustomer_group_id=(\d+)/.exec(document.cookie),
    dollar = "$";
  
  if ( arguments.length < 3 ) {
    // Backward compatibility for cached HTML.
    special_price = null;
    dollar = "";
  }
  
  if ( match && tiers[match[1]] ) {
    var price = tiers[match[1]];
    
    if ( special_price !== null ) {
      if ( parseFloat(special_price) < parseFloat(price) ) {
        price = special_price;
      }
    }
    
    $(id).innerHTML = dollar + price;
  } else if ( special_price !== null ) {
    $(id).innerHTML = dollar + special_price;
  }
}

function fix_catalogsearch_form () {
  var match = /\bcustomer_group_id=(\d+)/.exec(document.cookie);
  var cookie = "1";
  
  if ( match && match[1] && match[1] != "0" ) {
    cookie = match[1];
  }
  
  $('catalogsearch_tier').value = cookie;
}

function leftnav_less_all () {
  $$('.leftnav1border .leftnavgroup_more').each(function ( e ) {
    e.removeClassName("leftnav_more");
  });
  
  $('leftnavless_all').hide();
  $('leftnavmore_all').show();
}

function leftnav_more_all () {
  $$('.leftnav1border .leftnavgroup_more').each(function ( e ) {
    e.addClassName("leftnav_more");
  });
  
  $('leftnavless_all').show();
  $('leftnavmore_all').hide();
}

function leftnav_update_all () {
  var any_open = false, any_closed = false;
  
  $$('.leftnav1border .leftnavgroup_more').each(function ( e ) {
    if ( e.hasClassName("leftnav_more") ) {
      any_open = true;
    } else {
      any_closed = true;
    }
  });
  
  if ( any_closed ) {
    $('leftnavmore_all').show();
  } else {
    $('leftnavmore_all').hide();
  }
  
  if ( any_open ) {
    $('leftnavless_all').show();
  } else {
    $('leftnavless_all').hide();
  }
}

function leftnav_less ( source ) {
  $(source).up('.leftnavgroup').removeClassName('leftnav_more');
  leftnav_update_all();
}

function leftnav_more ( source ) {
  $(source).up('.leftnavgroup').addClassName('leftnav_more');
  leftnav_update_all();
}

if ( Prototype.Browser.IE ) {
  Event.observe(window, 'load', function () {
    $$('#nav2>ul>li').each(function ( li ) {
      li.observe('mouseenter', function () {
        li.addClassName("over");
      });
      li.observe('mouseleave', function () {
        li.removeClassName("over");
      });
    });
  });
}

function placeholder_is_empty ( input ) {
	return input.value == '' || input.value == input.title;
}

function clear_placeholder ( input ) {
	if ( input.value == input.title ) {
		input.value = '';
	}
}

function restore_placeholder ( input ) {
	if ( placeholder_is_empty(input) ) {
		input.value = input.title;
		input.addClassName('empty');
	}
}

function setup_placeholder ( input ) {
	restore_placeholder(input);
	
	Event.observe(input, 'focus', function(event) {
		clear_placeholder(input);
		input.removeClassName('empty');
	});
	
	Event.observe(input, 'blur', function(event) {
		restore_placeholder(input);
	});
	
	if (input.form) {
		Event.observe(input.form, 'submit', function(event) {
			clear_placeholder(input);
		});
	}
}


Event.observe(window, 'load', function () {
	$$('input.default_text').each(setup_placeholder);
});
Event.observe(window, 'load', setupGreenIconPopups);
Event.observe(window, 'load', setupInfoPopups);
Event.observe(window, 'load', function () {
  $$('.cms_process_forms form').each(function ( form ) {
    new Validation(form);
  });
});
