function openWindow(surl,windowName,params) {
// We have to double-encode some URL strings to account for an IE bug where
// IE un-encodes the URL before passing it to this function. This line
// causes the function to un-encode the URL if the URL was double-encoded
// but was (correctly) passed without decoding by a sane browser.
  if (surl.indexOf('%2520') != -1) {
    surl = unescape(surl);
  }    
  windowHandle = window.open(surl,windowName,params);
    
  if(window.focus) {
    windowHandle.focus();
  }
}

// add a name and value dynamically to the hard-coded URL before calling openWindow().

function modURLOpenWindow(the_name, the_value,surl,windowName,params) {
  if ( (the_value!=null) && (the_name!=null)) {
    if (surl.indexOf('#')>=0) {
      xa = surl.split("#");
      if (xa[0].indexOf('?')>=0) {
        surl = xa[0] + '&' + the_name + '=' + the_value + '#' + xa[1];
      } else {
        surl = xa[0] + '?' + the_name + '=' + the_value + '#' + xa[1];
      }
    } else {
      if (surl.indexOf('?')>=0) {
        surl = surl + '&' + the_name + '=' + the_value ;
      } else {
        surl = surl + '?' + the_name + '=' + the_value ;
      }
    }
  }
  openWindow(surl,windowName,params);

}

