﻿/*
Modified : 13/05/10
Version : 1.3v
Dev Date : 7/05/10
Developed By : Bal Jagpal
Dependencies :  Jquey.js, JessopsLightBox.js, productLightBox.css
Summary : Creates a lightbox in the center of the browser. JS consists of two classes.
JessopsLightBox - creates the template of the lightbox to be used
JessopsLightBoxData - constructs the data that is to be displayed with in the Lightbox.
Note: one of the args for JessopsLightBoxData requires the instanceName for access from its hardcodded html 
*/

function cleareTags(HtmlText){
    var stringToReplace = String(HtmlText);
    var pat = /<!--[.\n\t\r\w\W]*-->/gi
    stringToReplace = stringToReplace.replace(pat,'');
    var re=/(<\/?p)(?:\s[^>]*)?(>)|<[^>]*>/gi;
    return stringToReplace.replace(re,'');
}


/* -------------------------------
JessopsLightBoxData Class
--------------------------------- */
var JessopsLightBoxData = function(instanceName,id,height,width,bkAlpha,timeout){
    this._instanceName = instanceName;
	this._id = id;
    this._LightBox = new JessopsLightBox(id,height,width,bkAlpha,timeout);
    var _this = this;
    this.GetLightBox = function()
    {
        return _this._LightBox
    }
}
JessopsLightBoxData.prototype = {
    showProduct:function(sku,qString){
        var _this = this;
        var _qString = (typeof qString == 'undefined') ? "" : qString;
        var _LightBox = this.GetLightBox();
		this._LightBox.createLightBoxDiv();
        var url = "/online.store/products/"+ sku +"/show.xml";
        //for testing
        //url = "products/"+sku+"/show.xml";
        
        $.get(url,function(data){
            _this._LightBox.lightBoxAlert(_this.getProductData(data,_qString)); 
        });
    },
    closeProductAndAddItem:function(){
        this._LightBox.fadeOutLightBox();
        setTimeout("itemAlert.addItem()",1000);
    },
    getProductData:function(data,qString){
        var _this = this;
        var qSBool = qString.length > 0 ? true : false;
        var skuOffering = data.getElementsByTagName("skuOffering")[0];
        var product = skuOffering.getElementsByTagName("product")[0];
        var content = "";delivOptions="";addBasketUrl="";priceHtml="";
        var skuID,skuIDNum,skuOffID,prodName,manuf,price,shippingCosts,promotions,save,isOrder,stockStatusID,isCollect,orderMsg,hasCrossSell,desc,shortDesc,prodUrl;
        skuOffID = skuOffering.getAttribute("id");
        price = eval(skuOffering.getAttribute("currentPrice")).toFixed(2);
        skuID = skuOffering.getAttribute("skuCode");
        skuIDNum = skuOffering.getAttribute("skuCodeNumber");
        stockStatusID = skuOffering.getAttribute("homeDeliveryStockStatusId");
        isOrder =  eval(stockStatusID) == 1?true:false; // skuOffering.getAttribute("isAvailableToOrder");
        isCollect = skuOffering.getAttribute("isAvailableForCollectAtStore");
        hasCrossSell = eval(skuOffering.getAttribute("hasVisibleCrossSells"));
        prodUrl = skuOffering.getAttribute("url");
        prodUrl = qSBool ? (prodUrl + "?" + qString) : prodUrl;
        orderMsg = skuOffering.getElementsByTagName("skuStockStatusMessage")[0].firstChild.nodeValue;
        prodName = product.getAttribute("name");
        manuf = product.getAttribute("manufacturerName");
        fullProdName = manuf + " " + prodName;
        addBasketUrl = "/online.store/ShoppingCart/AddOrderLines.html?skuOfferingId=" + skuOffID + "&quantity=1";
        addBasketUrl = qSBool ? (addBasketUrl + "&amp;" + qString) : addBasketUrl;
        shippingCosts = skuOffering.getElementsByTagName("shippingCosts")[0];
        save = skuOffering.getElementsByTagName("saleInfo")[0];
        promotions = skuOffering.getElementsByTagName("promotions")[0];
        desc = product.getElementsByTagName("description")[0].firstChild.nodeValue;
        priceHtml = "<div class='lb_priceArea'><span class='lb_priceFinal'>&pound;" + price + "</span></div>";
        shortDesc = cleareTags(desc).substring(0,300);
        shortDesc = shortDesc + " . . . " + "<a class='gotolink' href='" + prodUrl + "'>...more info</a>";
        
        if(shippingCosts){
            var dOptions = shippingCosts.getElementsByTagName("shippingCostInfo");
            
            delivOptions = "<ul class='lb_deliveryoptions prodlinksright'>";
            for(var i=0;i<dOptions.length;i++){
                delivOptions += "<li class='deliverypd'>" + dOptions[i].getAttribute("shippingCostName") + "</li>";
            }
            delivOptions += "</ul>";
        }
        if(save){
            var saveprice = save.getAttribute("saving");
            var isSale = eval(save.getAttribute("isSalePrice"));
            if(saveprice){
                saveprice = eval(saveprice).toFixed(2);
                
                var wasprice = eval(eval(price) + eval(saveprice)).toFixed(2);
                
                priceHtml =  "<div class='lb_priceArea'>";
                priceHtml += "<span class='lb_priceSaveText1'>SAVE &pound;" + saveprice + "</span>";
                priceHtml += "<span class='lb_priceSaveText2'> (Was &pound;" + wasprice + ")</span>";
                priceHtml += "<br/>";
                priceHtml += "<span class='lb_priceFinal";
                priceHtml += isSale ? " lb_priceSaleText'>SALE PRICE &pound;" + price + "</span>" : "'>&pound;" + price + "</span>";
                priceHtml += "</div>";
            }
        }
        if(promotions){
            var promotion = promotions.getElementsByTagName("promotion");
            for(var j=0;j<promotion.length;j++){
                var promName = promotion[j].getAttribute("name");
                
                var pat = /cashback/ig
                if(promName.match(pat)){
                    var si = promName.indexOf("£");
                    var li = promName.indexOf(" ",si);
                    
                    var cbAmount = eval(promName.substring(si+1,li));
                    var cbDiscount = eval(price - cbAmount).toFixed(2);;
                    priceHtml =  "<div class='lb_priceArea'>";
                    priceHtml += "<span class='lb_priceFinal'>&pound;" + cbDiscount + "</span>";
                    priceHtml += "<span class='lb_priceCBText1'> including &pound;" + cbAmount + " cashback from " + manuf + "</span>";
                    priceHtml += "<br/>";
                    priceHtml += "<span class='lb_priceCBText2'>You pay £" + price + " today</span>";
                    priceHtml += "</div>";
                }
            }
            
        }
        var imageHTML = product.getElementsByTagName("images").length > 0?"<img src='http://www.jessops.com/ce-images/PRODUCT/PRODUCT_REGULAR/" + skuID + ".jpg' alt='" + fullProdName + "' />":"<span>Image Coming Soon</span>";
        
        content += "<div class='LightBox_prod' id='LightBox_"+ skuID +"'><div class='LightBox_prodContent'>";
            content += "<div class='LightBox_title'>";
                content += "<h2>"+ fullProdName +"</h2>" ;
                content += "<span>Product code : " + skuIDNum + "</span>";
            content += "</div>";
            content += "<div class='LightBox_mid'>";
                content += "<div class='LightBox_leftcol'>";
                    content += "<span class='lb_image'>" + imageHTML + "</span>";
                content += "</div>";
                content += "<div class='LightBox_rightcol'>";
                    
                    content += priceHtml;
                    content += "<div class='";
                    content += isOrder?'lb_delivery':'lb_nodelivery'; 
                    content += "'><span>" + orderMsg + "</span></div>";
                    content += delivOptions;
                    if(isCollect){
                        content += "<div class='dv_lb_collect'><span class='lb_collect'>Collect at store avaliable</span></div>";
                    }
                    else{
                        content += "<div class='dv_lb_nocollect'><span class='lb_nocollect'>Collect at store is not avaliable</span></div>";
                    }
                    content += "<div class='dv_lb_addtobasket'><span class='lb_addtobasket'>";
                    if(hasCrossSell){
                        addBasketUrl += "&orderDisplayMode=configure";
                        content +="<a class='processbtn' target='_top' href='" + addBasketUrl + "'>Add To Basket</a>";
                    }
                    else{
                        content +="<a class='processbtn' onclick='javascript:"+ _this._instanceName +".closeProductAndAddItem();' id='closeAndAddItem' target='thetrolley' href='" + addBasketUrl + "'>Add To Basket</a>";
                    }
                    content +="</span></div>";
                content += "</div>";
            content += "</div>";
            content += "<div class='LightBox_detailarea'>";
                content += "<div class='lb_titles'>";
                    content += "<span class='lb_titleDesc'>Description</span>";
                content += "</div>";
                content += "<div class='lb_detail'>" + shortDesc + "</div>";
            content += "</div>";
        content += "</div></div>";
        
        return content;
    }
}

