﻿/// <reference path="jquery/jquery.intellisense.js" />

Type.registerNamespace("Dabs.Ajax");
Type.registerNamespace("Dabs.Ajax.Panels");

AddEvent(window,'load',initialiseBundleSlaveDetails);

var bundlingSlaveDetailsPanels = new Object();
function initialiseBundleSlaveDetails(){

    if(!compatible || (navigator.userAgent.indexOf('MSIE 5.5') != -1))
        return false;
        
    var bundleDefinitionId;
    // arrBundleDefinitionIds should have already been output somewhere in the page as a global javascript array.
    for(ii=0;ii<arrBundleDefinitionIds.length;ii++){
        bundleDefinitionId = arrBundleDefinitionIds[ii];
        if($get("bundle_" + bundleDefinitionId))
            bundlingSlaveDetailsPanels["bundlingSlaveDetailsPanel_" + bundleDefinitionId] = new Dabs.Ajax.Panels.BundlingSlaveDetailsPanel(bundleDefinitionId);
    }
}

Dabs.Ajax.Panels.BundlingSlaveDetailsPanel = function(bundleDefinitionId){
    this._container = $get("bundle_" + bundleDefinitionId);
    this._slaveDetailPanel = $get("slavedetail_" + bundleDefinitionId)
    this._contentDiv = $get("slavedetailcontent_" + bundleDefinitionId);
    this._bundleDefinitionId = bundleDefinitionId;
    this._storeGroupId = sgid; // sgid var is generated by code behind/vb
    this._referrerCode = referrerCode; // referrerCode var is generated by code behind/vb
    this._manufacturerId = manufacturerId; // manufacturerId var may be generated by code behind/vb if browsing via featured brand
    // create an instance of the Content config object for use throughout this class
    this.registerEventHandlers();
    var qs = new Dabs.Ajax.Utilities.QueryString();
    var qsQuicklinx = qs.getValue("Quicklinx");
   
    if (qsQuicklinx == undefined){
        //support for MVC pages where QL not in querystring
        this._masterQuicklinx = pageQuicklinx;
    } else {
        this._masterQuicklinx = qsQuicklinx;
    }
    
}


