// section carousel
$.fn.sectionCarousel = function()
{
	var m_this = $(this);
	var m_setupDone = false;
	
	function setUp()
	{
		var els = m_this.find("li");
		var el1 = $(els.get(els.length-1));
		var el2 = $(els.get(els.length-2));
		m_this.prepend(el1.clone());
		m_this.prepend(el2.clone());
		el1.remove();
		el2.remove();
		
		m_this.jcarousel({
			scroll : 1,
			visible : 3,
			animation : "fast",
			start : 2,
			easing : "linear",
			wrap: 'circular',
			itemFirstInCallback:setMainItem,
			itemVisibleInCallback: {
  					onBeforeAnimation: _onBeforeAnimation,
  					onAfterAnimation: _onAfterAnimation
				},
			itemVisibleOutCallback:_itemVisibleOutCallback
		});
		
		m_setupDone = true;
	}
	
	function _onBeforeAnimation(carousel,element,i,status)
	{
		m_this.find("li").removeClass("light");
		var idx = carousel.index(i, carousel.options.size);
		carousel.add(i,carousel.get(idx).html())
	}
	
	function _onAfterAnimation(carousel,element,index,status)
	{
		var idx = carousel.index(index, carousel.options.size);
		carousel.selected=idx
	}
	
	function _itemVisibleOutCallback(carousel, item, i, state, evt)
	{
		if (i>carousel.options.size || i<0)
			carousel.remove(i);
	};
	
	function setMainItem(carousel, item, i, state, evt)
	{
		var current = $(item).next();
		current.addClass("light");
		
		var box = $(".carousel .layer");
		box.find(".boTitle").html(current.find(".carouselItemDetail .boTitle").html());
		box.find(".boDescription").html(current.find(".carouselItemDetail .boDescription").html());
		box.find(".boImage").attr("src",current.find(".carouselItemDetail .boImage").attr("src"));
		box.find(".boImageBig").attr("src",current.find(".carouselItemDetail .boImageBig").attr("src"));		
	}
	
	setUp();
}

$(document).ready(function() {
	
	function showModalDialog()
	{
		var modalHtml = "<div id=modalDialog style=\"position:absolute;left:0;top:0;display:none;background-color:#000;z-index:500;\">&nbsp;</div>";
		if ($("#modalDialog").length==0)
		{
			$(document.body).append(modalHtml);
			$(window).resize(sizeAndPosition);
			$(window).scroll(sizeAndPosition);
		}
		var dlg = $("#modalDialog");
		dlg.css("opacity",0.5);
		dlg.css("filter", "alpha(opacity='50')");
		sizeAndPosition();
		dlg.show();
	}
	
	function sizeAndPosition()
	{
		var dlg = $("#modalDialog");
		dlg.width($(window).width());
		dlg.height($(window).height()+$(document).scrollTop());
	}
			
	/*Language*/
	$("#language").change(languageChange);
	function languageChange(){
		var URL = $("#language option:selected").val();		
		window.location.href = URL;
	}
	
	/*Profile
	$("li.profile a:first").click(function() {
		//$(this).parent().find("div").fadeIn("fast");
		$(this).parent().find("div").animate({
		  "height": "toggle", "opacity": "toggle"
		}, 1000);
		if($(this).hasClass("active"))
		{
			$(this).removeClass("active");
		}
		else {
			$(this).addClass("active");
		}				
	});*/
	
	/*Basket
	$("li.basket_menu a:first").mouseover(function(){
		$(this).parent().find("div.basket_layer").show();				
	})

	$("li.basket_menu a.close").click(function(){
		$("div.basket_layer").hide();				
	})*/
	
	/*Help
	$("div.coldx a.help").click(function() {
		$("div.help_layer").animate({
		  "width": "show", "opacity": 0.95
		}, 1000);
		$("div.help_layer a.close").show();
	});

	$("div.help_layer a.close").click(function() {
		$(this).hide();
		$("div.help_layer").animate({
		  "width": "hide", "opacity": "toggle"
		}, 1000);
	});	*/
	
	/*Login
	$("li.login_menu a:first").click(function() {				
		showModalDialog();		
		$("#login").css("left", ($(window).width()-$("#login").width())/2);
		$("#login").css("top", 120 + $(document).scrollTop());		
		$("#login").fadeIn("fast");
		$("#login").fadeIn("fast");
	});

	$("#login div.close a").click(function() {
		$(this).parent().parent().fadeOut("fast");
		$("#modalDialog").hide();
	});*/
	
	
	/*Menu*/
	var url = document.location.href;
	$(".menu a, #footer a, .menu_top a, #assistance ul a").each(function()
	{
		var href = $(this).attr("href").split("../").join("");
		var hrefPrefix = href.indexOf("/")!=-1 ? href.substring(0, href.lastIndexOf("/"))+"/" : href;
		
		href = href.split("it/").join("");
		hrefPrefix = hrefPrefix.split("it/").join("");
		href = href.split("en/").join("");
		hrefPrefix = hrefPrefix.split("en/").join("");

		if (href!="" && url.indexOf(href)!=-1)
		{
			$(this).closest("li").find("ul").show();
			$(this).addClass("current");
		}
		else if (hrefPrefix!="" && url.indexOf(hrefPrefix)!=-1)
		{
			$(this).closest("li").find("ul").show();
			$(this).addClass("active");
		}
	})
	
	$(".carousel .layer .card").animate({opacity: 0.8});
});



