///<reference path="../TESCO.js" />
///<reference path="../event.js" />
///<reference path="../eventManager.js" />
///<reference path="../exception.js" />
///<reference path="../node.js" />
///<reference path="../position.js" />
///<reference path="flyout.js" />
///<reference path="flyout.behaviour.js" />

TESCO.UI.Carousel = (function() {

    TESCO.system.event.document.addEventListener("load",
		function() {
		    var cList = document.getElementsByClassName('featuredSpaceWrapper');
		    if (cList)
		        for (var idx = 0; idx < cList.length; idx++) {
		        new TESCO.UI.Carousel(50, cList[idx], 'horizontal');
		    }
		}
	);

    var NODE = TESCO.system.DOM.node;
    var _self = this;

    TESCO.system.event.manager.call(_constructor.event = {}, "scroll");

    function firstElement(arr) {
        if (arr) {
            if (arr[0]) return arr[0];
            if (arr.length == 0) return null;
            return arr;
        }
    }

    function _constructor(speed, container, orientation) {
        if (!container || !orientation) return;

        this.container = container;
        this.speed = speed;
        this.orientation = orientation;
        this.configuration = {};


        // create animation object
        if ((this.previous = firstElement(NODE.getElementsByClassName(this.container, "carousel-previous"))) &&
			(this.next = firstElement(NODE.getElementsByClassName(this.container, "carousel-next"))) &&
			(this.form = firstElement(NODE.getElementsByClassName(this.container, "featuredSpaceContainer"))) &&
			(this.list = firstElement(this.form.getElementsByTagName("ul")))) {
            this.previous.action = TESCO.sites.Configuration.carousel.step ;  // mark the buttons
            this.next.action = -(TESCO.sites.Configuration.carousel.step);
            this.animateObj = new TESCO.UI.Rectangle.Position.Animation(this.form, false);
            this.setConfiguration();
            this.animateObj.scrollTo(0, 0);  // reset the axis
            if (TESCO.sites.Configuration.carousel.paginationEnabled) {
                this.configurePagination();
            }
            this.resizeContainer();
            this.attachEventHandlers();
            this.configureFlyouts();
        }
        return this;
    }
    
	
    _constructor.prototype.NAME = "TESCO.UI.Carousel";

    //	attach events and handlers
    _constructor.prototype.attachEventHandlers = function() {
        var _self = this;
        TESCO.system.event.attach(this.container, "click",
			function(e) {
			    var _control = e.target;
			    if (!_control.action)
			        _control = _control.parentNode;
			    if (_control.action != undefined && !TESCO.system.DOM.node.hasClassName(_control, "pOff") && !TESCO.system.DOM.node.hasClassName(_control, "nOff")) {
			        _self.actuate(_control.action);
			        e.prevent();
			    } else if (TESCO.system.DOM.node.hasClassName(e.target, "page")) {
			        _self.paginate(e);
			        e.prevent();
			    }
			}
		);

        TESCO.system.event.attach(window, "resize", function(e) { _self.resizeContainer() }, false);

    }

    _constructor.prototype.configurePagination = function() {
        if (this.configuration.totalItems > this.configuration.itemsInWindow) {
            var _paginationContainer = document.createElement("div");
            TESCO.system.DOM.node.addClassName(_paginationContainer, "paginationContainer");        
            this.configuration.numPages = Math.ceil(this.configuration.totalItems/this.configuration.itemsInWindow);
            
            var _firstMargin = (640 - (this.configuration.numPages*25)) / 2;
            
            for(var i=0;i<this.configuration.numPages;i++) {
                var _page = document.createElement("a");
                
                //Create classname
                var _classVal = "p-" + (i+1);                
                i == 0 ? _classVal += " on page" : _classVal += " off page";
                if (i == this.configuration.numPages-1) _classVal+= " last";
                TESCO.system.DOM.node.addClassName(_page, _classVal);
                //Add margin if this is the first page
                if (i == 0) {
                    _page.style.marginLeft = (_firstMargin + TESCO.system.browser.px);
                }
                //Add other attributes
                _page.setAttribute("href", document.location.href + "#");
                _page.setAttribute("title", TESCO.locale.carousel.title + (i + 1));
                
                _textSpan = document.createElement("span");
                TESCO.system.DOM.node.addClassName(_textSpan, "hide");
                _textSpan.appendChild(document.createTextNode(TESCO.locale.carousel.title));
                _page.appendChild(_textSpan);
                _page.appendChild(document.createTextNode(i + 1));
                _paginationContainer.appendChild(_page);
            }
            
            //Create page counter
            var _pageCount = document.createElement("span");
            TESCO.system.DOM.node.addClassName(_pageCount, "pageCounter");
            _pageCount.appendChild(document.createTextNode("(1 / " + this.configuration.numPages + ")"));  
            _paginationContainer.appendChild(_pageCount);
           
            this.container.appendChild(_paginationContainer);
        }
    }
    
    _constructor.prototype.paginate = function(e) { 
        var _pageNum = e.target.className.trimLeft().split(" ")[0].split("-")[1];
        
        //If this is the last page, work out the final 5
        if (TESCO.system.DOM.node.hasClassName(e.target, "last")) {
            this.configuration.startItem = (this.configuration.totalItems - this.configuration.itemsInWindow)+1;
        } else {
            this.configuration.startItem = (_pageNum * this.configuration.itemsInWindow)-(this.configuration.itemsInWindow-1);
        }
        this.configuration.endItem = this.configuration.startItem + this.configuration.itemsInWindow;

        this.animateObj.scroll(this.configuration.itemWidth * (this.configuration.startItem-1), 0, this.speed);
        this.setButtonVisibility();
        this.updatePageData();
        
        this.tag();
    }
    
    _constructor.prototype.updatePageData = function() {
        //First reset all to 'off'
        var _pages = TESCO.system.DOM.node.getElementsByClassName(this.container, "page");
        for (var i=0;i<_pages.length;i++) {
            TESCO.system.DOM.node.removeClassName(_pages[i], "on");
            TESCO.system.DOM.node.addClassName(_pages[i], "off");
        }
        
        //Work out which page is now active
        var _activePage = Math.ceil((this.configuration.startItem + this.configuration.itemsInWindow -1) / this.configuration.itemsInWindow);
        TESCO.system.DOM.node.addClassName(_pages[_activePage - 1], "on");
        TESCO.system.DOM.node.removeClassName(_pages[_activePage - 1], "off");
        
        //Update Page counter
        var _pageCounter = TESCO.system.DOM.node.getElementsByClassName(this.container, "pageCounter")[0];
        TESCO.system.DOM.node.removeChildNodes(_pageCounter);
        _pageCounter.appendChild(document.createTextNode("(" + _activePage + " / " + this.configuration.numPages + ")"));  
    }

    //Setup product and promo flyouts
    _constructor.prototype.configureFlyouts = function() {
        var _flyoutCollection = NODE.getElementsByClassName(this.container, 'productMidi');
        var _productID;
        
        if (_flyoutCollection) {
//            for (var i = 0, L = _flyoutCollection.length; i < L; i++) {
//                _productID = _flyoutCollection[i].firstChild.id;
//                _productID = _productID.substr(2);
//                _productID = _productID.substr(0, _productID.length - 7);
//                TESCO.UI.Flyout.cache.setItem("carouselProduct" + _productID, _flyoutCollection[i]);
//            }
            new TESCO.UI.Flyout.Modal(this.container, TESCO.UI.Flyout.position.x.left, TESCO.UI.Flyout.position.y.centreoffset);
        }
    }

    _constructor.prototype.setConfiguration = function() {
        this.configuration.totalItems = TESCO.system.DOM.node.getElementsByClassName(this.list, "cp").length;
        this.configuration.windowWidth = this.list.parentNode.offsetWidth;
        this.configuration.itemWidth = parseInt(this.list.getElementsByTagName("li")[0].offsetWidth);
        this.configuration.startItem = 1;
        this.configuration.endItem = this.configuration.itemsInWindow = Math.floor((this.container.offsetWidth - 30) / this.configuration.itemWidth);
        this.list.style.width = (this.configuration.totalItems + 1) * this.configuration.itemWidth + TESCO.system.browser.px; // add one for rounding safety
        this.configuration.currentCandidates = this.getCurrentCandidates();
    }
    
    _constructor.prototype.getCurrentCandidates = function() {
        var _prods = TESCO.system.DOM.node.getElementsByClassName(this.list, "cp");
        var _cProds = Array();
        for (var i=0;i<this.configuration.totalItems;i++) {
            if (i < (this.configuration.startItem + this.configuration.itemsInWindow-1) && i >= this.configuration.startItem-1) {
                _cProds.push(_prods[i]);
            }
        }
        return _cProds;
    }

    _constructor.prototype.setButtonVisibility = function() {
        var NODE = TESCO.system.DOM.node;
        this.configuration.startItem == 1 ? NODE.addClassName(this.previous, "pOff") : NODE.removeClassName(this.previous, "pOff");
        this.configuration.endItem > this.configuration.totalItems ? NODE.addClassName(this.next, "nOff") : NODE.removeClassName(this.next, "nOff");
    }

    _constructor.prototype.actuate = function(action) {
    
        //If we're on the last 'page'
        if (this.configuration.endItem - action > this.configuration.totalItems) {
            this.configuration.startItem = (this.configuration.totalItems - this.configuration.itemsInWindow)+1;
        } else {
            //If current startItem is a multiple of itemsInWindow then minus action, else find closest multiple
            if (this.configuration.startItem == 1 || (this.configuration.startItem-1) % TESCO.sites.Configuration.carousel.step == 0) {
                this.configuration.startItem -= action;
            } else {
                 this.configuration.startItem = this.configuration.startItem - (this.configuration.totalItems % this.configuration.itemsInWindow);
            }
        }
        this.configuration.endItem = this.configuration.startItem + (this.configuration.itemsInWindow);
       
        this.animateObj.scroll(this.configuration.itemWidth * (this.configuration.startItem - 1), 0, this.speed);
        this.setButtonVisibility();
        if (TESCO.sites.Configuration.carousel.paginationEnabled) {
            this.updatePageData();
        }
          
        this.tag();   
    }
    
    _constructor.prototype.tag = function() {
        var _nextProds = this.getCurrentCandidates();
        var _prodObj = {};
        var _newProds = _nextProds.diff(this.configuration.currentCandidates);
        _prodObj.fsID = this.form.id.split("-")[1];
        _prodObj.products = _newProds;
        _constructor.event.dispatchEvent("scroll", _prodObj);   
        this.configuration.currentCandidates = _nextProds;
    }

    _constructor.prototype.resizeContainer = function() {
        var _pxWidth = Math.floor((this.container.offsetWidth) / this.configuration.itemWidth) * this.configuration.itemWidth;
        this.configuration.itemsInWindow = Math.floor((this.container.offsetWidth) / this.configuration.itemWidth);
        this.configuration.endItem = this.configuration.startItem + this.configuration.itemsInWindow;
        this.setButtonVisibility();
    }

    return _constructor;
})();
