var TPM = (function (name) { return name; }(TPM || {}));

TPM.SlideShow = function (opts) {
	var defaults = {
		speed: 300,
		duration: 6000
	};
	var totalWeight = 0;
	var aSelectors = '<div class="slide_selector"><div class="slide_selector_bg">';
	var that = this;
	// set the weights to percentages and get an inital index
	var r = Math.random();

	this.options = $.extend({}, defaults, opts);

	this.cssClass = 'TPM_slideshow_slide';

	this.cssIdentifier = this.options.container + " ." + this.cssClass;
	this.numSlides = 0;
	this.currentIdx = 0;
	this.timer = null;

	numSlides = this.options.slides.length;

	for (idx = 0; idx < numSlides; idx++) {
		$(this.options.slides[idx].el).addClass(this.cssClass);
		totalWeight += this.options.slides[idx].weight;
		aSelectors += '<a href="#' + idx + '"></a>';
	}
	aSelectors += '</div></div>';
	$(this.options.container).append(aSelectors);

	$(this.options.container + ' .slide_selector a').click(function (event) {
		event.stopPropagation();

		var playPause = that.timer != null;
		// get the index out of the href
		var href = $(this).attr('href');
		var newIdx = parseInt(href.substring(href.indexOf('#') + 1), 10);

		if (playPause) {
			that.pause();
		}

		if (newIdx === NaN) {
			newIdx = 0;
		}
		that.setCurrent(newIdx, false);

		if (playPause) {
			that.play();
		}
		return false;
	});

	// add events bindings to pause and play the slide show
	$(this.options.container + ' .' + this.cssClass).mouseover(function (event) {
		event.stopPropagation();
		that.pause();
	});
	$(this.options.container + ' .' + this.cssClass).mouseout(function (event) {
		event.stopPropagation();
		that.play();
	});

	for (idx = 0; idx < numSlides; idx++) {
		if (this.options.slides[idx].weightPercent === undefined) {
			this.options.slides[idx].weightPercent = this.options.slides[idx].weight / totalWeight;
		}
		if (this.options.slides[idx].weightPercent > r) {
			that.currentIdx = idx;
			break;
		}
		r -= this.options.slides[idx].weight;
	}
};

TPM.SlideShow.prototype.getCurrentSlideSelector = function () {
	return this.options.slides[this.currentIdx].el;
};

TPM.SlideShow.prototype.pause = function () {
	$(this.options.container + ' .' + this.cssClass).stop(true, true);
    clearInterval(this.timer);
    this.timer = null;
};

TPM.SlideShow.prototype.play = function () {
	var that = this;

	// tracks view, locale can be added here if needed, currently locale is included in the html
	this.trackView();

	// if a modal is visible ignore the resume call
	if ($(".mask:visible").length > 0) {
		return;
	}

	this.timer = setInterval(function () {
		that.next();
	}, this.options.duration);
};

TPM.SlideShow.prototype.trackView = function () {
	var gaID = $("#" + $(this.getCurrentSlideSelector()).attr('id') + ">a").attr('name');
	pageTracker._trackEvent("Homepage Intro", "Homepage Intro html view", gaID);
}

TPM.SlideShow.prototype.setCurrent = function (idx, animate) {

	var speed = animate ? this.options.speed : 0;
	var that = this;

	$(this.getCurrentSlideSelector()).hide();
	$(this.options.container + ' .slide_selector a').removeClass('current');
    this.currentIdx = idx;
	$(this.getCurrentSlideSelector()).fadeIn(speed);
	$($(this.options.container + ' .slide_selector a')[this.currentIdx]).addClass('current');
};

TPM.SlideShow.prototype.next = function () {
	this.setCurrent((this.currentIdx + 1) % numSlides, true);
};