/** 
 * Service list
 */
var serviceBasePath = "/";
var basePath = '/tvs/';
var priceRange = 30;
if (document.location.port == '8080') {
	if (document.location.hostname=='192.168.13.4')
		serviceBasePath = "http://192.168.13.4:8080/tvs-site/rest/tvs_site/default/content/";
} else {
	if (document.location.hostname=='' || document.location.hostname=='cms.timeo.biz')
		serviceBasePath = "http://cms.timeo.biz/tvs/rest/tvs_site/default/content/";
	if (document.location.hostname=='192.168.13.4')
		serviceBasePath = "http://192.168.13.4/rest/tvs_site/default/content/";
	if (document.location.hostname=='62.77.53.78')
		serviceBasePath = "http://62.77.53.78/rest/tvs_site/default/content/";
	if (document.location.hostname=='www.tvs-spa.it')
		serviceBasePath = "http://www.tvs-spa.it/rest/tvs_site/default/content/";
}

var SERVICES = {};
SERVICES.format = '.json';
SERVICES.productListByLine = 'product.json';
SERVICES.product = 'product.json';
SERVICES.productListBySimilar = 'product.json' ; 
SERVICES.productListByViews = 'product.json' ;
SERVICES.lineListBySense = 'line.json' ;

/**
* Catalogue Proxy
*/
var globalData = {};
var globalProductId = '' ;
var globalFatherId = '' ;
function CatalogueProxy() {

	this.getProductListByLine = function( id , callback ) {
		ProxyUtil.invokeService('productListByLine', 
								{ 'filter' : 'line=\'' + id + '\'' , 'expandReferencePath' : [ 'line' , 'icons' , 'family' ] },
								callback , 'data.contentList' );
	}
	
	this.getProduct = function( id , callback ) {
		ProxyUtil.invokeService('product', 
								{ 'filter' : 'kca:id=\'' + id + '\'' , 'expandReferencePath' : [ 'line' , 'icons' ] },
								callback , 'data.contentList[0]');
	}
	
	this.getSimilarProductList = function( parameters , callback ) {
		
		ProxyUtil.invokeService('product', 
								{ 'filter' : 'tipology=\'' + parameters.tipology + '\' AND (price>='+(Math.max((parameters.price-priceRange),0))+' AND price<='+(parameters.price+priceRange)+') AND family isNull AND NOT line=\''+parameters.line+'\'', 'expandReferencePath' : [ 'line' , 'icons' , 'family' ] , 'limit' : 5 },
								callback , 'data.contentList');
	}
	
	this.getProductListByViews = function( callback ) {
		// not easypretty!
		ProxyUtil.invokeService('productListByViews', 
								{ 'filter' : 'family isNull AND NOT line=\'2B7B890D-E307-5257-B0C1-785F9219013A\' AND NOT tipology=\'coperchio\'' , 'expandReferencePath' : [ 'line' , 'icons' ] , 'limit' : 100 },
								callback , 'data.contentList' );
	}
	
	this.getLineListBySense = function( callback ) {
		ProxyUtil.invokeService('lineListBySense', 
								{ 'expandReferencePath' : [ 'line' , 'icons' ] },
								callback , 'data.contentList' );
	}
	
}