/* -------------------------------
JessopsLightBox Class
---------------------------------*/
var JessopsLightBox = function(id,height,width,bkAlpha,timeout){
    //for future developments 'type' will assess the type of display required
    this._id = id;
    this._height = height;
    this._smallHeight = (this._height - 40);
    this._width = width;
    this._bkAlpha = bkAlpha;
    this._timeout = timeout;
    this._rootLightBox = this._id+"_LightBox";
    this._lock = false;
}

JessopsLightBox.prototype = {
    lightBoxAlert:function(content){
        //this.createLightBoxDiv();
        var _this = this;
        setTimeout(function(){_this.setContent(content);},500);
        
    },
    setContent:function(content){
        var _this = this;
        $("#"+_this._rootLightBox).html(content);
        if(_this._timeout>0){
            var _this =  this;
            setTimeout(function(){_this.fadeOutLightBox()},_this._timeout);
        }
    },
    createLightBoxDiv:function(){
        var _this = this;
	    if(!$('div').is('#'+_this._rootLightBox)){
		    var posX = this.getScreenCenterX() - (_this._width/2);
		    var posY = (this.getInnerHeight()/2) - (_this._height/2);
		    var bkDiv = "<div id='" + _this._rootLightBox + "_BKG' style='position:fixed;width:100%;height:" + eval(this.getScrollOffset() + this.getInnerHeight() + 10000) + "px;background:#333;top:0;left:0;z-index:9999;filter:alpha(opacity=" + eval(_this._bkAlpha * 100) + ");opacity:" + _this._bkAlpha + ";' ></div>";
		    var boxDiv = "<div id='" + _this._rootLightBox + "_container' style='position:fixed;width:" + _this._width + "px;height:" + _this._smallHeight + "px;background:#fff;top:"+ posY +"px;left:"+ posX +"px;border:10px solid #dbdfe1;z-index:10000;text-align:left;-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;' ><div id='" + _this._rootLightBox + "' style='z-index:10;overflow:hidden;float:left;background:#transparent;position:absolute;width:" + _this._width + "px;height:" + _this._height +"px; ' ></div><div id='" + _this._rootLightBox + "_closeTab' style='z-index:5;height:25px;margin-top:0px;position:absolute;float:right;right:0px;width:25px;background:transparent;overflow:hidden;' ><img src='/images/site/closebutton.gif' alt='close' class='closelightbox' style='display:block;float:right;color:red;margin:0;background:transparent;padding:0;cursor:pointer;' width='25px' height='25px' /></div></div>";
		    $(bkDiv).hide().appendTo("body").hide();
		    $("#"+_this._rootLightBox+"_BKG").click(function(){
			    _this.fadeOutLightBox();
		    });
		    $(boxDiv).hide().appendTo("body").hide();
		    $("#"+_this._rootLightBox+"_closeTab .closelightbox").click(function(){
			    _this.fadeOutLightBox();
		    });
		    _this.fadeInLightBox();
	    }
	    else{
		    _this.fadeInLightBox();
	    }
		$("#"+_this._rootLightBox).html("<div class='LightBox_Loading' style='margin:" + eval(_this._height/2.8).toFixed(0)  + "px auto 0;text-align:center;font-weight:bold;'><span style='display:block;margin:10px;font-size:1em;'>Loading</span><br><img alt='Loading items' src='/images/site/dotanim.gif'></div>");
    },
    fadeInLightBox:function(){
        var _this = this;
        if(!_this._lock){
            _this._lock = true;
            $("#"+_this._rootLightBox+"_BKG").fadeIn("fast");
            
		    $("#"+_this._rootLightBox+"_container").animate({
			    opacity: "toggle",
			    height: _this._height,
			    width: _this._width
		        }, "slow",'linear', function() {
                    // Animation complete. 
                    $("#"+_this._rootLightBox+"_closeTab").animate({right: "-=40px"}, "slow",function(){
                        setTimeout(function(){_this._lock = false;},1000);
                    });   
	        });
	    }
    },
    fadeOutLightBox:function(){
        var _this = this;
        if(!_this._lock){
            _this._lock = true;
	        $("#"+_this._rootLightBox+"_BKG").fadeOut("slow");
	        $("#"+_this._rootLightBox+"_closeTab").animate({
	            right: "+=36px"
	            }, "fast",function() {
		        // Animation complete.
    		    
		        $("#"+_this._rootLightBox+"_container").animate({
			    opacity: "toggle",
			    height: _this._smallHeight,
			    width: _this._width
		        }, "fast", function() {
		            setTimeout(function(){_this._lock = false;},1000);
		        });
		    });
		}
    },
    getScreenCenterY:function() {
	    var y = 0; 
	    y = getScrollOffset()+(getInnerHeight()/2);
	    return(y);
    },
    getScreenCenterX:function() {
	    return(document.body.clientWidth/2);
    },
    getInnerHeight:function() {
	    var y;
	    // all except Explorer
	    if (self.innerHeight) 
		    y = self.innerHeight;
	    // Explorer 6 Strict Mode
	    else if (document.documentElement && document.documentElement.clientHeight)
		    y = document.documentElement.clientHeight;
	    // other Explorers
	    else if (document.body)
		    y = document.body.clientHeight;
	    return(y);
    },
    getScrollOffset:function() {
	    var y;
	    // all except Explorer
	    if (self.pageYOffset)
		    y = self.pageYOffset;
	    // Explorer 6 Strict
	    else if (document.documentElement && document.documentElement.scrollTop)
		    y = document.documentElement.scrollTop;
	    // all other Explorers
	    else if (document.body)
		    y = document.body.scrollTop;
	    return(y);
    }
}