var cmbQuickZoomColoursId = "ctl00_cphMain_ctl00_ucQuickZoom_ctl00_cphMain_ctl00_cmbColours";
var cmbQuickZoomSizesId = "ctl00_cphMain_ctl00_ucQuickZoom_ctl00_cphMain_ctl00_cmbSizes";
var hidQuickZoomSizeFilterId = "ctl00_cphMain_ctl00_moduleSHPLinksOSP1980frFR_hidSizeFilter";
var imgQuickZoomMainPhotoId = "ctl00_cphMain_ctl00_ucQuickZoom_ctl00_cphMain_ctl00_imgMainPhoto";

var btnQuickZoomAddToCartId = "ctl00_cphMain_ctl00_btnAddToCart"; 
var hidQuickZoomAddToCartProductIdId = "ctl00_cphMain_ctl00_hidAddToCartProductId";
var hidQuickZoomAddToCartPresCodeId = "ctl00_cphMain_ctl00_hidAddToCartPresCode";
var hidQuickZoomAddToCartBasketSizeId = "ctl00_cphMain_ctl00_hidAddToCartBasketSize";
var hidQuickZoomAddToCartQuantityId = "ctl00_cphMain_ctl00_hidAddToCartQuantity";
var hidQuickZoomAddToCartTrackingCodeId = "ctl00_cphMain_ctl00_hidAddToCartTrackingCode";

var btnAddToCart;
var btnAddToCartDisabled;
var additionalArray;
var onZoomButton = -1;
var reqZoom;
var zooming = -1;
var documentLoaded=false;
var iframeElement=null;
var hiddenSelects = null;
var quickZoomButtonTarget="";





function AddToCart(productId, presCode, basketSize, quantity, trackingCode) {
    $("#" + hidQuickZoomAddToCartProductIdId).attr("value", productId);
    $("#" + hidQuickZoomAddToCartPresCodeId).attr("value", presCode);
    $("#" + hidQuickZoomAddToCartBasketSizeId).attr("value", basketSize);
    $("#" + hidQuickZoomAddToCartQuantityId).attr("value", quantity);
    $("#" + hidQuickZoomAddToCartTrackingCodeId).attr("value", trackingCode);    
    $("#" + btnQuickZoomAddToCartId).click();
}

var postbackElement;
function OnQuickZoomRequestBegin(sender, args) {
    postbackElement = args.get_postBackElement();
 }


function OnQuickZoomRequestEnd(sender, args) {
    if (postbackElement != null) {
        if (postbackElement.id.indexOf("btnQuickZoomAddToCart") != -1) {
            HideUpdatePanel();
        }
    }
}


function getInternetExplorerVersion() {

    var rv = -1; // Return value assumes failure.

    if (navigator.appName == 'Microsoft Internet Explorer') {

        var ua = navigator.userAgent;

        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");

        if (re.exec(ua) != null)

            rv = parseFloat(RegExp.$1);

    }

    return rv;

}

var ieVersion = getInternetExplorerVersion();

//////////////////////////////////////////// Additional Photos ////////////////////////////////////////////

function ShowLargePhotoZoom(imgID, imagePath, filename)
{

	cmbColour = document.getElementById(cmbQuickZoomColoursId);
	cmbSize = document.getElementById(cmbQuickZoomSizesId);

	// Loop ALL products so as to change the colour drop down
	for ( i = 0; i < additionalArray.length; i++)
	{

		// Get Product
		product = additionalArray[i];

		// If product's large image is the large image I want to show, set the drop down selectedIndex		
		if ( product.largeImage == filename )
		{
		
			selectedColour = product.colour;
		
			// Loop ALL colours to select the one
			for ( i = 0; i < cmbColour.options.length; i++)
			{	
				if ( cmbColour.options[i].value == product.colour )
				{
					cmbColour.selectedIndex = i;
					break;
				}
			}				
		
			break;
		}
		
	}

	$("#" + imgID).ImageSwitch({Type:"FlyZoom", Speed:1500, StartLeft: 150, NewImage:imagePath}); 
	SizeChanged(cmbSize.options[0].value, selectedColour);

}


