var email_regex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/;
var RedBox      = {

  loading: function()
  {
    this.showOverlay();
    this.setWindowPosition();
    Element.show('RB_loading');
  },

  addHiddenContent: function(id)
  {
    Element.hide('RB_loading');
    selected = 'product_details';
    new Effect.Appear('RB_window', {duration: 0.5, queue: 'end'});  
  },

  close: function()
  {
    new Effect.Fade('RB_window', {duration: 0.5});
    new Effect.Fade('RB_overlay', {duration: 0.5});
    Element.hide('RB_loading');
    document.documentElement.style.overflow  = 'auto';
    try {
      this.showSelectBoxes();
    } catch (ex){}
  },

  closeDos: function(dosId)
  {
    this.close();
    if ($('dos_list')){
      // We're in admin edit mode
      // Refresh the page
      Element.show('waitpanel');
      new Ajax.Updater('mainpage_content', '/dos_form/dos_admin',
                       {
                         asynchronous:true,
                         evalScripts:true,
                         onComplete:function(request){
                           Element.show('mainpage');
                           new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
                           vsrScrollTo('dos_list','dos_'+dosId);
                           new Effect.Pulsate('dos_'+dosId, {duration: 2, pulses: 4, queue: 'end'});
                         }
                       });
    }
  },

  closeParts: function(partId)
  {
    this.close();
    if ($('parts_list')){
      // We're in admin edit mode
      // Refresh the page
      Element.show('waitpanel');
      new Ajax.Updater('mainpage_content', '/parts_form/parts_admin',
                       {
                         asynchronous:true,
                         evalScripts:true,
                         onComplete:function(request){
                           Element.show('mainpage');
                           new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
                           vsrScrollTo('parts_list','part_'+partId);
                           new Effect.Pulsate('part_'+partId, {duration: 2, pulses: 4, queue: 'end'});
                         }
                       });
    }
  },
  
  closeProduct: function(productId)
  {
    this.close();
    if ($('edit_list_scrollable')){
      // We're in admin edit mode
      // Refresh the page
      Element.show('waitpanel');
      new Ajax.Updater('mainpage_content', '/product/edit_list',
                       {
                         asynchronous:true,
                         evalScripts:true,
                         onComplete:function(request){
                           Element.show('mainpage');
                           new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
                           vsrScrollTo('edit_list_scrollable','product_'+productId);
                           new Effect.Pulsate('product_'+productId, {duration: 2, pulses: 4, queue: 'end'});
                         }
                       });
    }
  },

  closeAccount: function(accountId, page)
  {
    this.close();
    if ($('account_list')){
      // We're in admin edit mode
      // Refresh the page
      Element.show('waitpanel');
      new Ajax.Updater('mainpage_content', '/account/edit_list?page='+page,
                       {
                         asynchronous:true,
                         evalScripts:true,
                         onComplete:function(request){
                           Element.show('mainpage');
                           new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
                           vsrScrollTo('account_list','account_'+accountId);
                           new Effect.Pulsate('account_'+accountId, {duration: 2, pulses: 4, queue: 'end'});
                         }
                       });
    }
  },
  
  closePriceSheet: function(priceSheetId)
  {
    this.close();
    if ($('edit_list_scrollable')){
      // We're in admin edit mode
      // Refresh the page
      Element.show('waitpanel');
      new Ajax.Updater('mainpage_content', '/price_sheet/edit_list',
                       {
                         asynchronous:true,
                         evalScripts:true,
                         onComplete:function(request){
                           Element.show('mainpage');
                           new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
                           vsrScrollTo('edit_list_scrollable','price_sheet_'+priceSheetId);
                           new Effect.Pulsate('price_sheet_'+priceSheetId, {duration: 2, pulses: 4, queue: 'end'});
                         }
                       });
    }
  },

  showOverlay: function()
  {
    yScroll = 0;
    if (window.innerHeight && window.scrollMaxY)
    {  
      yScroll = window.innerHeight + window.scrollMaxY;
    } 
    else if (document.body.scrollHeight > document.body.offsetHeight)
    { // all but Explorer Mac
      yScroll = document.body.scrollHeight;
    }
    else
    { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      yScroll = document.body.offsetHeight;
    }
    $('RB_overlay').style['height'] = yScroll +'px';

    new Effect.Appear('RB_overlay', {duration: 0.5, to: 0.6, queue: 'end'});
    try {
      this.hideSelectBoxes();
    } catch (ex){}
  },

  setWindowPosition: function()
  {
    var pagesize = this.getPageSize();  
    document.body.style.height    = '600px';

    // document.documentElement.style.overflow  = 'hidden';
    document.body.scrollTop       = pagesize[1];

    $("RB_window").style['left']  = ((pagesize[0] - 800)/2) + "px";
    $("RB_window").style['top']   = (pagesize[1]+25) + "px";
    $("RB_loading").style['left'] = ((pagesize[0] - 75)/2) + "px";
    $("RB_loading").style['top']  = (pagesize[1]+235) + "px";
  },

  getPageSize: function() {
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    var yScroll;

    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
    }

    arrayPageSize = new Array(w,yScroll) 
    return arrayPageSize;
  },

  hideSelectBoxes: function()
  {
    // Only show/hide specific select boxes
    // This is for IE6 select box bleedthrough
  	selects = $$("select");
  	for (i = 0; i != selects.length; i++) {
  		selects[i].style.visibility = "hidden";
  	}

    // Make sure we show the ones in the redbox

  },

  showSelectBoxes: function()
  {
    // Only show/hide specific select boxes
    // This is for IE6 select box bleedthrough
  	selects = $$("select");
  	for (i = 0; i != selects.length; i++) {
  		selects[i].style.visibility = "visible";
  	}
  }
}

