if (typeof self.carscom == 'undefined') self.carscom = {};

(function($) {
    $.fn.InventoryController = function(params) {
        var me = this;
        me.controller = new $.inventoryController(params);
        var crpSection = '';
        try { 
            crpSection = /section=(\w*?)(&|$)/.exec(location.search)[1];
            if (crpSection.length > 0) crpSection = crpSection+'-' 
        } catch(err) {};
        
        //"Public" API
        self.carscom.inventoryModule = {
            showZIP: function() {
                return me.controller.showZIP();
            },
            hideZIP: function() {
                return me.controller.hideZIP();
            },
            fetch: function() {
                return me.controller.fetch();
            },
            //Non-core, assistive functions, called on link objects
            openMapPopup: function(orgid) {
                try { trackLink(this, crpSection+'abbrListings_map'); } catch (err) {}
                window.open('/go/dealersearch/logDealerLead.jsp?leadType=map&orgid='+orgid, 'mapPopup', 'width=541,height=560,top=50,left=50,scrollbars=yes,resizable=yes');
            },
            doDetailTrack: function() {
                try { trackLink(this, crpSection+(me.controller.params.isNewSearch? 'New':'Used')+'MoreDetails'); } catch (err) {}
            },
            doDealerAggTrack: function() {
                try { trackLink(this, crpSection+'DealerAggResults'); } catch (err) {}
            },
            doAggTrack: function() {
                try { trackLink(this, crpSection+'UsedAggResults'); } catch (err) {}
            }
        }
        //DEBUG:
        $(self).ajaxError(function(event, request, settings) {
            self.badRequest = request;
        });
        return this;
    };
    
    $.inventoryController = function(params) {
        this.params = params;
        this.params.searchType = this.params.isNewSearch? 'newcc' : 'usedcc';
        
        this.$container = $('#inventoryModule');
        this.$header = this.$container.children(".hdr");
        this.$zipInfoHeader = this.$header.find('.zipInfo');
        this.$zipToggler = this.$header.find('.toggler');
        this.$zipContainer = $('#zipSubmitter');
        this.$zipInput = this.$container.find('input[@name = "zip"]');
        this.$fetchButton = $('#listingsButton');
        this.$listingsContainer = $('#listingsContainer');
        this.$errorContainer = this.$container.find('.error');
        this.init();
    };
    
    $.inventoryController.prototype = {
        init: function() {
            this.$fetchButton.hover(
                function() { $(this).css('color', '#FFCC00') },
                function() { $(this).css('color', '#FFF') }
            );
            if ($.trim(this.$zipInput.val()).length == 0) this.setNoZIPState();
            else this.fetch();
        },
        showZIP: function() {
            var me = this;
            this.$fetchButton.one('click', function() { me.fetch() });
            this.$zipContainer.slideDown('slow', function() {
                me.$zipToggler.text("Hide ZIP Entry").unbind().one('click', function() { me.hideZIP() } );
            });
            this.$zipContainer.addClass('bottom');
        },
        hideZIP: function() {
            var me = this;
            this.$fetchButton.unbind('click');
            this.$zipContainer.slideUp('slow', function() {
                me.$zipToggler.text("Change Location").unbind().one('click', function() { me.$zipContainer.removeClass('bottom');me.showZIP() } );
            });
        },
        fetch: function() {
            var me = this;
            this.$errorContainer.html("");
            if (!this.validateZIP()) return this.handleError(this.INVALID_ZIP_ERROR);
            
            this.$errorContainer.hide();
            this.params.userZIP = this.$zipInput.val();
            this.$container.block();
            $.getJSON(
                '/go/crp/includes/_doInventorySearch.jsp',
                {
                    makeid: this.params.makeID,
                    modelid: this.params.modelID,
                    makeName: this.params.makeName,
                    modelName: this.params.modelName,
                    rad: this.params.userRadius,
                    zip: this.params.userZIP,
                    year: this.params.year,
                    newSearch: this.params.isNewSearch? 'Y' : 'N'
                },
                function(json) {
                    me.$container.unblock();
                    
                    if (typeof json == 'undefined') return me.handleError(me.UNSPECIFIED_ERROR);
                    if (typeof json.error != 'undefined') return me.handleError(json.error);
                    if (json.length == 0) return me.handleError(me.NO_RESULTS_ERROR);
                    
                    if (typeof json.resultCount != 'undefined') /* resultCount only valid on used listings */    
                        me.writeUsedInventory(json);
                    else me.writeNewInventory(json);
                    me.doStyleCleanup();  //Generic CSS post-processing call
                    me.setZIPCookie();
                    me.$zipInfoHeader.text(" near "+me.params.userZIP);
                    me.hideZIP();
                }
            );
        },
        setNoZIPState: function() {
            var me = this;
            this.$fetchButton.one('click', function() { me.fetch() });
        },
        validateZIP: function() {
            return /[0-9]{5}/.test(this.$zipInput.val());
        },
        setZIPCookie: function() {
            var expiration = new Date();
            expiration.setTime(expiration.getTime()+(30*24*60*60*1000));
            expiration = "; expires="+expiration.toGMTString();
            document.cookie = "zipcode="+(this.$zipInput.val())+expiration+"; path=/";
        },
        handleError: function(errorType) {
            var me = this;
            var message = "";
            switch (errorType) {
                case this.INVALID_ZIP_ERROR:
                    message = "Please enter a valid 5-digit ZIP code to search for listings.";
                    break;
                case this.ZIP_NOT_FOUND_ERROR:
                    message = "We were unable to locate the ZIP code you entered. Please try again with a different ZIP code entry.";
                    break;
                case this.NO_RESULTS_ERROR:
                    message = "We were unable to find listings for the "+this.params.makeName+" "+this.params.modelName+" near the ZIP code you entered.  Please try another ZIP code.";
                    this.setZIPCookie();
                    break;
                case this.DEALER_ERROR:
                    message = "We were unable to find any dealers near your ZIP code with listings for the "+this.params.makeName+" "+this.params.modelName+".  Please try another ZIP code.";
                    this.setZIPCookie();
                    break;
            }
            this.$fetchButton.one('click', function() { me.fetch() });
            this.$errorContainer.html(message).show();
        },
        //These "write" methods are the messy bits
        writeNewInventory: function(json) {
            var me = this;
            var listingsHTML = '<table cellspacing="0" cellpadding="0" class="selectorbox" id="dlrListings">';
            $.each(json, function() {
                listingsHTML = listingsHTML + $.sprintf(me.DEALER_TEMPLATE, this.dealer);
                $.each(this.listings, function() {
                    if ($.trim(this.price).length == 0) this.price = 'Not Priced';
                    this.detailLink = me.writeDetailLink(this.paID);
                    listingsHTML = listingsHTML + $.sprintf(me.NEW_INVENTORY_TEMPLATE, this);
                });
                listingsHTML = listingsHTML + '<tr class="topBorder"><td colspan="4" class="bottom"><a href="'+me.writeDealerAggLink(this.dealer.legacyID)+'" onclick="carscom.inventoryModule.doDealerAggTrack.call(this)" style="font-size:10px">See all new '+me.params.makeName+' '+me.params.modelName+' listings for this dealer</a></td></tr>';
            });
            listingsHTML = listingsHTML + $.sprintf(this.SEE_ALL_TEMPLATE, this.params) + '</table>';
            this.$listingsContainer.html(listingsHTML);
            
            $('#dlrListings tr.inventory').hover(
                function() { $('#dlrListings tr.inventory').removeClass('selected');$(this).addClass('selected'); },
                function() { $(this).removeClass('selected') }
            ).click(function(evt) {
                var linky = $(this).find('a').get(0);
                carscom.inventoryModule.doDetailTrack.call(linky);
                if (typeof evt.originalTarget == 'undefined' || evt.originalTarget != linky) self.location.href = linky.href; 
            });
        },
        writeUsedInventory: function(json) {
            var me = this;
            var listingsHTML = '<table cellspacing="0" cellpadding="0" class="selectorbox" id="dlrListings">';
            $.each(json.listings, function() {
                    //We scrub the JSON return to get formatting right prior to the sprintf call
                    if ($.trim(this.price).length == 0) this.price = 'Not&nbsp;Priced';
                    this.model = this.model + (this.trim? " "+this.trim : "");
                    if (this.mileage.length > 0) this.mileage = this.mileage + '&nbsp;mi.';
                    if (this.color.length > 0) this.color = '<em>Color:</em> ' + this.color;
                    if (this.photo.length == 0) this.photo = '/configurator/images/modelwalk/NOIMAGE_112.gif';
                    this.certified = (this.certified? '<span class="certified">Certified</span>' : '');
                    
                    this.dealer.name = ($.trim(this.dealer.label).length > 0)? '<em>'+this.dealer.label+': </em>'+this.dealer.name : this.dealer.name;
                    this.detailLink = me.writeDetailLink(this.paID);
                    this.dealerHTML = $.sprintf(me.USED_SELLER_TEMPLATE, this.dealer);
                    listingsHTML = listingsHTML + $.sprintf(me.USED_INVENTORY_TEMPLATE, this);
            });
            listingsHTML = listingsHTML + $.sprintf(this.SEE_USED_TEMPLATE, $.extend(this.params, {
                resultCount: json.resultCount,
                actionText: 'See '+(json.resultCount > 1? json.resultCount+' local' : ' the')+' listing'+(json.resultCount > 1? 's' : '')+' for this car'
            })) + '</table>';
            this.$listingsContainer.html(listingsHTML);
        },
        writeDealerAggLink: function(dlid) {
            return '/go/search/search.jsp?mkid='+this.params.makeID+'&mdid='+this.params.modelID+'&tracktype='+this.params.searchType+'&searchType='+(this.params.isNewSearch? '45':'94')+'&dlid='+dlid;        
        },
        writeDetailLink: function(paID) {
            return '/go/search/detail.jsp?paId='+paID+'&searchType='+(this.params.isNewSearch? '45':'94')+'&tracktype='+this.params.searchType;
        },
        doStyleCleanup: function() {
            if (this.params.isNewSearch) $('tr#inventoryActions').children('td').css('borderTop', 'none');
        },
        INVALID_ZIP_ERROR: 'INVALID_ZIP_ERROR',
        ZIP_NOT_FOUND_ERROR: 'ZIP_NOT_FOUND_ERROR',
        DEALER_ERROR: 'DEALER_ERROR',
        NO_RESULTS_ERROR: 'NO_RESULTS_ERROR',
        UNSPECIFIED_ERROR: 'UNSPECIFIED_ERROR',
        DEALER_TEMPLATE: '<tr><td colspan="4"><span style="float:left"><strong>%(name)s</strong><br/><span style="font:10px Verdana;color:#808080">%(address)s (<a href="#" target="mapPopup" onclick="carscom.inventoryModule.openMapPopup.call(this,%(id)d);return false">Map</a>)</span></span><span style="float:right;background:url(/search/images/phone_Icon.gif) 0 1px no-repeat;padding-left:16px"><strong>%(phone)s</strong></span></td></tr>',
        NEW_INVENTORY_TEMPLATE: '<tr class="inventory topBorder pointer"><td>%(model)s %(trim)s</td><td style="text-align:center">%(price)s</td><td>%(color)s</td><td align="right"><a href="%(detailLink)s" id="%(paID)d" onclick="carscom.inventoryModule.doDetailTrack.call(this)">View Details</a></td></tr>',
        USED_INVENTORY_TEMPLATE: '<tr class="usedInventory"><td class="photo" rowspan="2"><a href="%(detailLink)s" onclick="carscom.inventoryModule.doDetailTrack.call(this)"><img width="100" height="75" src="%(photo)s" onerror="this.src = \'/configurator/images/modelwalk/NOIMAGE_112.gif\'" /></a></td><td class="detailsLink"><a href="%(detailLink)s" onclick="carscom.inventoryModule.doDetailTrack.call(this)">%(model)s</a></td><td class="mileage">%(mileage)s</td><td class="price">%(price)s</td></tr><tr><td class="modelInfo" colspan="3"><div>%(color)s</div>%(dealerHTML)s%(certified)s</td></tr>',
        USED_SELLER_TEMPLATE: '<div>%(name)s</div><div class="phone">%(phone)s</div>',
        SEE_ALL_TEMPLATE: '<tr id="inventoryActions"><td colspan="4"><table class="orngbttn" align="right" border="0" cellpadding="0" cellspacing="0" style="float:right;top:0px"><tr><td class="bttntxtprpl"><a href="/go/search/search.jsp?mkid=%(makeID)d&mdid=%(modelID)d&year=%(year)d&tracktype=%(searchType)s&rd=%(userRadius)d&zc=%(userZIP)s">See all local inventory for this car</a></td><td width="9"><a href="/go/search/search.jsp?mkid=%(makeID)d&mdid=%(modelID)d&year=%(year)d&tracktype=%(searchType)s&rd=%(userRadius)d&zc=%(userZIP)s"><img src="/images/bttncapPrpR.gif" border="0" height="17" width="8"></a></td></tr></table><a href="/go/dealersearch/searchResults.jsp?mkid=%(makeID)d&rd=%(userRadius)d&zc=%(userZIP)s" style="float:right;padding-right:12px;margin-top:2px;font-size:10px">See&nbsp;more&nbsp;dealers</a></td></tr>',
        SEE_USED_TEMPLATE: '<tr id="inventoryActions"><td colspan="5"><table class="orngbttn" align="right" border="0" cellpadding="0" cellspacing="0" style="float:right;top:0px"><tr><td class="bttntxtprpl"><a href="/go/search/search.jsp?mkid=%(makeID)d&mdid=%(modelID)d&year=%(year)d&tracktype=%(searchType)s&searchType=94&rd=%(userRadius)d&zc=%(userZIP)s" onclick="carscom.inventoryModule.doAggTrack.call(this)">%(actionText)s</a></td><td width="9"><a href="/go/search/search.jsp?mkid=%(makeID)d&mdid=%(modelID)d&year=%(year)d&tracktype=%(searchType)s&searchType=94&rd=%(userRadius)d&zc=%(userZIP)s" onclick="carscom.inventoryModule.doAggTrack.call(this)"><img src="/images/bttncapPrpR.gif" border="0" height="17" width="8"></a></td></tr></table></td></tr>'
    }
})(jQuery);
