/* Released: 2010-04-08 12:36:16 */

var $gJQ = jQuery.noConflict();

var gLightBox = null;
var gTabNavigation = null;
var gAccessoriesFilter = null;
var gProductPage = null;

$gJQ(document).ready(function () {
    try {
        gLightBox = new LightBox();
    } catch(err) {}
    
    try {
        gTabNavigation = new TabNavigation();
		/* attach click event on prev/next links */
	    $gJQ('.more-info-link-button.prev').click(function(e) {
	        gTabNavigation.gotoPrevious();
	        window.scrollTo(0,0);
	    });
	    $gJQ('.more-info-link-button.next').click(function(e) {
	        gTabNavigation.gotoNext();
	        window.scrollTo(0,0);
	    });
    } catch(err) {}
    
    try {
        gProductAccessoiresCategoryFilter = new CategoryFilter();
    } catch(err) {}
    
    try {
        gProductAccessoiresOverview = new ProductAccessoiresOverview();
    } catch(err) {}
    
    $gJQ("#go-category").click(function(){
    	gProductAccessoiresOverview.doFilter();
    });
    
    $gJQ("#go-pricerange").click(function(){
    	gProductAccessoiresCategoryFilter.doFilter();
    });
	
});

/**
 * @class ProductAccessoiresOverview
 * @author stec
 */
function ProductAccessoiresOverview() {
	this.init();
}

ProductAccessoiresOverview.prototype = {
	
	priceRangeWidget : "#price-range-widget",
	interval : 500,
	timeoutCount : 0,
	productPriceMap : {},
	filter : null,
	
	init : function() {
		this.__skusOnPage = this._getSkusOnPage();
		this.hidePriceRangeWidget();
		//only poll when tab-content #accessories is found on page.
		if ($gJQ("#accessories").length > 0) {
			this._startPolling();
		}
	},
	
	//proxy to internal filter
	doFilter : function() {
		if (this.filter) {
			this.filter.doFilter();
		}
	},
	
	showPriceRangeWidget : function() {
		$gJQ(this.priceRangeWidget).show();
	},
	
	hidePriceRangeWidget : function() {
		$gJQ(this.priceRangeWidget).hide();
	},
	
/**
 * Mockup service
 * 
window.TomTom = {}
window.TomTom.Prices = {}
window.TomTom.Prices.getBySku = function(sku) {return Math.random()*500;}
 */
	
	_startPolling : function() {
		var me = this;
		
		try {
			if      (typeof window.TomTom === "undefined")                 {throw new Error("TomTom is undefined");}
			else if (typeof window.TomTom.Prices === "undefined")          {throw new Error("TomTom.Prices is undefined");}
			else if (typeof window.TomTom.Prices.getBySku === "undefined") {throw new Error("TomTom.Prices.getBySku is undefined");}
			
			if (window.TomTom.Prices.getBySku) {
//				logTo("Pricing service found");
				me._onPollSucces();
			}
			clearTimeout(me.__timer);
		} catch(e) {
//			logTo("Polling... Pricing service unavailable");
			me.__timer = setTimeout(function(){me._startPolling()}, me.interval);
			me.timeoutCount++;
			
			/* stop after x miliseconds */
			if (me.timeoutCount * me.interval >= 10000) {
//				logTo("Polling timed out, stopping...");
				clearTimeout(me.__timer);
				me._onPollError();
			}
		}
		
	},
	
	_onPollSucces : function() {
		var me = this;
		var skus = me.__skusOnPage;
		for (var i in skus) {
			var price = window.TomTom.Prices.getBySku(skus[i])
			this.productPriceMap[skus[i]] = price; 
		}
		this._initiateFilter(this.productPriceMap);
	},
	
	_onPollError : function() {
		this.hidePriceRangeWidget();
	},
	
	_getSkusOnPage : function() {
		var p = [];
		$gJQ(".accessory-comp[id]").each(function(){
			p.push("" + $gJQ(this).attr("id"));	
		});
		return p;
	},
	
	_initiateFilter : function(productPriceMap) {
		var me = this;
		var maxPrice = 0;
		
		for (var i in productPriceMap) {
			var price = productPriceMap[i];
			price = parseFloat((""+price).replace(",", ""));
			
			maxPrice = (price > maxPrice) ? price : maxPrice;
		}
		
		try {
//			logTo("Initiating PriceFilter with maxValue: " + maxPrice);
			if(parseInt(maxPrice) > 0) {
				this.filter = new PriceFilter({onError: function(){me._onFilterError(me)}, onSucces: function(){me._onFilterSucces(me)}, maxValue:maxPrice});
				this.showPriceRangeWidget();
			}
		} catch(e) {
//			logTo(e);
		}
	},
	
	_onFilterError : function(me) {
		return;	//do nothing
	},
	
	_onFilterSucces : function(me) {
		var range = this.filter.getPriceRange();
		//return when range contains null 
		if (isNaN(range[1]) || isNaN(range)) {

			return;
		}
		
		this._toggleProducts();
		this._showPriceRangeText();
	},
	
	_toggleProducts : function() {
		var range = this.filter.getPriceRange();
		var min = range[0], max = range[1];
		var pricemap = this.productPriceMap;
		
		for(var sku in pricemap) {
			var selector = '[id='+sku+']';
			var price = parseInt(pricemap[sku]);
			if (price >= min && price <= max) {
				$gJQ(selector).show('slow');
			}else{
				$gJQ(selector).hide('slow');
			}
		}
	},
	
	_getPriceRangeText : function() {
		var range = this.filter.getPriceRange();
		var labels = this.filter.getPriceLabels();
		return [labels[0], range[0], labels[1], range[1]].join(" ").toLowerCase();
	},
	
	_showPriceRangeText : function() {
		var txt = this._getPriceRangeText();
		$gJQ(".product-header").find("span").remove().end().append("<span>" + txt + "</span>");
	}
	
};
