﻿$(document).ready(function() {
    ProdLocator.init();
    
    $(".ajaxLoader").ajaxStart( function() {
           $(this).show();
           //ProdLocator.hide();
			$('p.resultsCopy').show();
    });
    
    $(".ajaxLoader").ajaxStop( function() {
           $(this).hide();
           //ProdLocator.show();
    });
    
});

var ProdLocator = {

    $targetEl: null,
    $catSelect: null,
    $detail: null,
    $zip: null,

    getProductId: function() {
        return $(".sizeSelect").find("option:selected").val();
    },
    getRadius: function() {
        return $(".radius").find("option:selected").val();
    },

    proxy: "/Themes/Custom/Proxy/RegularProxy.ashx?url=",
    init: function() {
        var self = this;
        this.$targetEl = $(".prodFinder");
        this.$catSelect = $(".catSelect");
        this.$detail = $(".catDetail");
        this.$zip = $(".zip");

        var url = this.proxy + CSWebServices + "itemlocator%2Fservice.asmx%2FStoreLocatorXML%3Fstrbrand%3Dslimfast%26strCat%3D%26strSize%3D%26strProductLine%3D";
        $.get(url, null, function(data) { ProdLocator.prodCallback(data) }, "xml");
        $(".prodFinderSubmit").click(function() { self.getStores(self.getProductId(), self.$zip.val(), self.getRadius()); });

    },
    show: function() {
        this.$targetEl.show();
    },
    hide: function() {
        this.$targetEl.hide();
    },
    prodCallback: function(data) {
        this.makeTypeFinder($(data).find("Category"));
    },
    makeTypeFinder: function($data) {
        var self = this;
        $data.each(function() {
            $("<option value='" + $(this).attr("Name") + "'>" + $(this).attr("Name") + "</option>")
                    .appendTo(self.$catSelect)
                    .data("prods", $(this).find("Product"));
        });
        self.$catSelect.change(function() {

            if ($('.catSelect').attr("selectedIndex") > 0) {
                $('.prodType .errorMsg').hide();
            }

            var $prods = $(this).find("option:selected").data("prods");
            var $lines = $prods.find("Productline");

            var filtered = [];
            $lines.each(function() {
                var name = $(this).attr("ProductLine");
                if ($.inArray(name, filtered) === -1) {
                    filtered.push(name);
                }
            });

            // make a list for product line
            var $lineList = $(".lineSelect").empty();

            $(filtered).each(function() {
                $("<option value='" + this + "'>" + this + "</option>")
                        .appendTo($lineList);
            });


            $lineList.change(function() {
                var $list = $(".productSelect").empty();


                var selectedLine = $(this).find("option:selected").val();
                var filtProds = $.grep($prods, function(p) {
                    return $(p).find("Productline[ProductLine=" + selectedLine + "]").length > 0;
                });

                $(filtProds).each(function() {
                    $("<option value='" + $(this).attr("Name") + "'>" + $(this).attr("Name") + "</option>")
                            .appendTo($list)
                            .data("prod", this);
                });
                $list.change(
                    function() {
                        var $sizeList = $(".sizeSelect").empty();
                        var prod = $(this).find("option:selected").data("prod");
                        var sizes = $(prod).find("Psize");
                        $(sizes).each(function() {
                            var id = $(this).find("ProductId").attr("ProductId");
                            $("<option value='" + id + "'>" + $(this).attr("Size") + "</option>")
                            .appendTo($sizeList)
                        });
                    }
                );
                $list.change();

            });
            $lineList.change();
            $(".catDetail").show();
        });
    },
    getStores: function(id, zip, radius) {
        var self = this;
        if (self.validate()) {
            var s = new Stores(this.proxy, id, zip, radius);
        }
    },
    validate: function() {
        if ($('.catSelect').attr("selectedIndex") <= 0) {
            $('.prodType .errorMsg').show();
            return false;
        }
        else {
            $('.prodType .errorMsg').hide();
        }
        if (!$('.zipField input').val()) {
            $('.zipField .errorMsg').show();
            return false;
        }
        else {
            var val = $.trim($('.zipField input').val());
            if (!ProdLocator.REGEX_ZIP.test(val)) {
                $('.zipField .errorMsg').show();
                return false;
            }
            else {
                $('.zipField .errorMsg').hide();
            }
        }
        return true;
    },
    "REGEX_ZIP": /^\d{5}-\d{4}$|^\d{5}$/
}



