/*
85x56 365x241
MDD:  Complete code refactoring, IE6 option select bug workaround, pose memory on car change, enable load with passed-in acodes, load from cookie, enable permalink, slideshow
REQUIRES jQuery 1.2.1.  Not backwards-compatible.
*/
self.poses = [101,112,113,102,109,105,106,104,314,304,302,310,301,312,313];
self.imageprefix = 'http://car-pictures.cars.com/images/?quality=20&width=365&height=241&img=';
self.pose = "101";

self.currentModelYear = 2009;

(function($) {
    $.fn.Comparator = function() {
        var $collection = this;
        this.each(function(index) {
            this.comparator = new $.comparator(this, index);
        });
        self.poser = {
            callbacks: 0,
            setPose: function(pose, animate, callback) {
                if (typeof animate != "undefined" && animate && !self.slideshow.isStarted()) return;
            
                var me = this;
                if (typeof callback == "function")
                    this.callback = callback; 
                else
                    this.callback = null;
                self.pose = pose;
                $("a.angle img").css("border", "1px solid #666");
                $("a.angle[@name = '"+pose+"']").find("img").css("border", "1px solid #df4600");
                $collection.each(function() {
                    this.comparator.setPose(animate, function() { me.doCallback(); });
                });
            },
            doCallback: function() {
                if (typeof this.callback == "function") {
                    if (this.callbacks == 0) {
                        this.callbacks++;
                    }
                    else {
                        this.callbacks = 0;
                        if (self.slideshow.isStarted()) this.callback.apply();
                    }
                }
            }
        };
        $("a.angle").click(function() {
            if (typeof self.slideshow != "undefined" && self.slideshow.isStarted()) self.slideshow.stop();
            self.poser.setPose(this.name, false);
            //return false;
        });
        $(".displayHeader, #thumbTabs button").click(function() {
            $collection.each(function() {
                this.comparator.toggle();
            });
            //return false;
        });
        return this;
    };
    
    $.comparator = function(formContainer, index) {
        this.index = index;
        this.selectedVehicle = {}, this.workingVehicle = {};
        
        this.$container = $(formContainer);
        this.$bigImage = this.$container.find(".mediumCarViewContainer").find("img").error(function() { 
            var matcher = /\&img=CA/g;
            if (matcher.exec(this.src)) {
                this.src = this.src.replace(matcher, "&img=US");
            }
            else this.src = "/comparephotos/images/vehiclePhotoNotAvailable.jpg"; 
        });
        this.$form = this.$container.find("form");
        this.$thumbs = $(".thumbDisplay", "#thumbTabBox").eq(this.index);
        this.$thumbTab = $("button", "#thumbTabs").eq(this.index);
        this.$siteLinks = this.$container.find(".siteLinks");
        
        this.init();
    }
    
    $.comparator.prototype = {
        popmodel: function() {
            var $modSelect = $(this.$form[0].modbodstyle);
            this.workingVehicle = {};
            this.workingVehicle.make = this.$form[0].make.value;
            $modSelect.setOptions(dropdowns[this.workingVehicle.make], 'Select a Model/Style');
        },
        popyear: function() {
            var $yearSelect = $(this.$form[0].year);
            this.workingVehicle.modbod = this.$form[0].modbodstyle.value;
            this.workingVehicle.model = dropdowns[this.workingVehicle.make][this.workingVehicle.modbod]["name"];
            var years = {};
            $.each(dropdowns[this.workingVehicle.make][this.workingVehicle.modbod]["vehicles"], function(year, vehData) {
                years[vehData.imgcode] = year;
            });
            $yearSelect.setOptions(years, 'Select a Year', years);
            $yearSelect[0].selectedIndex = $yearSelect[0].options.length == 2? 1 : 0;
        },
        popthumbs: function() {
            var me = this;
            this.$thumbTab.html(this.selectedVehicle.model);
            this.$thumbs.find("img").attr("src", "/comparephotos/images/thumbblank.jpg").end().show();
            $.each(poses, function(index, nextPose) {
                me.$thumbs.find("a[@name = '"+nextPose+"']").find("img").attr("src", imageprefix+me.selectedVehicle.imageItem.imgcode+nextPose+'.jpg' );
            });
        },
        writelinks: function() {
            this.$siteLinks.empty();
            var me = this;
            $.getJSON("data/getRefData.jsp?myid="+this.selectedVehicle.imageItem.myid, function(mapping) {
                var myYear = Number(me.selectedVehicle.year);
                
          		me.$siteLinks.append('<a href="/go/crp/research.jsp?myid='+me.selectedVehicle.imageItem.myid+'&call=crp&section=summary&logtype=6">Research</a>');
            	if (myYear >= currentModelYear) {
            		me.$siteLinks.append(' | <a href="/go/dealersearch/checkConfiguratorZip.jsp?myid='+me.selectedVehicle.imageItem.myid+'">Build Your Own</a> ');
                }
                if (typeof mapping.error != "undefined") return;

          		me.$siteLinks.prepend('<a href="/go/search/provideZip.jsp?mdnm='+mapping.modelname+'&mknm='+mapping.makename+'&year='+myYear+'&tracktype='+(myYear >= currentModelYear?  "newcc":"usedcc")+'">See Inventory</a> | ');
            });
        },
        toggle: function() {
            this.setActive(!this.active);
        },
        getMake: function() {
            return this.$form[0].make.value;
        },
        getModel: function() {
            return this.$form[0].modbodstyle.value;
        },
        getYear: function() {
            return this.$form[0].year.options[this.$form[0].year.selectedIndex].text;
        },
        setPose: function(animate, callback) {
            var me = this;
            var mySrc = "/comparephotos/images/vehiclePhotoNotAvailable.jpg";
            if (typeof this.selectedVehicle.imageItem != "undefined") {
                mySrc = imageprefix+this.selectedVehicle.imageItem.imgcode+self.pose+'.jpg';
            }
            if (typeof animate != "undefined" && animate) {
                if (!self.slideshow.isStarted()) return;
                
                this.$bigImage.fadeOut(self.slideshow.interval, function() {
                    me.pose = self.pose;
                    me.$bigImage.attr("src", mySrc).fadeIn(self.slideshow.interval, function() {
                        if (typeof callback == "function")
                            callback.apply();
                    });
                })
            }
            else {
                me.pose = self.pose;
                this.$bigImage.attr("src", mySrc);
            }
        },
        setActive: function(isActive) {
            var me = this;
            this.active = isActive;
            if (this.active) {
                this.$thumbTab.removeClass("inactive").addClass("active");
                this.$container.find(".displayHeader").addClass("activeHeader");
                this.$thumbs.show();
            }
            else {
                this.$thumbTab.removeClass("active").addClass("inactive");
                this.$container.find(".displayHeader").removeClass("activeHeader");
                this.$thumbs.hide();
            }
        },
        setVehicle: function(vehicle, noSubmit) {
            $(this.$form[0].make).changeOptionValue(vehicle.make);
            $(this.$form[0].modbodstyle).changeOptionValue(vehicle.modbod);
            $(this.$form[0].year).changeOptionValue($("option", this.$form[0].year).filter(":contains('"+vehicle.year+"')").val());
            if (typeof noSubmit == "undefined") this.$form.submit();
        },
        show: function() {
            var me = this;
            var theForm = this.$form[0];
            this.selectedVehicle = this.workingVehicle;
            this.selectedVehicle.year = theForm.year.options[theForm.year.selectedIndex].text;
            this.selectedVehicle.imageItem = dropdowns[this.selectedVehicle.make][this.selectedVehicle.modbod]["vehicles"][this.selectedVehicle.year];

            this.$container.find(".changeCar").show().find("a").click();
            this.$container.find(".carName").html(this.selectedVehicle.year+" "+this.selectedVehicle.make+" "+this.selectedVehicle.model);
            this.$container.find(".vardesc").html(this.selectedVehicle.imageItem.caption+" pictured");
            this.writelinks();
            this.popthumbs();
            this.$thumbs.find("a[@name = '"+self.pose+"']").click();
            self.slideshow.setEnabled();
            writeCompareCookie();
        },
        init: function() {
            var me = this;
            this.setActive(this.index == 0);
            
            /*Define event handlers*/
            this.$thumbs.find("img").error(function() { 
                var matcher = /\&img=CA/g;
                if (matcher.exec(this.src)) {
                    this.src = this.src.replace(matcher, "&img=US");
                }
                else this.src = "/comparephotos/images/thumbblank.jpg"; 
            });
            this.$container.find(".BttnPill").click(function() { me.$form.submit(); return false; });
            this.$form.submit(function() {
                if (this.year.value == "") return false;
                
                if (!me.active) me.$thumbTab.click();
                me.show();
                return false;
            });
            $(this.$form[0].make).change(function() { if (this.value == '') return false; me.popmodel(); $(me.$form[0].year).empty(); });
            $(this.$form[0].modbodstyle).change(function() { if (this.value == '') return false; me.popyear(); });
            $(this.$form[0].year).change(function() {});
            this.$container.find(".changeCar a").toggle(
                function() { me.$container.find(".styleSelector").hide(); $(this).text("Change Car"); },
                function() {
                    me.setVehicle(me.selectedVehicle, true);
                    me.$container.find(".styleSelector").show();
                    $(this).text("Cancel");
                }
            );
        }
    }
})(jQuery);