ProxyUtil = new function()
{
	this.invokeService = function(serviceId, parameters, callback , rootObjectName ) 
	{
		ajaxCall(serviceBasePath + eval('SERVICES.'+serviceId), parameters, callback , rootObjectName);
	}

	function ajaxCall ( url, parameters, callback , rootObjectName )
	{
		// test
		if (document.location.hostname=="")
		{
			try 
			{
				netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			} 
			catch (err){}
		}
		jQuery.ajax({
			type: "GET",
			async: true,
			url: (url + (url.indexOf("?")!=-1 ? "&" : "?") + "rnd=" + new Date().getTime()),
			data: parameters,
			success: function(data) 
			{
				if (data)
				{
					globalData = null ;
					globalData = data;
					var d = data;
					if (rootObjectName)
					{
						d = eval(rootObjectName);
					}
					data = null ;
					callback(d);
				}
				else
				{
					//console.log("Error", resp);
					document.location = "#error";
				}
			},
			dataType: "json"
		});
	}
}



/**
* Services!
*/
function buildProductListByLine(list,r) {
	var l = list.length;
	var h = [];
	$('#mycarousel').empty();
	if( r ) {
		list.sort(function() {return 0.5 - Math.random()});
	}
	for( i = 0 ; i < l ; i++ ) {
		if( !list[i].family ) {
			var name = list[i].name[globalLang];
			var image = list[i].thumb_medium;
			if(image) {
				imageSrc = image["kca:src"] ;
			} else {
				imageSrc = '' ;
			}
			var line = list[i].$ref;
			var lineName = list[i].line.name;
			h[i] = '<li><a href="#'+list[i]['kca:id']+'" title="'+lineName+' - '+name+'" class="boBySimilar" rel="'+list[i].line['kca:id']+'"><img src="'+imageSrc+'" alt="'+lineName+' - '+name+'" width="138" height="100"/></a></li>';
		}
	}
	$('#mycarousel').append(h.join(''));
	$("#mycarousel").jcarousel({
		scroll : 1,
		visible : 5,
		animation : "fast",
		easing : "linear"
	});
}
function buildRandomProductListByLine(list) {
	buildProductListByLine(list,true);
}

function returnData(data) {
	return data;
}

function buildProductDetail(product) {
	$('#slideshow').empty();
	$diameter = $('#diametro');
	$diameter.empty();
	var $target = $('.product_card');
	var products = globalData.contentList;
	// line name
	if( product.line.imageproducttitle && product.line.imageproducttitle['kca:src'] ) {
		var lineName = product.line.imageproducttitle['kca:src'];
	} else {
		var lineName = '';
	}
	$target.find('.boLineName').html('<img src="'+lineName+'" alt="'+product.line.name+'" />');
	// name
	$target.find('.boProductName').text(product.name[globalLang]);
	// code
	$target.find('.boProductCode').text(product.code);
	// color
	$target.find('.boProductColor').text(product.color[globalLang]);
	// capacity
	$target.find('.boProductCapacity').text(product.capacity + ' cl');
	// price
	var price = product.price.toString();
	var pricePieces = price.split('.');
	if( pricePieces && pricePieces.length > 0 ) {
		if( pricePieces[1] ) {
			decimal = pricePieces[1] ;	
		} else {
			decimal = '0' ;	
		}
		price = pricePieces[0] + ',' + decimal + '0 &euro;';	
	}
	$target.find('.boProductPrice').html(price);
	// diameter
	if( product.family ) {
		globalFatherId = product.family['kca:id'] ;
	} else {
		globalFatherId = product['kca:id'] ;
	}
	for( i = 0 ; i < products.length ; i++ ) {
		if( products[i]['kca:id'] == product['kca:id'] || 
		( products[i].family && products[i].family['kca:id'] == product['kca:id'] ) ||
		( products[i].family && products[i].family['kca:id'] == globalFatherId ) || 
		products[i]['kca:id'] == globalFatherId ) {
			$diameter.append($("<option></option>").attr('value',products[i]['kca:id']).attr('id',products[i].line['kca:id']).text(products[i].diameter));
		}
	}
	globalFatherId = '' ;
	$diameter.find('option[value=\''+product['kca:id']+'\']').attr('selected','selected');
	// logo
	if( product['logo-material'] ) {
		logoSrc = product['logo-material']['kca:src'];
	} else {
		logoSrc = '' ;
	}
	$target.find('.boLogoImage').attr('src',logoSrc);
	// icons
	var icons = product.icons ;
	var ll = icons.length ;
	$('.boIcons').empty() ;
	if( product.line && product.line['logo-material'] ) {
		$('.boIcons').append('<li><img src="'+product.line['logo-material']['kca:src']+'" alt=""/></li>');
	}
	for( i = 0 ; i < ll ; i++ ) {
		$('.boIcons').append('<li><img src="'+icons[i].image['kca:src']+'" alt="'+icons[i].description[globalLang]+'"/></li>');
	}
	// slideshow
	var slides = [] ;
	var l = product.image.length ;
	if( l > 0 ) {
		for( i = 0 ; i < l ; i++ ) {
			active = ( i == 0 ? ' class="active"':'');
			slides.push('<div'+active+'><img src="' + product.image[i]["kca:src"] +'" alt="" width="350" height="254" /></div>');
		}
	} else {
		slides.push('<div class="active"><img src="' + product.image["kca:src"] +'" alt="" width="350" height="254" /></div>');
	}
	$('#nav').empty();
	$('#slideshow').html(slides.join(''));
	$('#slideshow').cycle({
        fx:      'scrollLeft',
        timeout:  4000,
        pager:   '#nav',
		size: slides.length
    });
	// pdf
	if( product.pdf[globalLang] ) {
		$target.find('.download').text( product.pdf[globalLang] );
	}
	// tracking
	//Tracker.track('' , {product:product});
	// similar products
	TVScatalogue.getSimilarProductList({ tipology : product.tipology , price : product.price , id : product['kca:id'] , family : globalFatherId , line : product.line['kca:id']} , buildSimilarProductList );
}

