var hex_chr = "0123456789abcdef";
function rhex(num)
{
  str = "";
  for(j = 0; j <= 3; j++)
    str += hex_chr.charAt((num >> (j * 8 + 4)) & 0x0F) + hex_chr.charAt((num >> (j * 8)) & 0x0F);
  return str;
}
function str2blks_MD5(str)
{
  nblk = ((str.length + 8) >> 6) + 1;
  blks = new Array(nblk * 16);
  for(i = 0; i < nblk * 16; i++) blks[i] = 0;
  for(i = 0; i < str.length; i++) blks[i >> 2] |= str.charCodeAt(i) << ((i % 4) * 8);
  blks[i >> 2] |= 0x80 << ((i % 4) * 8);
  blks[nblk * 16 - 2] = str.length * 8;
  return blks;
}
function add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}
function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}
function cmn(q, a, b, x, s, t)
{
  return add(rol(add(add(a, q), add(x, t)), s), b);
}
function ff(a, b, c, d, x, s, t)
{
  return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t)
{
  return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t)
{
  return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t)
{
  return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function calcMD5(str)
{
  x = str2blks_MD5(str);
  a =  1732584193;
  b = -271733879;
  c = -1732584194;
  d =  271733878;

  for(i = 0; i < x.length; i += 16)
  {
    olda = a; oldb = b;
    oldc = c; oldd = d;
    a = ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = ff(c, d, a, b, x[i+10], 17, -42063);
    b = ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = ff(d, a, b, c, x[i+13], 12, -40341101);
    c = ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = ff(b, c, d, a, x[i+15], 22,  1236535329);    

    a = gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = gg(c, d, a, b, x[i+11], 14,  643717713);
    b = gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = gg(c, d, a, b, x[i+15], 14, -660478335);
    b = gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = gg(b, c, d, a, x[i+12], 20, -1926607734);
    
    a = hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = hh(b, c, d, a, x[i+14], 23, -35309556);
    a = hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = hh(d, a, b, c, x[i+12], 11, -421815835);
    c = hh(c, d, a, b, x[i+15], 16,  530742520);
    b = hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = ii(c, d, a, b, x[i+10], 15, -1051523);
    b = ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = ii(d, a, b, c, x[i+15], 10, -30611744);
    c = ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = add(a, olda);
    b = add(b, oldb);
    c = add(c, oldc);
    d = add(d, oldd);
  }
  return rhex(a) + rhex(b) + rhex(c) + rhex(d);
}

    RecentComparisonHistory.settings.cookieHost = '.pricegrabber.com';

		function sortFilter(a, b) {
			var aValue = a.name;
			var bValue = b.name;
			if      (aValue == bValue) return  0;
			else if (aValue < bValue)  return -1;
			else                       return  1;
		}

		function filters_showAll(elem) {
			var filterDiv = elem.parentNode.parentNode.parentNode;
			if (!filterDiv) throw new Error('Unable to locate filter div element');
			var filterList = filterDiv.getElementsByTagName('ul')[0];
			if (!filterList) throw new Error('Unable to locate filter list element');
			filterList.removeChild(elem.parentNode);
			var list = filterList.getElementsByTagName('li');
			var ordered = new Array;
			for (var i=list.length - 1; i>=0; i--) {
				var li = list.item(i);
				if (li) {
					var name = li.firstChild.firstChild.nodeValue;
					ordered[ordered.length] = { name: name, node: li };
					filterList.removeChild(li);
				}
			}
			ordered.sort(sortFilter);
			for (var i=0; i<ordered.length; i++) {
				filter = ordered[i];
				if (!filter) throw new Error('filter is undefined');
				filter.node.style.display = '';
				filterList.appendChild(filter.node);
			}
			filterDiv.className = 'expanded';
		}


		AgentSmith = new Object();

		AgentSmith.client = 'BOT';

		// bot tracker image
		AgentSmith.img = new Image();

		AgentSmith.assignEvents = function () {

			// assume bot or spider
			var anchors = document.getElementsByTagName('a');

			for ( var i = 0; i < anchors.length; i++ ) {
				if ( anchors[i].href && anchors[i].href.match('rd.php') ) {
					window.addEvent(anchors[i], 'click', function(e) {

						if ( AgentSmith.client != 'BOT' ) {
							var reg = /\/k=([^\/]+)/i;
							var matches = reg.exec(this.href);

							AgentSmith.img.src = '/agntsmth.php/'+ matches[1];
						}

					}, anchors[i], true);
					window.addEvent(anchors[i], 'mouseover', function(e) { AgentSmith.client = 'USR'; }, document, true);
					window.addEvent(anchors[i], 'mouseout',  function(e) { AgentSmith.client = 'USR'; }, document, true);
				}
			}

		}

		function toggleCompareCbx(elem) {
			var masterId = elem.value;
			var pageId   = 0;
			var catName  = "";
			var langId   = "en";
			RecentComparisonHistory.toggleMasterId(pageId, masterId, catName, langId);
			RecentComparisonHistory.createCookie();
		}

		function pg_openPromo(src) {
			url = '/info_rebate.php?masterid='+src;
			window.open(url, 'promo','height=450,width=550,innerHeight=450,innerWidth=550,menubar=no,status=no,toolbar=no,resizable=yes,scrollbars=yes');
		}
		function attrib_toggles(subnum,subtype) {
			if ( subtype == 'a' ) {
				document.getElementById("sub" + subnum + "_a").style.display = "none";
				document.getElementById("sub" + subnum + "_b").style.display = "block";
			}
			else if ( subtype == 'b' ) {
				document.getElementById("sub" + subnum + "_a").style.display = "block";
				document.getElementById("sub" + subnum + "_b").style.display = "none";
			}
		}

		function newToggleCompareCbx(elem) { 
			var masterId = elem.value; 
			var pageId   = 0; 
			var catName  = ""; 
			var langId   = "en"; 

			RecentComparisonHistory.newToggleMasterId(pageId, masterId, catName, langId,compareText0, compareText1,compareText2);
			RecentComparisonHistory.createCookie();
		}


		function toggle_check(object){
			var cb = document.getElementById("checkbox_" + object.name);
			if (cb.checked)
			{
				cb.checked = false;
			}
			else
			{
				cb.checked = true;
			}

		}


		function compare_toggle_check(object){
			var cb = document.getElementById("productCompareCheckbox" + object.name);
			if (cb.checked)
			{
				cb.checked = false;
			}
			else
			{
				cb.checked = true;
			}

		}

		function toggle_children( id ){
			var parent_em = document.getElementById('checkbox_' + id);
			var i = 0;
			while (em = document.getElementById('checkbox_' + id + '_' + i)) {
				if (parent_em.checked == true){
					em.checked = true;
				}else{
					em.checked = false;
				}
				i++;
			}
		}

		function toggle_parent( id ){

			var num_checked = 0;
			var i = id.lastIndexOf('_');
			var parent_id = id.substr(0, i);
			var parent_em = document.getElementById('checkbox_' + parent_id);
			var em = document.getElementById('checkbox_' + id);

			if (em.checked == false) {
				parent_em.checked = false;
			}

			i = 0;
			while (em = document.getElementById('checkbox_' + parent_id + '_' + i)) {
				i++;
				if(em.checked==true)num_checked++;
			}

			if(i==num_checked) parent_em.checked = true;
		}



var ajaxLoaded = 0;
var ulistsLoaded = 0;
var ulist_masterid = 0;

function addProdToList_callback(HtmlResp) {
   var my_overlay = document.createElement('div');
   my_overlay.setAttribute('id', 'overlay');
   var my_overlaybubble = document.createElement('div');
   my_overlaybubble.setAttribute('id', 'overlaybubble');
   my_overlaybubble.innerHTML = HtmlResp;
   document.body.appendChild(my_overlay);
   document.body.appendChild(my_overlaybubble);
   addProdToListPost(ulist_masterid);

}

function addProdToList(masterid) {
  ulist_masterid = masterid;
  if(!document.getElementById('overlaybubble')){
     ajax = new AjaxRequest('POST', '/ulists.php/bubbleContent', true, 3000);
     ajax.setParameter('masterid', masterid);
     // ajax.setParameter('isbn', isbn);
     ajax.setResponseType('html');
     ajax.setCallback( addProdToList_callback );
     ajax.send();
   }else{
      addProdToListPost(ulist_masterid);
   }
}

function addProdToListPost(masterid) {
  
  if(!ulistsLoaded) {
	var s2 = document.createElement('script'); s2.src = 'http://www.pricegrabber.com/js/ulists_from_prodpage.js.php?prodpage_lists_only=1';
	document.body.appendChild(s2);
  }

  document.bubble.prod_id.value = masterid;
  document.bubble.id_type.value = 'M';
  waitForLoad();

}
function waitForLoad() {
	if(!ulistsLoaded) {
		if(window.ulists_js) { ulistsLoaded = 1; ShowListMessage('<img src="http://i.pgcdn.com/images/small_wait.gif" width=16 height=16>','Please hold while we process your request ...','#666666');}
		else { setTimeout('waitForLoad("");',200); return 0; }
	}
	if(!ajaxLoaded) {
		if(window.ajax) { ajaxLoaded = 1; }
		else { setTimeout('waitForLoad("");',200); return 0; }
	}
	if(ajaxLoaded && ulistsLoaded) { addToList(); }
}

 var SA_popup;   //current popup that is open
 var SA_popupString; //popup inner html string
 var SA_hoverTimerID;
 var SA_hoverCloseTimerID; // timer for closing popup after .5 seconds
 var SA_overSellersLink = false; //boolean, true if hovering over sellers link
function showSellersPopup(product_id,dw_search_id,dw_epoch_time, zip_code,view, retid, endcap_cobrand_id ,pid,product_type,free_shipping_filter, ab_test_id, ab_test_group){
     if(product_type === undefined || product_type == '') {
        product_type = 'masterid';
     }

     SA_hoverTimerID = setTimeout('requestOffersXml("' + product_id + '","' + dw_search_id + '","' + dw_epoch_time + '","' + zip_code + '","' + view +'","' + retid + '","' + endcap_cobrand_id + '","' + pid + '","' + product_type + '","' + free_shipping_filter + '","' + ab_test_id + '","' + ab_test_group + '")',100);
}
function clearSellerPopupTimeout(){
    clearTimeout(SA_hoverTimerID);
    SA_overSellersLink = false;
}

var sellerPopupView;
var sellerPopupProdId;
function requestOffersXml(product_id,dw_search_id,dw_epoch_time, zip_code,view, retid, endcap_cobrand_id, pid, product_type,free_shipping_filter, ab_test_id, ab_test_group) {
    var curPopup = document.getElementById('popSellers_'+ product_id);
    var anchor =  document.getElementById('Sellers_'+ product_id);
    SA_overSellersLink = true;
    clearTimeout(SA_hoverCloseTimerID);
    SA_hoverCloseTimerID = null;
    //if this popup already open, don't do anything
   
    if(SA_popup == curPopup){
        setPopupPosition(anchor,SA_popup,view);
        return;
    }

    //if a popup is already open, close it
    if(SA_popup){
        SA_popup.style.visibility = 'hidden';

    }

    SA_popup = curPopup;

    //if a request for this product has already been made, don't bother doing another one
    if(SA_popup.innerHTML != ""){
         setPopupPosition(anchor,SA_popup,view);
         SA_popup.style.visibility = "visible";
         document.onmousemove=SA_checkMousePosition;
         return;
    }
	var ajax = new AjaxRequest('POST', '/rpc_getSellers.php', true, 3000);
	if (product_id) {
		ajax.setParameter('product_id', product_id);
	}
	if (dw_search_id) {
		ajax.setParameter('dw_search_id', dw_search_id);
	}
	if (dw_epoch_time) {
		ajax.setParameter('dw_epoch_time', dw_epoch_time);
	}
	if (zip_code) {
		ajax.setParameter('zip_code', zip_code);
	}
	if (retid) {
		ajax.setParameter('retid', retid);
	}
	if (endcap_cobrand_id) {
		ajax.setParameter('endcap_cobrand_id', endcap_cobrand_id);
	}  
	if (pid) {
		ajax.setParameter('pid', pid);
	}
    if (product_type) {
		ajax.setParameter('product_type', product_type);
	}
	 if (free_shipping_filter) {
		ajax.setParameter('free_shipping_filter', free_shipping_filter);
	}
	ajax.setParameter('element_id', 'popSellers_'+ product_id);

    if( ab_test_id > 0 ) {
        ajax.setParameter('ab_test_id', ab_test_id);
        ajax.setParameter('ab_test_group', ab_test_group);
    }

	sellerPopupView = view;
    sellerPopupProdId = product_id;

    SA_popup.className = 'detailsPopupTopLeft';
    //add html to popup
    SA_popupString = "";
	SA_popup.innerHTML = "";
    SA_popupString += "<div class=\"popupTop\"></div>";
    SA_popupString += "<div class=\"popupBottom\">"
    SA_popupString += '<a href="javascript:closeOffersPopup();" class="closeBtn"><img src="http://i.pgcdn.com/images/ulists_bubbleclose.gif"></a>';

    ajax.setCallback(displayOffersPopup);
	ajax.send();
}

function displayOffersPopup(xml) {

	var offers = xml.getElementsByTagName('offers');
	var json = offers[0].firstChild;
    var objOffers = eval(json.firstChild.nodeValue);
	var totalOffers = objOffers[0]['num_sellers'];
	
	var element_id = xml.getElementsByTagName('element_id');
	if (element_id && element_id.length) {
		element_id = element_id[0].firstChild.nodeValue;
	}
	else {
		element_id = '';
	}
	
    for (var i = 0;i < objOffers.length; i++) {

		SA_popupString += '<div class="merchantPop">';
        SA_popupString += '	<div class="col1">';
        SA_popupString += '        <a class = "MerchantTitle"  href="' + objOffers[i]['merchant_link'] + '"  target="_blank" >';

        if(objOffers[i]['merchant_logo'] ){
            SA_popupString += '<img src="http://i.pgcdn.com/images/' + objOffers[i]['merchant_logo'] + '"  alt="'+objOffers[i]['title']+'">';
        }
        else{
            SA_popupString +=  objOffers[i]['title'];
        }
        SA_popupString += '</a><br />';
        if ( objOffers[i]['isMcAfee'] == 'y' ) {
		    // show hacker safe logo
            SA_popupString += '        <div class="hacker"><img src="http://i.pgcdn.com/images/mcafee_secure_80x12.gif" alt="McAfee Secure"></div>';
        }
        if(objOffers[i]['id_type'] == "merchant") {
            SA_popupString += '        <a href="' + objOffers[i]['info_retailer'] + '">Merchant Info</a>';
                    }
        else {
            SA_popupString += '<img src="http://i.pgcdn.com/images/enduser_sfrontgetprod.gif" alt="Storefronts" />';
        }
        SA_popupString += '    </div>';
        SA_popupString += '    <div class="col1">';
        if(objOffers[i]['reviews']['stars_image']){
            SA_popupString += '		<a href="' + objOffers[i]['reviews']['link'] + '">' + objOffers[i]['reviews']['stars_image'] + '</a><br>';
        }
        SA_popupString += '        <a href="' + objOffers[i]['reviews']['link'] + '">' + objOffers[i]['reviews']['info_message'] + '</a>';
        SA_popupString += '    <br /></div>';
        SA_popupString += '    <div class="colPrice">';
        SA_popupString += '		<a href="' + objOffers[i]['merchant_link'] + '" ';
        if(objOffers[i]['id_type'] == "merchant") {
            SA_popupString += ' target="_blank" ';
        }
        SA_popupString += '>';
        SA_popupString += objOffers[i]['price'] + '</a>';
        SA_popupString += '        <p>' + objOffers[i]['bottomline_text'] + '</p>';

        SA_popupString += '    </div>';
		if( totalOffers > objOffers.length || i < objOffers.length - 1 ){
			SA_popupString += '    <hr>';
		}
        SA_popupString += '    <div class="clearing">&nbsp;</div>';
        SA_popupString += '</div>';

	}
	if( totalOffers > objOffers.length ){
		SA_popupString += '<p class="moreSellers"><a href="' + objOffers[0]['product_link'] + '">See More Sellers</a></p>';
	}

    SA_popupString += '</div>';
    
	if (element_id) {
		// hide previous popup if it's popped up
    	if (SA_popup && SA_popup != document.getElementById(element_id)) {
			SA_popup.style.visibility = "hidden";
		}
	    SA_popup = document.getElementById(element_id);
	}
    
    SA_popup.innerHTML = SA_popupString;

	// show sellers popup
    setPopupPosition(document.getElementById('Sellers_'+ sellerPopupProdId),SA_popup,sellerPopupView);

    SA_popup.style.visibility = "visible";
    document.onmousemove=SA_checkMousePosition;
    document.onmousedown=SA_checkMousePosition;
}

function showSEOReviewPopup(product_id, anchor) {
    if( !product_id || product_id <= 0 ) {
        return false;
    }
    var curPopup = document.getElementById('seoReviewPopup_'+product_id);
    hoverCloseTimerID = null;
    SA_overSellersLink = true;
    if( SA_popup == curPopup ) {
        setPopupPosition(anchor, SA_popup, 'list');
        return;
    }
    if(SA_popup && (SA_popup != curPopup) ) {
        SA_popup.style.visibility = "hidden";
    }

        var seo_content_element = document.getElementById('seo_product_review_' + product_id);
    if( !seo_content_element | seo_content_element == null ) {
        return false;
    }
    displayPopup(curPopup, product_id, anchor, seo_content_element.innerHTML);
    
}

function displayPopup(popup_element, product_id, anchor, content) {
	
    SA_popup = document.getElementById('seoReviewPopup_'+product_id);
    
	if (popup_element) {
		// hide previous popup if it's popped up
    	if (SA_popup && SA_popup != popup_element) {
			SA_popup.style.visibility = "hidden";
		}
        SA_popup = popup_element;
	}
    
    //SA_popup.innerHTML = SA_popupString;

	// show sellers popup
    setPopupPosition(anchor,SA_popup,'list');

    SA_popup.style.visibility = "visible";
    document.onmousemove=SA_checkMousePosition;
    document.onmousedown=SA_checkMousePosition;
}

function SA_checkMousePosition(event){
	var pageX;
	var pageY;

    if(!SA_popup){
        return true;
    }
    ev = event || window.event;
     if (ev.target) {
        currentObj = ev.target;
    } else if (ev.srcelement) {
        currentObj = ev.srcelement;
    }
    
    pageX = ev.pageX;
    pageY = ev.pageY;
    // get X/Y mouse coordinates of page for 
    // browsers that don't support event pageX and pageY (IE)
    if (!pageX || ! pageY) {
	    pageX = ev.clientX;
	    pageY = ev.clientY;
	    
	    // just add the scrollbar x/y to client x/y to get the page's xy coordinate
	    if( document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			pageX += document.body.scrollLeft;
			pageY += document.body.scrollTop;
		}
		else if( document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			pageX += document.documentElement.scrollLeft;
			pageY += document.documentElement.scrollTop;
		}
	}
    popleft = parseInt(SA_popup.style.left);
	popwidth = DomUtils.getElementWidth(SA_popup);
    
    if(!SA_overSellersLink && (pageX < parseInt(SA_popup.style.left) || pageX > (parseInt(SA_popup.style.left) + DomUtils.getElementWidth(SA_popup)))) {
        //alert(ev.pageX);
        if(ev.type == "mousedown"){
                closeOffersPopup();
        }
        else if(!SA_hoverCloseTimerID){
                SA_hoverCloseTimerID = setTimeout("closeOffersPopup()",500);
        }
    }
    else if(!SA_overSellersLink && (pageY < parseInt(SA_popup.style.top) || pageY > (parseInt(SA_popup.style.top) + DomUtils.getElementHeight(SA_popup)))){
        if(ev.type == "mousedown"){
                closeOffersPopup();
        }
        else if(!SA_hoverCloseTimerID){
                SA_hoverCloseTimerID = setTimeout("closeOffersPopup()",500);
        }
    }

    else{
        clearTimeout(SA_hoverCloseTimerID);
        SA_hoverCloseTimerID = null;
    }
}

function setPopupPosition(anchor,elem,view){
    var dX = 0;
    var dY = 0;
    if(view == "list"){
      dX_left = -113;
      dY_bottom = 18;
      dX_right = 15;
      dY_top = 10;
    }
    else if (view == "popup") {
      dX_left = 5;
      dY_bottom = 18;
      dX_right = 15;
      dY_top = 10;
    }
    else if (view == "popdown") {
      dX_left = -200;
      dY_bottom = 18;
      dX_right = 15;
      dY_top = 10;
    }
    else if (view == "popdown_fav") {
      dX_left = -77;
      dY_bottom = 10;
      dX_right = -251;
      dY_top = 10;
    }
    else{
      dX_left = -98;
      dY_bottom = 10;
      dX_right = -251;
      dY_top = 10;
    }
    
    var wWidth  = parseInt(DomUtils.getWindowWidth(window));
    var wHeight = parseInt(DomUtils.getWindowHeight(window));
    var scrollX = parseInt(DomUtils.getWindowScrollX(window));
    var scrollY = parseInt(DomUtils.getWindowScrollY(window));
    var aWidth  = parseInt(DomUtils.getElementWidth(anchor));
    var aHeight = parseInt(DomUtils.getElementHeight(anchor));
    var aX      = parseInt(DomUtils.getElementLeft(anchor));
    var aY      = parseInt(DomUtils.getElementTop(anchor));
    var aWidth  = parseInt(DomUtils.getElementWidth(anchor));
    var aHeight = parseInt(DomUtils.getElementHeight(anchor));
    aHeight = ( isNaN(aHeight) ? 0 : aHeight);
    var eWidth  = parseInt(DomUtils.getElementWidth(elem));
    var eHeight = parseInt(DomUtils.getElementHeight(elem));

    var roomBottom = false;
    var roomRight = false;

    if((wHeight + scrollY) > (aY + dY_bottom + eHeight)){
        roomBottom = true;
    }
    else{
       roomBottom = false;
    }
    if((wWidth + scrollX) > (aX + dX_left + eWidth)){

        roomRight = true;
    }
    else{
       roomRight = false;
    }

	if (view == "popup") {
        roomBottom = true;
        roomRight = true;
    }
    
	if (view == "popdown") {
        roomBottom = true;
        roomRight = true;
    }
    
	if (view == "popdown_fav") {
        roomBottom = true;
        roomRight = true;
    }
    
    if(roomBottom && roomRight){
        elem.style.top = (aY + aHeight) + "px";
        elem.style.left = (aX + dX_left) + "px";
        elem.className = 'detailsPopupTopLeft';
    }
    else if(!roomBottom && roomRight){
        elem.style.top = (aY - eHeight) + "px";
        elem.style.left = (aX + dX_left) + "px";
        elem.className = 'detailsPopupBottomLeft';
    }
    else if(roomBottom && !roomRight){
        elem.style.top = (aY + aHeight) + "px";
        elem.style.left = (aX + dX_right) + "px";
        elem.className = 'detailsPopupTopRight';
    }
    else if(!roomBottom && !roomRight){
        elem.style.top = (aY - eHeight) + "px";
        elem.style.left = (aX + dX_right) + "px";
        elem.className = 'detailsPopupBottomRight';
    }
}

function closeOffersPopup() {
    clearTimeout(SA_hoverCloseTimerID);
    SA_hoverCloseTimerID = null;
    document.onmousemove = null;
    if(SA_popup){
        SA_popup.style.visibility="hidden";
        SA_popup = null;
    }
}



function saSendEmail(page_title){
    var username = util.readCookie('bake_username');
    ajax = new AjaxRequest('GET', '/login.php/check', true, 3000);
    ajax.setCallback( saEmailCallback );
    if(username){
       var challenge = calcMD5(username) + '05c6edcab60673c5974b82d0070f3bf416';
       ajax.setParameter('challenge', challenge);
    }
    ajax.setParameter('type', 'email_login');
    ajax.send();

}

function saEmailCallback(XmlResp){
	if(!XmlResp) {
		return false;
	}
	else {
        var msgnb = XmlResp.getElementsByTagName("nb")[0].firstChild.nodeValue;
		var msgdesc = XmlResp.getElementsByTagName("desc")[0].firstChild.nodeValue;
		var act = XmlResp.getElementsByTagName("action")[0].firstChild.nodeValue;
            if( act == 'email_login' ) {
            var loggedin = XmlResp.getElementsByTagName("logged-in")[0].firstChild.nodeValue;
            if(loggedin > 0) {
                var username = XmlResp.getElementsByTagName("username")[0].firstChild.nodeValue;
                var email = XmlResp.getElementsByTagName("email")[0].firstChild.nodeValue;
                if( username && email ) {
                    var input_elem = document.getElementById("sender_name");
                    if(input_elem) {
                        input_elem.value = username + " <"+email+">";
                        document.getElementById("friend_e").focus();
                    }
                }
                else {
                    var input_elem = document.getElementById("sender_name");
                    if(input_elem) {
                        input_elem.focus();
                    }
                }
            }
            else {
                var input_elem = document.getElementById("sender_name");
                if(input_elem) {
                    input_elem.focus();
                }
            }
            showSAOverlayBubble(1, 'email');
        }
        else if( act == 'sa_email' ) {
            var msg_sent = XmlResp.getElementsByTagName("msg_sent");
            if( msg_sent[0].firstChild && msg_sent[0].firstChild.nodeValue > 0 ) {
                ShowSAMessage('',msgdesc,'#666');
                setTimeout('saBubbleClose();', 1200);
            }
            else {
                var email_error = document.getElementById("sabubble_email_error");
                if(email_error) {
                    email_error.innerHTML = msgdesc;
                    email_error.style.display = '';
                }
                showSAOverlayBubble(1, 'email');
            }
        }
    }
}

function getCaptcha(){
    ajax = new AjaxRequest('POST', '/login.php/captcha', true, 3000);
    ajax.setCallback( SACaptchaCallback );
    ajax.setParameter('type', 'captcha');
    ajax.send();
}

function SACaptchaCallback(XmlResp){
        if(!XmlResp) {
           return false;
        }
        else {
           var msgnb = XmlResp.getElementsByTagName("nb")[0].firstChild.nodeValue;
           var msgdesc = XmlResp.getElementsByTagName("desc")[0].firstChild.nodeValue;
           var act = XmlResp.getElementsByTagName("action")[0].firstChild.nodeValue;
           if( act == 'captcha'){
                var captcha_encrypt = XmlResp.getElementsByTagName("encrypt")[0].firstChild.nodeValue;
                var captcha_iv = XmlResp.getElementsByTagName("iv")[0].firstChild.nodeValue;
                var captcha_raw_encrypt = XmlResp.getElementsByTagName("raw_encrypt")[0].firstChild.nodeValue;
                var captcha_raw_iv = XmlResp.getElementsByTagName("raw_iv")[0].firstChild.nodeValue;

                if(document.getElementById('captcha_image')){
                   document.getElementById('captcha_image').src = 'http://www.pricegrabber.com/cptch_img.php?s='+captcha_raw_encrypt+'&iv='+captcha_raw_iv;
                }
                if(document.getElementById('captcha_value')){
                   document.getElementById('captcha_value').value = captcha_encrypt;
                }
                if(document.getElementById('captcha_iv')){
                   document.getElementById('captcha_iv').value = captcha_iv;
                }
           }
        }
}

function showSAOverlayBubble(show,type) {
	showSAOverlay(show);

	if(!show && !saBubbleIsClosed()) {
		document.getElementById('saoverlaybubble').style.left = '-1000px';
                if(document.getElementById('captcha_image')) document.getElementById('captcha_image').src = 'http://i.pgcdn.com/images/spacer.gif';
	}
	else if(show){
                      getCaptcha();

        if(document.getElementById('sabubblemsg')) {
			document.getElementById('sabubblemsg').style.display = (type=='msg' ? '' : 'none');
        }
        if(document.getElementById('sabubbleemail')) {
            document.getElementById('sabubbleemail').style.display = (type=='email' ? '' : 'none');
        }
		var width = DomUtils.getWindowWidth();
		var height = DomUtils.getWindowHeight();
		var scrollX = DomUtils.getWindowScrollX();
		var scrollY = DomUtils.getWindowScrollY();
		if(width==0 || height==0) {
			if(typeof window.opera=="undefined" && document.documentElement.clientWidth) {
				width = document.documentElement.clientWidth;
				height = document.documentElement.clientHeight;
			}
			else {
				width = document.body.clientWidth;
				height = document.body.clientHeight;
			}
		}
		if(scrollX==0 || scrollY==0) {
			scrollX = document.documentElement.scrollLeft;
			scrollY = document.documentElement.scrollTop;
		}
		var bwidth = DomUtils.getElementWidth(document.getElementById('saoverlaybubble'));
		var bheight = DomUtils.getElementHeight(document.getElementById('saoverlaybubble'));
		document.getElementById('saoverlaybubble').style.top = (scrollY + (height/2) - (bheight/2)) + 'px';
		document.getElementById('saoverlaybubble').style.left = (scrollX + (width/2) - (bwidth/2)) + 'px';
	}
}

function saBubbleClose() {
    document.getElementById("sabubble_email_error").style.display = "none";
    document.getElementById('sabubblemsgimage').style.display = 'none';
	showSAOverlayBubble(0,'');
}
function saBubbleIsClosed() {
	return parseInt(document.getElementById('saoverlaybubble').style.left)>0 ? false : true;
}


function showSAOverlay(show) {
    var isIE6 = DomUtils.browser.isIE6();
	if(!show) {
		document.getElementById('login_overlay').style.display = 'none';
        if(isIE6){
            document.getElementById('shim').style.display = 'none';
        }
	}
	else {
        var scrollX = DomUtils.getWindowScrollX();
        var scrollY = DomUtils.getWindowScrollY();
        var height = DomUtils.getElementHeight(document.body);
        var width = DomUtils.getElementWidth(document.body);
        if(height < screen.height) {
            height = (screen.height * .8);
        }
        //THIS IS FOR OPERA ONLY
        //opacity doesn't exist, so we just don't show the overlay
        if (typeof window.opera == "undefined") {
            document.getElementById('login_overlay').style.width = width + 'px';
            document.getElementById('login_overlay').style.height = height + 'px';
            document.getElementById('login_overlay').style.display = 'block';
        }

        //ADD IFRAME SHIM - for IE6 so select box doesn't show through the popup
        //instead of adding the code for the shim to each page, and potentially missing one, create it manually and append to the body
        if(isIE6){
            if(document.getElementById('shim') == null){
                var shim = document.createElement('iframe');
                shim.setAttribute('src', 'javascript:false;');
                shim.setAttribute('scrolling', 'no');
                shim.setAttribute('frameborder', '0');
                shim.setAttribute('id', 'shim');

                //set needed styles for the shim
                shim.style.zIndex = 99;
                shim.style.display = "none";
                shim.style.position = "absolute";
                shim.style.backgroundColor = "transparent";
                shim.style.top = "0px";
                shim.style.left = "0px";
                document.body.appendChild(shim);
            }
            document.getElementById('shim').style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
            document.getElementById('shim').style.width = width + 'px';
            document.getElementById('shim').style.height = height + 'px';
            document.getElementById('shim').style.display = 'block';
        }
    }
}

function submitSAOverlay(type) {
    var errors = 0;
    var error_msg = '';
    if( document.sa.sender_name.value=='' ) {
        errors = 1;
        error_msg = 'Please supply a name.';
    }
    else if( !isValidEmail(document.sa.friend_e.value) ) {
        errors = 1;
        error_msg = 'Invalid email address.';
    }
    if( errors == 1 ) {
        document.getElementById("sabubble_email_error").innerHTML = error_msg;
    }
    else if( errors == 0 ) {
        saBubbleClose();
        ShowSAMessage('<img src="/small_wait.gif" width=16 height=16>','Please hold while we process your request ...','#666666');
        ajax = new AjaxRequest('GET', '/search_attrib_email.php', true, 3000);
        ajax.setParameter('sender_name', document.sa.sender_name.value);
        ajax.setParameter('friend_email', document.sa.friend_e.value);
        ajax.setParameter('captcha_value', document.sa.captcha_value.value);
        ajax.setParameter('captcha_response', document.sa.captcha_response.value);
        ajax.setParameter('captcha_iv', document.sa.captcha_iv.value);
        ajax.setParameter('email_msg', document.sa.email_msg.value);
        ajax.setParameter('type', 'sa_email');
        ajax.setParameter('page_header',page_header);
        ajax.setParameter('url',page_url);
        ajax.setCallback( saEmailCallback );
        ajax.send();
    }
}

function ShowSAMessage(img,txt,color) {
	document.getElementById('sabubblemsgbody').style.color = color;
	document.getElementById('sabubblemsgbody').innerHTML = txt;
	if(img == '') {
		document.getElementById('sabubblemsgimage').style.display = 'none';
	}
	else {
		document.getElementById('sabubblemsgimage').innerHTML = img;
		document.getElementById('sabubblemsgimage').style.display = '';
	}
	showSAOverlayBubble(1,'msg');
}

function isValidEmail(emailStr) {
    var emailPat=/^(.+)@(.+)$/;
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    var validChars="\[^\\s" + specialChars + "\]";
    var quotedUser="(\"[^\"]*\")";
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom=validChars + '+';
    var word="(" + atom + "|" + quotedUser + ")";
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
    var matchArray=emailStr.match(emailPat);
    if (matchArray==null) {
        return false;
    }
    var user=matchArray[1];
    var domain=matchArray[2];
    if (user.match(userPat)==null) {
        return false;
    }
    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null) {
        for (var i=1;i<=4;i++) {
            if (IPArray[i]>255) {
                return false;
            }
        }
        return true;
    }
    var domainArray=domain.match(domainPat);
    if (domainArray==null) {
        return false;
    }
    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>4) {
        return false;
    }
    if (len<2) {
        return false;
    }
    return true;
}


