var PG_use_https; 
//image
function PPbubbleListClose(){
   is_modal = false;
   if(document.getElementById('modal_popup_content_overlay')){
      document.getElementById('modal_popup_content_overlay').style.display = 'none';
      document.body.removeChild(document.getElementById('modal_popup_content_overlay'));  
   }
   if(document.getElementById('modal_popup_background_overlay')){
      document.getElementById('modal_popup_background_overlay').style.display = 'none';
      document.body.removeChild(document.getElementById('modal_popup_background_overlay')); 
   }

   var isIE6 = DomUtils.browser.isIE6();
   if(isIE6){
      document.getElementById('shim').style.display = 'none';
   }
}
function ShowProductPagePopUpAlert(){
   if(is_modal) return;
   ajax = new AjaxRequest('GET', baseurl + 'search_getprod_ajax.php', true, 3000);
    
   ajax.setResponseType('html');
   ajax.setParameter('action', 'defaultAction');
      ajax.setParameter('product_id', product_id);
   ajax.setParameter('id_type', id_type);
   ajax.setParameter('search_id', search_id);
   ajax.setParameter('search_epoch_time', search_epoch_time);
   ajax.setParameter('session_id', session_id);
   ajax.setParameter('session_epoch_time', session_epoch_time);
   ajax.setCallback( callbackShowProductPagePopUpAlert );
   ajax.send();
}
function callbackShowProductPagePopUpAlert(HtmlResp){

   var width = document.body.clientWidth ? document.body.clientWidth : DomUtils.getWindowWidth();
   var height = document.body.clientHeight ? document.body.clientHeight : DomUtils.getWindowHeight();
   var scrollX = DomUtils.getWindowScrollX();
   var scrollY = DomUtils.getWindowScrollY();
   if(width==0 || height==0  || isNaN(width) || isNaN(height) || typeof window.opera !="undefined" || (window.opera == 'undefined' && window.opera.version() > 9.5)) {
      if((typeof window.opera=="undefined" || window.opera.version() > 9.5) && document.documentElement.clientWidth) {
         width = document.documentElement.clientWidth;
         height = document.documentElement.clientHeight;
      }
   }
   if(scrollX==0 || scrollY==0 || isNaN(scrollX) || isNaN(scrollY)) {
      scrollX = document.documentElement.scrollLeft;
      scrollY = document.documentElement.scrollTop;
   }

   var div = document.createElement('div');
   div.id = 'modal_popup_content_overlay';
   div.style.position = 'absolute';
   div.style.left = ((width/2)-220)+'px';
   var screenCenter = getScreenCenter(parseInt(220),parseInt(220));
        screenCenter[0] = parseInt(screenCenter[0]) + 100;
        screenCenter[0] = screenCenter[0] + 'px';
        div.style.top= screenCenter[0];
   div.style.zIndex = '10001';

   div.innerHTML = HtmlResp;
   background_overlay(true);
   var db = document.body;
   db.appendChild(div);
   
   // Omniture impression tracking for getprod price alert pop up
   
}
function ProdPagePopupAlertOnclick(type){
   var newsletter = 'Y' ;
   }