function getCookieVal(offset) {
  var endstr = document.cookie.indexOf(";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal(j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}

function getAffiliateID() {
  var PAT = getCookie("PAT");
  var ID = 0;
  if(PAT != null) {
    var i = PAT.indexOf("=", 0) + 1;
    var j = PAT.indexOf(":", i);
    ID = PAT.substring(i, j);
  }
  return ID;
}

function stripSpaces(string) {
  while('' + string.charAt(string.length-1) == ' ')
    string = string.substring(0, string.length-1);
  while('' + string.charAt(0) == ' ')
    string = string.substring(1, string.length);
  return string;
}

function clearCookie(name) {
  document.cookie = name + "=" + "" + ";PATH=/";
}

function emailCheck (emailStr) {

/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */

var emailPat=/^(.+)@(.+)$/

/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address.
   These characters include ( ) < > @ , ; : \ " . [ ]    */

var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

/* The following string represents the range of characters allowed in a
   username or domainname.  It really states which chars aren't allowed. */

var validChars="\[^\\s" + specialChars + "\]"

/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")"

/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

/* The following string represents an atom (basically a series of
   non-special characters.) */

var atom=validChars + '+'

/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
   
var word="(" + atom + "|" + quotedUser + ")"

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$")

/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
   
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

/* Strip leading spaces */

while(''+emailStr.charAt(0)==' ')
  emailStr=emailStr.substring(1,emailStr.length);

/* Strip trailing spaces */

while(''+emailStr.charAt(emailStr.length-1)==' ')
  emailStr=emailStr.substring(0,emailStr.length-1);

/* Finally, let's start trying to figure out if the supplied address is
   valid. */

   if(emailStr.length == 0) {
     var errStr="You must enter a valid email address"
     alert(errStr)
     return false
   }

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat)
if (matchArray==null) {

  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */

  alert("The e-mail address must include a @ and a . to be valid. Please try again.")
  return false
}

var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid

if (user.match(userPat)==null) {

    // user is not valid

    alert("The e-mail address must include a username without spaces or punctuation.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat)

if (IPArray!=null) {

    // this is an IP address

    for (var i=1;i<=4;i++) {
      if (IPArray[i]>255) {
          alert("Destination IP in email address is invalid!")
          return false
      }
    }
    return true
}

// Domain is symbolic name

var domainArray=domain.match(domainPat)
if (domainArray==null) {
  alert("The e-mail address must include an extension: (.com, .org, .ca, etc.)")
  return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
   
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
    domArr[domArr.length-1].length>6) {
    
   // the address must end in a two letter or three letter word.

   alert("The e-mail address must include an extension: (.com, .org, .ca, etc.)")
   return false
}

// Make sure there's a host name preceding the domain.

if (len<2) {
   var errStr="The e-mail address must include an extension: (.com, .org, .ca, etc.)"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!

return true;
}

function printpage() {
  if (window.print != null) {
    window.print();
  } else {
    alert("Unfortunately, your browser does not support this shortcut.  Please select File and then Print from your browser's menu.");
  }
}

function setCookie(name, value) {
  document.cookie=name+"="+escape(value)+";PATH=/";
}

function DelCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path == null) ? "" : "; path=" + path) +
      ((domain == null) ? "" : "; domain=" + domain) +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}


// common_header processing (safe every page?)

var affiliateID = getAffiliateID();

if ((affiliateID == "9048" || affiliateID == "11917" || affiliateID == "14028" || affiliateID == "14172") && window.location.protocol == "https:") {
  if (top.location != self.location) {
    top.location = self.location;
  }
}

var numOfItems = getCookie("rei_cart");
var loggedIn = getCookie("loggedin");

if (!numOfItems) numOfItems = 0;


var cartStatusText = '';

if (document.title != "REI.com: Shopping Basket") {
    if (numOfItems == 1) {
        cartStatusText = '(contains ' + numOfItems + ' item)';
    } else {
        cartStatusText = '(contains ' + numOfItems + ' items)';
    }
}

// PLOONEY ADDITION
// Read the two GR cookies if they exist.

function ReadGRCookie (CookieName) {
    var gr_id = 0;
    var gr_event_type = "";
    var gr_event_date = "";
    var gr_personal_name = "";
    var which_cookie = "";

    var cook_obj = new Object();

    which_cookie = CookieName;
    
    var CookieString = document.cookie;
    var CookieSet = CookieString.split (';');
    var SetSize = CookieSet.length;
    var CookiePieces
    var ReturnValue = "";
    var x = 0;

    for (x = 0; ((x < SetSize) && (ReturnValue == "")); x++) {

        CookiePieces = CookieSet[x].split ('=');

        if (CookiePieces[0].substring (0,1) == ' ') {
            CookiePieces[0] = CookiePieces[0].substring (1, CookiePieces[0].length);
        }

        if (CookiePieces[0] == CookieName) {
            ReturnValue = CookiePieces[1];
        }
    }

    if (ReturnValue != "") {
        CleanRetVal = unescape(ReturnValue);
        RetArray = CleanRetVal.split(":");
        gr_id = RetArray[0];
        gr_event_type = RetArray[1];
        gr_event_date = RetArray[2];
        gr_personal_name = RetArray[3];

        //if (gr_id) alert(gr_id);
        //if (gr_personal_name) alert(gr_personal_name);

        var alertStr = "ID: " + gr_id + "\n" +
        "Name: " + gr_personal_name + "\n" +
        "Type: " + gr_event_type + "\n" +
        "Date: " + gr_event_date;
        
        cook_obj.cook_name = which_cookie;
        cook_obj.id = gr_id;
        cook_obj.event_type = gr_event_type ;
        cook_obj.event_date = gr_event_date ;
        cook_obj.personal_name = gr_personal_name ;

        return cook_obj;
    } 
}

var setup_cook_obj = ReadGRCookie("GiftRegistrySetup");

// END PLOONEY ADDITION

//
// QueryString
//

function QueryString(key) {
	var value = null;
	for (var i=0;i<QueryString.keys.length;i++)
	{
		if (QueryString.keys[i]==key)
		{
			value = QueryString.values[i];
			break;
		}
	}
	return value;
}
QueryString.keys = new Array();
QueryString.values = new Array();

function QueryString_Parse() {
	var query = window.location.search.substring(1);
	var pairs = query.split("&");
	
	for (var i=0;i<pairs.length;i++)
	{
		var pos = pairs[i].indexOf('=');
		if (pos >= 0)
		{
			var argname = pairs[i].substring(0,pos);
			var value = pairs[i].substring(pos+1);
			QueryString.keys[QueryString.keys.length] = argname;
			QueryString.values[QueryString.values.length] = value;		
		}
	}

}

QueryString_Parse();
  
// Product page check for MID pages

function checkSKUSelect() {
  var quantity = 0;
  var total = 0;
  var fieldNumber = 0;
  var quantityField = document.additem.quantity_1;
  for (var counter = 2; quantityField; counter++) {
    fieldNumber = counter - 1;
    quantity = quantityField.value;
    //alert("q = " + quantity + " for field " + fieldNumber);
    total += quantity;
    if (quantity > 0) { // Check quantity
      if (eval("document.additem.catEntryId_" + fieldNumber).value == "LABEL") { // Then check dropdown list
        alert("You must choose a size/color for each item selected!");
        quantityField.focus();
        quantityField.select();
        return false;
      }
    }
    quantityField = eval("document.additem.quantity_" + counter);
  }
  if(total == 0) {
    alert("All of the items you selected had 0 quantity indicated.\n\nPlease indicate quantities and click the \"Add to Shopping Cart\" button at the bottom of the page.");
    return false;
  }
  quantityField = document.additem.quantity_1;
  for (counter = 2; quantityField; counter++) {
    fieldNumber = counter - 1;
    quantity = quantityField.value;
  myField = eval("document.additem.catEntryId_" + fieldNumber);
    if (quantity < 1) { // Add dropdown value with no catalogId
      if (myField.options[0].value == "") {
        myField.options[0].selected = true;
      } else {
        myField.options[myField.length] = new Option ("--Choose your Color/Size--","");
        myField.options[myField.length-1].selected = true;
      }
  }
    quantityField = eval("document.additem.quantity_" + counter);
  }
  return true;
}

function escapeHTML (str) {
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}


//Put onKeyPress="onReturnKeySubmit(this)" in any <form> element that you want to force to submit when the "return" or "enter" keys are pressed.
//NOTE: Textareas in forms should be able to accept "return" values without the form submitting. This function may need to be modified to support textareas.

function onReturnKeySubmit(theForm, theFn, thePar){
	

	if (window.event)
	{
    var node = (event.target) ? event.target : ((event.srcElement) ? event.srcElement : null);

 if (node.type && node.type != "textarea")
 {
 try
 { 
  if(event.keyCode == 13)
  {
  if (!theFn){
   theForm.submit();
  }
  else
  {
  theFn(thePar);
  }
  }
  
 }
 catch(err)
 {
  try
  {
   if(event.which == 13)
   
   if (!theFn){
  
  theForm.submit();
  }
  else
  {
  
  theFn(thePar);
  }
  
  
  }
  catch(err){}
  }
 }
}
}


// this code fixes the IE6 flicker bug 
try {
document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}
// end IE6 flicker bug fix
			