//
//  Simplified version of the Show Search Attrib Popup function
//	just show the SA popup with given popup element id, anchor element id, and text to put in the popup
//  ( no need to hardcode crap)
//   ex: showSAPopup('mypopup_element_id', 'myanchor_element_id', 'blah blah text that goes inside popup');
//
function showSAPopup(popup_id, anchor_id, text, popup_type, checkwidth, setdelay, closeall)
{

	if (SA_overSellersLink && closeall != "close"){
		return;
	}

    var curPopup = document.getElementById(popup_id);
    var anchor =  document.getElementById(anchor_id);
	if(!popup_type) popup_type = "popup";
    SA_overSellersLink = true;
    clearTimeout(SA_hoverCloseTimerID);
    SA_hoverCloseTimerID = null;

    //if this popup already open, don't do anything
    if(SA_popup == curPopup  && closeall != "close"){
//        setPopupPosition(anchor,SA_popup,'list');
        return;
    }

    //if a popup is already open, close it
    if(SA_popup){
        SA_popup.style.visibility = 'hidden';
    }

    SA_popup = curPopup;
    
    if (text) {
    	SA_popup.innerHTML = text;
    }
    
    // begin hack: sorry but i had to hardcode the width of the popup to make it work
    // with different popup designs
    // we need to rework popup code to handle different sized popups later.
    // (right now there is a fixed width of 360px in the detailspopup css class)
    var width = "250";
	if (popup_type == "popdown") width = 350;
	if (popup_type == "popdown_fav") width = 160;
	
	if(checkwidth != "nowidth"){
		SA_popup.style.width = width + 'px';
	}
	// end hack


    setPopupPosition(anchor ,SA_popup, popup_type);
	if(!setdelay) setdelay = 0;
	setTimeout("SA_popup.style.visibility='visible';", setdelay); 
    document.onmousemove=SA_checkMousePosition;
    document.onmousedown=SA_checkMousePosition;
}