function ProductPagePopUpAlertSubmit(){
   document.getElementById('ProductPagePopUpAlertErr').innerHTML = 'Моля изчакайте...';
   var email = document.getElementById('ProductPagePopUpAlertEmail').value;
   var price = document.getElementById('ProductPagePopUpAlertPrice').value;
   var newsletter =  'Y' ;
   var product_id = document.getElementById('ProductPagePopUpAlertProductId').value;
   var id_type = document.getElementById('ProductPagePopUpAlertIdType').value;
   var low_price = document.getElementById('ProductPagePopUpAlertLowPrice').value;
   if(isValidEmail(email)){
      document.getElementById('ProductPagePopUpAlertErr').innerHTML = '';
      if(newsletter){
         ajax = new AjaxRequest('GET', baseurl + 'search_getprod_ajax.php', true, 3000);
         ajax.setCallback( ProductPagePopUpAlertNewsletterCallback );
         ajax.setParameter('temp_newsletter_req', 'yes');
         ajax.setParameter('email', email);
         ajax.setParameter('price', price);
         ajax.setParameter('newsletter', newsletter);
         ajax.setParameter('product_id', product_id);
         ajax.setParameter('id_type', id_type);
         ajax.setParameter('low_price', low_price);
         ajax.setParameter('action', 'ProductPagePopUpAlertSubmit');
         ajax.send();
      }


   }else
      document.getElementById('ProductPagePopUpAlertErr').innerHTML = 'Невалиден email адрес!';
}

 function ProductPagePopUpAlertNewsletterCallback(XmlResp){
   if(!XmlResp){
      document.getElementById('ProductPagePopUpAlertErr').innerHTML = 'Възникна грешка, моля опитайте по-късно!';
   }else{
      var error = XmlResp.getElementsByTagName('error') ? XmlResp.getElementsByTagName('error') : null;
      var success = XmlResp.getElementsByTagName('success') ? XmlResp.getElementsByTagName('success') :  null;
      if(error.length > 0){
         var nb = XmlResp.getElementsByTagName("nb")[0].firstChild.nodeValue;
         var desc = XmlResp.getElementsByTagName("desc")[0].firstChild.nodeValue;
         var action = XmlResp.getElementsByTagName("action")[0].firstChild.nodeValue;
         document.getElementById('ProductPagePopUpAlertErr').innerHTML = desc;
      }
      else if(success.length > 0){
         var verification_email = XmlResp.getElementsByTagName("verification_email")[0] ? XmlResp.getElementsByTagName("verification_email")[0].firstChild.nodeValue : null;
         var optin_update = XmlResp.getElementsByTagName("optin_update")[0] ? XmlResp.getElementsByTagName("optin_update")[0].firstChild.nodeValue : null;
         var price_alert = XmlResp.getElementsByTagName("price_alert")[0] ?  XmlResp.getElementsByTagName("price_alert")[0].firstChild.nodeValue : null;
         var msg = '';
         if(price_alert=='Y'){ msg = 'Благодарим Ви, че използвате нашите услуги. Когато цената на този продукт падне под посочената от вас ще ви изпратим известие на посочения email адрес.'; }
         else if(verification_email=='Y'){ msg = 'Благодарим Ви, че използвате нашите услуги. Когато цената на този продукт падне под посочената от вас ще ви изпратим известие на посочения email адрес.'; }

         document.getElementById('ppPriceAlertBox').style.display = 'none';
         document.getElementById('ppPriceAlertBoxMsg').style.display = 'block';
         document.getElementById('ppPriceAlertBoxMsg').innerHTML = '<font color="green">'+msg+'</font>';
      }else{
         document.getElementById('ProductPagePopUpAlertErr').innerHTML = 'Възникна грешка, моля опитайте по-късно!';
      }
   }
}
function RefreshProductPageAlert(){
         document.getElementById('ppPriceAlertBoxMsg').innerHTML = '';
         document.getElementById('ppPriceAlertBoxMsg').style.display = 'none';
         document.getElementById('ppPriceAlertBox').style.display = 'block';
         document.getElementById('ProductPagePopUpAlertEmail').value = 'Въведи Email';
         document.getElementById('ProductPagePopUpAlertPrice').value = 'Цена';
}