TPM.SlideShow.prototype.start = function () {
	var that = this;
	$(that.options.slides[that.currentIdx].el).show();
	// needed for vertical align, this update is made because IE7 cannot handle $("#vehicle_selector").css("display", "table");
	$("#vehicle_selector").css("top", "9px");
	$($(this.options.container + ' .slide_selector a')[this.currentIdx]).addClass('current');
	this.play();
};

// vehicle selector object takes in slidehsow
TPM.HoverSlideShow = function (slideShow) {
	var timer = null;
	var that = this;
	var timeBeforePromo = 500; // how long after mouse leave before starting the promos again
	var mainShow = slideShow;
	var active = false;
	// caching jquery objects
	var bodyTag = $("body");
	var vehicle_slides = $("#vehicle_slides");
	var vehicle_selector_div = $("#vehicle_selector .vehicle_selector_container div");
	var promo_slides = $("#promo_slides");
	var homepage_slides_slide = $("#homepage_slides .slide");

	// go back to the promos
	bodyTag.live('mouseover', function (event) {
		if (timer == null && active && $(".mask:visible").length === 0) {
			timer = setTimeout(resume, timeBeforePromo);
		}
		// this is for IE, when hovering off the vehicle selector too fast, the timer var does not get set
		else if (timer != null && active && $(".mask:visible").length === 0) {
			clearInterval(timer);
			timer = null;
			timer = setTimeout(resume, timeBeforePromo);
		}
	});

	vehicle_slides.mouseover(function (event) {
		event.stopPropagation();
		if (timer != null) {
			clearInterval(timer);
			timer = null;
		}
	});

    // hover on vehicle links
	vehicle_selector_div.mouseover(function (event) {
		event.stopPropagation();

		// adjust padding so the top and bottom link does not move
		vehicle_selector_div.addClass("special_padding");

		// stop everything
		homepage_slides_slide.stop(true, true);
		mainShow.pause();
		clearInterval(timer);

		// show the selected vehicle
		$("#vehicle_slides .slide").hide();
		$($(this).attr("id")).show();
		vehicle_slides.show();

		// mark the current vehicle
		vehicle_selector_div.stop(true, false);
		if( TCI.Browser.isIE7() ) {
			vehicle_selector_div.removeAttr("style");
		} else {
			vehicle_selector_div.animate({
				paddingTop: "2px",
				paddingBottom: "1px",
				fontSize: "11px",
				height: "14px"
			}, {
				duration: 200,
				queue: false,
				complete: function() {
					vehicle_selector_div.removeAttr("style");
				}
			});
		}

		$(this).animate({
			paddingTop: "10px",
			paddingBottom: "6px",
			fontSize: "14px",
			height: "19px"
		}, {
			duration: 200,
			queue: false
		});

		vehicle_selector_div.removeClass('current');
		$(this).addClass('current');

		// hide the promos
		promo_slides.hide();		
		active = true;
	});

	vehicle_selector_div.click(function () {
		var vehicle = $(this).attr('class');
		if (vehicle.indexOf(" ") > 0) {
			vehicle = vehicle.substring(0, vehicle.indexOf(" "));
		}
		window.location = "http://" + TCI.Globals.domainPath + "/toyota/" + TCI.Globals.locale +"/vehicles/"+ vehicle +"/overview";
	});

	// set tracking for clicks
	$("#promo_slides .slide a").click(function (event) {
		event.stopPropagation();
		pageTracker._trackEvent("Homepage Intro", "Homepage Intro html clickthrough", $(this).attr('name'));
	});

	// turn of the vehicle slides 
	$('#vehicle_close a').click(function (event){
		event.stopPropagation();
	    resume();	
	    return false;
	});

	// resume hide the vehicles and return to the promos
	var resume = function () {
		clearInterval(timer);
		timer = null;

		// adjust padding back to normal
		vehicle_selector_div.animate({
			paddingTop: "2px",
			paddingBottom: "2px",
			fontSize: "11px",
			height: "14px"
		}, {
			duration: 200,
			queue: false,
			complete: function() {
				vehicle_selector_div.removeClass("special_padding");
			}
		});

		// if a modal is visible ignore the resume call
		if ($(".mask:visible").length > 0) {
			return;
		}

		// stop everything
		homepage_slides_slide.stop(true, true);

		// hide the vehicles, show the promos
		vehicle_slides.hide();
		promo_slides.fadeIn(mainShow.options.speed);

		// remove the current vehicle 
		vehicle_selector_div.removeClass('current');

		active = false;
		mainShow.play();
	};
};

