﻿// product browser class
var ProductBrowser = function(elem, query, category, brand) {
    productBrowser = null;
    this.content = [];
    this.pageVisited = [];
    this.elem = elem;
    this.query = query;
    this.category = category;
    this.brand = brand;
    this.template = null;
    this.carousel = null;
    this.page = 1;
    this.numPerPage = 4;
    
    this._sortCallback = function(event) {
        me = event.data.me;
        me.content = [];
        me.pageVisited = [];
        me.carousel.reset();
        me.scroll(1);
    }
    
    // search submit event handler
    this._search = function(event) {
        event.data.me.query = event.data.me.elem.find("#searchResBoxSearchInput").val();
        event.data.me.content = [];
        event.data.me.pageVisited = [];
        event.data.me.carousel.reset();
        event.data.me.scroll(1);
    }
    
    // updates pagers
    this.updatePagers = function() {
        var c = this._getContent(this.query, this.category, this.brand, this.page)
        var pager = this._getPager(c.pn, c.ps);
        this.elem.find("#titleBarPaging").empty().append(pager);
        this.elem.find("#ftrPager").empty().append(pager.clone(true));
    }
    
    // builds and returns pager elem w/ bound events
    this._getPager = function(curPage, numPages) {
        var elem = $("<span />");
        var a;
        if (this.page == 1) {
            a = $("<span>Prev</span>").addClass("pagerDisabled");
        } else {
            a = $("<a href='#" + (this.page - 1) + "'>Prev</a>");
            a.addClass("fake_link");
            a.bind("click", {pb:this,action:"prev"}, this._pagerAction);
        }
        elem.append(a);
        elem.append(" ");
        for (var i=1; i<=numPages; i++) {
            a = $("<span><a href='#" + i + "'>"+i+"</a></span>");
            if (i == this.page) { a.addClass("pagerCurPage"); }
            a.bind("click", {pb:this, action:i}, this._pagerAction);
            a.addClass("fake_link");
            elem.append(a);
            elem.append(" ");
        }
        if (curPage == numPages) {
            a = $("<span>Next</span>").addClass("pagerDisabled");
        } else {
            a = $("<a href='#" + (this.page + 1) + "'>Next</a>");
            a.addClass("fake_link");
            a.bind("click", {pb:this,action:"next"}, this._pagerAction);
        }
        elem.append(a);
        return elem;
    }
    
    // pager event handler
    this._pagerAction = function(event) {
        var me = event.data.pb;
        var action = event.data.action;
        if (action == "next") {
            me.next();
        } else if (action == "prev") {
            me.prev();
        } else {
            me.scroll(action);
        }
    }
    
    // carousel event handler
    this._carouselGetItems = function(carousel, state) {
        // NOTE: must use 'self' in place of 'this' in this method
        var self = this.productBrowser;
        //alert("first: "+carousel.first+"\nlast: "+carousel.last+"\nstate: "+state);
        if (state == "init") {
            var cont = self._getContent(self.query, self.category, self.brand, 1);
            var items = self._getItemsFromContent(cont.pds);
            for (var i in items) {
                self.carousel.add(i, items[i]);
            }
        } else if (state == "next" || state == "prev") {
            if (!self.pageVisited[self.page]) {
                var cont = self._getContent(self.query, self.category, self.brand, self.page);
                var items = self._getItemsFromContent(cont.pds);
                for (var i in items) {
                    self.carousel.add((parseInt(i) + (self.page - 1) * 4), items[i]);
                }
            }
        } 
    }
    
    // carousel initialization callback
    this._carouselInit = function(newCarousel) { 
        productBrowser.carousel = newCarousel; 
        newCarousel.productBrowser = productBrowser;
    }
    
    // fetch next page
    this.next = function() { 
        this.page++;
        var cont = this._getContent(this.query, this.category, this.brand, this.page);
        if (this.page > cont.ps) { 
            this.page = cont.ps;
            return; 
        }
        this.carousel.next(); 
        this.updatePagers();
        
    }
    
    // fetch prev page
    this.prev = function() { 
        this.page--;
        if (this.page < 1) { this.page = 1; }
        this.carousel.prev(); 
        this.updatePagers();
    }
    
    // fetch specified page
    this.scroll = function(n) { 
        this.page = n;
        this.carousel.scroll((n-1)*4+1); 
        this.updatePagers();
    }
    
    // get array of product elems from array of content
    this._getItemsFromContent = function(content) {
        var result = []
        var prodElemMaster = this.template.find(".searchResProd").eq(0);
        for (var i in content) {
            var prodData = content[i];
            var prodElem = prodElemMaster.clone();
            prodElem.find(".prodImgURL").eq(0).attr("href", prodData.u);
            var imgUrl = prodData.i;
            prodElem.find(".prodImg").eq(0).attr("src", imgUrl);
            var prodDesc = prodElem.find(".prodDescUrl").eq(0).empty().append(prodData.d);
            prodDesc.attr("href", prodData.u);
            prodElem.find(".prodPrice").eq(0).empty().append(parseFloat(prodData.p).toFixed(2));
            if (parseFloat(prodData.p) < 50) { prodElem.find(".freeShipMsg").remove() }
            prodElem.find(".prodQty").eq(0).empty().append(prodData.q);
            if (prodData.q == 1) {
                prodElem.find(".prodUnitPriceBox").remove()
            } else {
                prodElem.find(".prodUnitPrice").eq(0).empty().append(parseFloat(prodData.up).toFixed(2));
            }
            if (prodData.a == null) {
                prodElem.find(".prodAbsorbencyBox").remove();
            } else {
                prodElem.find(".prodAbsorbency").eq(0).empty().append(prodData.a);
            }
            prodElem.find(".prodId").eq(0).empty().append(prodData.id);
            prodElem.find(".prod_id_hdn").attr("value", prodData.id)
            
            var sa = prodElem.find(".samplesAvailable");
            if (prodData.hs) {
                sa.attr("href","productdetail.aspx?id=S" + prodData.id)
            } else {
                sa.remove()
            }
            
            if (!prodData.cn) { 
                prodElem.find(".nroCont").remove()
            } else {
                var calc_box = $(".pd_nro_calculator").eq(0).clone()
                new NroTool($("<div />"), // hack
                            prodElem.find(".nro_box"),
                            calc_box,
                            prodElem.find(".show_calc_btn"),
                            prodElem.find(".freq_input"),
                            prodData.p,
                            prodData.q);
                $("body").append(calc_box);
            }
            
            
            result.push(prodElem);
        }
        return result;
    }
    
    // fetch template html
    this._getTemplate = function() {
        var tmp;
        function cb_getTemplate(data, status) {
            tmp = $(data);
        }
        
        $.ajaxSetup({async: false});
        $.get("/Templates/search_paging_template.html", null, cb_getTemplate, 'html');
        
        return tmp;
    }
    
    // draws the control
    this._createControl = function() {
        var cont = this._getContent(this.query, this.category, this.brand, 1);
        var c = this.elem;
        c.empty();
        var t = this.template.clone()
        
        // fill search query box
        var sb = t.find("#searchResBoxSearchInput");
        sb.val(cont.qs);
        sb.bind("keypress", {me:this}, function(event){if(event.keyCode==13){event.data.me._search(event);}});
        t.find("#searchBoxSubmit").bind("click", {me:this}, this._search);
        //sb.bind("keypress", {me:this}, function(event){alert(event.data.me);});
        var clearbox = t.find(".clearBox").eq(0);
        
        t.find("#searchSort").bind("change", {me:this}, this._sortCallback);
        
        var results = t.find("#searchResults");
        results.empty();

        c.append(t);
        this.updatePagers();    // this call must come after c.append!
        
        var ul = $("<ul></ul>");
        ul.addClass("jcarousel-skin-tango");
        results.append(ul);
        ul.jcarousel({
            scroll:4,
            initCallback:this._carouselInit,
            itemLoadCallback: {onBeforeAnimation: this._carouselGetItems},
            buttonNextHTML: null,
            buttonPrevHTML: null
        });
        
    }
    
    // fetches content (with cacheing)
    this._getContent = function(query, category, brand, pageNum) {
        if (this.content[pageNum] == undefined) {
            this.content[pageNum] = invokeRemote("ProdSearch", {q:query, n:4, p:pageNum, c:category, b:brand, s:parseInt($("#searchSort").val())});
        }
        return this.content[pageNum];
    }
    
    // constructor...
    productBrowser = this;
    this.template = this._getTemplate();
    this._createControl();
    return true;
}

function initControl() {
    var brand_re = /\?Brand=([^#&]+).*/;
    var textsearch_re = /\?TextSearch=([^#&]+).*/;
    var segmentid_re = /\?SegmentID=([^#&]+).*/;
    var url = window.location.href;
    var query = url.match(textsearch_re);
    if (query != null) { query = query[1] }
    var category = url.match(segmentid_re);
    if (category != null) { category = category[1] }
    var brand = url.match(brand_re);
    if (brand != null) { brand = brand[1] }
    var page = url.match(/[^#]*#([0-9]+)/)
    if (page != null) { page = page[1] }
    if (query != null && category != null) { category = null; }
    if (category != null) { category = parseInt(category); }
    var controlElem = $("#prod_browser");
    
    productBrowser = new ProductBrowser(controlElem, query, category, brand);
    if (page != null) { productBrowser.scroll(page * 1) }
}