function ShowAdditionalPhotosZoom(addArr, websiteLanguage)
{

	try
	{
		if ( addArr == null )
			addArr = additionalArray;
		
		if ( addArr == null )
		    return;
	}

	catch(err)
	{    
		alert(err);    
		return;
	}
	
	additionalArray = addArr;
    
	divMainPhotoClientID = imgQuickZoomMainPhotoId;

	$("#imgAdditional1").attr("src", additionalArray[additionalIndex]["smallImage"]);
	
	$("#imgAdditional1").click
	(
		function()
		{
			ShowLargePhotoZoom(divMainPhotoClientID, additionalArray[additionalIndex]["mediaPath"] + additionalArray[additionalIndex]["largeImage"], additionalArray[additionalIndex]["largeImage"]); return false;
		}
	)
	
	if ( additionalLength > 0 )
	{
	
		$("#imgAdditional2").attr("src", additionalArray[parseInt(additionalIndex)+1]["smallImage"]);

		$("#imgAdditional2").click		
		(
			function()
			{
				ShowLargePhotoZoom(divMainPhotoClientID, additionalArray[parseInt(additionalIndex)+1]["mediaPath"] + additionalArray[parseInt(additionalIndex)+1]["largeImage"], additionalArray[parseInt(additionalIndex)+1]["largeImage"]); return false;
			}
		)
		
	}
	else
		$("#imgAdditional2").attr("src", "/products/images/emptySmall_" + websiteLanguage + ".gif");
	
	if ( additionalLength > 1 )
	{

		$("#imgAdditional3").attr("src", additionalArray[parseInt(additionalIndex)+2]["smallImage"]);

		$("#imgAdditional3").click
		(
			function()
			{
				ShowLargePhotoZoom(divMainPhotoClientID, additionalArray[parseInt(additionalIndex)+2]["mediaPath"] + additionalArray[parseInt(additionalIndex)+2]["largeImage"], additionalArray[parseInt(additionalIndex)+2]["largeImage"]); return false;
			}
		)	
	}
	else
		$("#imgAdditional3").attr("src", "/products/images/emptySmall_" + websiteLanguage + ".gif");

}


function ShowAdditionalPreviousZoom()
{
	if ( additionalIndex != 0 )
	{
		additionalIndex--;
		ShowAdditionalPhotosZoom();
	}
}


function ShowAdditionalNextZoom()
{
    
	if ( (additionalLength-additionalIndex) > 2 )
		additionalIndex++;
	else
		additionalIndex = 0;
		
	ShowAdditionalPhotosZoom();
}



////////////////////////////////////////////////// Zoom //////////////////////////////////////////////////

function getMouseXY(evt) 
{
	if(evt!=null)
	{
		var tooltip = document.getElementById('iframeZoomBox');
		standardbody=document.body;
		mouseX = (ns5)? evt.pageX: window.event.clientX + standardbody.scrollLeft;
		mouseY = (ns5)? evt.pageY: window.event.clientY + standardbody.scrollTop;    
		winWd = (ns5)? window.innerWidth-20+window.pageXOffset: standardbody.clientWidth+standardbody.scrollLeft;
		winWd = 905+(winWd - 905)/2;
		winHt = (ns5)? window.innerHeight-20+window.pageYOffset: document.documentElement.clientHeight+document.documentElement.scrollTop;
	}
}


function PositionIFrame(iframeCtrl)
{
	iframeCtrl.style.top = "130px";
	iframeCtrl.style.left = "387px";
}

var hideZoomTimer;
var hideZoomProductId;	 
var lastProductId;