function background_overlay(show){
   if(show){
      if(!document.getElementById('modal_popup_backgroud_overlay')){

         var width = document.body.clientWidth ? document.body.clientWidth : DomUtils.getWindowWidth();
         var height = document.body.clientHeight ? document.body.clientHeight : DomUtils.getWindowHeight();
         var scrollX = DomUtils.getWindowScrollX();
         var scrollY = DomUtils.getWindowScrollY();
         if(width==0 || height==0  || isNaN(width) || isNaN(height) || typeof window.opera !="undefined" || (window.opera == 'undefined' && window.opera.version() > 9.5)){
            if((typeof window.opera=="undefined" || window.opera.version() > 9.5) && (document.documentElement.clientWidth > document.body.clientWidth )) {
               width = document.documentElement.clientWidth;
               height = document.documentElement.clientHeight;
            }
         }
         if(scrollX==0 || scrollY==0 || isNaN(scrollX) || isNaN(scrollY)) {
            scrollX = document.documentElement.scrollLeft;
            scrollY = document.documentElement.scrollTop;
         }

         var div = document.createElement('div');
         div.id = 'modal_popup_background_overlay';
         div.style.position = 'absolute';
         div.style.left = '0px';
         div.style.top = '0px';
         div.style.width = '100%';
         div.style.height = (document.body.clientHeight ? document.body.clientHeight : (scrollY + DomUtils.getWindowHeight())) + 'px';
         div.style.background = '#666666';
         div.style.zIndex = '10000';
         div.style.opacity = '0.4';
         div.style.MozOpacity = '0.4';
         div.style.filter = "alpha(opacity='40')";
         div.style.display = 'block';
         var db = document.body;
         db.appendChild(div);
      }else{
         document.getElementById('modal_popup_backgroud_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
      var isIE6 = DomUtils.browser.isIE6();
      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 = 9999;
            shim.style.display = "none";
            shim.style.position = "absolute";
            shim.style.backgroundColor = "transparent";
            shim.style.top = "0px";
            shim.style.left = "0px";
            document.body.appendChild(shim);
         }

         scrollX = DomUtils.getWindowScrollX();
         scrollY = DomUtils.getWindowScrollY();
         height = DomUtils.getElementHeight(document.body);
         if(document.body.scrollTop) height += document.body.scrollTop ;
         width = DomUtils.getElementWidth(document.body);
         if(height < screen.height) {
            height = (screen.height * .8);
         }

         document.getElementById('shim').style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
         document.getElementById('shim').style.width = width + scrollX + 'px';
         document.getElementById('shim').style.height = height + scrollY + 150  + 'px';
         document.getElementById('shim').style.display = 'block';
      }


   }else{
      if(!document.getElementById('modal_popup_backgroud_overlay')){
         document.getElementById('modal_popup_backgroud_overlay').style.display = 'none';
      }
   }
}

function showImageOverlay(show) {

    //determine if browser is ie6
    temp=navigator.appVersion.split('MSIE');
    ieVer=parseInt(temp[1]);
    var isIE6=(ieVer == 6)?1:0;
    if(!show) {
        document.getElementById('overlay').style.display = 'none';
        document.getElementById('overlay').onclick = null;
        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('overlay').style.width = width + 'px';
            document.getElementById('overlay').style.height = height + 'px';
            document.getElementById('overlay').style.display = 'block';
            document.getElementById('overlay').onclick = closeLargerImage;
        }

        //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 = 9999;
                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';
        } 
    }
}

var PP_resizeIntervalId;
var PP_popupImage;
var PP_popupImageLinks = Array();

var PP_scaleTime = 300;
var PP_scaleSpeed = 15;
var PP_startTime;
var PP_finishTime;
var PP_totalTime;
var PP_pic;
var News_pic;
var PP_dir;
var PP_scaleQueue;
var PP_imageLoadIntervalId;
var PP_popupProductTitle;
var PP_loadImage = new Image();
PP_loadImage.src = baseurl +'templates/v2/images/new/imagePopupLoad.gif';
var PP_origDims;
var PP_origLocation;
var PP_content;
var PP_showMerchantInfo = true;