/********************************************************************************
PriceDisplayManager is from toyota core, we have made two changes which will need to be merged back.
1) populateLowestPrices
2) Adding the container param to populate
********************************************************************************/
var Toyota = (function (name) { return name; } (Toyota || {}));
Toyota.PriceDisplayManager = ( function () {
    var addPrice = function ( elem, price, series ) {
        //TCI.Log.debug("has lowercase: " + elem.hasClass("lowercase"));
        
        var priceHtml;
        if ( elem.hasClass('just_price') ) {
            priceHtml = '&nbsp;' + price + '&nbsp;';
        }
		else if ( elem.hasClass('lowercase') ) {
            priceHtml = '<span class="price_label">' + TCI.Utils.getLabel('label_from_lowercase') + '</span> <span class="price_amount">' + price + ( elem.hasClass('legal_disclaimer') ? '*' : '' ) + '</span>';
        }
		else {
            //TCI.Log.debug( TCI.Utils.getLabel('label_from') );
            priceHtml = '<span class="price_label">' + TCI.Utils.getLabel('label_from') + '</span> <span class="price_amount">' + price + ( elem.hasClass('legal_disclaimer') ? '*' : '' ) + '</span>';
        }

        if ( elem.hasClass('legal_disclaimer') ) {
            priceHtml += '<span href="legal-disclaimer" id="vehicle_price_disclaimer_trigger" data-series="' + series + '">* <label>' + TCI.localize.getLabel('disclaimer_button_label') + '</label></span>';
            $('#vehicle_price_disclaimer_trigger').live( 'click', function () {
                Toyota.PriceDisclaimerModal.getInstance().show();
                return false;
            });
        }
            
        elem.html( priceHtml );
        elem.addClass('has_price');
    };

    var addComingSoon = function ( elem ) {
        elem.html( TCI.Utils.getLabel('price_not_available') );
        elem.removeClass ('has_price');
    };

    return {

		populateLowestPrices : function () {
            // Populate series MSRP
            var vehiclePriceContainers = $('span.vehicle_lowest_price_container');
            if ( vehiclePriceContainers.length > 0 ) {
                // Factor this out
                var tmp = new Array();

                // For all model/pockage price containers
                vehiclePriceContainers.each( function () {
                    var model = null;
                    var dontShow = false;

                    if ( $(this).attr('code') ) {
                        var codes = $(this).attr('code').trim().split('-');
                        if ( codes.length == 2 ) {
	
                            var seriesCode = $(this).attr('code').trim().split('-')[0].toUpperCase();
                            var modelYear  = $(this).attr('code').trim().split('-')[1].toUpperCase();
							
							var vehiclePrice = Brand.getMinMaxPriceBySeries(seriesCode, modelYear).min; 
							
							if ( vehiclePrice ) {
	                            addPrice( $(this), new String( vehiclePrice).toCurrency(), seriesCode );
	                        }
							else {
	                            TCI.Log.debug('Toyota.PriceDisplayManager.populate: did not find model' );
	                            addComingSoon($(this));
	                        }
                        }
                    }

                });
            }
		},

        populate : function (container) {
			container = container || '';
            // Populate series MSRP
            var vehiclePriceContainers = $(container+' span.vehicle_price_container');
            if ( vehiclePriceContainers.length > 0 ) {
                // Factor this out
                var tmp = new Array();

                // Register to get notified when a model data is loaded, so that package prices can be inserted
                Series.registerObserver( Toyota.PriceDisplayManager );

                // For all model/pockage price containers
                vehiclePriceContainers.each( function () {
                    var model = null;
                    var dontShow = false;

                    if ( $(this).attr('code') ) {
                        var codes = $(this).attr('code').trim().split('-');
                        if ( codes.length > 2 ) {
                            var seriesCode = $(this).attr('code').trim().split('-')[0].toUpperCase();
                            var modelCode  = $(this).attr('code').trim().split('-')[1].toUpperCase();
                            var modelYear  = $(this).attr('code').trim().split('-')[2].toUpperCase();

                            if ( seriesCode && modelCode && modelYear ) {
                                if ( !tmp[seriesCode] ) {
                                    TCI.Log.debug('Toyota.PriceDisplayManager.populate: get series data for ' + seriesCode );
                                    tmp[seriesCode] = Series.getSeries( seriesCode );
                                }
                                TCI.Log.debug('Toyota.PriceDisplayManager.populate: looking for model ' + modelCode );
                                model = !tmp[seriesCode] ? null : tmp[seriesCode].getCheapestModelByShortCode( modelYear, modelCode );
                            }

                            // Populate packages
                            if ( !!model && codes.length == 4 ) {
                                dontShow = true;
                                var packageCode = $(this).attr('code').trim().split('-')[3].toUpperCase();
                                if ( !model.isLoaded() && !model.isLoading() ) {
                                    TCI.Log.debug('Toyota.PriceDisplayManager.populate: load model data for ' + model.code );
                                    model.loadData(true);
                                }
                            }
                        }
                    }

                    if ( !dontShow ) {
                        if ( model ) {
                            TCI.Log.debug('Toyota.PriceDisplayManager.populate: insert price for ' + model.code + ': ' + model.price );
                            // The correct price to show here is the List Price from Series data, not Vehicle data
                            addPrice( $(this), new String( model.listPrice /*model.price*/ ).toCurrency(), model.series.code );
                        }
						else {
                            TCI.Log.debug('Toyota.PriceDisplayManager.populate: did not find model' );
                            addComingSoon($(this));
                        }
                    }
                });
            }

            // Populate model MSRP
            var seriesPriceContainers = $('span.model_price_container');
            if ( seriesPriceContainers.length > 0 ) {
                TCI.Data.getBrand({

                    success : function ( seriesDetails ) {
                        var tmp = new Array();
                        for ( var i in seriesDetails.TciGetSeriesModelViewDataArea ) {
                            var model = seriesDetails.TciGetSeriesModelViewDataArea[i].TciSeriesModelView.TciSeriesModelView.TciSeries;
                            var code  = model.TciSeriesInfo.SeriesCode.$;
                            var name  = TCI.Data.getLanguageSpecificNodeValue( model.TciSeriesInfo.SeriesName );
                            var price = ( !!model.TciSeriesModel.length ) ? model.TciSeriesModel[0].Price.ChargeAmount.$ : model.TciSeriesModel.Price.ChargeAmount.$;
                            tmp[code] = { name: name, price: price };
                        }

                        seriesPriceContainers.each( function () {
                            var code = !!$(this).attr('code') ? $(this).attr('code').trim().toUpperCase() : '';
                            !tmp[code] ? addComingSoon($(this)) : addPrice($(this));
                        });
                    },

                    error : function () {
                        seriesPriceContainers.each( function () {
                            addComingSoon( $(this) );
                        });
                    }
                });
            }
        },

        notifyModelLoaded : function ( model ) {
            if ( !model || !model.isLoaded() ) {
                return;
            }

            // Populate packages
            var vehiclePriceContainers = $('span.vehicle_price_container');
            if ( vehiclePriceContainers.length > 0 ) {
                vehiclePriceContainers.each( function () {
                    if ( $(this).attr('code').indexOf( model.series.code.toUpperCase() + '-' + model.code.toUpperCase() + '-' + model.year + '-' ) > -1 ) { //CAH-BB3EKP-2011-C
                        var pcode = $(this).attr('code').split('-')[3];
                        var package = model.getPackage(pcode);

                        if ( package ) {
                            TCI.Log.debug('Toyota.PriceDisplayManager.populate: insert price for package ' + package.code + ': ' + package.getPrice() );
                            addPrice( $(this), new String( model.price + package.getPrice() ).toCurrency() );
                        }
						else {
                            TCI.Log.debug('Toyota.PriceDisplayManager.populate: did not find package' );
                            addComingSoon($(this));
                        }
                    }
                });
            }
        },

        notifyModelLoadFailed : function ( model ) {
            if ( model != null ) {
                // Populate packages
                var vehiclePriceContainers = $('span.vehicle_price_container');
                if ( vehiclePriceContainers.length > 0 ) {
                    vehiclePriceContainers.each( function () {
                        if ( $(this).attr('code').indexOf( model.series.code.toUpperCase() + '-' + model.code.toUpperCase() + '-' + model.year + '-' ) > -1 ) { //CAH-BB3EKP-2011-C
                            TCI.Log.debug('Toyota.PriceDisplayManager.populate: did not find package' );
                        }
                    });
                }
            }
        }
    };
})();