//-- Note, as products may be at prescode level <in the product list so that they are at colour level>, pTemp can either be Productid_PresCode, or ProductId.  We need the PresCode
//-- to have unique ids for the different zoom divs.  Product Id is required for the mini pdp iframe.  Therefore, if we find '_', we split and obtain both values.  If not, we initialize
//-- PresCode and ProductId to the given value; that is the ProductId.  Just for reference, products are at prescode level in the product listing, and are at ProductId level in areas such
//-- as carousel etc etc. --//
function InitializeZoomButton(pTemp, documentId, price) {
    
    var productId = '';
    var prescode = '';

    //-- check for 2 conditions; do we have _ (1234567_7654321) and is there anything after _ (1234567_); if yes then it's the prescode, else it's empty --//
    if (pTemp.indexOf('_') != -1 && pTemp.length - 1 != pTemp.indexOf('_')) {
        var temp = pTemp.split('_');
        productId = temp[0];
        prescode = temp[1];
    }
    else {

    //-- if _ exists say; 12345678_ , we remove it
        if (pTemp.length - 1 == pTemp.indexOf('_')) {
            pTemp = pTemp.replace('_', '');
        }

        productId = pTemp;
        prescode = pTemp;
    }

    var hidSubHomePage = $('#hidSubHomePage_' + prescode).val();
    var hidCategory = $('#hidCategory_' + prescode).val();
    var hidProductDescription = $('#hidProductDescription_' + prescode).val();

    /*if(!documentLoaded)
	{
		setTimeout("InitializeZoomButton('"+productId+"','"+documentId+"','"+price+"')",10)
	}
	else
	{*/
    //var zoomBtnWrapper = document.getElementById('Zoom_'+productId);
    var zoomBtnWrapper = $('#Zoom_' + prescode);
    
		var zoomBtn=null;
		var i=0;
		
		// -- hide all other buttons --//
		
		if(lastProductId!=prescode)
		{
//			var divs = document.getElementsByTagName("div");
//			for(i=0;i<divs.length;i++)
//			{
//			    if (divs[i].id.match("Zoom$"))
//			    {
//				   divs[i].style.display="none";
//			    }
		    //			}
		    $("div[id^='Zoom']").css("display", "none");
		}
		lastProductId = prescode;
		zoomBtn = zoomBtnWrapper.children('.ZoomButtonCtrl');
		
		/*for(i=0;i<zoomBtnWrapper.childNodes.length;i++)
		{
			var child = zoomBtnWrapper.childNodes[i];
			if(child.tagName!=null && child.tagName.toLowerCase()=="input")
			{
				zoomBtn=child;
				break;
			}
		}  */
		
		//zoomBtnWrapper.style.display='';
		zoomBtnWrapper.css("display","");
		
		zoomBtn = zoomBtn.get(0);

		zoomBtn.onmouseover = function () {		    
		    onZoomButton = prescode;
		}

//zoomBtn.onmousemove = function () {

//    var divs = $("div[id^='Zoom']")
//    var i = 0;
//    for (i = 0; i < divs.length; i++) {
//        if (divs[i].id != "Zoom_" + productId) {
//            divs[i].style.display = "none";
//        }
//    }
//}

		zoomBtn.onmouseout= function()
		{		    
			onZoomButton=-1;
		}
		zoomBtn.onclick = function () {

		    //-- Google Analytics Parametrisation in mini product page --//
		    var gaqValue = productId + '-' + $('#hidProductTitleGAQ_' + productId).val();
		    _gaq.push(['_trackEvent', 'FicheProduit', 'MiniFicheProduit', gaqValue]);

		    if (quickZoomButtonTarget == "PDP") {
		        window.location = "/" + hidSubHomePage + "/" + hidCategory + "/" + "prodid-" + productId + "-" + documentId + ".aspx";
		        return;
		    }

		    //ShowLoadingZoom(prescode);
		    iframeElement = document.createElement("iframe");

		    if (ieVersion < 0 || (ieVersion > 7 && document.documentMode > 7)) {


		        iframeElement.setAttribute("onload", "QuickZoomIFrameLoaded(this);");
		        iframeElement.setAttribute("id", "quickZoomIframe");
		        //iframeElement.setAttribute("src","/products/quickzoom.aspx?productID="+productId+"&documentID="+documentId);
		        iframeElement.setAttribute("style", "display:none;width:760px;height:450px;z-index:10001;position:relative");
		        iframeElement.setAttribute("frameBorder", "0");
		        iframeElement.setAttribute("scrolling", "no");
		        iframeElement.setAttribute("allowtransparency", "true");
		        iframeElement.width = "760px";
		        iframeElement.height = "450px";
		        iframeElement.allowTransparency = true;

		        //-- chrome compatibility --//
		        var cell = document.getElementById("divQuickZoomContainer");

		        if (cell.hasChildNodes()) {
		            while (cell.childNodes.length >= 1) {
		                cell.removeChild(cell.firstChild);
		            }
		        }

		        document.getElementById('divQuickZoomContainer').appendChild(iframeElement);
		    }
		    else {

		        if (ieVersion <= 6) {

		            var i = 0;
		            var k = 0;
		            var selects = document.getElementsByTagName("select");
		            hiddenSelects = new Array();

		            for (i = 0; i < selects.length; i++) {
		                if (selects[i].style.display == "") {
		                    selects[i].style.display = "none";
		                    hiddenSelects[k] = selects[i];
		                    k++;
		                }
		            }
		        }
		        iframeElement.attachEvent("onload", function () { QuickZoomIFrameLoaded(this); });
		        iframeElement.style.display = "none";
		        iframeElement.style.width = "760px";
		        iframeElement.style.height = "450px";
		        iframeElement.style.zIndex = "10001";

		        //iframeElement.style.position="relative";

		        iframeElement.frameBorder = "0";
		        iframeElement.scrolling = "no";

		        //iframeElement.src="/products/quickzoom.aspx?productID="+productId+"&documentID="+documentId;
		        iframeElement.allowTransparency = true;





		    }
			
			var source;
			if ((window.location.protocol + "//" + window.location.host).indexOf("https") == -1)
				source = "/" + hidSubHomePage + "/" + hidCategory + "/miniprodid-" + productId + "-" + documentId + "-" + hidProductDescription + ".aspx";
			else
				//-- HTTPS Protocol --//
				source = (window.location.protocol + "//" + window.location.host) + "/products/quickzoom.aspx?productID=" + productId + "&documentID=" + documentId;
		   
            document.getElementById('divQuickZoomContainer').appendChild(iframeElement);
		    //-- Set the src after appendChild, otherwise the src page gets called twice --//
		    if (ieVersion <= 6) {
		        iframeElement.src = source;
		    }
		    else {
		        iframeElement.setAttribute("src", source);
		    }

		    this.parentNode.style.display = "none";
		    return false;
		}
	//}
		
    
}