function showLargerImage(masterid){
    
    is_modal = true;

    

    showImageOverlay(true);
    PP_pic = document.getElementById('picturePopup');
     
    if(PP_pic == null){
      
        var newDiv = document.createElement('div');
        newDiv.setAttribute('id','picturePopup');
        newDiv.setAttribute('class','cb');
        newDiv.style.width = "300px";
        var picturePopupContent = "<div class=\"bt\"><div></div></div>";
        picturePopupContent += "<div class=\"i1\">";
        picturePopupContent += "<div class=\"i2\">";
        picturePopupContent += "<div class=\"i3\" id=\"picturePopup_content\" style=\"height:300px;text-align:center\">";
        picturePopupContent += "<div id=\"picturePopup_close\">";
        picturePopupContent += "<a href='javascript:closeLargerImage()' class=\"close_text\">Затвори</a>";
        picturePopupContent += "<a href='javascript:closeLargerImage()'>&nbsp;<img src='"+ baseurl +"templates/v2/images/new/overlayImg_btn.png' />";
        picturePopupContent += "</a>";
        picturePopupContent += "</div>";
        picturePopupContent += "<div id='picturePopup_load' style=\"position:relative;width:100%;text-align:center;display:none;\">";
        picturePopupContent += "<img src='"+ baseurl +"templates/v2/images/new/imagePopupLoad.gif' alt=\"зареждане\">";
      picturePopupContent += "</div>";
        picturePopupContent += "<div>";
        picturePopupContent += "<img src='' id=\"picturePopup_image\" style=\"margin-left:auto;margin-right:auto\" />";
       picturePopupContent += "</div>";

        picturePopupContent += "</div>";            
        picturePopupContent += "</div>";
        picturePopupContent += "</div>";
        picturePopupContent += "<div class=\"bb\"><div></div></div>";

        newDiv.innerHTML = picturePopupContent;
       document.body.appendChild(newDiv);
        PP_pic = newDiv;
    }
    PP_content = document.getElementById('picturePopup_content');  //have to use content box to set height. Setting the container's
                                                                   //height breaks the box. Also, setting the content box's width also breaks it, so we have to use both.
    var ppMerchant = document.getElementById("picturePopup_merchant");
    if(ppMerchant){
        ppMerchant.style.visibility = "hidden";
    }
    var screenCenter = getScreenCenter(parseInt(PP_pic.style.width),parseInt(PP_content.style.height));

    PP_pic.style.top = screenCenter[0];
    PP_pic.style.left = screenCenter[1];

    PP_origDims = [parseInt(PP_content.style.height),parseInt(PP_pic.style.width)];
    PP_origLocation = [PP_pic.style.top.substring(0,PP_pic.style.top.length-2),
                    PP_pic.style.left.substring(0,PP_pic.style.left.length-2)]


    PP_pic.style.display = "block";
    PP_popupImage = new Image();
    PP_popupImage.src = PP_popupImageLinks['link_' + masterid][0];
    PP_popupProductTitle =  PP_popupImageLinks['link_' + masterid][1];
    PP_popupImage.alt = PP_popupImageLinks['link_' + masterid][1];

    //if image loaded, show the image
    if(PP_popupImage.complete){
      //add a slight delay so it doesn't flicker
      setTimeout('getImagePopupMerchant('+masterid+')',10);
    }
    //otherwise show loading screen
    else{
        loadImageTop = (parseInt(PP_content.style.height)/2) - parseInt(PP_loadImage.height)/2;
        document.getElementById('picturePopup_load').style.top = loadImageTop + 'px';
        document.getElementById('picturePopup_load').style.display = 'block';
        PP_popupImage.onload = function(){
            getImagePopupMerchant(masterid);
        }
    }
}

function getScreenCenter(width,height){

    var screenWidth = DomUtils.getWindowWidth();
    var screenHeight = DomUtils.getWindowHeight();
    var scrollX = DomUtils.getWindowScrollX();
    var scrollY = DomUtils.getWindowScrollY();


    if(screenWidth==0 || screenHeight ==0) {
        if(typeof window.opera=="undefined" && document.documentElement.clientWidth) {
            screenWidth = document.documentElement.clientWidth;
            screenHeight = document.documentElement.clientHeight;
        }
        else {
            screenWidth = document.body.clientWidth;
            screenHeight = document.body.clientHeight;
        }
    }
    if(scrollX==0) {
        scrollX = parseInt(document.documentElement.scrollLeft);
   }
   if(scrollY==0) {
        scrollY = parseInt(document.documentElement.scrollTop);
    }

    //var top =  (scrollY + (screenHeight/2) - (height/2) - 20) + 'px';
    var top = (scrollY + screenHeight*.1) + 'px';
    var left = (scrollX + (screenWidth/2) - (width/2) ) + 'px';
    return Array(top,left);
}