function buildProductDetailOnDiameterChange(list) {
	product = getProductFromData( globalProductId , list );
	buildProductDetail(product);
}

function getProductFromData( productId , productList ) {
	
	if( productId.indexOf('#') > -1 ) {
		p = productId.split('#');
		productId = p[1];
	}
	var list;
	if( productList ) {
		list = productList;
	} else {
		list = globalData.contentList;
	}
	var l = list.length;
	for( i = 0 ; i < l ; i++ ) {
		if( list[i]['kca:id'] == productId )
			return list[i];
			
	}
}

function buildSimilarProductList(list) {
	var l = list.length;
	var h = [];
	$('.boSimilarProductList').empty();
	for( i = 0 ; i < l ; i++ ) {
		var name = list[i].name[globalLang];
		var lineName = list[i].line.name
		var image = list[i].thumb_medium;
		if(image) {
			imageSrc = image["kca:src"] ;
		} else {
			imageSrc = '' ;
		}
		var line = list[i].$ref;
		h[i] = '<li><a href="#'+list[i]['kca:id']+'" rel="'+list[i].line['kca:id']+'" title="'+lineName+' - '+name+'" class="boByLine"><img src="'+imageSrc+'" alt="'+lineName+' - '+name+'" width="138" height="100"/></a></li>';
	}
	$('.boSimilarProductList').append(h.join(''));
}

/**
 * Tracking
 */
var pageTracker;

Tracker = new function(){};

Tracker.track = function(src, params)
{
	// google analytics
		try
		{	
		
			p = document.location.protocol + '//' + document.location.hostname ;
		
			if( params && params.product ) {
				product = params.product;
				if( globalLang == 'IT' ) {
					uu = [ globalLang.toLowerCase() , 'catalogo', product.line.name , product.name[globalLang] + '_' + product.diameter ];
				} else if( globalLang == 'EN' ) {
					uu = [ globalLang.toLowerCase() , 'catalogue', product.line.name , product.name[globalLang] + '_' + product.diameter ];
				}
				u = uu.join('/').split(' ').join('_');
			} else {
				u = src.split(p).join('').split('/index.jsp').join('/').split('.jsp').join(''); 
			}
			u=u.split('#1').join('').split(basePath).join('');
			
			if( console && console.log ) {
				console.log("Tracking GA: " + u.toLowerCase());
			}
				
			pageTracker._trackPageview(u);
		}
		catch (e)
		{
			if( console && console.log ) {
				console.log("GA tracking error", e);
			}
		}
}