function QuickZoomIFrameLoaded(ctrl)
{	
	
    if(iframeElement!=null)
    {
    
        var i = 0;
        var iframes = document.getElementsByTagName("iframe");
        for (i=0;i<iframes.length;i++)
        {
            iframes[i].style.display="none";            
        }
        iframeElement.style.display="";
        
        document.getElementById("divQuickZoomContainer").style.display="";
        document.getElementById("zoomLoading").style.display="none";
        RepositionUpdatePanel(zooming);
    }
}

function HideZoomButton(productId)
{
    setTimeout("if(onZoomButton!=" + productId + "){document.getElementById('Zoom_" + productId + "').style.display='none';}", 10);    
}


function HideUpdatePanel() {
    var divQuickZoomContainer = document.getElementById('divQuickZoomContainer');
    if(divQuickZoomContainer==null)
        divQuickZoomContainer = parent.document.getElementById('divQuickZoomContainer');
	divQuickZoomContainer.style.display='none';
	var upnlQuickZoom = document.getElementById("ctl00_cphMain_ctl00_upnlQuickZoom");
	if(upnlQuickZoom!=null)
	    upnlQuickZoom.style.display="none";
	var divQuickZoomLoadingContainer = document.getElementById("divQuickZoomLoadingContainer");
	if (divQuickZoomLoadingContainer!=null)
	    divQuickZoomLoadingContainer.style.display="none";
	window.onresize = function(event) {return;}
	window.onscroll = function (event) { return; }
	
	if(iframeElement!=null)
	{
	    var parentNode = iframeElement.parentNode;
	    //parentNode.removeChild(iframeElement);
	    iframeElement=null;
	}
	if(ieVersion<=6)
    {
        var i =0;
        if(hiddenSelects==null)
        {
            hiddenSelects = parent.hiddenSelects;
        }
        if(hiddenSelects!=null)
        {
            for(i=0;i<hiddenSelects.length;i++)
            {  
                hiddenSelects[i].style.display="";            
            }
        }
    }
	zooming=-1;

}