function closeSAPopup(popup_id)
{
    var curPopup = document.getElementById(popup_id);

    SA_overSellersLink = false;
    clearTimeout(SA_hoverCloseTimerID);
    SA_hoverCloseTimerID = null;

    curPopup.style.visibility = "hidden";
	SA_popup = null;
}

function pg_openPromo(src) {
	url = '/info_rebate.php?masterid='+src;
	window.open(url, 'promo', 'height=450,width=550,innerHeight=450,innerWidth=550,menubar=no,status=no,toolbar=no,resizable=yes,scrollbars=yes');
}

function searchoffers(strBaseurl, reject_id, group_id, offer_id, offer_group_id, strKeyword, strSearch){

  document.frmMain.action = strBaseurl + "/search_getoffers.php?keyword=" + strKeyword + "&search=" + strSearch;
  document.frmMain.reject_id.value = reject_id;
  document.frmMain.group_id.value = group_id;
  document.frmMain.offer_id.value = offer_id;
  document.frmMain.offer_group_id.value = offer_group_id;
  document.frmMain.submit();
}

function toggleFilter(triggerEl) {
	// get first unordered list element
	var ul = triggerEl.nextSibling;

	// if nodetype is a text node, get next sibling
	if (ul.nodeType == 3) {
		ul = ul.nextSibling;
	}
	
	if (ul) {
		if ( ul.style.display == '' || ul.style.display == 'block' ) {
			ul.parentNode.className = 'off';
			ul.style.display = 'none';
		}
		else {
			ul.parentNode.className = 'on';
			ul.style.display = 'block';
		}
	}
}