(function($) {
    $.fn.SlideShow = function() {
        var ss = new $.slideshow(this);
        window.slideshow = {
            interval: 500,
            enabledState: false,
            isStarted: function() { return ss.isStarted; },
            start: function() {
                ss.setState("playing");
                ss.isStarted = true;
                ss.startQueue();
                ss.automate();
            },
            setEnabled: function() {
                if (!this.enabledState) {
                    var reDead = /dead/, reEnabled = /enabled/;
                    ss.$controls.each(function() {
                        var prior = $(this).css("backgroundImage");
                        $(this).css("backgroundImage", prior.replace(reDead, "enabled"));
                        
                        $.data(this, "disabledState", prior);
                        $.data(this, "enabledState", $(this).css("backgroundImage"));
                        $.data(this, "onState", $.data(this, "enabledState").replace(reEnabled, "on"));
                    });
                    /*Initialize button state handlers*/
                    $.data($("#ss-pause")[0], "setState", function(state) {
                        switch (state) {
                            case "paused":
                                $(this).css({"backgroundImage": $.data(this, "onState"), "cursor":"auto"}).unbind();
                                break;
                            case "playing":
                                $(this).css({"backgroundImage": $.data(this, "enabledState"), "cursor":"pointer"}).click(function() { self.slideshow.stop(); });
                                break;
                        }
                    });
                    $.data($("#ss-play")[0], "setState", function(state) {
                        switch (state) {
                            case "paused":
                                $(this).css("backgroundImage", $.data(this, "enabledState")).unbind().click(function() { self.slideshow.start(); });
                                break;
                            case "playing":
                                $(this).css("backgroundImage", $.data(this, "onState")).unbind().css({"cursor":"auto"})/*.click(function() { self.slideshow.stop(); })*/;
                                break;
                        }
                    });
                    $("#ss-prev, #ss-next").each(function() {
                        $.data(this, "setState", function(state) {
                            switch (state) {
                                case "paused":
                                    $(this).css({'backgroundImage': $.data(this, "enabledState"), 'cursor': 'pointer'}).mousedown(function() { $(this).css("backgroundImage", $.data(this, "onState")); }).mouseup(function() { $(this).css("backgroundImage", $.data(this, "enabledState")); });
                                    if (this.id == "ss-prev") {
                                        $(this).click(function() { self.slideshow.back(); });
                                    }
                                    else {
                                        $(this).click(function() { self.slideshow.next(); });
                                    }
                                    break;
                                case "playing":
                                    $(this).css({'backgroundImage': $.data(this, "disabledState"), 'cursor': 'auto'}).unbind();
                                    break;
                            }
                        });
                    });

                    ss.setState("paused");
                    this.enabledState = true;
                }
            },
            stop: function() {
                ss.isStarted = false;
                ss.queue = [];
                $(".mediumCarViewContainer").find("img").each(function() {
                    $(this).stop();
                    $(this).css("opacity", 1);
                });
                self.poser.setPose($(".carDisplay")[0].comparator.pose);
                ss.setState("paused");
            },
            next: function() { 
                ss.startQueue();
                ss.getNextThumb().click();
            },
            back: function() { 
                ss.startQueue();
                ss.getBackThumb().click();
            }
        }
        return this;
    }
    
    $.slideshow = function($thumbs) {
        this.$thumbs = $thumbs;
        this.$controls = $("#slideShowControls button");
        this.isStarted = false;
        this.queue = [];
        this.queue.lock = false;
    }
    
    $.slideshow.prototype = {
        /*Private functions*/
        getNextThumb: function() {
            var toClick = null;
            var idx = this.$thumbs.index(this.queue[this.queue.length-1][0])+1;
            if (idx < this.$thumbs.length) {
                toClick = this.$thumbs.eq(idx);
            }
            else {
                toClick = this.$thumbs.eq(0);
            }
            return toClick;
        },
        getBackThumb: function() {
            var toClick = null;
            var idx = this.$thumbs.index(this.queue[this.queue.length-1][0])-1;
            if (idx < 0) {
                toClick = this.$thumbs.eq(this.$thumbs.length-1);
            }
            else {
                toClick = this.$thumbs.eq(idx);
            }
            return toClick;
        },
        startQueue: function() {
            this.queue = [];
            this.queue.push(this.$thumbs.filter("[@name = "+self.pose+"]").eq(0));
        },
        automate: function() {
            var me = this;
            if (this.isStarted && this.queue.length > 0) {
                var interval = this.queue.length == 1? 100 : 1500;
                var nextThumb = this.getNextThumb();
                this.queue.push(nextThumb);
                setTimeout(function() {
                        self.poser.setPose(nextThumb.attr("name"), true, function() { me.automate(); })
                    }, interval);
            }
        },
        setState: function(state) {
            this.$controls.each(function() {
                $.data(this, "setState").call(this, state);
            });
        }
    }
})(jQuery);

