/*--
NOTICE:
This source code has been created by Westring Technologies
All Rights Reserved.

Created on Apr 20, 2005
Created by Ryan Bowman
--*/
/******************************
  Table of Contents
 ******************************
  1. Global Variables
  2. Functions
    - addToTotal()
    - changeVeh()
    - clearTextInput()
    - setInput()
    - unsetInput()
    - hideElementByName()
    - hideElementById()
    - showElementById()
    - hideShowElement(id/el, control)
    - isAddrElement()
    - openWindow()
    - showArea()
    - noShowArea()
    - storeFormValues()
    - toggleUseAddress()
    - togglePayment()
    - updateLength()
    - viewLargerImage()
    - jumpto()
    - resizeBannerArea()
    - showICAdd()
    - hideICAdd()
    - internationalShipping ()
    - hideLiveChatLinks()
    - toggleRelatedInputs()
    - setChildInputsDisabled()
    - newImage(arg)
    - hideshow()
    - activateTabRollover(image, index)
    - deactivateTabRollover(image, index)
    - preloadActives()
    - preloadInactives()
    - setActiveTab(prod, elid, index)
    - showTab(elid, index)
    - verifyUsername(el)
    - clearCheckbox(el)
    - clearZeroValue(el)
    - resetZeroValue(el)
    - formatMoneyInput(el)
    - toggleCheckboxes(el, ancestor)
    - toggleChildInputs(el, check)
**********/

/**
 * Global Variables and their usages
 */
var errorClr = '#fede00';
var defaultClr = '#fff';


/**
 * REGEXP used with viewLargerImages to change the urls for the images from the
 * small size to the larger size.
 */
var smallSizes = /\/1.0\//;

/**
 * Used with toggleUseAddress() this one stores the default billing address.
 */
var storedAddrInfo;

/**
 * Used with toggleUseAddress() this stores the last changes the user made for a
 * different billing address.
 */
var storedUserAddr = new Array();



/**
 * this function reads the value of element (which should be a checkbox) and
 * adds price * 2 to the total price of the currently selected tire/wheel
 * package if the element is checked, or subtracts price * 2 from the total if
 * element is unchecked, returns new total.
 */
function addToTotal(price, element)
{
  var total = (document.getElementsByName("total"))[0];
  total.readOnly = false;
  var t = total.value;
  price *= 2;
  if( t.charAt(0) == '$' )
  {
    t = parseFloat(t.substring(1));
  }
  else
  {
    t = parseFloat(t);
  }

  if( element.checked )
  {
    t += price;
  }
  else
  {
    t -= price;
  }
  total.value = '$' + t.toFixed(2).toString();
  total.readOnly = true;
}


/**
 * This function adds a fragment identifier to the form's action field, so as to
 * put the vehicle select form at the top of the page.
 */
function addVehicleSelectFragment(form)
{
  form.action += "#vehicleSelect";
}

/**
 * This function is used by vehicleSelect.jsp to cause the year combo box to
 * auto submit
 */
function changeVeh(form, val)
{
  var hid = document.getElementById("appFilterHidden");
  hid.value = val;
  enableEl(hid);
}



/**
 * This function simply clears the value of a <input type="text"> element.
 * 
 * @param element -
 *            the element whose value will be cleared.
 */
function clearTextInput(element)
{
  element.value = "";
}


/**
 * Given a checkbox/radio, or the id of checkbox or radio button this function
 * selects/checks that input Used places where more than one input element has
 * information to be entered, this can automatically select an associated radio
 * or checkbox.
 * 
 * @param element -
 *            the element that will be selected/checked
 */
function setInput(element)
{
  if (element.tagName == undefined)
  {
    element = document.getElementById(element);
  }
  if (element && (element.type == "checkbox" || element.type == "radio"))
  {
      element.checked = true;
  }
}
function unsetInput(element)
{
  if (element.tagName == undefined)
  {
    element = document.getElementById(element);
  }
  if (element && (element.type == "checkbox" || element.type == "radio"))
  {
      element.checked = null;
  }
}



/*
 * These functions can be used to hide elements. They was designed to hide
 * submit buttons on forms that use eventhandlers to submit the form. The first
 * takes as an input the name of the element to hide, the second takes the id.
 */