Dabs.Ajax.Panels.BundlingSlaveDetailsPanel.prototype = {

    registerEventHandlers: function(){
        var closePanelHyperlink = $get("closeslavedetails_" +  this._bundleDefinitionId);
        var arrThumbs = getElementsByClass('slavethumblink',this._container,'A');
        
        // attach an event handler to the close button
        if(closePanelHyperlink)
            AddEvent(closePanelHyperlink,'click',this.fadePanel.closure(this));
        
        // attach event handlers to each thumbnail image
        for (i=0;i<arrThumbs.length;i++){
            AddEvent(arrThumbs[i],'click',this.slaveThumb_Click.closure(this));
        }
    },
    
    slaveThumb_Click: function(e){
        var evt = e || window.event;
        var evtTarget = evt.target || evt.srcElement;

        // get a reference to the anchor tag if we don't already have one
        if(evtTarget.nodeName != "A")
        evtTarget = evtTarget.parentNode;
        
            
        if(evtTarget.nodeName != 'A')
        { 
            while(evtTarget.nodeType != 3)
            {
                evtTarget = evtTarget.parentNode;
            }
        }
        
        // stop the anchor from doing its thing
        if(evt.preventDefault)
           evt.preventDefault();
        else
           evt.returnValue = false;
         
        // store the href of the link in case we need to default to using it later
        this._thumbHref = evtTarget.href;
        
        // get a reference to the thumb img within the <a> tag
        this._thumbImage = evtTarget.getElementsByTagName("IMG")[0];
        
          
        // get the quicklinx of this slave item from the id attribute of the thumbnail image
        this._quicklinx = this._thumbImage.id.split("_")[1];
        
        if(this._thumbImage.className.indexOf("active") > -1){
            //user clicked the active thumb - make it inactive and fade the panel
            this.fadePanel(e);
        
        }else{
        
            // make any previously active thumbnails inactive
            this.resetAllActiveThumbs();
            
            // make this thumbnail appear active
            this._thumbImage.className += " active ";
            
            // configure the slave detail panel
            this._slaveDetailPanel.style.display = "block";
            this._slaveDetailPanel.style.filter = "alpha(opacity=85)";
            this._slaveDetailPanel.style.MozOpacity = "0.85";
            this._slaveDetailPanel.style.opacity = "0.85";
            
            $(this._contentDiv).fadeOut('medium', this.doAsyncRequest.closure(this))
        }
        
    },
    
    doAsyncRequest: function(){
        // setup preloader
        this.showPreloader();
        this._asyncRequestActive = true;
        
        // call the webservice to get the product details for this quicklinx
        var asyncRequest = Dabs.Ajax.ProductDetails.GetProductDetails(this._quicklinx, this._storeGroupId, this._referrerCode, this.getProductDetails_Complete.closure(this),this.getProductDetails_Timeout.closure(this),this.getProductDetails_Error.closure(this));  
    },
    
    getProductDetails_Complete: function(args){
    
        // cancel the loader timeout
        clearTimeout(this._loaderTimeout);
        this._asyncRequestActive = false;
        
        // hide the preloader
        this.hidePreloader();
        
        // args contains the xml returned from the webservice - extract the product and marketing descriptions from this
        this._productDescription = args.getElementsByTagName("ProductDescription")[0].childNodes[0].nodeValue;
        this._marketingDescription = args.getElementsByTagName("MarketingDescription")[0].childNodes[0].nodeValue;

        this.populatePanel();       
    },
    
    getProductDetails_Timeout: function(args){
        // cancel the loader timeout
        clearTimeout(this._loaderTimeout);
        
        // the webservice timed out - default to redirecting user to product view page
        window.open(this._thumbHref,'_self');
    },
    
    getProductDetails_Error: function(args){
        // cancel the loader timeout
        clearTimeout(this._loaderTimeout);
        
        // the webservice errored - default to redirecting user to product view page
        window.open(this._thumbHref,'_self');
    },
    
    populatePanel: function(){
        this._contentDiv.style.filter = "alpha(opacity=0)";
        this._contentDiv.style.MozOpacity = "0";
        this._contentDiv.style.opacity = "0";
        
        // populate the content div with the product details
        if(this._manufacturerId)
            this._contentDiv.innerHTML = '<p><strong>' + this._productDescription + '</strong><br />' + this._marketingDescription + '<div class="clr"></div><a href="/productview.aspx?quicklinx=' + this._quicklinx + '&aQuicklinx=' + this._masterQuicklinx + '&bdi=' + this._bundleDefinitionId + '&fb=' + this._manufacturerId +'">More...</a></p>';
        else
            this._contentDiv.innerHTML = '<p><strong>' + this._productDescription + '</strong><br />' + this._marketingDescription + '<div class="clr"></div><a href="/productview.aspx?quicklinx=' + this._quicklinx + '&aQuicklinx=' + this._masterQuicklinx + '&bdi=' + this._bundleDefinitionId + '">More...</a></p>'; 
    
        // check/move the relative position of the panel
        //this.positionPanel();
        
        $(this._contentDiv).fadeIn('medium', this.positionNieghbouringPanels);

    },
    
    positionNieghbouringPanels:function(){
        // this repositions any other bundle detail panels in neighbouring bundles to accomodate for any movement when closing/opening this detail panel
        for(ii=0;ii<arrBundleDefinitionIds.length;ii++){
            bundleDefinitionId = arrBundleDefinitionIds[ii];
            if(bundlingSlaveDetailsPanels["bundlingSlaveDetailsPanel_" + bundleDefinitionId]!=null)
                bundlingSlaveDetailsPanels["bundlingSlaveDetailsPanel_" + bundleDefinitionId].positionPanel();
        }
    },
    
    fadePanel: function(e){
        var evt = e || window.event;
        var evtTarget = evt.target || evt.srcElement;
        
        
        // stop the anchor from doing its thing
        if(evt.preventDefault)
           evt.preventDefault();
        else
           evt.returnValue = false;
        
        $(this._contentDiv).fadeOut('medium', this.hidePanel.closure(this));
          
    },
    
    hidePanel: function(e){
        var bundleContainer = $get("bundle_" + this._bundleDefinitionId);
        var thumbsContainer = getElementsByClass("bundledetail",bundleContainer,"div")[0];
         
        this._contentDiv.innerHTML = "";
        this._slaveDetailPanel.style.display = "none";
        this._thumbImage.className = RemoveClassFromClassList(this._thumbImage.className, "active");
        thumbsContainer.style.paddingBottom = 0;
        
        this.resetAllActiveThumbs();
        
        // this repositions any other bundle detail panels in other bundles to accomodate for the space reclaimed when closing this detail panel
        for(ii=0;ii<arrBundleDefinitionIds.length;ii++){
            bundleDefinitionId = arrBundleDefinitionIds[ii];
            if (bundlingSlaveDetailsPanels["bundlingSlaveDetailsPanel_" + bundleDefinitionId] != null)
                bundlingSlaveDetailsPanels["bundlingSlaveDetailsPanel_" + bundleDefinitionId].positionPanel();
        }
        
        $(this._contentDiv).fadeIn('medium');
    },
    
    positionPanel: function(){
        if(!this._thumbImage)
            return;   
        var bundleContainer = $get("bundle_" + this._bundleDefinitionId);
        var thumbsContainer = getElementsByClass("bundledetail",bundleContainer,"div")[0];
        thumbsContainer.style.paddingBottom = 0;
        var panelTop = this._thumbImage.offsetTop + this._thumbImage.offsetHeight -1;
        var allThumbs = getElementsByClass("slavethumb",thumbsContainer,"IMG");
        var allThumbLinks = getElementsByClass("slavethumblink",thumbsContainer,"A");
        var thumbHeight = allThumbLinks[0].offsetHeight;
        var thumbWidth = allThumbLinks[0].offsetWidth + 2;
        var numberOfThumbs = allThumbs.length;
        var numberOfRows = Math.floor(thumbsContainer.offsetHeight / thumbHeight);
        var numberOfCols = Math.floor(thumbsContainer.offsetWidth / thumbWidth);
        var numberOfThumbsPerRow = Math.round(numberOfThumbs / numberOfRows);
        
        var currentThumbIndex;
        for (i=0;i<numberOfThumbs;i++){
            if (this._thumbImage.id == allThumbs[i].id){
                currentThumbIndex = i+1;
                break;
            }
        }
        
        var currentRow = Math.ceil(currentThumbIndex / numberOfCols);   
        var thumbsContainerBottomMargin = this._slaveDetailPanel.offsetHeight - ((numberOfRows - currentRow) * thumbHeight);

        this._slaveDetailPanel.style.top = panelTop + "px";
        if(thumbsContainerBottomMargin>0)
            thumbsContainer.style.paddingBottom = thumbsContainerBottomMargin +"px";       
    },
    
    resetAllActiveThumbs: function(){
        var arrSlaveThumbs = getElementsByClass("slavethumb",this._container,"IMG");
        for(i=0;i<arrSlaveThumbs.length;i++){
            arrSlaveThumbs[i].className = RemoveClassFromClassList(arrSlaveThumbs[i].className, "active");
        }
    },
    
    showPreloader: function(){
        this._contentDiv.innerHTML = '<div style="margin:10px auto; text-align:center;"><img src="/images/' + this._storeGroupId + '/icons/ajax_preloader.gif" /></div>';
        this._contentDiv.style.filter = "alpha(opacity=0)";
        this._contentDiv.style.MozOpacity = "0";
        this._contentDiv.style.opacity = "0";
        this.positionPanel();
        var contentDiv = this._contentDiv;
        this._preloaderTimeout = setTimeout(function(){
            contentDiv.style.filter = "alpha(opacity=100)";
            contentDiv.style.MozOpacity = "1";
            contentDiv.style.opacity = "1";
        },2000);
    },
    
    hidePreloader: function(){
        this._contentDiv.style.filter = "alpha(opacity=100)";
        this._contentDiv.style.MozOpacity = "1";
        this._contentDiv.style.opacity = "1";
        this._contentDiv.style.visibility = "visible";
        this._contentDiv.innerHTML = '';
    },
    
    dispose: function(){
    
    }
}

Dabs.Ajax.Panels.BundlingSlaveDetailsPanel.registerClass('Dabs.Ajax.Panels.BundlingSlaveDetailsPanel',null,Sys.IDisposable)