$.fn.extend({
    setOptions: function(optValueList, defaultItem, optTextList) {
        /*
        We'd like to do this via jQuery/DOM manipulation, but thanks to IE6 refusing to set
        javascript properties immediately on DOM-created elements, that won't work w/o some ugly
        timeout hacks--so we'll do it the clunky way.
        */
        var re = /&amp;/gi;
        return this.each(function() {
            $(this).empty();
            var count = 0;
            var me = this;
            if (typeof defaultItem != "undefined") this.add(new Option(defaultItem, '', true, true), $.browser.msie? count : null);
            $.each(optValueList, function(val, item) {
                count++;
                var optText = (typeof optTextList != "undefined"? optTextList[val] : val);
                me.add(new Option(optText.replace(re, "&"), val), $.browser.msie? count : null);
            });
        });
    },
    changeOptionValue: function(targetVal) {
        return this.each(function() {
            this.value = targetVal;
            $(this).trigger("change");
        });
    }
});

function writeCompareCookie() {
    var val = "";
    $(".carDisplay").each(function(index) {
        if (this.comparator.selectedVehicle != null) {
            try {
            val += (index == 0? "":"|")+"{make:'"+this.comparator.getMake()+"',modbod:'"+this.comparator.getModel()+"',year:'"+this.comparator.getYear()+"'}";
            } catch (error) {}
        }
    });
    if (val.length > 0) {
        $.cookie("compare", val, {domain: "cars.com", path: "/go/comparephotos/"});
    }
}