function togglePriceRangeFilter(triggerEl) {
	var ul = triggerEl.parentNode.parentNode;

	// if nodetype is a text node, get next sibling
	if (ul.nodeType == 3) {
		ul = ul.nextSibling;
	}
	
	if (ul) {
		if ( ul.style.display == '' || ul.style.display == 'block' ) {
			ul.parentNode.className = 'off';
			ul.style.display = 'none';
		}
		else {
			ul.parentNode.className = 'on';
			ul.style.display = 'block';
		}
	}
}

function toggleParent(triggerEl) {
	var children = triggerEl.parentNode.parentNode.getElementsByTagName('input');
	var selectedNodes = 0;
	for ( var i = 0; i < children.length; i++ ) {
		if ( children[i].checked ) selectedNodes++;
	}
	
	// deselect the parent if selected
	var li = triggerEl.parentNode.parentNode.parentNode;
	if ( selectedNodes == children.length ) { 
		if (! li.firstChild.checked ) li.firstChild.checked = true;
	}
	else if ( li.firstChild.checked ) {
		li.firstChild.checked = false;
	}
}

function toggleChildren(triggerEl) {
	var li = triggerEl.parentNode;
	var children = li.getElementsByTagName('input');
	var parentChecked = children[0].checked ? true : false;

	// select/deselect all children
	for ( var i = 1; i < children.length; i++ ) 
		children[i].checked = parentChecked;
}

