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

function saSendEmail(page_title){
    is_modal = true;
    var username = util.readCookie('bake_username');
    ajax = new AjaxRequest('POST', '/login.php/check', true, 3000);
    ajax.setCallback( saEmailCallback );
    ajax.setParameter('type', 'email_login');
    if(username){
       var challenge = calcMD5(username) + '04b13afe9c1f4b9f76042f7b64678d8629';
       ajax.setParameter('challenge', challenge);
    }
    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' ) {
            showSAOverlayBubble(1, 'email');
            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+">";
                    }
                }
                else {
                    var input_elem = document.getElementById("sender_name");
                    if(input_elem) {
                    }
                }
            }
            else {
                var input_elem = document.getElementById("sender_name");
                if(input_elem) {
                }
            }
        }
        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');
            }
        }
        else 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 || typeof window.opera!="undefined") {
			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() {
    is_modal = false;
    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(id_type, p_id, url) {
    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="/images/small_wait.gif" width=16 height=16>','Please hold while we process your request ...','#666666');
        ajax = new AjaxRequest('GET', '/get_prod_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('url', url);
        ajax.setParameter('type', 'sa_email');
        ajax.setParameter('id_type',id_type);
        ajax.setParameter('p_id',p_id);
       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;
}

// set this global var if on a secure page for ajax calls
var PG_use_https;
/**
 *  Add user favorite
 *   ajax call to add a user favorite (merchant or brand)
 */ 
function addUserFavorite(user_id, preference_id_type, preference_id, element_id, element_class, element_content, callback)
{

	// if no user id is given, then load the login overlay bubble
	if (!user_id) {
		user_id = util.readCookie('bake_userid');

		// this hack is for IE6 only.... we saved the userid in document.login cuz it cant read cookies well
		if (!user_id && document.login && document.login.loginSuccessUserid) {
			user_id = document.login.loginSuccessUserid;
		}
		// end IE6 hack
		
		if (!user_id) {
			if (document.login) {
				// set login success callback
				// (try adding to favorites again, once login is successful)
				document.login.loginSuccessCallback = function () { addUserFavorite('', preference_id_type, preference_id, element_id, element_class, element_content, callback); };
			}

                        callbackfuncafterlogin = "addUserFavorite('"+(user_id?user_id:"")+"','"+preference_id_type+"','"+preference_id+"','"+element_id+"','"+element_class+"','"+(element_content?element_content:"")+"','"+(callback?callback:"")+"');";
                        //Tracking from where we require user login/registration
                        if (preference_id_type == 'vendor') refer_page = 'Add Brand to Favs';
                        if (preference_id_type == 'merchant') refer_page = 'Add Merchant to Favs';
                        
                        iframe_login('login_registration', callbackfuncafterlogin, refer_page);
			return;
		}
	}

	if (!user_id) {
		return false;
	}
	
//	console.log('addUserFavorite ' + user_id + ' - ' + preference_id_type + ' - ' + preference_id);
	var ajax = new AjaxRequest('GET', '/ajax.php', true, 3000);
	ajax.setParameter('action', 'addUserFavorite');
	ajax.setParameter('user_id', user_id);
	ajax.setParameter('preference_id_type', preference_id_type);
	ajax.setParameter('preference_id', preference_id);
	ajax.setParameter('element_id', element_id);
	ajax.setParameter('element_class', element_class);
	if (element_content) {
		ajax.setParameter('element_content', element_content);
	}
	
	// lame secure hack
	if (PG_use_https) {
		ajax.setParameter('secure', 1);
	}

	if (callback) {
		ajax.setCallback(callback);
	}
	else {
	    ajax.setCallback(addUserFavoriteResponse);
	}
	ajax.send();
}

/**
 * default ajax response after adding user favorite
 */ 
function addUserFavoriteResponse(xml)
{
	// get json
    var data = eval('(' + xml.getElementsByTagName('json')[0].firstChild.nodeValue + ')');

	if (!data['success']) {
		return false;
	}    
	
    if (data['element_id']) {
	    em = document.getElementById(data['element_id']);
	    if (data['element_class']) {
		    em.className = data['element_class'];
		}
	    em.innerHTML = data['message'];
	}

	// update browse favorite stores/brands link if its on the page
	// todo: this should be moved elsewhere
	var store_link = document.getElementById('browse_favorite_stores_link');
	if (store_link && data['preference_id_type'] == "merchant") {
		// update count
		stores_link_count_em = document.getElementById('favorite_stores_count');
		var count = parseInt(stores_link_count_em.innerHTML);
		count++;
		stores_link_count_em.innerHTML = count;
		// update href link
		store_link.href += '/retid[]=' + data['preference_id'];
	}
	var brands_link = document.getElementById('browse_favorite_brands_link');
	if (brands_link && data['preference_id_type'] == "vendor") {
		// update count
		brands_link_count_em = document.getElementById('favorite_brands_count');
		var count = parseInt(brands_link_count_em.innerHTML);
		count++;
		brands_link_count_em.innerHTML = count;
		// update href link
		brands_link.href += '/vendorIds[]=' + data['preference_id'];
	}
        
}

/**
 *	delete a user preference/favorite
 */ 
function deleteUserPreference(user_preference_id, preference_id_type, element_id, callback)
{
	user_id = util.readCookie('bake_userid');

	if (!user_id) {
		LoginOverlay_login();
		return;
	}

	var ajax = new AjaxRequest('GET', '/ajax.php', true, 3000);
	ajax.setParameter('action', 'deleteUserFavorite');
	ajax.setParameter('user_id', user_id);
	ajax.setParameter('secure', 1);
	ajax.setParameter('user_preference_id', user_preference_id);
	ajax.setParameter('preference_id_type', preference_id_type);
	ajax.setParameter('element_id', element_id);
    ajax.setCallback(callback);
	ajax.send();
}

// functions related to login popup to load the external JS files required to handle it
function LoginOverlay_login() {
        if(!loginLoaded) {
                var s2 = document.createElement('script'); s2.src = login_pop_script;
                document.body.appendChild(s2);
        }
        if(!ajaxLoaded) {
                var s1 = document.createElement('script'); s1.src = login_pop_ajax;
                document.body.appendChild(s1);
        }
        LoginOverlay_waitForLoad();
}
function LoginOverlay_waitForLoad() {
        if(!loginLoaded) {
                if (window.login_js) {
                        loginLoaded = 1;
                        ShowLoginMessage('<img src="'+login_pop_wait+'" width=16 height=16>',login_pop_msg,'#666666');}
                else {
                        setTimeout('LoginOverlay_waitForLoad("");',200);
                        return 0;
                }
        }
        if(!ajaxLoaded) {
                if(window.ajax) {
                        ajaxLoaded = 1;
                }
                else {
                        setTimeout('LoginOverlay_waitForLoad("");',200);
                        return 0;
                }
        }
        if (ajaxLoaded && loginLoaded) {
                showLoginBubble();
        }
}
var ajaxLoaded = 0;
var ulistsLoaded = 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();

}

function addProdToList() {
  if(!document.getElementById('overlaybubble')){
     ajax = new AjaxRequest('POST', '/ulists.php/bubbleContent', true, 3000);
     if(ulist_masterid>0){
        ajax.setParameter('masterid', ulist_masterid);
     }
     if(ulist_isbn>0){
        ajax.setParameter('isbn', ulist_isbn);
     }
     ajax.setResponseType('html');
     ajax.setCallback( addProdToList_callback );
     ajax.send();
   }else{
      addProdToListPost();
   }
}

function addProdToListPost() {
  is_modal = true;
  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);
  }
  if(!ajaxLoaded) {
	var s1 = document.createElement('script'); s1.src = 'http://ah.pricegrabber.com/js/classes/ajaxrequest.js';
	document.body.appendChild(s1);
  }
  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(); }
}
function openBookmark(ut)
{
    var bkmrk="http://www.pricegrabber.com/?mode=bkmrk";
    var title="PriceGrabber.com - Shopping Comparison";
	window.external.AddFavorite(bkmrk,title);
	url = "/redirect_bookmark.php?ut="+ ut + "";	
	features = "toolbar=no,width=1,height=1,resizable=yes,bgcolor=#000000,scrollbars=no";
    window.name="bookmark";
	window.open( url, "", features );
}
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 openSoundclips(masterid)
{
	url = "/info_soundclips.php?masterid=" + masterid + "";	
	features = "toolbar=no,width=500,height=450,resizable=yes,bgcolor=#000000,scrollbars=yes";
	window.open( url, "", features );
}
function openVideo( masterid )
{
	url = "/info_streaming.php?PublishedId=" + masterid;	
	features = "toolbar=no,width=300,height=285,resizable=yes,bgcolor=#000000,scrollbars=no";
    window.name="MyWindow";
	window.open( url, "", features );
}
function openlarge( masterid, big_x, big_y )
{
	url = "/info_picture.php?masterid=" + masterid;
	features = "toolbar=no,width=" + big_x + ",height=" + big_y + ",resizable=no,scrollbars=no";
	window.open( url, "techspecs"+masterid+"image", features );
}
function openptw( masterid, desc, topcat )
{
	if( desc )
	{
		url = "/info_ptw.php?masterid=" + masterid + "#description";
	}
	else
	{
		url = "/info_ptw.php?masterid=" + masterid + "&tab_id=" + topcat;	
	}
	features = "toolbar=no,width=540,height=450,resizable=yes,scrollbars=yes";
	window.open( url, "", features );
}
function opengetproddef(type)
{
	url = "/info_getproddef.php?type=" + type;
	features = "toolbar=no,width=400,height=275,resizable=yes,scrollbars=yes";
	window.open( url, "", features );
}
function open_def_win(type)
{
	url = "/info_minipage.php?type=" + type;
	features = "toolbar=no,width=500,height=250,resizable=yes,scrollbars=yes";
	window.open( url, "", features );
}
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 openGameTrailers( id )
{
  
	url = "/info_streaming_gt.php?gt_id=" + id;
	features = "toolbar=no,width=660,height=400,resizable=yes,bgcolor=#000000,scrollbars=no";
	window.open( url, "", features );
}
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"; 	  
   } 
}