function showPermalink() {
    var query = "";
    $(".carDisplay").each(function(index) {
        if (typeof this.comparator.selectedVehicle.year != "undefined") {
            var vehicleQuery = "vehicle=";
            with (this.comparator.selectedVehicle) {
                vehicleQuery += year+"+"+make.replace(/\s/g, "_")+"+"+modbod.replace(/\s/g, "_");
            }
            query += (index == 0? "?":"&")+vehicleQuery;
        }
    });
    var myLink = self.location.href.toString().split("?", 1);
    $("#permalinkText").val(myLink[0]+query);
    $("#plink").show();
    $("#permalinkText")[0].focus();
}

function doVehicleSelect() {
    $.each(vehicles, function(index, vehicle) {
        var $myForm = $(".styleSelector").eq(index);
        
        if (vehicle.bodyStyle == "") {
            var selectedBS;
            $.each(dropdowns[vehicle.make][vehicle.model], function(prop, item) {
                if (prop != "carsref" && typeof selectedBS == "undefined" && typeof dropdowns[vehicle.make][vehicle.model][prop][vehicle.year] == "object") {
                    selectedBS = prop;
                }
            });
            vehicle.bodyStyle = selectedBS;
        }
        $myForm.parents(".carDisplay")[0].comparator.setVehicle(vehicle);
    });
}