function toggleCheckbox(triggerEl) {
	var li = triggerEl.parentNode;
	var input = li.firstChild;

	// if nodetype is a text node, get next sibling
	if (input.nodeType == 3) {
		input = input.nextSibling;
	}
	
	if ( input.checked ) input.checked = false;
	else input.checked = true;
}

function hideCompareSubmit(input) {
	input.style.display = 'none';
}

function showCompareLink(link) {
	link.style.display = '';
}

function sortVendorNodes(ul) {
	// clone unordered list (shallow cloning)
	var ulClone = ul.cloneNode(false);
	var children = ul.childNodes;

	// sort bucket of elements
	var vendorIds = new Array();
	var vendorCount = 0;
	var selectedVendorIds = new Array();
	var selectedVendorCount = 0;
	for ( var i = 0; i < children.length; i++ ) {
		var id = children[i].getAttribute('id');
		if (id) {
			var checked = children[i].getElementsByTagName("input")[0].checked;
			if (checked) {
				 selectedVendorIds[selectedVendorCount] = id;
				 selectedVendorCount++;
			}
			else {
				 vendorIds[vendorCount] = id;
				 vendorCount++;
			}

		}
	}

	vendorIds.sort();

	for ( var i = 0; i < selectedVendorCount; i++ ) {
		var vendorId = selectedVendorIds[i];
		var li = document.getElementById(vendorId);
		li.style.display = 'block';
		ulClone.appendChild(li);
		ulClone.lastChild.getElementsByTagName("input")[0].setAttribute('checked', 'checked');
		ulClone.lastChild.getElementsByTagName("input")[0].setAttribute('defaultChecked', 'true');
	}
	for ( var i = 0; i < vendorCount; i++ ) {
		var vendorId = vendorIds[i];
		var li = document.getElementById(vendorId);
		li.style.display = 'block';
		ulClone.appendChild(li);
	}

	
	ulClone.style.width = '159px';
	ulClone.style.height = '190px';

	ul.parentNode.replaceChild(ulClone, ul);
	
}

