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   = "es";
			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   = "es"; 

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

		function openlarge( masterid, big_x, big_y ){
			url = "/info_picture.php?masterid=" + masterid;
			features = "toolbar=no,width=" + big_x + ",height=" + big_y + ",resizable=yes,scrollbars=yes";
			window.open( url, "techspecs"+masterid+"image", features );
		}


 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'] + '">Datos de Tienda</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'] + '">Ver Más Tiendas</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) + '05b13afe9c1f4b9f76042f7b64678d8629';
       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 = 'Favor proporcionar un nombre.';
    }
    else if( !isValidEmail(document.sa.friend_e.value) ) {
        errors = 1;
        error_msg = 'Dirección de email incorrecta.';
    }
    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();
}