function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  obj.style.filter = "alpha(opacity:"+opacity+")";
  obj.style.opacity = opacity/100;
}

function getImagePopupMerchant(masterid){
    var ajax = new AjaxRequest('POST', baseurl + 'rpc_getSellers.php', true, 3000);
    if (masterid) {
        ajax.setParameter('product_id', masterid);
    }
  
    ajax.setCallback(loadPopupImage);
    ajax.send();

}

function loadPopupImage(xml){
    PP_showMerchantInfo = true;
    var merchant_box_width = 0;
    var merchant_box_height = 0;
    var ppContent = document.getElementById('picturePopup_content');
    var ppMerchant = document.getElementById("merchants");
    if(ppMerchant != null){
        
        ppContent.removeChild(ppMerchant);
        ppMerchant = null;  
    
    }
    if(ppContent != null && ppMerchant != null && ppMerchant.parentNode == ppContent){
        var tmpDiv = ppMerchant;
        ppContent.removeChild(ppMerchant);
        document.body.appendChild(tmpDiv);
       // document.getElementById('picturePopup_merchant').style.float = "left";
    }
    if(ppMerchant == null){
        
        var offers = xml.getElementsByTagName('offers');
        var json = offers[0].firstChild;
        var objOffer = eval(json.firstChild.nodeValue);
        
        if(objOffer[0] != null){
         
            var newDiv1 = document.createElement('div');
        newDiv1.setAttribute('id',"merchants");
           picturePopupContent = ""; 
           var count =0;
            for (var i = 0;i < objOffer.length; i++) {
        var merchantLogo =   objOffer[i]['merchant_logo'];
          count++;
        picturePopupContent += "<div id=\"picturePopup_merchant_"+ i +"\">";
        picturePopupContent += " <div id=\"popup_merchant_cont\"><nobr>";
        picturePopupContent += "    <div class=\"popup_pricing_right\" id=\"popup_pricing_right_"+ i +"\" >";
        picturePopupContent += "        <span class=\"ie6\">";
        picturePopupContent += "            Купи сега от ";
        picturePopupContent += "            <span id=\"picturePopup_merchant_logo_"+ i +"\"></span>";
          picturePopupContent += "          за";
        picturePopupContent += "            <span id=\"picturePopup_merchant_price_"+ i +"\"></span>";
        picturePopupContent += "        </span>";
        picturePopupContent += "        <span id=\"picturePopup_merchant_button_"+ i +"\">";
        picturePopupContent += "        </span>";
        picturePopupContent += "    </nobr></div>";
        picturePopupContent += "</div>";

        
            }
            newDiv1.innerHTML  = picturePopupContent
       document.body.appendChild(newDiv1); 
        ppMerchant = newDiv1;
        
        }
       
        
    }
        if(xml == null) {
        PP_showMerchantInfo = false;
    }
    else {      
        
        var offers = xml.getElementsByTagName('offers');
        var json = offers[0].firstChild;
        var objOffer = eval(json.firstChild.nodeValue);
        if(objOffer.length > 3)
        objOffer.length = 3;
        if(objOffer[0] != null){
            var count =0;
            for (var i = 0;i < objOffer.length; i++) { 
         
            var merchantName = objOffer[i]['title'];
            var price =          objOffer[i]['price'];
            var merchantLink =      objOffer[i]['merchant_link'];
            var productLink =      objOffer[i]['product_link'];
            var bottomlineText =       objOffer[i]['bottomline_text'];
            var merchantLogo =   objOffer[i]['merchant_logo'];
            count ++;
            var id_type = objOffer[i]['id_type'];
            target = "";

                target = " target = '_blank'";

            
            var price_span = document.getElementById("picturePopup_merchant_price_"+ i);
            var button_span = document.getElementById("picturePopup_merchant_button_"+ i);

            price_span.innerHTML = "<a style='color:#DD2626;' href='" + productLink + "'" + target + " >" + price + "</a>";
            button_span.innerHTML = "<a href='" + productLink + "'" + target + "  class=\"shopButton_green\"><span>" + "Купи" + "</span></a>";

            var merchant_logo = document.getElementById("picturePopup_merchant_logo_"+ i);
            var merchant_logo_html = "<a href='" + productLink + "' " + target + " class=\"picturePopup_link\" style=\"color:#0068B3;\" >";
            var merchant_logo_html = "<a href='" + productLink + "' " + target + " class=\"picturePopup_link\" style=\"color:#0068B3;\" >";
            
            if(objOffer[i]['merchant_logo'] != ''){
                merchant_logo_html += '<img src="' + objOffer[i]['merchant_logo'] + '"  alt="'+objOffer[i]['title']+'" class="vAlign" style="margin-top:-5px;">';
            }
            
            else{
                merchant_logo_html +=  objOffer[i]['title'];
            }
            
            merchant_logo_html += "</a> ";
            merchant_logo.innerHTML = merchant_logo_html;
            }
            
            //move the merchant box off of the view, retrieve it's size, and then hide it again.
            //only way to retrieve the correct width
            ppMerchant.style.left = "-1000px";
            ppMerchant.style.visibility = "visible";
            merchant_box_width = ppMerchant.offsetWidth;        
            
            merchant_box_height = DomUtils.getElementHeight( ppMerchant );
            if(document.getElementById('picturePopup_merchant_0')){
            merchant_box_height = 65;  
            document.getElementById('popup_pricing_right_0').style.paddingTop = "17px";
            }
        if(document.getElementById('picturePopup_merchant_1')){
           merchant_box_height = 130;
           document.getElementById('popup_pricing_right_0').style.paddingTop = "17px";
        }
        if(document.getElementById('picturePopup_merchant_2')){
            merchant_box_height = 195 ;
            document.getElementById('popup_pricing_right_0').style.paddingTop = "17px";
        }
            ppMerchant.style.visibility = "hidden";
            document.body.removeChild(ppMerchant);
            ppContent.appendChild(ppMerchant);
            
            PP_content.style.height = parseInt(PP_content.style.height) - 140 + "px";
        
        }
        else{
            PP_showMerchantInfo = false;
        } 
  
    }
    document.getElementById('picturePopup_load').style.display = 'none';
    PP_pic = document.getElementById('picturePopup');

    var bwidth = PP_popupImage.width;
    var bheight = PP_popupImage.height + merchant_box_height; 
    
    var total_width = Math.max(bwidth,merchant_box_width) + 112; //112 accounts for padding of the border

    //prepare effects
    PP_scaleQueue = Array();
    var xStretch = new Object();
    var yStretch = new Object();
    xStretch.scaleStart = parseInt(PP_pic.style.width);
    xStretch.scaleEnd =  total_width;
    xStretch.dir = "x";
    yStretch.scaleStart = parseInt(PP_content.style.height);
    yStretch.scaleEnd =   bheight;
    yStretch.dir = "y";

    //only add effects to queue if they are neccessary
    if(yStretch.scaleStart != yStretch.scaleEnd){
         PP_scaleQueue.push(yStretch);
    }
    if(xStretch.scaleStart != xStretch.scaleEnd){
         PP_scaleQueue.push(xStretch);
    }


    PP_startTime = new Date().getTime();
    PP_finishTime = PP_startTime + PP_scaleTime;
    PP_totalTime = PP_scaleTime;
    PP_resizeIntervalId = setInterval('resizePopup()',PP_scaleSpeed);

}