function Stores(proxy,id,zip,radius) {
    
    $(".storeList").empty();
    $(".pagination").empty();

    this.proxy = proxy;
    this.zip = zip;
    this.id = id;
    this.radius = radius;
    this.showPage(1);            
}


$.extend(Stores.prototype,
{
    id: null,
    zip: null,
    storeCount: 0,
    radius: 5,
    perPage: 10,
    url: "http://productlocator.infores.com/productlocator/servlet/ProductLocatorEngine?searchradius={radius}&clientid=10&productfamilyid=UNIL&zip={zip}&producttype=upc&productid={id}&storespagenum={page}",
    getStores: function(page) {
        var self = this;
        var url = escape(this.url.supplant({ id: this.id, zip: this.zip, page: page, radius: this.radius }));
        var wProx = this.proxy + url;
        $.get(wProx, null, function(data) { self.callBack(data, page) }, "text"); // do not pass datatype as it isn't valid xml returned
    },
    callBack: function(data, page) {

        data = $.xmlDOM(data);
        var self = this;
        $stores = $(data).find("STORE");
        this.storeCount = $(data).find("RESULTS > STORES").attr("COUNT");
        this.pageCount = Math.ceil(this.storeCount / this.perPage);
        if (parseInt(this.storeCount) === 0) {
            $(".storeList").append('<p class="errorMsg" style="display:block">No results were returned.</p>');
        }

        if (this.pageCount > 1 && $(".pagination").children().length === 0) {
            $(".pagination a").live("click", function() {
                self.showPage($(this).text());
            });

            $(".pagination").append("<li>Page</li>");
            for (var i = 1; i <= this.pageCount; i++) {
                $(".pagination")
                    .append("<li><a href='javascript:void(0)'>{num}</a></li>".supplant({ num: i }));
            }
        }
        
        $(".pagination li").removeClass("on");
        $($(".pagination li")[page]).addClass("on");
        $stores = $(data).find("STORE");
        this.createPage($stores, page);

    },

    showPage: function(num) {
        //var $page = $("table[storenum={num}]".supplant({ num: num }));
        var $page = $("ul[storenum={num}]".supplant({ num: num }));
        //$(".storeListTable").hide();
        $(".storeListUL").hide();
        $(".pagination li").removeClass("on");
        $($(".pagination li")[num]).addClass("on");
        if ($page.length > 0) { // page exists           
            $page.fadeIn();
        } else { // page doesn't exist
            this.getStores(num);
        }
    },
    createPage: function($stores, number) {
        var self = this;
        $list = $("<ul class='storeListUL' storeNum='{num}'></ul>".supplant({ num: number }));
        //$table = $("<table class='storeListTable' storeNum='{num}'></table>".supplant({ num: number }));
        $stores.each(function() {
            //$table.append(self.formatStore(this));
            $list.append(self.formatStore(this));
        });
        $list.appendTo(".storeList");

    },
    formatStore: function(storeData) {
        blah = storeData;
        var $s = $(storeData);
        var obj = {
            id: $s.find("STORE_ID").text(),
            name: $s.find("NAME").text(),
            phone: $s.find("PHONE").text(),
            address: $s.find("ADDRESS").text(),
            distance: $s.find("DISTANCE").text(),
            city: $s.find("CITY").text(),
            state: $s.find("STATE").text(),
            zip: $s.find("ZIP").text()
        }
        //        var row = "<tr><td>{distance}</td>" +
        //                      "<td>{name}</td>" +
        //                      "<td>{phone}</td>" +
        //                      "<td>{address}</td>" +
        //                      "<td>{city}</td>" +
        //                      "<td>{state}</td>" +
        //                      "<td>{distance}</td></tr>";
        var row = "<li><div class='leftCol'>" +
                      "<div class='name'>{name}</div>" +
                      "<div class='phone'>{phone}</div>" +
                      "</div><div class='rightCol'>" +
                      "<div class='distance'>{distance} miles</div>" +
                      "<div class='address'>{address}<br />{city} {state}, {zip}</div>" +
                  "</div></li>";

        return row.supplant(obj);
    }
});