function exposeAllVendors(triggerEl) {
	var ul = triggerEl.parentNode;
	ul.style.overflow = 'auto';
	sortVendorNodes(ul);
}

function exposeAllStores(triggerEl) {
	var ul = triggerEl.parentNode;
	ul.removeChild(ul.lastChild);
	var children = ul.childNodes;
	for ( var i = 0; i < children.length; i++ ) {
		children[i].style.display = 'block';
	}
	
	ul.style.width = '159px';
	ul.style.height = '190px';
}
function initCompareLinks() {
	var form = document.getElementById('productCompareForm');
	var inputNodes = form.getElementsByTagName('input');

	for ( var j = 0; j < inputNodes.length; j++ ) {
		if ( inputNodes[j].type == 'submit' && inputNodes[j].className == 'compareSubmit' ) {
			inputNodes[j].disabled = false;
			inputNodes[j].style.display='none';

			// Get parent node
			var p = inputNodes[j].parentNode;
			var a_tags = p.getElementsByTagName('a');
			if(a_tags[0]) {
				a_tags[0].style.display='';
			}
		}
	}
}
function initFilters() {
	var ul = document.getElementById('sa_filters_main');
	var children = ul.getElementsByTagName('ul');
	var selectedNodes = new Array('count','total_count');
	selectedNodes['total_count'] = 0;
	var firstFilter = 0;
	for ( var i = 0; i < children.length; i++ ) {
		if ( children[i].className != 'sa_filters_sub' ) continue;
		if (! firstFilter ) {
			var li = children[i].parentNode;
			li.setAttribute('id', 'first');
			firstFilter = 1;
		}
		// are there children selected?
		selectedNodes['count'] = 0;
		var inputNodes = children[i].getElementsByTagName('input');
		for ( var j = 0; j < inputNodes.length; j++ ) {
			if ( inputNodes[j].type == 'checkbox' ) {
				inputNodes[j].disabled = false;
				var a = inputNodes[j].nextSibling.nextSibling;
				if (a) {
					a.setAttribute('href', 'javascript:void(0);');
				}
				if ( inputNodes[j].checked ) selectedNodes['count']++;
			}
		}

		selectedNodes['total_count'] += selectedNodes['count'];

		if (selectedNodes['count'] == 0) {
			children[i].style.display = 'none';
			children[i].parentNode.className = 'off';
		}
	}

	var vFilter = children[0]; // usually the first element
	var pRangeFilter = children[children.length-2]; // always last filter element (always exposed)

	// show / hide price range filter
	if ( pRangeFilter ) {
		var lo_p = document.filters.lo_p.value;
		var hi_p = document.filters.hi_p.value;
		if ( lo_p > 0 || hi_p > 0 ) {
			pRangeFilter.style.display = 'block';
			pRangeFilter.parentNode.className = 'on';
		}
	}

	var searchFilter = children[children.length-1]; // always last filter element (always exposed)

	if ( searchFilter ) {
		searchFilter.style.display = 'block';
		searchFilter.parentNode.className = 'on';
	}

	var easeOut = 1;
	var vendorNodes = vFilter.getElementsByTagName('input');
	for ( var j = 0; j < vendorNodes.length; j++ ) {
		if ( vendorNodes[j].type == 'checkbox' ) {
			if ( vendorNodes[j].checked ){
				document.getElementById('vendorFilters').parentNode.className = 'on';
				easeOut = 0;
				break;
			}

		}
	}

	// disable href on see more button
	if ( vFilter && vFilter.hasChildNodes() && selectedNodes['total_count'] <= 5 ) {
		// vendor filters have an id attribute for sorting
		if ( vFilter.firstChild.id ) {
			// Old version : display vendors if no other attrib filters have been selected
			// New version : display them anyway
			if (easeOut) {
			 //show vendor filters after page loads + short delay (initial view only)
				window.addOnload( function() { setTimeout(displayVendorFilters, 500) } );
			}
			var a = vFilter.lastChild.lastChild;
			if ( a.href ) {
				if ( vFilter.childNodes.length > 6 ) 
					vFilter.lastChild.replaceChild(a.firstChild, a);
				else 
					vFilter.removeChild(vFilter.lastChild);
			}
		}
	}
}

