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 urlencode(str) {
    return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

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";
  }
}

function Set_Cookie( name, value, expires)
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );
    
    /*
    if the expires variable is set, make the correct expires time, the current script below will set it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires ){
        expires =  parseInt(expires, 10) * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    
    document.cookie = name + "=" + escape( value ) + ";path=/" +( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" );
}

// 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 multipleItems = (numOfItems == 1) ? 's':'';
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
//
// this is duplicated from querystring.js

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 error;
	$('.quantity').each(function(i){
		var j = i+1;
		var quantity = document.getElementsByName('quantity_'+j)[0].value;
		var selection = document.getElementById('dropDown_'+j).value;
		if(quantity==0 || selection=='LABEL'){
			$('#selectFlag_'+j).show();
			$('.selectFlagFooter').show();
			error = true;
		}
		else if(quantity!=0 && selection!='LABEL'){
			$('#selectFlag_'+j).hide();
		}
		else{
			$('#selectFlag_'+j).hide();
			$('.selectFlagFooter').hide();
			error = false;
		}
	});
	if(error==true){
		return false;
	}
	else{
		return true;
	}
	
}

//new product validation for collection pages
function collectionsSelectVerifyAndSend(theFormSent) {
	
	var f = $(theFormSent);
	var returnValue = false;
	
	// check the dropdown and quantity for this form to make sure we have valuse in both
	if (($(theFormSent).find('.dropDown').val() === 'LABEL') || (parseInt($(theFormSent).find('input[name^="quantity"]').val())) <= 0) {
		// show the error message
		$(theFormSent).find('.selectFlagFooter').show();
	}
	else {
		// all good, put it in the cart
		returnValue = true;
		//hide the error
		$(theFormSent).find('.selectFlagFooter').hide();
	}
	
	if (returnValue) { //if evertything is okay
		// change the value in this marker field to make the ajax cart update happen
		$("input[name=URL]",f).val("/minicart?storeId=" + storeId);
		// update the minicart
		minicart.addToCart("/REIOrderItemUpdate?" + f.serialize());
	}
	return false;
}

//Product page validation for Collections pages
function checkSKUCollectionsSelect(){
	var error = new Array(), selectedItem = new Array();
	var returnValue = false;
	
	$('.quantity').each(function(i){//loop through each item on page
		var j = i+1;
		var quantity = parseInt(document.getElementsByName('quantity_'+j)[0].value);
		var selection = document.getElementById('dropDown_'+j).value;
		var selected = document.getElementById('selectCollectionCheckBox-'+j).checked;
		if(selected==true){
			if(quantity==0 || selection=='LABEL'){//either input value is invalid
				$('#selectFlag_'+j).show();
				$('.selectFlagFooter').show();
				selectedItem[i] = false;
				error[i] = true;
			}			
			if(quantity>0 && selection!='LABEL'){//valid inputs on both input fields
				$('#selectFlag_'+j).hide();
				$('.selectFlagFooter').hide();
				selectedItem[i] = true;
				error[i] = false;
			}
		}
		else{
			$('#selectFlag_'+j).hide();
                    		selectedItem[i] = false;
			error[i] = false;
		}
	});
	
	var oneSelectedItemPassed = false;
	var errorFound = false;
	for(var i=0; i<error.length; i++){//check productError array for input errors
		if(error[i]==false){//submit document.additem[form] here
		        if(selectedItem[i] == true){
		            oneSelectedItemPassed = true;
		        }
 		}
 		else{//found an error in the array
            $('.selectFlagFooter').show();
            errorFound = true;
            break;
 		}
 	}
	if (errorFound) {
		returnValue = false;
	} else {
		if(oneSelectedItemPassed){//want to remove form fields for unSelected Items here 	
            for(var j = 0; j<error.length; j++){
                if(selectedItem[j] == false){
                	removeUnselectedItemFromForm(j+1);
                }
            }
            returnValue = true;
		} else {
			$('.selectFlagFooter').show();
			returnValue = false;
		}
	}
	if (returnValue) {
		var f = $("#additem");
		$("input[name=URL]",f).val("/minicart?storeId=" + storeId);
		//minicart.addToCart("/REIOrderItemUpdate?" + f.serialize());
		
		if($('#addingToCart').length == 0){
			$('#collections_addToCart').append('<div id="addingToCart" style="margin-top:20px;"><b>adding your selection to cart, please wait...</b></div>');
		}
		$('#addingToCart').show();
		$('#addToCart').hide();
		minicart.addToCart("/REIOrderItemUpdate?" + f.serialize(), function(){
			$('#addingToCart').hide();
			$('#addToCart').show();
		});
		
	}
	
	try{
		restoreUnselectedItems();
	}
	catch(err){}

	return false;

	function removeUnselectedItemFromForm(itemPos){
    	if($('#dropDown_'  + itemPos).parents('.priceQtyWrapper').hasClass('item' + itemPos) == false){
    		$('#dropDown_'  + itemPos).parents('.priceQtyWrapper, .priceQty').addClass('item' + itemPos) ;
    		$('#dropDown_'  + itemPos).parents('.priceQtyWrapper').attr({targetClass : 'item' + itemPos}) ;
    	}
    	if($('#saguli_mu').length == 0){
    		$('#productCollections').append('<div id="saguli_mu"></div>');
    	}
    	$('#saguli_mu').append($('#dropDown_'  + itemPos).parents('.priceQtyWrapper'));
	}
	
	function restoreUnselectedItems(){
    	if($('#saguli_mu').length > 0){
    		$('.priceQtyWrapper', '#saguli_mu').each(function(index){
    			$('.priceQty.' + $(this).attr('targetClass')).append($(this));
    		});
    	}
	}
}

function getCheckedItems() {
    var subTotal = 0, returnTotal = 0, elemPos = 0, itemsSelected = 0;
    var cBoxes = document.additem.selectCollectionCheckBox;
    for (ii = 0; ii < cBoxes.length; ii++) {
        subTotal = 0;        

        if (cBoxes[ii].checked) {
            elemPos = cBoxes[ii].id;
                elemPos = elemPos.substring(elemPos.lastIndexOf('-')+1, elemPos.length);
                
            itemsSelected++;
            if (parseInt($("#quantity_" + elemPos).val()) > 0) {
                subTotal = getSubTotal(elemPos, getItemPrice(elemPos));
            }
        }
        returnTotal += subTotal;
    }
    $("#merchSubTotal").html(returnTotal.toFixed(2));
    $("#itemsSelected").html(itemsSelected);

}
function getItemPrice(pricePos){
        var itemPrice = $(".pricePara span#price_" + pricePos).html();
        itemPrice = itemPrice.substring(itemPrice.indexOf('$')+1, itemPrice.length);
        return parseFloat(itemPrice);
}
function getSubTotal(pricePos, itemPrice){
        var qty = $('#quantity_'  + pricePos).val();
        var returnVal = itemPrice * parseInt(qty);
        return returnVal;
}


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
	
/* create searchId cookie for SC event serialization */
function genSearchId(){        
               var newDate = new Date();
           
                      var myYear = newDate.getUTCFullYear();
                      myYear = myYear.toString();
                      myYear = myYear.substring(myYear.length-2,myYear.length);
                      
                      var myMonth = newDate.getUTCMonth() +1;
                      myMonth = myMonth < 10 ? ('0'+myMonth) : myMonth;
                      
                      var myDay = newDate.getUTCDate();                      
                      myDay = myDay < 10 ? ('0'+myDay) : myDay;                   
                      
                      var myMinutes = newDate.getUTCHours()*60 + newDate.getUTCMinutes();                         
                      var shortDate=myYear+myMonth+myDay;                        
                     
                     var newValue = shortDate+myMinutes+rei.util.randomID(10);
           
               Set_Cookie('searchId', newValue, 1);        	     
}
			
function checkSearchBoxValue(form){
	if(form){
	    var parentForm = form.headerQuery;
	    if (parentForm.value=='') {
	        var url = '/emptysearch';
	        if (storeClass == 'outlet') {
	        	url = '/outlet/emptysearch';
	        }
	        window.location.replace(url);
	        return false;
	    } else {
	        /* create searchId cookie for SC event serialization */
	       genSearchId();
	    }
	}else{
	    return false;
	}
}

function getUserInfoCookie(dIngredient){
	var cookieData = getCookie('rei_user_info');
	
		if(cookieData == null){
			return null;
		}
		else if(cookieData.length > 1){
			cookieData = cookieData.split('~');
		}
		else if(cookieData.length == 1){
			
		}
		else{ return null; }
			
		switch(dIngredient){
			case 'userName':
				if(cookieData.length > 1){
					return cookieData[0].toString();
				}
				else{
					return cookieData.toString();
				}
				break;
				
			case 'memberType':
				if(cookieData.length > 1){
					return cookieData[1].toLowerCase();				
				}
				else{
					return null;
				}
				break;
			
			case 'zipCode':
				break;				
		}
		
}