function hideElementByName(element)
{
  var es = document.getElementsByName(element);
  var len = es.length;
  for( var i = 0; i < len; i++ )
  {
    var e = es[i];
    e.style.display = "none";
  }
}


function hideElementById(element)
{
  var e = document.getElementById(element);
  e.style.display = "none";
}


function showElementById(element)
{
  var e = document.getElementById(element);
  e.style.display = "block";
  
}

/*
 * hideShowElement hides or unhides element, if control is present, it is
 * assumed to be a checkbox or radio button and shows/hides based on selected,
 * if no control then toggles show/hide based on style.display,
 */
function hideShowElement(element, control)
{
  if (element.tagName == undefined)
  {
    element = document.getElementById(element);
  }
  if (element)
  {
    if (control)
    {
      if (control.checked)
      {
        showElementById(element.id);
      }
      else
      {
        hideElementById(element.id);
      }
    }
    else
    {
      if (element.style.display == 'none')
      {
        showElementById(element.id);
      }
      else
      {
        hideElementById(element.id);
      }
    }
  }
}

/**
 * Returns true if element is of type 'text', 'select-one', or select-multiple'
 * or if it's one of the address type radio buttons Phones and email are not
 * address elements
 */
function isAddrElement(element)
{
  var sel = "select-";
  var type = String(element.type)
  var TorS = type == "text" || type.substring(0,sel.length) == sel;
  var isAddType = element.className == "addrType" ? true : false;
  /* exclude phone and email fields */
  if (element.name == 'dayPhone' || element.name == 'dayPhoneExt' || element.name == 'eveningPhone' ||
    element.name == 'eveningPhoneExt' || element.name == 'email')
  {
    return false;
  }
  return TorS || isAddType;
}


function openWindow(theURL, winName, features)
{
  window.open(theURL, winName, features);
}


function showArea(e)
{
  var height;
  var href;
  var aleft;
  var atop;
  var width;

  if (e.coords)
  {
    var coords = e.coords.split(",");
    if (coords.length == 4)
    {
      var t = coords[1];
      var l = coords[0];
      var b = coords[3];
      var r = coords[2];

      atop = t;
      aleft = l;
      height = b - t;
      width = r - l;
      href = e.href;
    }
  }
  else if (e.tagName == 'IMG')
  {
    height = e.height;
    width = e.width;
    href = e.parentNode.href;
    var pos = findPos(e);
    aleft = pos.left;
    /* IE bowser only */
    if (navigator.systemLanguage)
    {
      var bod = document.getElementById('body');
      aleft = aleft - bod.offsetLeft;
    }
    atop = pos.top;
  }
  var ah = document.getElementById("AreaHover");
  ah.href = href;
  ah.style.display = "block";
  ah.style.height = height + "px";
  ah.style.width = width + "px";
  if (atop != undefined && aleft != undefined)
  {
    ah.style.top = atop + "px";
    ah.style.left = aleft + "px";
  }
}


/**
 * findPos by Peter-Paul Koch http://www.quirksmode.org/js/findpos.html with
 * modifications by me, because something didn't seem to work in IE
 */