function displayVendorFilters() {
	var vFilter = document.getElementById('vendorFilters');
	vFilter.style.height = '0px';
	vFilter.style.overflow = 'hidden';
	vFilter.style.display = 'block';
	//vFilter.parentNode.className = 'on';
	//vFilter.parentNode.setAttribute('id', 'first');
	//toggleFilter(vFilter.firstChild.firstChild);
	vFilter.parentNode.className = 'on';
	//vFilter.parentNode.id = 'first';
	var attributes = { 
		height: { to: 130 } 
	}; 
	var anim = new YAHOO.util.Anim(vFilter, attributes, 1, YAHOO.util.Easing.easeOut);
	anim.animate();
}

/** Show Description popup for text **/
function showDescriptionTitle(elem,box){
	var posYLink=DomUtils.getElementTop(elem);
    var posXLink=DomUtils.getElementLeft(elem);
	var desc_box = document.getElementById(box);
	desc_box.style.top = posYLink + 34 + 'px';
	desc_box.style.left = posXLink + 170 + 'px';

	desc_box.style.display = "block";

}
/** Original Show Description - for icons **/
function showDescription(elem,box){
	var posYLink=DomUtils.getElementTop(elem);
    var posXLink=DomUtils.getElementLeft(elem);
	var desc_box = document.getElementById(box);
	desc_box.style.top = posYLink + 34 + 'px';
	desc_box.style.left = posXLink + 3 + 'px';
	var imageIcon = elem.firstChild;
	imageIcon.alt = "";	
	desc_box.style.display = "block";

}

function hideDescription(box){
	var desc_box = document.getElementById(box);
	desc_box.style.display = "none";	

}


var SPIO_TimeoutID = new Array();
var SPIO_curFading = new Array();

function SPIO_fadeIn(masterid,opacity) {
    obj = document.getElementById('picOverlay_' + masterid);
    if (opacity <= 80) {
      setOpacity(obj, opacity);
      opacity += 10;
      window.setTimeout("SPIO_fadeIn('"+masterid+"',"+opacity+")", 6);
    }
    else{
        SPIO_curFading["'" + masterid + "'"] = false;
    }
}
function SPIO_fadeOut(masterid,opacity) {
    obj = document.getElementById('picOverlay_' + masterid);
    if (opacity >= 0) {
      setOpacity(obj, opacity);
      opacity -= 10;
      SPIO_TimeoutID["'" + masterid + "'"] = window.setTimeout("SPIO_fadeOut("+masterid+","+opacity+")", 6);
    }
    else{
     var overlayBox = document.getElementById('picOverlay_' + masterid); 
      overlayBox.style.display = "none"; 
    }
}

/**
 *	onclick function for user favorite merchants/stores checkbox/link.
 *	basically just submit the form if a user clicks on it 
 */ 
function favoritesFilterOnClick(triggerEl)
{
	var li = triggerEl.parentNode;
	var input = li.firstChild;

	// if nodetype is a text node, get next sibling
	if (input.nodeType == 3) {
		input = input.nextSibling;
	}
	
	var merchantFilter = document.getElementById('merchantFilters');

	// deselect all merchant filters	
	if (merchantFilter) {
		var inputNodes = merchantFilter.getElementsByTagName('input');
		for ( var j = 0; j < inputNodes.length; j++ ) {
			if ( inputNodes[j].type == 'checkbox' ) {
				inputNodes[j].checked = false;
			}
		}
	}
	
	var vendorFilter = document.getElementById('vendorFilters');

	// deselect all vendor filters	
	if (vendorFilter) {
		var inputNodes = vendorFilter.getElementsByTagName('input');
		for ( var j = 0; j < inputNodes.length; j++ ) {
			if ( inputNodes[j].type == 'checkbox' ) {
				inputNodes[j].checked = false;
			}
		}
	}	
	// submit the form
	document.getElementById('sa_filters_form').submit();

}

/**
 *	onclick function for user favorite vendors checkbox/link.
 *	basically just submit the form if a user clicks on it 
 */ 