function resizePopup(){
    var timeStamp = new Date().getTime();
    if(PP_startTime > timeStamp){
        return;
    }
    if(PP_scaleQueue.length == 0){
         clearInterval(PP_resizeIntervalId);
         insertImage();

         return;
    }
    //current width and height
    var height = parseInt(PP_content.style.height);
    var width = parseInt(PP_pic.style.width);

    //current scale the popup should be, based off of the current time
    var fraction   = (timeStamp - PP_startTime) / PP_totalTime;
    //finished
    if(timeStamp > PP_finishTime){
        //finalize width/height
        if(PP_scaleQueue[0].dir == "x"){
            PP_pic.style.width= PP_scaleQueue[0].scaleEnd + 'px';
        }
        else{
          PP_content.style.height  = PP_scaleQueue[0].scaleEnd + 'px';
        }
        clearInterval(PP_resizeIntervalId);
        PP_scaleQueue.shift();
        //if there are still effects, pop the next one
        if(PP_scaleQueue.length > 0){
            PP_startTime = new Date().getTime();
            PP_finishTime = PP_startTime + PP_scaleTime;
            PP_totalTime = PP_scaleTime;
            PP_resizeIntervalId = setInterval('resizePopup()',PP_scaleSpeed);
        }
        //completely done with scale effects. Fade in the image
        else{
           insertImage();
        }
        return;
    }
    else{

         if(PP_scaleQueue[0].dir == "x"){
            width = PP_scaleQueue[0].scaleStart + (PP_scaleQueue[0].scaleEnd-PP_scaleQueue[0].scaleStart)*fraction;
         }
         else{
            height = PP_scaleQueue[0].scaleStart + (PP_scaleQueue[0].scaleEnd-PP_scaleQueue[0].scaleStart)*fraction;
         }
    }
    PP_content.style.height = height + "px";
    PP_pic.style.width = width + "px";
    if(PP_scaleQueue[0].dir == "x"){
        PP_pic.style.left = (PP_origLocation[1] - (width - PP_origDims[1])/2) + 'px';
    }
}