function RepositionUpdatePanel(productId)
{    
    
    if(zooming!=productId)
        HideUpdatePanel();
    
    PositionUpdatePanel(productId);
    window.onresize = function(event) 
    {    
        RepositionUpdatePanel(productId);
    }
    window.onscroll = function(event) 
    {    
        RepositionUpdatePanel(productId);
    }
        
}


function PositionUpdatePanel(productId)
{
    
	//var upnlQuickZoom = document.getElementById('ctl00_cphMain_ctl00_upnlQuickZoom');
	var upnlQuickZoom = document.getElementById('divQuickZoomContainer');
	var loading = false;
	
	if(upnlQuickZoom.style.display=="none")
	{
	    upnlQuickZoom = document.getElementById('divQuickZoomLoadingContainer');
	    upnlQuickZoom.style.zIndex="1000";
	    loading = true;
	}
	
	var ratio = 0.380;
	var windowWidth = 0; 
	var windowHeight = 0;

	var scrollTop = document.documentElement.scrollTop;

	if(scrollTop==0)
		scrollTop = document.body.scrollTop; //-- Chrome/Safari --//

	if(IE)
	{
		ratio=0.375;        
		windowWidth = document.documentElement.offsetWidth;
		windowHeight = document.documentElement.offsetHeight;
	}
	else
	{
		windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
	}

	if (windowWidth>=1200)
		ratio+=0.02;
	windowWidth = $(document).width();
	
	var upnlWidth = $("#"+upnlQuickZoom.id).width();
	
		
	var upnlHeight = $("#"+upnlQuickZoom.id).height();
	
	if(upnlHeight>windowHeight)
		upnlHeight = windowHeight/2;
		    
	upnlQuickZoom.style.position="absolute";    
	upnlQuickZoom.style.top=((windowHeight-upnlHeight)/2+scrollTop)+'px';
	//upnlQuickZoom.style.left=(ratio*windowWidth)+'px';       
	upnlQuickZoom.style.left = ((windowWidth - upnlWidth)/2)+'px';
	   

	if ( zooming != productId )
	{
		if (!loading)
		{
			$("#divQuickZoomContainer").fadeIn('fast');
		}
		else
		{
			$("#divQuickZoomLoadingContainer").fadeIn('fast');
		}
	}

	zooming=productId;
    
}


function ShowLoadingZoom(productId)
{
	
    RepositionUpdatePanel(productId);
    document.getElementById("zoomLoading").style.display="";
    
    $("#divQuickZoomLoadingContainer").fadeIn('fast');
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endZoomReq);
}


function endZoomReq(sender, args) 
{
    /*if (args.get_error() != undefined)
    {
        args.set_errorHandled(true);
        return;        
    }*/
    RepositionUpdatePanel(zooming);
}