function favoriteBrandsOnClick(triggerEl)
{
	var li = triggerEl.parentNode;
	var input = li.firstChild;

	// if nodetype is a text node, get next sibling
	if (input.nodeType == 3) {
		input = input.nextSibling;
	}
	
	var vendorFilter = document.getElementById('vendorFilters');

	// if unchecked, deselect all vendor filters	
	if (input.checked == false && vendorFilter) {
		
		var inputNodes = vendorFilter.getElementsByTagName('input');
		for ( var j = 0; j < inputNodes.length; j++ ) {
			if ( inputNodes[j].type == 'checkbox' ) {
				inputNodes[j].checked = false;
			}
		}
	}
	// submit the form
	document.getElementById('sa_filters_form').submit();

}

function openGetCoupon( coupon_id, masterid, redirurl )
{
        url = "/coupons_popup.php?coupon_id=" + coupon_id + "&masterid=" + masterid + "&url=" + redirurl;
		
		features = "toolbar=no,width=444,height=500,resizable=yes,scrollbars=yes";
		window.open( url, "", features );
}
function MM_preloadImages() { 
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { 
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { 
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { 
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function setfocus() {
	if (document.forms['mastsearch'].form_keyword) document.forms['mastsearch'].form_keyword.focus();
}
var show;
function showmenu()
{
  var el = document.getElementById("channels");
  var iframe_menu = document.getElementById('iframe_menu');
  var moretab=document.getElementById("menupos");
  if (el) {
	  	el.style.top=(DomUtils.getElementTop(moretab)+23)+"px";
		el.style.left=(DomUtils.getElementLeft(moretab)-100)+"px";
    el.style.visibility = "visible";
    el.style.zIndex = '100';
      iframe_menu.style.width = el.offsetWidth;
      iframe_menu.style.height = el.offsetHeight;
      iframe_menu.style.top = el.style.top;
      iframe_menu.style.left = el.style.left;
      iframe_menu.style.zIndex = el.style.zIndex - 1;
      iframe_menu.style.display = "block";
    show = 1;
  }
}


function hidemenu()
{
  show = 0;
  setTimeout("hide()", 600);
}
function hide()
{
  var el = document.getElementById("channels");
  var iframe_menu = document.getElementById('iframe_menu');
  if (el) {
    if (!show)
    {
      el.style.visibility = "hidden";
      iframe_menu.style.display = "none";
    }
  }
}
function showmenu2()
{
  var el = document.getElementById("back");
  if (el) {
    el.style.visibility = "visible";
    show = 1;
  }
}
function hidemenu2()
{
  show = 0;
  setTimeout("hide2()", 400);
}
function hide2()
{
  var el = document.getElementById("back");
  if (el) {
    if (!show)
    {
      el.style.visibility = "hidden";
    }
  }
}



/**
 * Append this JavaScript to every page
 */
if (document.getElementById('footerMenuContent') != undefined) {
	var footerMenuContentEl = document.getElementById('footerMenuContent');
}

// When there is no footer menu in action in the page, we should not try to execute
// this series of actions.  It is not just pointless but also causes JS errors.
if (typeof footerMenuContentEl != undefined && footerMenuContentEl) {
  window.addOnLoad(padPopupLinks);
  new ypSlideOutMenu('footerMenu', 'up', getMenuLeftPos(), getMenuTopPos(), 140, 155);
  window.addOnResize(repositionMenu);
  initCursorTargets();

  // position main menu pointer needle
  // possible x coords
  var cursorTimeout;

  // init menu pointer
  setMenuCursorPos();
}

function padPopupLinks() {
    var anchorElements = footerMenuContentEl.getElementsByTagName('a');
	for (var i = 0; i < anchorElements.length; i++) {
		var text = anchorElements[i].firstChild.nodeValue;
		anchorElements[i].removeChild( anchorElements[i].firstChild );
		var span = document.createElement('span');
		span.style.position = 'relative';
		span.style.top  = '5px';
		span.style.left = '10px';
		span.appendChild( document.createTextNode(text) );
		anchorElements[i].appendChild( span );
	}
}

function getMenuLeftPos() {
	var targetLeft = DomUtils.getElementLeft( document.getElementById('i18nMoreButton') );
	var x = targetLeft - 67;
	return x;
}

function getMenuTopPos() {
	var cursorTop = DomUtils.getElementTop( document.getElementById('cursorElement') );
	var y = cursorTop - 160;
	return y;
}

function repositionMenu() {
	ypSlideOutMenu.repositionMenu('footerMenu', getMenuLeftPos(), getMenuTopPos());
}

function initCursorTargets() {
	var i18nEl = document.getElementById('i18n');
	var li = i18nEl.getElementsByTagName('li'); // make global
	var cursorEl = document.getElementById('cursorElement');
	var cursorElWidth = 0;
	for ( var i = 0; i < li.length; i++ ) {
		if ( document.all ) { /* IE */
			cursorElWidth += DomUtils.getElementWidth(li[i]) + 15;
		}
		else {
			cursorElWidth += DomUtils.getElementWidth(li[i]);
		}
		if ( i == (li.length - 1) ) break; /* skip more button element */
		window.addEvent(li[i], 'mouseover', setMenuCursorPos, cursorEl, false);
		window.addEvent(li[i], 'mouseout', resetMenuCursorPos, cursorEl, false);
	}
	cursorEl.style.width = cursorElWidth + 'px';
	i18nEl.style.width = cursorElWidth + 'px';
	var moreLangEl = document.getElementById('footerMenuContent');
	window.addEvent(moreLangEl, 'mouseover', hideMenuCursor, document, false);
	window.addEvent(moreLangEl, 'mouseout', resetMenuCursorPos, document, false);
	var moreLangButton = document.getElementById('i18nMoreButton');
	window.addEvent(moreLangButton, 'mouseover', hideMenuCursor, document, false);
	window.addEvent(moreLangButton, 'mouseout', resetMenuCursorPos, document, false);
}

function setMenuCursorPos(e) {
	var cursorElement;
	var targetEl;
	if (e) {
	/* 
	 * event triggered 
	 * e.target ( moz target )
	 * e.srcElement ( ie target )
	 */
		cursorElement = this;
		targetEl = (e.target) ? e.target : (e.srcElement) ? e.srcElement : null;
	}
	else {
		cursorElement = document.getElementById('cursorElement');
		var anchorElements = cursorElement.getElementsByTagName('a');
		for (var i = 0; i < anchorElements.length; i++) {
			if ( anchorElements[i].hreflang == PG_LOCALE ) {
				targetEl = anchorElements[i];
				break;
			}
		}
	}
	var absContainerLeft = DomUtils.getElementLeft(cursorElement);
	var absTargetLeft = DomUtils.getElementLeft(targetEl);
	var targetLeft = absTargetLeft - absContainerLeft;
	var targetWidth = DomUtils.getElementWidth(targetEl);
	// minus anchor left padding
	targetWidth = targetWidth - 5;
	cursorElement.style.backgroundPosition = ( targetLeft + (targetWidth / 2) ) +'px bottom';
	if ( cursorTimeout )
		clearTimeout(cursorTimeout);
}

function resetMenuCursorPos() {
	cursorTimeout = setTimeout('setMenuCursorPos()', 500);
}

function hideMenuCursor(e) {
	var cursorElement = this.getElementById('cursorElement');
	cursorElement.style.backgroundPosition = '-10px bottom';
	
	if ( cursorTimeout )
		clearTimeout(cursorTimeout);
}