function insertImage(){

    var height = parseInt(PP_content.style.height);
    var width = parseInt(PP_pic.style.width);
    var  dWidth = (width  - PP_origDims[1])/2;
    PP_pic.style.left = (PP_origLocation[1]-dWidth) + 'px';
    PP_startTime = new Date().getTime();
    PP_finishTime = PP_startTime + PP_scaleTime;
    PP_totalTime = PP_scaleTime;
    var image = document.getElementById('picturePopup_image');
    image.src = PP_popupImage.src;
    image.alt = PP_popupImage.alt;
    //setOpacity(image, 0);

    //need to set both due to IE6 issue
    image.style.visibility = 'visible';
    image.style.display= 'block';

    PP_imageLoadIntervalId = setInterval('fadeImage()',PP_scaleSpeed);

}
function fadeImage(obj){
    var timeStamp = new Date().getTime();
    if(timeStamp > PP_finishTime){
        clearInterval(PP_imageLoadIntervalId);
        addPopupFoot();
    }
    var fraction = (timeStamp - PP_startTime) / PP_totalTime;
    setOpacity(document.getElementById('picturePopup_image'),100*fraction);
}

function addPopupFoot(){
      
    //move the merchant popup to its correct location
    if(PP_showMerchantInfo){
           
        
        document.getElementById('merchants').style.visibility = "visible";
        document.getElementById('merchants').style.position = "absolute";
        document.getElementById('merchants').style.left = (parseInt(PP_pic.style.width)/2 -         
            DomUtils.getElementWidth(document.getElementById('merchants'))/2) + "px";
        document.getElementById('merchants').style.top = (parseInt(PP_popupImage.height)+60) + "px";
        
        
    }
    else {
        document.getElementById('merchants').style.visibility = "hidden";
    }
    document.getElementById('picturePopup_close').style.visibility = 'visible';
}


function closeLargerImage(){

    is_modal = false;

    var pic = document.getElementById('picturePopup');
    pic.style.display = "none";

    showImageOverlay(false);
    document.getElementById('picturePopup_close').style.visibility = 'hidden';
    var image = document.getElementById('picturePopup_image');
    setOpacity(image, 0);
    document.getElementById('picturePopup_image').style.visibility = 'hidden';
    document.getElementById('merchants').style.visibility = 'visible';
    document.getElementById('picturePopup_image').style.display = 'none';

}