function getPosition(element) {
  element = $(element);
  var elementwh = Element.getDimensions(element);
  var tly = element.y ? element.y : element.offsetTop;
  var bry = tly + elementwh['height'];
  return {tly:tly, bry:bry};
}

// Scroll to a position variable returned from getPosition()
function vsrScrollToPos(container, pos) {
  container = $(container);
  // get top and bottom values for currently viewable area of container
  var containerwh = Element.getDimensions(container);
  var top         = container.scrollTop;
  var bottom      = containerwh['height'] + container.scrollTop;

  // Image falls below bottom
  if (pos.bry > bottom) container.scrollTop = top + (pos.bry - bottom) +10 ;
  // if image is above top
  if (pos.tly < top) container.scrollTop = top - (top - pos.tly) -10 ;
}

function vsrScrollTo(container, element){
  container = $(container);
  element = $(element);

  if (container && element) {
    // get element top left xy
    //var tlx = element.x ? element.x : element.offsetLeft;
    var tly = element.y ? element.y : element.offsetTop;

    // get element  bottom right xy
    var elementwh = Element.getDimensions(element)
    //var brx = tlx + elementwh['width'];
    var bry = tly + elementwh['height'];

    // get top and bottom values for currently viewable area of container
    var containerwh = Element.getDimensions(container)
    var top = container.scrollTop
    var bottom = containerwh['height'] + container.scrollTop

    // Image falls below bottom
    if(bry > bottom) container.scrollTop= top + (bry - bottom) +10 ;
    // if image is above top
    if(tly < top) container.scrollTop= top - (top - tly) -10 ;
    return element;
  }
  else {
    return null;
  }
}

function highlightProduct(productId, container, event) {
  if (checkMouseEnter(container, event) ||
      $('prod_inner_'+productId).style.visibility == 'hidden'){
    $('prod_inner_'+productId).style.visibility = 'visible';
    $('product_'+productId).className = 'product_category_view_selected';
  }
}

function unHighlightProduct(productId, container, event) {
  if (checkMouseLeave(container, event)){
    $('prod_inner_'+productId).style.visibility = 'hidden';
    $('product_'+productId).className = 'product_category_view';
  }
}

