function openNewWindow(whichUrl) 
{
  newWin = window.open(whichUrl, 'newWin', 'scrollbars=1,resizable=1,width=780,height=580');
  newWin.focus();
}

function openHelpWindow(whichUrl) 
{
  window.open(whichUrl, 'helpWin', 'scrollbars=1,resizable=1,width=680,height=580');
}

function openCouponWindow(whichUrl) 
{
  window.open(whichUrl, 'newWin', 'scrollbars=0,resizable=0,width=520,height=490');
}

function openWishListWindow(whichUrl) 
{
  window.open(whichUrl, 'newWin', 'scrollbars=1,resizable=1,width=975,height=600');
}
function openFlexWindow(whichUrl,width,height,top,left)
{
  params = "'scrollbars=0,resizable=0,width=" + width + ",height=" + height + "top=" + top + ",left=" + left + "'";
  window.open(whichUrl, 'newWin', params);
}

// Swaps (sets or unsets) a style class on a given tag
function swapClass(tagID, setClass, unsetClass)
{
	var tag = document.getElementById(tagID);
	if (unsetClass != null)
		tag.className = tag.className.replace(new RegExp("\\s*" + unsetClass + ""), "");
	if (setClass != null)
		tag.className += " " + setClass;
}

// Jumps the page to the specified anchor
function jumpTo(position)
{
	// remove any previous anchor and jump
 	window.location = String(window.location).replace(/\#.*$/, "") + "#" + position;
}

// -------------------------------------------------------------------------------
// CREDIT - formatCurrency
// Originator:  Cyanide_7 (leo7278@hotmail.com) http://www7.ewebcity.com/cyanide7
// Copied From:  http://javascript.internet.com/forms/currency-format.html
// -------------------------------------------------------------------------------
function formatCurrency(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

// Clears the value for a text input field if that text matches the given text
function clearValue(elem, text)
{
	if (elem.value == text) elem.value = "";
}

// -------------------------------------------------------------------------------
// CREDIT - selectRange
// Adapted From:  http://www.webreference.com/programming/javascript/ncz/
// -------------------------------------------------------------------------------
function selectRange(elem, beg, len) 
{
	if (elem.createTextRange)
	{
        var oRange = elem.createTextRange(); 
        oRange.moveStart("character", beg); 
        oRange.moveEnd("character", len - elem.value.length); 
        oRange.select();
    } 
    else if (elem.setSelectionRange) 
    {
        elem.setSelectionRange(beg, len);
    }
    
    elem.focus(); 
}

function nextField(tabIndex, range)
{
	for (i = tabIndex + 1;i<range + 1; i++)
	{
		for (j = 0, jsz=document.forms.length;j<jsz;j++)
		{
			for (k = 0, ksz=document.forms[j].elements.length;k<ksz;k++)
			{
				if (document.forms[j].elements[k].tabIndex == tabIndex + i)
					return document.forms[j].elements[k];
			}
		}		
	}
	
	return null;
}

// Returns a URL parameter string for selective fields (matching the given
// regular expression) of a form (specified by id).  The string does not
// include the '?'.  
function formParams(formID, submitID, fieldRE)
{
	var paramString = '';
	var fields = document.getElementById(formID).elements;

	var matcher = new RegExp(fieldRE);
	for (var i=0;i<fields.length;i++)
	{
		var field = fields[i];
		if (field.name.match(matcher))
		{
			if (paramString.length > 0) paramString += '&';
			if (submitID == field.name)
				paramString += "submit=" + field.name;
			else
				paramString += field.name + '=' + encodeURIComponent(field.value);
		}
	}
	return paramString;
}

// Returns a URL parameter string for selective fields (matching the given
// regular expression) of a form (specified by id).  The string does not
// include the '?'.  Returns only selected form fields and fields contained 
// in Div (specified by wlDivID).
function formParamWishList(formID, submitID, wlDivID, fieldRE)
{
	var paramString = '';
	var fields = document.getElementById(formID).elements;

        // Add form fields to param string, stop when GIFT_REGISTRY_HEADER<>grh_id is reached.   
	var matcher = new RegExp(fieldRE);       
	for (var i=0;i<fields.length;i++)
	{
		var field = fields[i];
               
		if (field.name.match(matcher))
		{
			if (paramString.length > 0) paramString += '&';
                       
			if (submitID == field.name)
				paramString += "submit=" + field.name;
			else
                            paramString += field.name + '=' + encodeURI(field.value)+"\n"; 

                        if (field.name == "GIFT_REGISTRY_HEADER<>grh_id") {
                           break;
                        }
		}
	}

        // Add element fields of DIV to param string.
        var myDiv =  document.getElementById( wlDivID );
        var inputArr =myDiv.getElementsByTagName("input");    
        for (var i = 0; i < inputArr.length; i++) {           
            var field = inputArr[i];
            switch(inputArr[i].type) {
                case "hidden":
                case "text":
                case "submit":
                    paramString += '&';
                    paramString += inputArr[i].name + '=' + encodeURI(inputArr[i].value) +"\n"; 
                    break;
            } 
         }        

	return paramString;
}

// Clears the value of all the fields with names matching the [fieldRE]
// regular expression in the form identified by [formID].
function clearFormFields(formID, fieldRE)
{
	var fields = document.getElementById(formID).elements;
	var matcher = new RegExp(fieldRE);
	for (var i=0;i<fields.length;i++)
	{
		var field = fields[i];
		if (field.name.match(matcher)) field.value = "";
	}
}

function prependValue(fieldID, preVal)
{
	var field = document.getElementById(fieldID);
	field.value = preVal + field.value;
}

function submitForm(formID, submitID, destUrl, func)
{
	if (!destUrl) destUrl = '/home/service/svc_dummy_page.jsp';
	sendXMLRequest('POST', destUrl, func, formParams(formID, submitID, '.*'));
}

function submitFormWishList(formID, submitID, wlDivID, destUrl, func)
{
	if (!destUrl) destUrl = '/home/service/svc_dummy_page.jsp';
	sendXMLRequest('POST', destUrl, func, formParamWishList(formID, submitID, wlDivID, '.*'));
}

// Replaces the content of the element specified by [elemID] with the
// responseText in [xmlhttp].
function replaceContent(xmlhttp, elemID)
{
	var element = document.getElementById(elemID);
	element.innerHTML = xmlhttp.responseText;
}

// Returns true if a quantity field is found on the page with a value greater than
// 0 
function checkCartQty(formIdent)
{
  var form, elements, i, elm; 
  form = document.getElementById 
    ? document.getElementById(formIdent) 
    : document.forms[formIdent]; 

    if (document.getElementsByTagName)
    {     
        elements = form.getElementsByTagName('input');
        for( i=0, elm; elm=elements.item(i++); )
        {
            if (elm.getAttribute('type') == "text") {

                if (elm.name == "ADD_CART_ITEM_ARRAY<>quantity") {               
                    if (elm.value > 0) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

// Returns true if valid text is found in the ATR_crt_txt_personalization
// field(s)
function checkPersonalization(formIdent)
{
  var form, elements, i, elm; 
  var matchesPattern = true;
  var isBlank = false;
  var allowBlank = false;
  var pattern = new RegExp("^[A-Za-z0-9 \\-\\.,]*$");
  //var pattern = new RegExp('^[A-Za-z0-9 \-\.,]*$');
  form = document.getElementById 
    ? document.getElementById(formIdent) 
    : document.forms[formIdent]; 

    if (document.getElementsByTagName)
    {     
        elements = form.getElementsByTagName('input');
        for( i=0, elm; elm=elements.item(i++); )
        {
            if (elm.getAttribute('type') == "checkbox") {
                if (elm.name == "ADD_CART_ITEM_ARRAY<>ATR_crt_txt_pers_blank") {               
                    if ( elm.checked == true ) {
                        allowBlank = true;
                    }
                }
            }

            if (elm.getAttribute('type') == "text") {

                if (elm.name == "ADD_CART_ITEM_ARRAY<>ATR_crt_txt_personalization") {               
                    if ( elm.value == "" ) {
                        isBlank = true;
                    } else {
                        if ( ! elm.value.match(pattern) ) {
                            matchesPattern = false;
                        }
                    }
                }
            }
        }
    }
 
    if ( isBlank ) {
      if ( allowBlank ) {
        return "";
      } else {
        return "blank";
      }
    }
    else {
      if ( allowBlank ) {
        return "blank";
      }
      else if ( matchesPattern ) {
        return "";
      } else {
        return "pattern";
      }
    }
}

function isInteger (s)
{
      var i;
      if (isEmpty(s))
      if (isInteger.arguments.length == 1) return 0;
      else return (isInteger.arguments[1] == true);

      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);

         if (!isDigit(c)) return false;
      }

      return true;
}
function isEmpty(s)
{
      return ((s == null) || (s.length == 0))
}

function isDigit (c)
{
      return ((c >= "0") && (c <= "9"))
}

function validateCartQty(formIdent)
{

  var form, elements, i, elm; 
  form = document.getElementById 
    ? document.getElementById(formIdent) 
    : document.forms[formIdent]; 

    if (document.getElementsByTagName)
    {     
        elements = form.getElementsByTagName('input');
        for( i=0, elm; elm=elements.item(i++); )
        {
            if (elm.getAttribute('type') == "text" && elm.name == "ADD_CART_ITEM_ARRAY<>quantity" && !isInteger(elm.value) && !isEmpty(elm.value)) {
                        return false;
            }
        }
    }
    return true;
}

function validateCartQtyWishlist(formIdent,wlDivID)
{
    var myDiv, elements, i, elm; 
    myDiv =  document.getElementById( wlDivID );
    elements = myDiv.getElementsByTagName("input");    
    for( i=0, elm; elm=elements.item(i++); )
    {
        if (elm.getAttribute('type') == "text" && elm.name == "ADD_CART_ITEM_ARRAY<>quantity" && !isInteger(elm.value) && !isEmpty(elm.value)) {
                    return false;
        }
    }
    return true;
}

// Properly prepares a form button with an onClick event that
//   1. Sets the okToSubmit value
//   2. Consumes additional clicks (beyond the first one)
function setupButtonOnClickEvent(button)
{
	if (button instanceof String) button = document.getElementByID(button)

	button.clickCounter = 0;
	button.onclick = function()
	{
		this.clickCounter ++;
		okToSubmit = this.clickCounter <= 1;
		return okToSubmit;
	};
}


function setupImageButtonOnClickEvents()
{
	var tags = document.getElementsByTagName("input");
	for (var h=0;h<tags.length;h++)
		if ("image" == tags[h].type) setupButtonOnClickEvent(tags[h]);
}

//   Disables place order image button when clicked
function disablePlaceOrderButtonOnClickEvent()
{
             var submitButton1 = document.getElementById("placeOrder_1");
             var submitImage1 = document.getElementById("img_placeOrder_1");
             var submitButton2 = document.getElementById("placeOrder_2");
             var submitImage2 = document.getElementById("img_placeOrder_2");

             if (submitButton1 != null) {
                submitButton1.style.display='none';
             } 
             if (submitImage1 != null) {  
                submitImage1.style.display='inline';
             }
 
             if (submitButton2 != null) {
                submitButton2.style.display='none';
             } 
             if (submitImage2 != null) {  
                submitImage2.style.display='inline';
             }
}

function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

function selectOtherProgramTitle() {
  if ( document.getElementById('VIPREGISTRATION<>TITLE').options[document.getElementById('VIPREGISTRATION<>TITLE').selectedIndex].text == "Other" ) {
    document.getElementById('titleOther').style.display="";
  }
  else {
    document.getElementById('titleOther').style.display="none";
  }
  if ( document.getElementById('VIPREGISTRATION<>PROGRAM').options[document.getElementById('VIPREGISTRATION<>PROGRAM').selectedIndex].text == "Other" ) {
    document.getElementById('programOther').style.display="";
  }
  else {
    document.getElementById('programOther').style.display="none";
  }
}

function checkSafetyWarnings(s1, s2, s3, s4) {
    if (s1 == 1 & s2 == 1 & s3 == 1) {
        showSafetyWarnings('smallPartsBallMarbleWarning');
    } else if (s1 == 1 & s2 == 1) {
        showSafetyWarnings('smallPartsBallWarning');
    } else if (s1 == 1 & s3 == 1) {
        showSafetyWarnings('smallPartsMarbleWarning');
    } else if (s2 == 1 & s3 == 1) {
        showSafetyWarnings('smallBallMarbleWarning');
    } else if (s1 == 1) {
        showSafetyWarnings('smallPartsWarning');
    } else if (s2 == 1) {
        showSafetyWarnings('smallBallWarning');
    } else if (s3 == 1) {
        showSafetyWarnings('marbleWarning');
    }
    if (s4 == 1) {
        showSafetyWarnings('balloonWarning');
    }
    if (s1 + s2 + s3 + s4 > 0) {
        showSafetyWarnings('safetyHref'); 
        showSafetyWarnings('safetyHRule'); 
    }
}

function showSafetyWarnings(objId) {
    var elem = document.getElementById(objId);
    if (elem) elem.style.display = 'block';
}

function createBVReviewDropdown(sku) {
//    sku[1] = 'RE190X-Classroom Classics CD Read-Alongs - Set 1';
//    '<option value="RA601">MY ITEM-2</option>'
    var code = "";
//    var desc = "";
    var itemReview = document.getElementById('itemReview');
    if (sku.length == 1) {
        // only 1 product so hide the itemReview dropdown.
        itemReview.style.display = 'none';
    } else {
        itemReview.style.display = 'inline';
        itemReview.options[0] = new Option('Select an item to review','');
        for (i = 0; i < sku.length; i++) {

            sku[i] = sku[i].replace("&#8217;", "'");
            sku[i] = sku[i].replace("&#146;", "'");
            sku[i] = sku[i].replace("&#34;", '"');
            sku[i] = sku[i].replace("&#147;", '"');           // curly double quotes
            sku[i] = sku[i].replace("&#148;", '"');           // curly double quotes
            sku[i] = sku[i].replace("&#8220;", '"');          // curly double quotes
            sku[i] = sku[i].replace("&#8221;", '"');          // curly double quotes
            sku[i] = sku[i].replace("&#151;", '-');           // long dash
            sku[i] = sku[i].replace("&#8212;", '-');          // long dash
            sku[i] = sku[i].replace("&#8482;", "");           // (TM)
            sku[i] = sku[i].replace("&#174;", "");            // (R)
            sku[i] = sku[i].replace("&#161;", "");            // spanish upside down !
            sku[i] = sku[i].replace("&#225;", "");            // spanish accent a
            sku[i] = sku[i].replace("&#233;", "");            // spanish accent e
            sku[i] = sku[i].replace("&#237;", "");            // spanish accent i
            sku[i] = sku[i].replace("&#243;", "");            // spanish accent o
            sku[i] = sku[i].replace("&#241;", "n");           // spanish enya n
            sku[i] = sku[i].replace("&#226;", "");            // carrot on top of a
            sku[i] = sku[i].replace("&#133;", "...");   
            sku[i] = sku[i].replace("&#8230;", "...");             
 
            code = sku[i].substring(0, sku[i].indexOf('-'));
            //desc = sku[i].substring(sku[i].indexOf('-')+1, sku[i].length);
            itemReview.options[i+1] = new Option(sku[i],code);
        }
    }
}

function setFeatureItemCartQty(objID){
    var formProd = document.getElementById(objID);
    if (formProd) formProd.value=1;
}

function trim(str) { 
    charFound = false;
    i = 0;

    while (( i < str.length ) && (!charFound)) {
    if (str.charAt(i) != " ") {
      charFound = true;
      str = str.substring(i, str.length);
    }
    i++;
    }

    if (charFound) {
    endCharFound = false;
    i = str.length - 1;
    while (( i >= 0) && (!endCharFound)) {
      if (str.charAt(i) != " ") {
        endCharFound = true;
        str = str.substring(0, i+1);
      }
      i--;
    }
    return str;
    } else {
    return "";
    }
}

function nextField(from, to) {
	if(from.getAttribute("maxlength") == from.value.length) {
		document.getElementById(to).focus();
		document.getElementById(to).select();
	}
}

function disableTab(event) {
	var e = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (e == 9) {
		return false;
	}
	return true;
}

function PDFLink(filename) {
    pageTracker._trackPageview(filename);
    var PDFWindow = window.open('/fileRedirect.jsp?filename=' + filename, 'newWin', 'scrollbars=yes,status=no,width=600,height=500,resizable=yes');
    return;
}