function findPos(obj)
{
  var curleft = curtop = 0;
  if (obj.offsetParent)
  {
    do
    {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
  }
  // I like this way better, but IE is retarded and can't do mulitple
	// assignements
  // return [curleft,curtop];
  var pos = new Object();
  pos.left = curleft;
  pos.top = curtop;
  return pos;
}


function noShowArea()
{
  var ah = document.getElementById("AreaHover");
  ah.style.display = "none";
}

/**
 * Stores the (text and select) field values from the passed in form for later
 * retreival. Returns an Array
 */
function storeFormValues(form)
{
  var a = Array(form.length);

  for( var i = 0; i < form.length; i++ )
  {
    if( isAddrElement(form.elements[i]) )
    {
      if( form.elements[i].value )
      {
        a[i] = form.elements[i].value;
      }
      else
      {
        a[i] = "";
      }
    }
  }
  return a;
}


/**
 * toggleUseAddress() the value of the checkbox
 * 
 * form is the form to manipulate el is the element controlling the toggle
 */
function toggleUseAddress(form, el)
{
  /*
	 * store form values if this is the first time this method has run note
	 * storedAddrInfo is global
	 */
  if( !storedAddrInfo && el.checked )
  {
    storedAddrInfo = storeFormValues(form);
  }

  if( !el.checked )
  {
    /* if checked then use default address for address */
    /* for each input in form disable and populate from stored values (if any) */
    for( var i = 0; i < form.length; i++ )
    {
      var e = form.elements[i];
      if( isAddrElement(e) && e.name != "pwdHint" )
      {
        storedUserAddr[i] = e.value;
        if( storedAddrInfo )
        {
          e.value = storedAddrInfo[i];
        }
        else
        {
          e.value = "";
        }
        disableEl(e);
      }
    }
  }
  else
  {
    /* for each input in form store value, clear and enable */
    for( var i = 0; i < form.length; i++ )
    {
      var e = form.elements[i];
      if( isAddrElement(e) )
      {
        if( storedUserAddr[i] )
        {
          e.value = storedUserAddr[i];
        }
        else
        {
          e.value = "";
        }
        enableEl(e);
      }
    }
  }
}


function togglePayment()
{
  var bml = document.getElementById("pay_bml");
  var cc = document.getElementById("pay_cc");
  var pp = document.getElementById("pay_paypal");

  var ccnum = document.getElementById("ccnum");
  var months = document.getElementById("months");
  var years = document.getElementById("years");
  var cvv = document.getElementById("cvv");

  var btnel = document.getElementById("reviewconfirmBtn");
  if (btnel)
  {
    var btnsrc = btnel.src;
    var index = btnsrc.lastIndexOf("-");
    if (index != -1)
    {
      btnsrc = btnsrc.substring(0, index);
    }

    if (bml && bml.checked)
    {
      btnsrc += "-bml.jpg";
      btnel.src = btnsrc;
      disableEl(ccnum);
      disableEl(months);
      disableEl(years);
      disableEl(cvv);
    }
    else if (cc && cc.checked)
    {
      btnsrc += "-confirm.jpg";
      btnel.src = btnsrc;
      ccnum.disabled = null;
      months.disabled = null;
      years.disabled = null;
      cvv.disabled = null;
    }
    else if (pp && pp.checked)
    {
      btnsrc += "-pp.jpg";
      btnel.src = btnsrc;
      disableEl(ccnum);
      disableEl(months);
      disableEl(years);
      disableEl(cvv);
    }
  }
}

/**
 * assumes the specified textfield has a sibling span element where the message
 * will be written textEl can be the element itself, or it's id textEl =
 * getElementById(textElId)
 */
function updateLength(textEl, len)
{
  if (textEl && textEl.tagName == undefined)
  {
    textEl = document.getElementById(textEl);
  }
  if (textEl)
  {
    var parEl = textEl.parentNode;
    var msgEl;
    var maxLen;
    if (len)
    {
      maxLen = len;
    }
    else
    {
      maxLen = textEl.maxLength;
    }
    if (parEl && parEl.childNodes)
    {
      for (var j = 1, msgEl = parEl.childNodes[0];
        msgEl.tagName != "SPAN" && j < parEl.childNodes.length; j++ )
      {
        msgEl = parEl.childNodes[j];
      }
    }

    if (msgEl)
    {
      var tmpLen = maxLen - textEl.value.length;
      if (tmpLen <= 0)
      {
        tmpLen = 0;
        msgEl.innerHTML = "No letters remaining";
        textEl.value = textEl.value.substr(0, maxLen);
      }
      else if (tmpLen < maxLen)
      {
        msgEl.innerHTML = tmpLen + " letters remain.";
      }
      else
      {
        msgEl.innerHTML = maxLen + " letter max.";
      }
    }
  }
}


/**
 * Assuming there is an image element called LargerImageImg on any page from
 * which this function is used, this function replaces the source of that
 * element with the source from the given image element.
 * 
 */
function viewLargerImage(thumb)
{
  if (thumb)
  {
    var larger = document.getElementById("LargerImageImg");
    if (larger)
    {
      // var s = thumb.src;
      larger.src = thumb.src.replace(smallSizes, "/400/");
      // larger.src = s;
    }
  }
}


/**
 * Used to scroll the page to specific location after loading, so the customer
 * doesn't have to. *
 */
function jumpto(targetAnchor)
{
  var targAnc = document.getElementsByName(targetAnchor);
  if (targAnc)
  {
    window.location.hash = targetAnchor;
  }
}

/**
 * Functions for slide show
 * 
 */
function resizeBannerArea(ss, imgContainer)
{
  // account for differing banner heights.
  imgContainer = document.getElementById(imgContainer);
  if (imgContainer)
  {
    var maxH = 275; // arbitrary number used as min-height in home.css
    var elH = imgContainer.style.height;
    for (var ssl = 0; ssl < ss.slides.length; ssl++)
    {
      var img = ss.slides[ssl];
      var curH = img.image.height;
      if (curH > maxH)
      {
        maxH = curH;
      }
    }
  }
  imgContainer.style.height = maxH + "px";
}

function sizeComboBox(boxname)
{
  var box = document.getElementById(boxname);
  if (box.length <= 1)
  {
    box.style.width = "5em";
  }
}
function hideICAdd()
{
	$("#ICAdd").slideUp('normal');
}

function showICAdd()
{
		$("#ICAdd").slideDown('slow')
		setTimeout("hideICAdd()", 20000);
	}
function internationalShipping()
{
$("#InternationalTab").click(function()
  {
    $("#InternationalSubTab").slideDown('slow');
  });
  $("#InternationalTab").mouseleave(function()
  {
    $("#InternationalSubTab").slideUp('hover');
  });
}


function hideLiveChatLinks()
{
  var tmphref = document.getElementById('ts-livechatlink');
  if (tmphref)
  {
    var tmpimg = tmphref.firstChild;
    if (tmpimg && tmpimg.tagName == 'IMG' && tmpimg.width == 1 && tmpimg.height == 1)
    {
      tmphref.style.display = 'none';
    }
  }
  tmphref = document.getElementById('rt-livechatlink');
  if (tmphref)
  {
    tmpimg = tmphref.firstChild;
    if (tmpimg && tmpimg.tagName == 'IMG' && tmpimg.width == 1 && tmpimg.height == 1)
    {
      tmphref.style.display = 'none';
    }
  }
}

/**
 * Disables all form inputs that are descended from ancestor. Parameter el is
 * assumed to be a checkbox or radio button, or the ID of a checkbox or radio
 * button, is passed into the function, all checkboxes or radio buttons with the
 * same name will not be disabled (presumably other choices will re-enable the
 * disabled inputs). Parameter el can be an HTML element or the ID of an
 * element, but must refer to the input that toggles the other input elements'
 * enabled state.
 */
function toggleRelatedInputs(el, ancestor)
{
  if (!el)
  {
    return;
  }
  if (el.tagName != 'INPUT')
  {
    el = document.getElementById(el);
  }
  if (el.tagName != 'INPUT')
  {
    return;
  }

  if (ancestor.tagName == undefined)
  {
    ancestor = document.getElementById(ancestor);
  }
  if (!ancestor)
  {
    return;
  }
  setChildInputsDisabled(ancestor, el.checked, el.name);
}

function setChildInputsDisabled(el, disable, except)
{
  if ((el.tagName == 'INPUT' || el.tagName == 'SELECT') && el.name != except)
  {
    if (disable)
    {
      disableEl(el);
    }
    else
    {
      enableEl(el);
    }
  }
  if (el.childNodes.length > 0)
  {
    for (var i = 0; i < el.childNodes.length; i++)
    {
      setChildInputsDisabled(el.childNodes[i], disable, except);
    }
  }
}

function disableEl(el)
{
  if (el.tagName == undefined)
  {
    el = document.getElementById(el);
  }
  el.disabled = true;
}
function enableEl(el)
{
  if (el.tagName == undefined)
  {
    el = document.getElementById(el);
  }
  el.disabled = null;
}

function newImage(arg)
{
  if (document.images)
  {
    rslt = new Image();
    rslt.src = arg;
    return rslt;
  }
}

var imagePath = "/images/rmsite/common/";

var btnsShowHideLoaded = false;
var btnsShowHide = new Array();
function hideshow(id, imgel)
{
  if (!btnsShowHideLoaded)
  {
    btnsShowHide[0] = newImage(imagePath + "btn-collapse.jpg");
    btnsShowHide[1] = newImage(imagePath + "btn-expand.jpg");
    btnsShowHideLoaded = true;
  }
  var el = document.getElementById(id);
  if (el.style.display == 'none')
  {
    showElementById(id);
    imgel.src = btnsShowHide[0].src;
    
  }
  else
  {
    hideElementById(id);
    imgel.src = btnsShowHide[1].src;
  }
}

var activeTabs = new Array();
var inactiveTabs = new Array();
var activesPreloaded = false;
var inactivesPreloaded = false;
var tabIds = ['ProductDetails', 'ProdReviews', 'ProductVideos', 'ProductDocs'];
var curProdTab;
var curProdTabIndex;
var curTireTab;
var curTireTabIndex;
var curWheelTab;
var curWheelTabIndex;
var TIRE = 'tire';
var WHEEL = 'wheel';


function activateTabRollover(el,i)
{
  if (!activesPreloaded)
  {
    preloadActives();
  }
  var pageParam = false;
  if (el.tagName != 'IMG')
  {
    el = document.getElementById(el);
    pageParam = true;
  }
  if (el)
  {
    var tire = el.id.toLowerCase().match(TIRE);
    var wheel = el.id.toLowerCase().match(WHEEL);
    var query = window.location.search.substring(1);
    
    if (query.match('page'))
    {
      pageParam = true;
    }

    if ( (tire == null && wheel == null && (curProdTabIndex != i || pageParam)) ||
      (tire != null && i != curTireTabIndex) || (wheel != null && i != curWheelTabIndex) )
    {
      el.src = activeTabs[i].src;
    }
  }
}

function deactivateRollovers()
{
  for (var i = 0; i < arguments.length-1; i += 2)
  {
    var el = document.getElementById(arguments[i]);
    if (el)
    {
      if (!inactivesPreloaded)
      {
        preloadInactives();
      }
      el.src = inactiveTabs[arguments[i+1]].src;
    }
  }
}

function deactivateTabRollover(el, i)
{
  if (!inactivesPreloaded)
  {
    preloadInactives();
  }
  var tire = el.id.toLowerCase().match(TIRE);
  var wheel = el.id.toLowerCase().match(WHEEL);
  var query = window.location.search.substring(1);
  var pageParam = false;
  if (query.match('page'))
  {
    pageParam = true;
  }

  if ( (tire == null && wheel == null && (curProdTabIndex != i || pageParam)) ||
    (tire != null && i != curTireTabIndex) || (wheel != null && i != curWheelTabIndex) )
  {
    el.src = inactiveTabs[i].src;
  }
}

function preloadActives()
{
  if (document.images)
  {
    activeTabs[0] = newImage(imagePath + "tabs-active-01.jpg");
    activeTabs[1] = newImage(imagePath + "tabs-active-02.jpg");
    activeTabs[2] = newImage(imagePath + "tabs-active-03.jpg");
    activeTabs[3] = newImage(imagePath + "tabs-active-04.jpg");
    activesPreloaded = true;
  }
}

function preloadInactives()
{
  if (document.images)
  {
    inactiveTabs[0] = newImage(imagePath + "tabs-01.jpg");
    inactiveTabs[1] = newImage(imagePath + "tabs-02.jpg");
    inactiveTabs[2] = newImage(imagePath + "tabs-03.jpg");
    inactiveTabs[3] = newImage(imagePath + "tabs-04.jpg");
    inactivesPreloaded = true;
  }
}

function setActiveTab(prod, elid, index)
{
  if (prod == TIRE)
  {
    curTireTab = elid;
    curTireTabIndex = index;
  }
  else if (prod == WHEEL)
  {
    curWheelTab = elid;
    curWheelTabIndex = index;
  }
  else
  {
    curProdTab = elid;
    curProdTabIndex = index;
  }
  for ( var j = 0; j < tabIds.length; j++) {
	var i = document.getElementById(tabIds[j]);
	if (i){
	  i.style.display = 'none';
	}
   }
  document.getElementById(elid).style.display = 'block';
}

function showTab(elid, index)
{
  var el = document.getElementById(elid);
  if (el)
  {
    var active;
    var activeIndex;
    if (elid.match(TIRE))
    {
      active = document.getElementById(curTireTab);
      activeIndex = curTireTabIndex;
    }
    else if (elid.match(WHEEL))
    {
      active = document.getElementById(curWheelTab);
      activeIndex = curWheelTabIndex;
    }
    else
    {
      active = document.getElementById(curProdTab);
      activeIndex = curProdTabIndex;
    }
    if (active)
    {
      active.style.display = 'none';
    }
    el.style.display = 'block';
    if (elid.match(TIRE))
    {
      curTireTab = elid;
      curTireTabIndex = index;
    }
    else if (elid.match(WHEEL))
    {
      curWheelTab = elid;
      curWheelTabIndex = index;
    }
    else
    {
      curProdTab = elid;
      curProdTabIndex = index;
    }
  }
}

function verifyUsername(textFld, errSpan)
{
  var regex = /^[A-Za-z0-9._-]+$/;
  if (!textFld || textFld.tagName != 'INPUT')
  {
    textFld = document.getElementById(textFld);
  }
  if (!errSpan || errSpan.tagName != 'SPAN')
  {
    errSpan = document.getElementById(errSpan);
  }
  if (textFld && errSpan)
  {
    if (textFld.value)
    {
      if (!regex.test(textFld.value))
      {
        textFld.style.background = errorClr;
        errSpan.innerHTML = 'Only letters, numbers, hypens(-), underscores(_) and periods(.) are allowed.';
        errSpan.style.display = "block";
      }
      else
      {
        textFld.style.background = defaultClr;
        errSpan.style.display = "none";
      }

    }
  }
}

function clearCheckbox(el)
{
  if (el)
  {
    if (el.tagName == undefined)
    {
      el = document.getElementById(el);
    }
    el.checked = 'false';
  }
}

function clearZeroValue(el)
{
  if (el)
  {
    if (el.tagName == undefined)
    {
      el = document.getElementById(el);
    }
    if (parseFloat(el.value) == 0.0)
    {
      el.value = '';
    }
  }
}

function resetZeroValue(el)
{
  if (el)
  {
    if (el.tagName == undefined)
    {
      el = document.getElementById(el);
    }
    if (el && el.value)
    {
      if (el.value == '' || el.value.toLowerCase() == 'free' ||
        parseFloat(el.value) == 0.0)
      {
        el.value = (0.0).toFixed(2);
        el.style.background = defaultClr;
      }
    }
  }
}


function formatMoneyInput(el)
{
  if (el)
  {
    if (el.tagName == undefined)
    {
      el = document.getElementById(el);
    }
    if (el.value && !isNaN(el.value))
    {
      el.value = parseFloat(el.value).toFixed(2);
    }
  }
}

function formatMoneyAsString(amt)
{
  if (amt)
  {
    return '$' + parseFloat(amt).toFixed(2);
  }
  else
  {
    return '$0.00';
  }
}

/**
 * Checks/Unchecks all checkbox inputs that are descended from ancestor.
 * Parameter el must be a checkbox or the ID of a checkbox. All checkboxes
 * descended from ancestor will be checked or unchecked to match el
 */
function toggleCheckboxes(el, ancestor)
{
  if (!el)
  {
    return;
  }
  if (el.tagName != 'INPUT')
  {
    el = document.getElementById(el);
  }
  if (el.tagName != 'INPUT')
  {
    return;
  }

  if (ancestor.tagName == undefined)
  {
    ancestor = document.getElementById(ancestor);
  }
  if (!ancestor)
  {
    return;
  }
  toggleChildInputs(ancestor, el.checked);
}

function toggleChildInputs(el, check)
{
  if (el.tagName == 'INPUT')
  {
    if (check == true)
    {
      setInput(el);
    }
    else
    {
      unsetInput(el);
    }
  }
  if (el.childNodes.length > 0)
  {
    for (var i = 0; i < el.childNodes.length; i++)
    {
      toggleChildInputs(el.childNodes[i], check);
    }
  }
}