function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  }
  while (containee != null);
  return isParent;
}

function checkMouseEnter (element, evt) {
  if (element.contains && evt.fromElement) {
    return !element.contains(evt.fromElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function checkMouseLeave (element, evt) {
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function getDragElement(element){
  var el = element.cloneNode(true);
  el.id = 'sub'+element.id;
  el.style.position = 'relative';
  $('mainpage_bottom').appendChild(el);
  return el;
}

selected = 'product_details';

// Toggle product tab
function toggle_tab(tabId, action, productId, forceAjax, updateFunction) {

  if (selected != tabId){

    // Set wait
    new Effect.Appear('product_contents_wait', {duration: 0, queue: 'end'});

    // Set link classes
    $('product_details_tab').className    = 'product_tab_off';
    $('product_multimedia_tab').className = 'product_tab_off';
    $('product_documents_tab').className  = 'product_tab_off';
    $(tabId+'_tab').className             = 'product_tab_on';

    // Set up wait action effects
    new Effect.Fade(selected+'_frame', {duration: .40, queue: 'end'});
    selected = tabId;

    // Perform AJAX update to main product image
    new Ajax.Updater('product_image_loader', '/product_image/show_primary/'+productId, {asynchronous:true, evalScripts:true});

    // Perform AJAX request to fill the contents if they haven't been loaded already
    if (forceAjax || Element.empty(tabId+'_frame')) {
      new Ajax.Updater(tabId+'_frame', action+productId, {
          method: 'get',
          onComplete: function() {
            if (updateFunction){
              updateFunction();
            }
            new Effect.Appear(tabId+'_frame', {duration: .40, queue: 'end'});
            new Effect.Fade('product_contents_wait', {duration: 0, queue: 'end'});
          }
      });
    }
    else {
      new Effect.Appear(tabId+'_frame', {duration: .40, queue: 'end'});
      new Effect.Fade('product_contents_wait', {duration: 0, queue: 'end'});
    }

    // Cleanup to ensure other frames are hidden
    if (tabId != 'product_details') {
      new Effect.Fade('product_details_frame', {duration: 0, queue: 'end'});
    }

    if (tabId != 'product_multimedia') {
      new Effect.Fade('product_multimedia_frame', {duration: 0, queue: 'end'});
    }

    if (tabId != 'product_documents') {
      new Effect.Fade('product_documents_frame', {duration: 0, queue: 'end'});
    }
  }
  else {
    new Effect.Highlight(tabId+'_frame', { duration: .3, queue: 'end'});
  }
  // Unfocus the anchor
  $(tabId+'_anchor').blur();
}

function reload_admin_frame(action, updateFunction){
  // Perform AJAX update to admin display
  Element.show('waitpanel');
  new Effect.Fade('mainpage', {from: 1, to: 0, duration: .6, queue: 'end'});
  new Ajax.Updater('mainpage_content', action, {
    asynchronous:true,
    evalScripts:true,
    onComplete: function() {
      new Effect.Appear('mainpage', {from: 0, to: 1, duration: .6, queue: 'end'});
      new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
      if (updateFunction){
        updateFunction();
      }
    }
  });
}

function reload_product_frame(frame_id, base_url, action, product_id, errmsg){

  if (errmsg){ alert(errmsg); }

  // Perform AJAX update to documents display
  new Effect.Fade(frame_id, {duration: .40, to: 0.01, queue: 'end'});
  new Ajax.Updater(frame_id, base_url+action+product_id, {
    asynchronous:true,
    evalScripts:true,
    onComplete: function() {
      new Effect.Appear(frame_id, {duration: .40, queue: 'end'});
    }
  });
}

function getValue(el) {
  return ($(el)) ? $(el).value.replace(/\s/g, '') : null;
}

function removeItem(el, child) {
  $(el).removeChild($(child));
}

function addPartsItem() {
  var count   = $$('table.dos_table').length;
  var newItem = document.createElement('table');

  newItem.setAttribute("id", "item_"+count);
  newItem.setAttribute("class", "dos_table");
  $(newItem).update("<tbody><tr><td colspan=\"4\"><hr></td></tr><tr>"+
                    "<td class=\"admin_key\"><input class=\"small_delete_button\" onclick=\"removeItem('parts_items', 'item_"+count+"'); return false;\" title=\"Remove this Item\" type=\"button\" value=\"\" />* Model/Item #:</td>"+
                    "<td class=\"value\"><input class=\"text\" id=\"item[]\" name=\"item[]\" style=\"width: 175px;\" value=\"\" type=\"text\"></td>"+
                    "<td class=\"admin_key\">Serial/Lot #:</td><td class=\"value\"><input class=\"text\" id=\"serial[]\" name=\"serial[]\" style=\"width: 175px;\" value=\"\" type=\"text\"></td>"+
                    "</tr><tr><td class=\"admin_key\">Date of Manufacturing:</td><td class=\"value\" colspan=\"3\"><input class=\"text\" id=\"dom[]\" name=\"dom[]\" style=\"width: 175px;\" value=\"\" type=\"text\"> <img alt=\"Calendar\" class=\"calendar_date_select_popup_icon\" onclick=\"new CalendarDateSelect( $(this).previous(), {buttons:false, time:false, year_range:10} );\" src=\"/images/calendar_date_select/calendar.gif\" style=\"border: 0px none ; cursor: pointer;\"></td></tr>"+
                    "<tr><td class=\"admin_key\">Part(s) Requested and Reason(s):</td>"+
                    "<td class=\"value\" colspan=\"3\"><textarea class=\"text\" id=\"parts[]\" name=\"parts[]\" rows=\"2\" style=\"width: 100%;\"></textarea></td>"+
                    "</tr></tbody></table>");
  $('parts_items').appendChild(newItem);
}

function addDosItem() {
  var count   = $$('table.dos_table').length;
  var newItem = document.createElement('table');

  newItem.setAttribute("id", "item_"+count);
  newItem.setAttribute("class", "dos_table");
  $(newItem).update("<tbody><tr><td colspan=\"4\"><hr></td></tr><tr>"+
                    "<td class=\"admin_key\"><input class=\"small_delete_button\" onclick=\"removeItem('dos_items', 'item_"+count+"'); return false;\" title=\"Remove this Item\" type=\"button\" value=\"\" />* Item #:</td>"+
                    "<td class=\"value\">"+
                    "<input class=\"text\" id=\"item[]\" name=\"item[]\" style=\"width: 175px;\" value=\"\" type=\"text\"></td>"+
                    "<td class=\"admin_key\">Item Description:</td><td class=\"value\">"+
                    "<input class=\"text\" id=\"description[]\" name=\"description[]\" style=\"width: 175px;\" value=\"\" type=\"text\"></td>"+
                    "</tr><tr><td class=\"admin_key\">Serial/Lot #:</td>"+
                    "<td class=\"value\"><input class=\"text\" id=\"serial[]\" name=\"serial[]\" style=\"width: 175px;\" value=\"\" type=\"text\"></td>"+
                    "<td class=\"admin_key\">Quantity:</td>"+
                    "<td class=\"value\"><input class=\"text\" id=\"quantity[]\" name=\"quantity[]\" style=\"width: 175px;\" value=\"\" type=\"text\"></td></tr>"+
                    "<tr><td class=\"admin_key\">Date of Manufacturing:</td>"+
                    "<td class=\"value\" colspan=\"3\"><input class=\"text\" id=\"dom[]\" name=\"dom[]\" style=\"width: 175px;\" value=\"\" type=\"text\"> <img alt=\"Calendar\" class=\"calendar_date_select_popup_icon\" onclick=\"new CalendarDateSelect( $(this).previous(), {buttons:false, time:false, year_range:10} );\" src=\"/images/calendar_date_select/calendar.gif\" style=\"border: 0px none ; cursor: pointer;\"></td></tr>"+
                    "<tr><td class=\"admin_key\">Problem Description:</td>"+
                    "<td class=\"value\" colspan=\"3\"><textarea class=\"text\" id=\"problem[]\" name=\"problem[]\" rows=\"2\" style=\"width: 100%;\"></textarea></td>"+
                    "</tr></tbody></table>");
  $('dos_items').appendChild(newItem);
}

function validateParts() {
  var email = getValue('email');
  
  if (!getValue('company_name')) {
    alert('Please enter a Company Name');
    $('company_name').focus();
  	return false;
  }
  else if (!getValue('account_number')) {
    alert('Please enter an Account Number');
    $('account_number').focus();
  	return false;
  }
  else if (!getValue('address_line1')) {
    alert('Please enter an Address Line 1');
    $('address_line1').focus();
  	return false;
  }
  else if (!getValue('city')) {
    alert('Please enter a City');
    $('city').focus();
  	return false;
  }
  else if (!getValue('state')) {
    alert('Please enter a State/Province');
    $('state').focus();
  	return false;
  }
  else if (!getValue('zip')) {
    alert('Please enter a Postal Code');
    $('zip').focus();
  	return false;
  }
  else if (!email || !email_regex.test(email)) {
    alert('Please enter a valid Email Address');
    $('email').focus();
  	return false;
  }
  else {
    return true;
  }
}

function validateDos() {
  var email = getValue('email');

  if (!getValue('company_name')) {
    alert('Please enter a Company Name');
    $('company_name').focus();
  	return false;
  }
  else if (!getValue('address_line1')) {
    alert('Please enter an Address Line 1');
    $('address_line1').focus();
  	return false;
  }
  else if (!getValue('city')) {
    alert('Please enter a City');
    $('city').focus();
  	return false;
  }
  else if (!getValue('state')) {
    alert('Please enter a State/Province');
    $('state').focus();
  	return false;
  }
  else if (!getValue('zip')) {
    alert('Please enter a Postal Code');
    $('zip').focus();
  	return false;
  }
  else if (!email || !email_regex.test(email)) {
    alert('Please enter a valid Email Address');
    $('email').focus();
  	return false;
  }
  else {
    return true;
  }
}

function addCompare(productId, productName, productNo) {
  if ($('compare_'+productId)){
    // Already added to compare box
    toggleMenuTabs('search');
    new Effect.Highlight('compare_'+productId, {queue: 'end'});
  }
  else {

    var count      = 0;
    var compareBox = $('compare_box');

    for (i=0; i<compareBox.childNodes.length; i++){
      if (compareBox.childNodes[i].id){
        count++;
      }
    }

    if (count >= 4){
      alert('You can only compare a maximum of 4 products at one time.');
    }
    else {
      var newCompare = document.createElement('div');
      newCompare.setAttribute("id", "compare_"+productId);
      newCompare.setAttribute("class", "compare_item");
      newCompare.innerHTML = "<input class=\"small_delete_button\" onclick=\"removeCompare('"+productId+"'); return false;\" title=\"Remove From Product Comparison\" type=\"button\" value=\"\" /> "+productName;
      $('compare_box').appendChild(newCompare);
      $('compare_'+productId).className = 'compare_item';
      toggleMenuTabs('search');
      new Effect.Highlight('compare_'+productId, {queue: 'end'});
    }
  }
}

function productCompare() {

  var count      = 0;
  var ids        = 'compare=';
  var compareBox = $('compare_box');

  for (i=0; i<compareBox.childNodes.length; i++){
    if (compareBox.childNodes[i].id){
      ids += (count > 0) ? ','+compareBox.childNodes[i].id.substring(8) : compareBox.childNodes[i].id.substring(8);
      count++;
    }
  }

  Element.show('waitpanel');
  new Ajax.Updater('product_compare', '/product/compare', {
    asynchronous:true,
    evalScripts:true,
    parameters:ids,
    onComplete: function() {
      toggleMainTabs('compare');
    }
  });
}

function removeCompare(productId) {
  $('compare_box').removeChild($('compare_'+productId));

  // Reload the compare window if we are currently viewing it
  if (Element.visible('product_compare')){
    productCompare();
  }
}

function toggleMenuTabs(item){
  switch(item){
    case 'search':
      if (!Element.visible('leftbar_search')){
        Element.show('waitpanel');
        new Effect.Fade('leftbar_cart', {duration: .3, queue: 'end'});
        Element.hide('search_tab_off');
        Element.hide('cart_tab_on');
        Element.show('search_tab_on');
        Element.show('cart_tab_off');
        new Effect.Appear('leftbar_search', {duration: .3, queue: 'end'});
      }
      new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
      break;
    case 'cart':
      if (!Element.visible('leftbar_cart')){
        Element.show('waitpanel');
        new Effect.Fade('leftbar_search', {duration: .3, queue: 'end'});
        Element.hide('search_tab_on');
        Element.hide('cart_tab_off');
        Element.show('search_tab_off');
        Element.show('cart_tab_on');
        new Effect.Appear('leftbar_cart', {duration: .3, queue: 'end'});
      }
      new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
      break;
  }
}

function toggleMainTabs(item){
  switch(item){
    case 'display':
      if (!Element.visible('product_list')){
        Element.show('waitpanel');
        new Effect.Fade('product_list', {duration: .3, queue: 'end'});
        new Effect.Fade('product_compare', {duration: .3, queue: 'end'});
        new Effect.Fade('checkout_cart', {duration: .3, queue: 'end'});
        Element.hide('display_tab_off');
        Element.hide('compare_tab_on');
        Element.hide('order_tab_on');
        Element.show('display_tab_on');
        Element.show('compare_tab_off');
        Element.show('order_tab_off');
        new Effect.Appear('product_list', {duration: .3, queue: 'end'});
        enableCart();
      }
      new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
      break;
    case 'compare':
      if (!Element.visible('product_compare')){
        Element.show('waitpanel');
        new Effect.Fade('product_list', {duration: .3, queue: 'end'});
        new Effect.Fade('checkout_cart', {duration: .3, queue: 'end'});
        Element.hide('display_tab_on');
        Element.hide('compare_tab_off');
        Element.hide('order_tab_on');
        Element.show('display_tab_off');
        Element.show('compare_tab_on');
        Element.show('order_tab_off');
        new Effect.Appear('product_compare', {duration: .3, queue: 'end'});
        enableCart();
      }
      new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
      break;
    case 'order':
      if (!Element.visible('checkout_cart')){
        Element.show('waitpanel');
        new Effect.Fade('product_list', {duration: .3, queue: 'end'});
        new Effect.Fade('product_compare', {duration: .3, queue: 'end'});
        Element.hide('display_tab_on');
        Element.hide('compare_tab_on');
        Element.hide('order_tab_off');
        Element.show('display_tab_off');
        Element.show('compare_tab_off');
        Element.show('order_tab_on');
        new Effect.Appear('checkout_cart', {duration: .3, queue: 'end'});
        disableCart();
      }
      new Effect.Fade('waitpanel', {duration: 0, queue: 'end'});
      break;
  }
}


function runFilter(categoryId) {
  toggleMainTabs('display');
  new Ajax.Request('/product_category/narrow/'+categoryId,
                  {
                    asynchronous:true,
                    evalScripts:true,
                    parameters:Form.serialize($('filter_form'))
                  });
  Element.show('leftbar_wait');
  $('filter_form').disable();  
}

function updateEditItems(id, value, tag) {
  // ID format: <id>_<field>@<category>  
  // Loop through all the <tag> elements created by the
  // in_place_editor and update those with a matching ID (<id>_<field>)
  var elems = document.getElementsByTagName(tag);
  for (var i=0; i<elems.length; i++) {
    if (elems[i].id.split("@")[0] == id.split("@")[0]) {
      if (tag == "span") {    
        elems[i].innerHTML = value;
      }
      else if (elems[i].type == "checkbox") {
        elems[i].checked = value;  
      }    
    }  
  }  
}

function followMouse(e){
  mouseX = Event.pointerX(e)+3;
  mouseY = Event.pointerY(e)+3;
  widget = $('hovermsg');
  widget.style.left = mouseX + 'px';
  widget.style.top = mouseY + 'px';
}

function showToolTip(text){
  widget = $('hovermsg');
  widget.update(text);
  Element.show(widget);
}

function hideToolTip(){
  Element.hide('hovermsg');
}

function showTimeframeEditor(anchor, product_id){

  new Ajax.Updater('timeframe_editor', '/production_timeframe/edit', {
    asynchronous:true,
    evalScripts:true,
	parameters: 'product_id='+product_id
  });

  // Get anchor element top left x
  var parent = $(anchor).up();
  var tly    = parent.y ? parent.y : parent.offsetTop;
  var editor = $('timeframe_editor');
  editor.update('<img src="/images/large_waitloader.gif" style="margin: 75px auto;">');

  editor.style.top = (tly+65)+'px';
  Element.show(editor);
  document.body.scrollTop = tly;

}

function disableCart() {
  var cartitems = $$('div#leftbar input, div#leftbar button, div#leftbar submit, div#leftbar select');
  for(var i=0; i<cartitems.length; i++){
    cartitems[i].disable();
  }
  Element.hide('checkout_controls');
  Element.show('disabled_cart');
}

function enableCart() {
  var cartitems = $$('div#leftbar input, div#leftbar button, div#leftbar submit, div#leftbar select');
  for(var i=0; i<cartitems.length; i++){
    cartitems[i].enable();
  }
  Element.show('checkout_controls');
  Element.hide('disabled_cart');
}

function addToCart(productId) {
  toggleMenuTabs('cart');
  Element.show('cart_spinner');
  Element.show('ptocart_'+productId);
  $('ptocart_msg_'+productId).update('Adding item ...');
  new Effect.Appear('ptocart_'+productId, {duration: .01, queue: 'end'});
  new Ajax.Request('/product_category/add_cart_item/'+productId, {asynchronous:true, evalScripts:true});
}

function removeFromCart(productId, container) {
  if (!container){
    container = 0;
  }
  toggleMenuTabs('cart');
  Element.show('cart_spinner');
  new Ajax.Request('/product_category/delete_cart_item/'+productId+'/'+container, {asynchronous:true, evalScripts:true});
}

function clearCart() {
  toggleMenuTabs('cart');
  Element.show('cart_spinner');
  new Ajax.Request('/product_category/clear_cart', {asynchronous:true, evalScripts:true});
}

function checkForCartUpdate(productId, container) {
  updateCartQuantity(productId, container);
}

function checkForCartEnter(productId, e, container) {
  var characterCode = (document.all) ? window.event.keyCode : e.keyCode;
  if(characterCode == 13){
    $('cartitem_count_'+productId).blur();
  }
}

function updateCartQuantity(productId, container) {
  if (!container){
    container = 0;
  }
  Element.show('cart_spinner');
  new Ajax.Request('/product_category/update_item_quantity/'+productId+'/'+container,
                   {
                     asynchronous:true,
                     evalScripts:true,
                     parameters:'count='+$('cartitem_count_'+productId).value
                     //onComplete: focusCartItem('cartitem_count_'+productId)
                     // This won't work from here, call is done from controller
                   });
}

function checkout() {
  Element.show('waitpanel');
  new Ajax.Updater('checkout_cart', '/purchase_order/prepare_order', {
    asynchronous:true,
    evalScripts:true,
    onComplete: function() {
      toggleMainTabs('order');
      vsrScrollTo('checkout_cart','topelement');
    }
  });
}

function focusCartItem(id) {
  // Try to set focus to the next order item input box
  var items = $$('input.cart_count');
  var item  = $(id);
  var sel   = items[0];
  var index = items.indexOf(item);

  if (index >= 0 && index < items.size()-1) {
    sel = items[index+1];
  }

  sel.focus();
  sel.select();
}