var TCI = (function (name) { return name; } (TCI || {}));
Toyota.Globals = (function (name) { return name; } (Toyota.Globals || {}));
TCI.Globals.locale = 'en';

Toyota.Core = (function (name) { return name; } (Toyota.Core || {}));
Toyota.Core.hideTooltips = function (){};

var messages = {
	en : {
		price_not_available : 'Price not available',
		label_loading : 'Loading'
	},
	fr : {
		price_not_available : 'Prix non disponible',
		label_loading : 'En cours<br/>de chargement'
	}
};


/********************************************************************************
Initialize the page
********************************************************************************/

var slideShow;
var vehicleShow;
var loadingSpinner;

$(document).ready(function () {
	if ($('#locale').length > 0 && $('#locale').val() == 'fr') {
		TCI.Globals.locale = 'fr';
	}
	loadingSpinner = new TCI.LoadSpinner({ container: $('#loading_slide'), attach: true });
	loadingSpinner.show();
});

$(window).load(function () {
	// weights set here is for english
	var input = {
		container: '#promo_slides',
		slides: [
			{
				el: "#slide_drivehome1",
				weight: 1
			},
			{
				el: "#slide_drivehome5",
				weight: 0
			},
			{
				el: "#slide_drivehome2",
				weight: 0
			},
			{
				el: "#slide_drivehome3",
				weight: 0
			},
			{
				el: "#slide_winter_tires",
				weight: 0
			}
		]
	};
	
	if (TCI.Globals.locale === 'fr') {
		// Set the french promo weights
		input.slides[0].weight = 1;
		input.slides[1].weight = 0;
		input.slides[2].weight = 0;
		input.slides[3].weight = 0;
		input.slides[4].weight = 0;
	}

	slideShow = new TPM.SlideShow(input);
	vehicleShow = new TPM.HoverSlideShow(slideShow);

    // set up the disclaimer modal triggers
	$('.disclaimer_content').each(function (idx) {

        new TCI.Core.Modal({
            name : 'disclaimer_content'+idx,
            title : $(this).attr('title'),
            height : 'auto', 
            trigger : 'a.disclaimer_link[href="#' + $(this).attr('id') + '"]',
            selector : 'jquery',
            content : {type: 'html', target: '#' + $(this).attr('id')},
			onBeforeShow : function () {
				Toyota.PriceDisplayManager.populate('#' + this.name);
			}
        });
    });

	Toyota.PriceDisplayManager.populateLowestPrices();
	loadingSpinner.hide();
	$('#vehicle_selector').show();
	$('#promo_slides').show();
	//Toyota.PriceDisplayManager.populate();

	slideShow.start();
});