function showProductImageOverlay(masterid,aTag,show){ 
   
    var overlayBox = document.getElementById('picOverlay_' + masterid); 
    var magImg = document.getElementById('zoom_' + masterid); 
    if(show == true){ 
        /*clearTimeout(SPIO_TimeoutID["'" + masterid + "'"]);
        if(overlayBox.style.display == "block"){
            if(SPIO_curFading["'" + masterid + "'"] == false){
                setOpacity(overlayBox,80);
             }
          return;
        }
        setOpacity(overlayBox,0);
        SPIO_curFading["'" + masterid + "'"] = true;
        overlayBox.style.display = "block";
        SPIO_fadeIn(masterid,0); */ 
        overlayBox.style.display = "block";
    }
    else{
        overlayBox.style.display = "none";
        //SPIO_TimeoutID["'" + masterid + "'"] = setTimeout("SPIO_fadeOut(" + masterid + ",80)",100);          
    }  
}


//addtolist
var ajaxLoaded = 0;
var ulistsLoaded = 0;
function addProdToList() {

  is_modal = true;

  waitForLoad();
}
function waitForLoad() {
    if(!ulistsLoaded) {
        if(window.ulists_js) { ulistsLoaded = 1; ShowListMessage('<img src="'+ baseurl +'templates/v2/images/new/small_wait.gif" width=16 height=16>','Моля изчакайте докато обработим вашата заявка ...','#666666');}
        else { setTimeout('waitForLoad("");',200); return 0; }
    }
    if(!ajaxLoaded) {
        if(window.ajax) { ajaxLoaded = 1; }
        else { setTimeout('waitForLoad("");',200); return 0; }
    }
    if(ajaxLoaded && ulistsLoaded) { addToList(); }
}

//emailpopup
function saSendEmail(page_title){
    ajax = new AjaxRequest('GET', baseurl + 'login.php', true, 3000);
    ajax.setCallback( saEmailCallback );
    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 showSAOverlayBubble(show,type) {

    showSAOverlay(show);

    if(!show && !saBubbleIsClosed()) {
        document.getElementById('saoverlaybubble').style.left = '-1000px';
               
    }
    else if(show){
                     

        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('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('overlay').style.width = width + 'px';
            document.getElementById('overlay').style.height = height + 'px';
            document.getElementById('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 = 'Моля, попълнете име.';
    }
    else if( !isValidEmail(document.sa.friend_e.value) ) {
        errors = 1;
        error_msg = 'Невалиден email адрес.';
    }
    if( errors == 1 ) {
        document.getElementById("sabubble_email_error").innerHTML = error_msg;
    }
    else if( errors == 0 ) {
        saBubbleClose();
        ShowSAMessage('<img src="'+ baseurl +'templates/v2/images/new/small_wait.gif" width=16 height=16>','Моля изчакайте докато обработим вашата заявка ...','#666666');
        ajax = new AjaxRequest('GET', baseurl + '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('email_msg', document.sa.email_msg.value);
        ajax.setParameter('type', 'sa_email');
        
        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)
{
    if (SA_overSellersLink)
        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){
//        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;
    
    SA_popup.style.width = width + 'px';
    // end hack


    setPopupPosition(anchor ,SA_popup, popup_type);
    SA_popup.style.visibility = "visible";
    document.onmousemove=SA_checkMousePosition;
    document.onmousedown=SA_checkMousePosition;

}



//favorites
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:"")+"');";
                        iframe_login('login_registration', callbackfuncafterlogin);
            return;
        }
    }

    if (!user_id) {
        return false;
    }
    
//    console.log('addUserFavorite ' + user_id + ' - ' + preference_id_type + ' - ' + preference_id);
    var ajax = new AjaxRequest('GET', baseurl + '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'];
    }
        
}