function AddToCartClick(ctrl)
{
    ctrl.style.display="none";
    document.getElementById("addToCartLoader").style.display="";
}

function ToggleAddToCart(isEnabled)
{        
    if(isEnabled)
    {        
        btnAddToCart.style.display="";
        btnAddToCartDisabled.style.display="none";        
    }
    else
    {
        btnAddToCart.style.display="none";
        btnAddToCartDisabled.style.display="";
    }
}



// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false;

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE);

// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;  

// Temporary variables to hold mouse x-y pos.s
var tempX = 0+'px'; var tempY = 0+'px'

// how far from mouse to show tip
var offX= 20; var offY= 12;
var ie=document.all

//Set handler to update the mouse position variables when the mouse moves
var ns5=document.getElementById && !document.all
var mouseX; var mouseY; var winWd; var winHt; var zoomBoxTimerId=0;

$(document).ready(function() 
{
	documentLoaded=true;
});


function SWFShowQuickZoom(productId, documentId) {
    var hidSubHomePage = $('#hidSubHomePage_' + productId).val();
    var hidCategory = $('#hidCategory_' + productId).val();
    var hidProductDescription = $('#hidProductDescription_' + productId).val();

    var zoomBtn = $('.ZoomButtonCtrl');

        if (quickZoomButtonTarget == "PDP") {
            window.location = "/" + hidSubHomePage + "/" + hidCategory + "/" + "prodid-" + productId + "-" + documentId + ".aspx";
            return;
        }

        ShowLoadingZoom(productId);
        iframeElement = document.createElement("iframe");

        if (ieVersion < 0 || (ieVersion > 7 && document.documentMode > 7)) {


            iframeElement.setAttribute("onload", "QuickZoomIFrameLoaded(this);");
            iframeElement.setAttribute("id", "quickZoomIframe");
            //iframeElement.setAttribute("src","/products/quickzoom.aspx?productID="+productId+"&documentID="+documentId);
            iframeElement.setAttribute("style", "display:none;width:760px;height:450px;z-index:10001;position:relative");
            iframeElement.setAttribute("frameBorder", "0");
            iframeElement.setAttribute("scrolling", "no");
            iframeElement.setAttribute("allowtransparency", "true");
            iframeElement.width = "760px";
            iframeElement.height = "450px";
            iframeElement.allowTransparency = true;
            document.getElementById('divQuickZoomContainer').appendChild(iframeElement);
        }
        else {

            if (ieVersion <= 6) {

                var i = 0;
                var k = 0;
                var selects = document.getElementsByTagName("select");
                hiddenSelects = new Array();

                for (i = 0; i < selects.length; i++) {
                    if (selects[i].style.display == "") {
                        selects[i].style.display = "none";
                        hiddenSelects[k] = selects[i];
                        k++;
                    }
                }
            }
            iframeElement.attachEvent("onload", function () { QuickZoomIFrameLoaded(this); });
            iframeElement.style.display = "none";
            iframeElement.style.width = "760px";
            iframeElement.style.height = "450px";
            iframeElement.style.zIndex = "10001";

            //iframeElement.style.position="relative";

            iframeElement.frameBorder = "0";
            iframeElement.scrolling = "no";

            //iframeElement.src="/products/quickzoom.aspx?productID="+productId+"&documentID="+documentId;
            iframeElement.allowTransparency = true;


        }
        var source = "/" + hidSubHomePage + "/" + hidCategory + "/miniprodid-" + productId + "-" + documentId + "-" + hidProductDescription + ".aspx";

        document.getElementById('divQuickZoomContainer').appendChild(iframeElement);
        //-- Set the src after appendChild, otherwise the src page gets called twice --//
        if (ieVersion <= 6) {
            iframeElement.src = source;
        }
        else {
            iframeElement.setAttribute("src", source);
        }

          return false;


      }

