/*
	_filterItems.js:
	
	Copyright 2007-2009 Eclectic Etc., Inc. ALL RIGHTS RESERVED
	
	Ajax items to server and automatically mark out-of-stock or discontinued items as such.
	
	aka - AUTOPUTO
	
   MODIFIED 7-FEB-2007 
   DEPLOYED 15-FEB-2007
   
      adds find in page functionality - either from picosearch search (rewires onsubmit event) or from
      a search term in the querystring (looks for ?s=(term to search))
  
      begins below at SEARCH STUFF!    

   MODIFIED 24-FEB-2007
   DEPLOYED 08-MAR-2007
   
      adds a link in [Out of Stock] to notify customers when item returns to stock.

   MODIFIED 12-MAR-2007
   DEPLOYED 12-MAR-2007
      
      look up prices of items and insert total price for ideas.  Also insert link to print the page.

   MODIFIED 20-MAR-2007
   DEPLOYED 21-MAR-2007
   
      ajax to find # of items and subtotal $ in cart, insert this just below cart link at top right of page

   MODIFIED 13-FEB-2008
   DEPLOYED 16-FEB-2008
   
      adds search for sale items in page and insert icon and sale price when found.  Supports "PUT ON SALE" initiative.
      
   MODIFIED 25-JAN-2009
   DEPLOYED ??
   
      look up side ads, customer testimonial, current year, squirt into left side and copyright statement
      modified mini cart code for new layout
      modified notify link to use highslide popup iframe
      
*/
   
	function scanforitems() {

		var str, i;
		
		str = '';
		
		if (window.document.URL.indexOf('dummy') > 0) return null;
				
		//walk through all forms:
		for (var l = 0; l < document.forms.length; l++) {
			//walk through all elements:
			if (document.forms[l].action == 'https://www.eebeads.com/cart.asp' || document.forms[l].action == 'https://www.eebeads-test.com/cart.asp' || document.forms[l].action == 'http://secureebeadscom/cart.asp') {
			   searchablePage = true;
				for (var m = 0; m < document.forms[l].length; m++) {
					//now check if this is a text box?:
					i = document.forms[l].elements[m].name;
					if (i != 'ID' && i != 'ADDALL' && i != 'idea') str += (str.length > 0 ? '&' : '') + ('e=' + i);
				}
			}
		}
		return str;
	}

   function ajax_getItemPrices(d) {
	  //try to set up the request object:
	  
	   try {
	     request_p = new XMLHttpRequest();
	   } catch (trymicrosoft) {
	     try {
	       request_p = new ActiveXObject("Msxml2.XMLHTTP");
	     } catch (othermicrosoft) {
	       try {
	         request_p = new ActiveXObject("Microsoft.XMLHTTP");
	       } catch (failed) {
	         request_p = false;
	       }  
	     }
	   }

	   // if (request_p) - we have XML connectivity.  send items & get list of prices: 
	   if (request_p) {
			//invoke JSGetFilters.asp to get filters:
			request_p.open("POST", "/advscripts/_ajaxGetItemPrices.asp", true);
			request_p.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request_p.onreadystatechange = GotPrices;
			request_p.send(d);
	   }
	}

	function GotPrices() {
       var str = '';
   
       var totalPrice = 0;
       var textInputs;
       var qty = 0;
   
	    if (request_p.readyState == 4) {
	       if (request_p.status == 200) {
				var rs = request_p.responseText;
            var x = eval('(' + rs + ')');
            if (x) {
               for (var p in x.prices) {
                  if (x.prices[p].indexOf('|') > -1) {
                     var price = x.prices[p].split('|');
                     str += 'item ' + p + ' costs $' + parseFloat(price[0]).toFixed(2) + ' ' + (price[1] == '0' ? 'not on sale' : 'on sale') + '\n';
                     textInputs = document.getElementsByName(p);
                     qty = (textInputs.length == 1 ? textInputs[0].value : 0);
                     totalPrice += (parseFloat(price[0]) * qty);
                     // writeItemPrice(p, parseFloat(price[0]).toFixed(2), price[1]);
                  } 
               }
            }
            //now find the ADDALL button and insert the total price:
            var addall = document.getElementsByName('ADDALL');
            if (addall.length == 1 && totalPrice > 0) {
               var addallparent = addall[0].parentNode;
               var totalPriceDiv = document.createElement('div');
               totalPriceDiv.className = 'IdeaTotalPrice';
               var totalPriceText = document.createTextNode('The total for this idea with the original quantities above is $' +  totalPrice.toFixed(2) + '.  You will have left over beads and findings.');
               totalPriceDiv.appendChild(totalPriceText);
               var brs = new Array();
               for (var b = 0; b < 6; b++) brs[b] = document.createElement('br');
               var a = document.createElement('a');
               a.href = '#';
               a.onclick = function() { window.print(); return false;};
               var t1 = document.createTextNode('Click Here');
               a.appendChild(t1);
               var t2 = document.createTextNode(' to print this page.');
               
               /* addallparent.insertBefore(totalPriceDiv, addall[0]);
               addallparent.insertBefore(brs[3], totalPriceDiv);
               addallparent.insertBefore(brs[0], addall[0]);
               addallparent.insertBefore(t2, addall[0]);
               addallparent.insertBefore(a, t2);
               addallparent.insertBefore(brs[2], addall[0]);
               addallparent.insertBefore(brs[4], addall[0]); */
			   addallparent.appendChild(brs[3]);
			   addallparent.appendChild(brs[0]);
			   addallparent.appendChild(totalPriceDiv);
			   addallparent.appendChild(brs[2]);
			   addallparent.appendChild(a);
			   addallparent.appendChild(t2);
			   addallparent.appendChild(brs[1]);
               
            }
				return;
			 } else {
			   //fail silently:
			   alert('Error - _ajaxGetItemPrices.asp returned status = ' + request_p.status);
			 }
	     }
	}


	function ajax_getiteminfo(d) {
	
	  //try to set up the request object:
	  
	   try {
	     request = new XMLHttpRequest();
	   } catch (trymicrosoft) {
	     try {
	       request = new ActiveXObject("Msxml2.XMLHTTP");
	     } catch (othermicrosoft) {
	       try {
	         request = new ActiveXObject("Microsoft.XMLHTTP");
	       } catch (failed) {
	         request = false;
	       }  
	     }
	   }

	   // if (request) - we have XML connectivity.  Begin by getting out of stock/discontinued filters: 
	   if (request) {
			//invoke JSGetFilters.asp to get filters:
			request.open("POST", "/advscripts/_ajaxGetItemStatus.asp", true);
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request.onreadystatechange = GotFilters;
			request.send(d);
	   }
	}


	function GotFilters() {

	    var thisfilter;

	    if (request.readyState == 4) {
	       if (request.status == 200) {
				var rs = request.responseText;
				if (rs.length > 1) {
					var x = eval('(' + rs + ')');
					if (x) {
						for (var f in x.filters) replaceItem(f, x.filters[f]);
					}
				}

            //new 13-FEB-2008 - check for items on sale:
            //if (window.document.URL.toLowerCase().indexOf('testsale') > 0) ajax_getsaleprices(items);
            ajax_getsaleprices(items);

				return;
			 }
	     }
	}


	function replaceItem(itm, ftype) {
		//replace the form element named itm with a [Out of Stock], or [Discontinued] (ideas)/[Sold Out] (regular pages) phrase:
		var i = document.getElementsByName(itm)[0];
      if (ftype != 'oos') {
		   var f = document.createElement("span");
		   f.className = "filter";
		   if (window.document.URL.toLowerCase().indexOf('/ideas/') > 0) {
		      var ft = document.createTextNode('[Discontinued]')
		   } else {
		      var ft = document.createTextNode('[Sold Out]')
		   }
		   f.appendChild(ft);
		   var j = i.parentNode;
		   j.replaceChild(f, i);
		} else {
		
		   //create the span with a link for notifying out of stock items:
		   var f = document.createElement("span");
		   f.className = "filter";
         var ft = document.createTextNode('[Out of Stock:');
         f.appendChild(ft);
         var a = document.createElement("a");
         a.className = "notifyLink";
         a.href = '/advscripts/notify2.asp?i=' + itm;
         a.onclick = function() { return hs.htmlExpand(this, { objectType: 'iframe', preserveContent: false, dimmingOpacity: 0.6, objectHeight: 248, outlineType: 'rounded-white'} )};
         a.title = 'Click Here to be notified by email when ' + itm + ' becomes available.';
         var at = document.createTextNode('Notify Me');
         a.appendChild(at);
         f.appendChild(a);
         var ft2 = document.createTextNode("]");
         f.appendChild(ft2);
         var j = i.parentNode;
         j.replaceChild(f, i);
         
		}
	}
            
	function ajax_getsaleprices(d) {
	
	  //try to set up the request object:
	  
	   try {
	     request_s = new XMLHttpRequest();
	   } catch (trymicrosoft) {
	     try {
	       request_s = new ActiveXObject("Msxml2.XMLHTTP");
	     } catch (othermicrosoft) {
	       try {
	         request_s = new ActiveXObject("Microsoft.XMLHTTP");
	       } catch (failed) {
	         request_s = false;
	       }  
	     }
	   }

	   // get sale prices for items on this page: 
	   if (request_s) {
			request_s.open("POST", "/advscripts/_ajaxGetSalePrices.asp", true);
			request_s.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request_s.onreadystatechange = GotSaleItems;
			request_s.send(d);
	   }
	}


	function GotSaleItems() {

	    if (request_s.readyState == 4) {
	       if (request_s.status == 200) {
            
				var rs = request_s.responseText;
				if (rs.length > 1) {
					var x = eval('(' + rs + ')');
					if (x) {
						for (var f in x.saleItems) ShowSalePrice(f, x.saleItems[f]);
					}
				}
				return;
			 }
	     }
	}


	function ShowSalePrice(itm, salePrice) {
		//append the sale price to the form element named itm:
		var i = document.getElementsByName(itm)[0];
      
      //hop around sale - set to true for live, false for not:
      var has = false;
      
      //only do this if it's still in the page:
      if (i) {
         
		   var f = document.createElement("span");
		   f.className = "salePrice";

	      var ft = document.createTextNode(' $' + CurrencyFormatted(salePrice))
         if (window.document.URL.toLowerCase().indexOf('_sale.html') == -1) {
            //display the sale icon for all pages except sale page (too visually crowded CSN):
            
            if (!has) {
               var im = document.createElement("img");
               im.src = '/_UI_Graphics/salesmall1.gif';
               im.height = 26; im.width = 35;
               im.className = 'saleIcon';
            } else {
               //Hop Around Sale!:
               var im = document.createElement("a");
               im.href = '/_dominoSale.html';
               im.title = 'This item is On Sale!  Click for more info on Domino\'s Hop Around Sale!';
               var im2 = document.createElement("img");
               im2.src = '/DominoSaleIcon3.gif';
               im2.height = 38; im2.width = 35;
               im2.className = "saleIcon2";
               im2.border = 0;
               im.appendChild(im2);
            }
            f.appendChild(im);
         } else {
            //put the word Sale: on the sale page (no icon):
            var ft1 = document.createTextNode(' Sale:');
            f.appendChild(ft1);
         }
		   f.appendChild(ft);
         
         if (i.nextSibling) { 
            //alert('item ' + itm + ' has a nextSibling?') 
            var j = i.nextSibling;
            i.parentNode.insertBefore(f, j);
         } else { 
            //alert('item ' + itm + ' is the Last In Line!') 
		      var j = i.parentNode;
		      j.appendChild(f);
         
         }		
      }
	}
   
   function CurrencyFormatted(amount) {
	   var i = parseFloat(amount);
	   if(isNaN(i)) { i = 0.00; }
	   var minus = '';
	   if(i < 0) { minus = '-'; }
	   i = Math.abs(i);
	   i = parseInt((i + .005) * 100);
	   i = i / 100;
	   s = new String(i);
	   if(s.indexOf('.') < 0) { s += '.00'; }
	   if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	   s = minus + s;
	   return s;
   }


	function notify_old(f) {

      
		if (!tnw || tnw.closed) {
			tnw = window.open('/advscripts/notify.asp?' + f,null,'height=200,width=450,status=no,toolbar=no,scrollbars=yes,resizable=no,menubar=no,location=no,left=200,top=200');
		} else {
			//tmw.moveTo(100,100);
			tnw.location = '/advscripts/notify.asp?' + f;
			tnw.focus();
		}
	}

	var tnw;

   /* Search functions */

   function findText(s) {

      /* cancel null strings: */
      if (s == '') return false;

      /* first clear any existing highlights: */
      var highlighted = document.getElementsByTagName('SPAN');
         
      for (var i = 0; i < highlighted.length; i++) if (highlighted[i].className == 'highlighted') {
         highlighted[i].style.backgroundColor = '';
         highlighted[i].style.color = '#000000';
         highlighted[i].className = '';
      }
    
      //reset result counter:
      finds = 0;

      //launch search if applicable:
      if (searchablePage) { 
         //don't look in the ideas pages:
         var lUrl = window.document.URL.toLowerCase();
         var x = lUrl.indexOf('/ideas/');
         if ((x == -1) && testSearchable(s)) {
            //not an idea - search in page:
            findString(s, document.body);
         } else {
            //fire off site-wide search:
            ajax_getSiteSearch(s);
            //shut off form post (we'll call it directly if no results from sitewide search:
            return false;
         }
      } else {
         //fire off site-wide search:
         ajax_getSiteSearch(s);
         //shut off form post (we'll call it directly if no results from sitewide search:
         return false;
      }
            
      //page search is done, result is in finds:
      if (finds > 0) {
         //reset for next search:
         finds = 0;
         return false;
      } else {
         //fire off sitewide search:
         ajax_getSiteSearch(s);
         //shut off form post (we'll call it directly if no results from sitewide search:
         return false;
      }
   }


   function testSearchable(s) {
      //limit in-page searching to items:
      if (s.length < 2) return false;
      var sLow = s.toLowerCase();
      if (isNaN(sLow.substr(0, 1))) {
         switch(sLow.substr(0, 1)) {
            case 'j':
               if ( (sLow.substr(1, 1) == '-') || (sLow.substr(1, 1) == 's') || (!(isNaN(sLow.substr(1, 1)))) ) {
                     return true;
                } else {
                  return false;
               }
            case 'd':
               if ( (sLow.substr(1, 1) == '-') || (sLow.substr(1, 1) == 'l') || (!(isNaN(sLow.substr(1, 1)))) ) {
                     return true;
                } else {
                  return false;
               }
            case 't':
               if ( (sLow.substr(1, 1) == '-') || (!(isNaN(sLow.substr(1, 1)))) ) {
                     return true;
                } else {
                  return false;
               }
            case 'e':
               if ( (sLow.substr(1, 1) == '-') || (!(isNaN(sLow.substr(1, 1)))) ) {
                     return true;
                } else {
                  return false;
               }
            case 'b':
               if ( (sLow.substr(1, 1) == 'k') && (!(isNaN(sLow.substr(2, 1)))) ) {
                     return true;
                } else {
                  return false;
               }
            default:
               return false;
         }   
      } else {
         return true;
      }
   
   }

   function highlight(x) {
         
      /* first clear any existing highlights: */
      var allSpans = document.getElementsByTagName('SPAN');
         
      for (var i = 0; i < allSpans.length; i++) if (allSpans[i].className == 'highlighted') {
         allSpans[i].style.backgroundColor = '';
         allSpans[i].style.color = '#000000';
         allSpans[i].className = '';
      }

      //reset vars and launch animation:
      hV.curRepeat = hV.repeats;
      hV.curValue = hV.startValue;
      hV.whichspan = x;
      hV.theSpan = document.getElementById('IFOUNDYOU' + x);
      hV.increment = Math.floor((hV.endValue - hV.startValue) / hV.steps);
      updateTheSpan();
      return false;
   }

   function updateTheTD() {
      
      var curR, curG, curB;
      curR = Math.floor(tdAnim.startR + (tdAnim.curstep * ((255 - tdAnim.startR) / tdAnim.steps)));
      curG = Math.floor(tdAnim.startG + (tdAnim.curstep * ((255 - tdAnim.startG) / tdAnim.steps)));
      curB = Math.floor(tdAnim.startB + (tdAnim.curstep * ((255 - tdAnim.startB) / tdAnim.steps)));
      if (curR > 255) curR = 255;if (curB > 255) curB = 255;if (curG > 255) curG = 255;
      tdAnim.theTD.style.backgroundColor = 'rgb(' + curR + ',' + curB + ',' + curG + ')';
      
      if (tdAnim.curstep++ < tdAnim.steps) {
         window.setTimeout(updateTheTD, Math.floor(tdAnim.millis - (tdAnim.curstep * 8.5)));
      } else {
         tdAnim.theTD.style.backgroundColor = '';
      }
   }

      
   function updateTheSpan() {

      if ((hV.curValue + hV.increment) > hV.endValue) {
         //in the animation:
         hV.curValue += hV.increment;
         //shift color:
         hV.theSpan.style.backgroundColor = 'rgb(' + hV.curValue + ',' + hV.curValue + ',255)';
         //adjust font color if necessary:
         hV.theSpan.style.color = (hV.curValue < 200) ? '#FFFFCC' : '#000000';
         //set up next iteration:
         hV.timerHandle = window.setTimeout(updateTheSpan, hV.millis);

      } else {
         //at end of this animation cycle:
         //var x = document.getElementById('IFOUNDYOU' + hV.whichspan);
         //remember this span for next search:
         hV.theSpan.className = 'highlighted';
         hV.theSpan.style.color = '#FFFFCC';
            
         if (--hV.curRepeat > 0) {
            //start over:
            hV.curValue = hV.startValue;
            hV.timerHandle = window.setTimeout(updateTheSpan, hV.millis);
         } 
      }
   }



   function findString(s, scopeNode){

   	var sLCase = s.toLowerCase();

      //break out of here if an item has been found:
      if (finds > 0) return;

   	for (var i=0; i < scopeNode.childNodes.length; i++) {
   		
   		//break out of here also:
   		if (finds > 0) break;
   		
   		var thisNode = scopeNode.childNodes[i];
         
   		if (thisNode.nodeType == 3) {
   			var nodeData = thisNode.data;
   			var nodeDataLCase = nodeData.toLowerCase();
   			if (nodeDataLCase.indexOf(sLCase) != -1) {
   				//s found!
   				
   				var nodeParent = thisNode.parentNode;
   				
   				while (nodeParent) {
   				   if (nodeParent.nodeType == 1 && nodeParent.nodeName.toLowerCase() == 'td') {
   				      //do something with it:
   				      //alert('found the td node!');
   				      //$.scrollTo(nodeParent, {duration:1000});
   				      $.scrollTo(nodeParent, 1000, {offset:-20});
   				      tdAnim.curstep = 0;
   				      tdAnim.theTD = nodeParent;
   				      window.setTimeout(updateTheTD, 1000);
   				      break;
   				   }
   				   //iterate up the chain:
   				   nodeParent = nodeParent.parentNode;
   				}
   				
   				
   				//create span to hold entire text:
   				var newSpanNode = document.createElement('SPAN');
   				//replace existing with new span node:
   				thisNode.parentNode.replaceChild(newSpanNode, thisNode);
   				//find location of s in text:
   				var sLocation = nodeDataLCase.indexOf(sLCase);
   				//append prepending text:
   				newSpanNode.appendChild(document.createTextNode(nodeData.substr(0, sLocation)));
   				//append found text inserting found span:
   				newSpanNode.appendChild(createFoundSpan(document.createTextNode(nodeData.substr(sLocation, s.length))));
   				//append rest of text:
   				newSpanNode.appendChild(document.createTextNode(nodeData.substr(sLocation + s.length)));
   				//increment finds:
   				finds++;
   				//get the new found span element and scroll to it:
   				var element = document.getElementById('IFOUNDYOU' + searches.toString());
   	         
   	         //before super scrolly:
   	         //window.scrollTo(0, findYPos(element) - 200);
               //after:
               //alert('about to scroll!');
               
               
               
               
               //launch highlight animation:
               highlight(searches);
               //increment searches:
   	         searches++;
   		   } //end s found
   		 } else {
   			//not a text node - recurse:
   			findString(s, thisNode);
   		 } //end if text node
   	} //end for loop

   } //end function


   function createFoundSpan(childNode){
      //create the SPAN node containing the found text, mark id to find it:
   	var newNode = document.createElement('SPAN');
   	newNode.setAttribute('id', 'IFOUNDYOU' + searches.toString());
   	newNode.appendChild(childNode);
   	return newNode;
   }

   function findYPos(el) {
      //find the y position of an element, adding all possible offsetParents:
   	var curY = 0;
   	if (el.offsetParent) {
   		curY = el.offsetTop;
   		while (el = el.offsetParent) {
   			curY += el.offsetTop;
   		}
   	}
   	return curY;
   }

   function checkForURLSearch() {
      //see if a search is specified in the url:      
      var x = window.document.URL.indexOf('s=');
      if ((x > -1) && testSearchable(window.document.URL.substr(x + 2))) {
         //get just the "s" part:
         var y = window.document.URL.indexOf('&', x);
         var s = (y > -1 ? window.document.URL.substr(x + 2, y - (x + 2)) : window.document.URL.substr(x + 2));
         findString(seedify(s), document.body);
      }
   }

   function interceptSearchForm() {

      var rewired = 0;
      
   	//walk through all forms:
   	for (var f = 0; f < document.forms.length; f++) {
   		//look for our picosearch index value:
   		for (var e = 0; e < document.forms[f].elements.length; e++) {
   		   if (document.forms[f].elements[e].name == 'index' && document.forms[f].elements[e].value == '159200') {
   			   //rewire it:
   			   document.forms[f].onsubmit = function() { return findText(seedify(this.query.value)); }
               rewired = 1;
               break;
   			}
   	   }
   	   //jump out if we found it:
   	   if (rewired > 0) break;
   	}
   }
   
   //phase 2 - also search sitewide.  begins 10-FEB-2007.  Thanks Jo!
   
	function ajax_getSiteSearch(s) {
	
	  //try to set up the request object:
	  
	   try {
	     request2 = new XMLHttpRequest();
	   } catch (trymicrosoft) {
	     try {
	       request2 = new ActiveXObject("Msxml2.XMLHTTP");
	     } catch (othermicrosoft) {
	       try {
	         request2 = new ActiveXObject("Microsoft.XMLHTTP");
	       } catch (failed) {
	         request2 = false;
	       }  
	     }
	   }

	   // if (request2) - we have XML connectivity.  
	   if (request2) {
	      //set up the timer to wait 5 seconds and go to picosearch if no results yet:
	      searchTimeout = window.setTimeout(siteSearchTimeout, 5000);
	      
			//invoke _ajax_sitesearch.asp to get result:
			request2.open("POST", "/advscripts/_ajax_sitesearch.asp", true);
			request2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request2.onreadystatechange = GotSiteSearch;
			request2.send("s=" + encodeURI(s));
	   }
	}


	function GotSiteSearch() {

	    if (request2.readyState == 4) {
	       if (request2.status == 200) {
				
            //cancel the timeout handler:
				window.clearTimeout(searchTimeout);
				
				var rs = request2.responseText;
				if (rs.length > 1) {
					//alert('_ajax_sitesearch.asp returned:\n\n' + rs);
					try {
					   var x = eval('(' + rs + ')');
					} catch(e) {
					   //alert('error in ajax response:\n\n' + e);
					   submitPico();
					   return;
					}
					if (x) {
					   //Item search?
					   if (x.hitType == 'Item') {
					      //Item search - append s=:
					      window.location.href = 'http://' + window.location.hostname + '/' + x.Page + '?s=' + x.Term;
					   } else {
					      //Simple page redirect:
					      window.location.href = 'http://' + window.location.hostname + '/' + x.Page;
					   }
					}
               					
				} else {
				   //alert('found nothing - engaging picosearch!');
				   submitPico();
				}
			 }
	     }
	}

   function siteSearchTimeout() {
      //it's been too long with no result - unhook the request and fire off the picosearch search:
      if (request2) request2.abort();
      
      //alert('Search timed out.  Call pico now...');
      submitPico();
            
   }
   
   function submitPico() {
   
      //finds the picosearch form and submits it.
      var foundit = 0;
      
   	//walk through all forms:
   	for (var f = 0; f < document.forms.length; f++) {
   		//look for our picosearch index value:
   		for (var e = 0; e < document.forms[f].elements.length; e++) {
   		   if (document.forms[f].elements[e].name == 'index' && document.forms[f].elements[e].value == '159200') {
   			   //submit it:
   			   document.forms[f].submit();
               foundit = 1;
               break;
   			}
   	   }
   	   //jump out if we found it:
   	   if (foundit > 0) break;
   	}
      
   }

   function checkForCartStats() {
      
      var CartID;
      
      //first see if we have a cookie:
      var allcookies = document.cookie;
      var pos = allcookies.indexOf('CartID='); //"CartIDTest=");
      if (pos != -1) {
         var start = pos + 7;
         var end = allcookies.indexOf(";", start);
         if (end == -1) end = allcookies.length;
         CartID = unescape(allcookies.substring(start, end));
      } else {
         //haven't been to the cart yet - don't do nuthin:
         //alert('checkForCartStats(): no cookies!');
         return;
      }
      
      //create the request and fire it off:
	   try {
	     request_c = new XMLHttpRequest();
	   } catch (trymicrosoft) {
	     try {
	       request_c = new ActiveXObject("Msxml2.XMLHTTP");
	     } catch (othermicrosoft) {
	       try {
	         request_c = new ActiveXObject("Microsoft.XMLHTTP");
	       } catch (failed) {
	         request_c = false;
	       }  
	     }
	   }

	   // if (request_c) - we have XML connectivity.  
	   if (request_c) {
			//invoke _ajax_getCartStats.asp to get results:
			request_c.open("POST", "/advscripts/_ajax_getCartStats.asp", true);
			request_c.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request_c.onreadystatechange = GotCartStats;
			request_c.send("cid=" + encodeURI(CartID));
	   }
   }

   function GotCartStats() {
	   if (request_c.readyState == 4) {
	      if (request_c.status == 200) {
				var rs = request_c.responseText;
            var stats = rs.split('|');
	         //alert('OK!\n\n_ajax_getCartStats.asp returned ' + rs + '\nitems: ' + stats[0] + '\nvalue: $' + stats[1]); 
	         //return;

	         var cbItems = document.getElementById('cartBoxItems');
	         var cbTotal = document.getElementById('cartBoxTotal');
	         
	         clearChildElements(cbItems);
	         clearChildElements(cbTotal);
	         
	         //alert('Items, Total should be cleared!');
	         
	         var cbIT = document.createTextNode(stats[0]);
	         var cbTT = document.createTextNode('$' + stats[1]);
	         
	         cbItems.appendChild(cbIT);
	         cbTotal.appendChild(cbTT);
	          
	      } else {
	        //alert('Error - _ajax_getCartStats.asp returned ' + request_c.status);
	      }
	   }
   
   }

   function getIEorMOZ() {
      if (navigator.appName.indexOf('Microsoft') != -1) { return 'IE' } else { return 'Moz'};
   }

   function redirectForms() {
      if (window.location.href.toLowerCase().indexOf('eebeads-test.com') != -1) {
         //redirect the form(s):
         for (var i = 0; i < document.forms.length; i++) if (document.forms[i].action.toLowerCase().indexOf('secureebeadscom') != -1) {
            document.forms[i].action = 'http://secure.eebeads-test.com/cart.asp';
         }
         //now change the linky:
         for (var j = 0; j < document.links.length; j++) if (document.links[j].href.toLowerCase().indexOf('secureebeadscom') != -1) {
            document.links[j].href = 'http://secure.eebeads-test.com/cart.asp';
         }
      }
   }

   function ajax_getSideItems() {
	  //try to set up the request object:
	  var page = document.URL;
	  
      try {
	     request_a = new XMLHttpRequest();
	   } catch (trymicrosoft) {
	     try {
	       request_a = new ActiveXObject("Msxml2.XMLHTTP");
	     } catch (othermicrosoft) {
	       try {
	         request_a = new ActiveXObject("Microsoft.XMLHTTP");
	       } catch (failed) {
	         request_a = false;
	       }  
	     }
	   }

	   // if (request_a) - we have XML connectivity.
	   if (request_a) {
			//invoke JSGetFilters.asp to get filters:
			request_a.open("POST", "/advscripts/_ajaxGetSideItems.asp", true);
			request_a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request_a.onreadystatechange = GotSideItems;
			request_a.send(page);
	   }
	}

	function GotSideItems() {
   
	    if (request_a.readyState == 4) {
	       if (request_a.status == 200) {
				var rs = request_a.responseText;
            var x = eval('(' + rs + ')');
            if (x) {
               for (var p in x.sidebits) {
                  switch (x.sidebits[p].type) {
                     case 'image':
                        showImage(x.sidebits[p]);
                        break;
                     case 'comment':
                        showComment(x.sidebits[p]);
                        break;
                     case 'year':
                        showYear(x.sidebits[p]);
                        break;
                     default:
                        break;
                  }
               }
            }
			 } else {
			   //fail silently:
			   alert('Error - _ajaxGetSideItems.asp returned status = ' + request_a.status);
			 }
	     }
	}

   function showImage(x) {
      var a = document.getElementById('AdArea');
      if (a) {
         var newDiv = document.createElement('div');
         newDiv.className = 'AdCopy';
         var newAnch = document.createElement('a');
         newAnch.href = x.url;
         var newImg = document.createElement('img');
         newImg.src = '/PromoPix/' + x.fn;
         newImg.alt = x.alt;
         newAnch.appendChild(newImg);
         newDiv.appendChild(newAnch);
         a.appendChild(newDiv);
      }
      
      //alert('call to show Image with FileName of ' + x.fn + ', url of ' + x.url + ', alt text of ' + x.alt);
   }
   
   function showComment(x) {

      /*<div class="AdCustComment">
         <p>I enjoy shopping here. The examples you have are a great help. I'm new at this and I am having a lot of fun. Thanks!!</p>
         <p class="CustCommentByLine">- Della Rose Pereira from California</p>

      </div> */
      var a = document.getElementById('AdArea');
      if (a) {
         var newDiv = document.createElement('div');
         newDiv.className = 'AdCustComment';
         var newP1 = document.createElement('p');
         var newP1T = document.createTextNode('"' + x.comment + '"');
         newP1.appendChild(newP1T);
         var newP2 = document.createElement('p');
         newP2.className = 'CustCommentByLine';
         var newP2T = document.createTextNode('- ' + x.custname + ' from ' + x.custcity);
         newP2.appendChild(newP2T);
		 var br = document.createElement('br');
		 var moreLink = document.createElement('a');
		 moreLink.href = '/CustComments.asp';
		 var moreLinkText = document.createTextNode('More...');
		 moreLink.appendChild(moreLinkText);
		 newP2.appendChild(br);
		 newP2.appendChild(moreLink);
         newDiv.appendChild(newP1);
         newDiv.appendChild(newP2);
         a.appendChild(newDiv);
      }
      //alert('call to show comment with text of ' + x.comment + ', cust name of ' + x.custname + ', location of ' + x.custcity);
      
   }

   function showYear(x) {
      //find the current year and replace it:
      //alert('call to replace current year with ' + x.value + '?');
      var oldYear = document.getElementById('curYear');
      if (oldYear) {
         var newSpan = document.createElement('span');
         var newYear = document.createTextNode(x.value);
         newSpan.appendChild(newYear);
         var a = oldYear.parentNode;
         a.replaceChild(newYear, oldYear);
      }
   }


   function clearChildElements(x) {
      if (x.hasChildNodes()) {
          while (x.childNodes.length >= 1) x.removeChild( x.firstChild );       
      }
   }
   
   function seedify(s) {
      // converts j112 to J-112 or dl1 to DL-1 for better finding in page:
      
      var firstChar = s.substr(0,1).toUpperCase();
      if (firstChar == 'E' || firstChar == 'J' || firstChar == 'T') {
         if (s.substr(1,1).search(/[0-9]/) != -1) {
            return firstChar + '-' + s.substring(1);
         } else {
            return s;
         }
      }
      if (firstChar == 'D') {
         if (s.substr(1,1).search(/[0-9]/) != -1) {
            return firstChar + '-' + s.substring(1);
         } else {
            if (s.substr(0,2).toUpperCase() == 'DL') {
               if (s.substr(2,1).search(/[0-9]/) != -1) {
                  return 'DL-' + s.substring(2);
               } else {
                  return s;
               }
         }  else
            return s;
         }
      } else {
         return s;
      }
   }


	//global context:
	var searchablePage = false;
	var request = false;
	var request_p = false;
	var request_c = false;
	var request_s = false;
	var request_a = false;

  //search specific global context:	
   //search counter:
   var searches = 1;
   //items found per search:
   var finds = 0;

   //xmlhttprequest object: 
   var request2 = false;

   //search timeout handler:
   var searchTimeout = null;

   //highlight animation specific vars:
   var hV = { 
         startValue:    255,  //animation start color
         endValue:      0,   //animation end color
         steps:         3,   //# of steps to animation
         millis:        100,   //millisecond wait between steps
         increment:     -8,   //color steps per iteration
         timerHandle:   null, //handle of timer to cancel - (not used)
         repeats:       9,    //number of times to repeat
         curValue:      255,  //current color value (volatile)
         curRepeat:     6,    //current repeat count (volatile)
         whichspan:     '1',   //which span to animate (volatile)
         theSpan:       null  //DOM element of span to animate
   };

   var tdAnim = {
      startR: 171,
      startG: 205,
      startB: 171,
      steps: 22,
      millis: 70,
      curstep: 0,  //volatile
      theTD: null  //volatile
   };
   
   var items;

   //autoexec.bat:
   
   $(document).ready(function(){
      //enable smooth scroll:
      $.localScroll();
      
      //get items for sale on this page:
      items = scanforitems();
   	
   	  if (items) ajax_getiteminfo(items);
	  
      checkForURLSearch();
      interceptSearchForm();

      //new 12-MAR-2007 - put current total price (and link to print) in ideas:
      if ((window.document.URL.toLowerCase().indexOf('/ideas/') > 0) && items) ajax_getItemPrices(items);

      //new 20-MAR-2007 - check for, insert cart values:
      checkForCartStats();

      //new 25-JAN-2009 - get ads + customer comments, squirt into page:
      ajax_getSideItems();

    });

   //for testing GetCartStats - redirect forms and links to correct domain:
   //redirectForms();
