// API accessing object for the carousel
var carouselApi;
// Width of each item on carousel
var itemWidth = 142;
// Starting item
var actualItem = 1;
// Quantity of items in the carousel
var qtyItems = 0;
// Size of the carousel
var carouselSize = 5;
// Carousel autoslide time
var carouselDelay = 8000;
// Timer object for the autorotate
var autorotateTimer = null;
// Query string
var qs = null;
// Array used for deep linking
var urlsArray = new Array();
// Array used to get the relationship item <-> page
var pageIndexes = new Array();
// Carousel initialization code
$(document).ready(function(){
	var urlXML = "";
	qs = $.param.querystring();
	$('<div class="loader-msg">Loading</div>').appendTo('body');
	if (isAuthenticated)
	{
		urlXML = "includes/xml/homepage.xml";
	
	}
	else 
	{
		urlXML = "includes/xml/homepageNotLogged.xml";
	}
	
	$.ajax({
			type: "GET",
			url: urlXML,
			dataType: "xml",
			success: function(xml) {
				// Markup of the product information
				var productInfoMarkup = "";
				// Markup of the bottom navigation carousel
				var carouselMarkup = "";
				// Markup of dynamic css rules
				var cssRules = "<style type='text/css'>\n";
				var page = 0;
				$(xml).find('item').each(function(index){
					productInfoMarkup += '<div id="' + $(this).attr('name') + '" class="homeContainer">\n<div class="leftColumn">\n';
					if ($(this).find('subheader').text())
						productInfoMarkup += $(this).find('subheader').text() + '\n<div class="leftDivider png-fix"></div>\n';
					productInfoMarkup += $(this).find('copy').text() + '\n</div>\n<div class="productHeadline">'
					+ $(this).find('header').text() + '</div>\n</div>\n';
					carouselMarkup += '<a href="?' + $(this).find('url').text()
					+ '" rel="' + $(this).attr('name')
					+ '" title="' + $(this).find('thumbnailText').text() + '">'
					+ '<img src="' + $(this).find('thumbnail').text()
					+ '" onclick="pageTracker._trackEvent(\'view\',\'home_scroll\',\''
					+ $(this).find('trackingTag').text() + '\');" alt="'
					+ $(this).find('thumbnailText').text() + '" /></a>\n';
					urlsArray[index] = $(this).find('url').text();
					if(index % 5 == 0 && index > 0) {
						page++;
					}
					pageIndexes[index] = page;
					cssRules += '#' + $(this).attr('name') + ' { '
					+ 'background-image:url(' + $(this).find('largeImage').text() + '); }\n';
					qtyItems++;
				});
				cssRules += "</style>";
				$("head").append(cssRules);
				$("#main-content").append(productInfoMarkup);
				$(carouselMarkup).insertAfter(".activeIndicator");
				initializePage();
				$(".loader-msg").hide().remove();
				$("#bottomNav").fadeIn('slow');
			},
			error: function(e){
				$(".loader-msg").hide().remove();
				$('<div class="error-msg">We&rsquo;re sorry.<br/><b>Data loading error!</b><br/>Please try again in a few minutes!</div>').appendTo('body');
			}
		});
	// Load the information
	function initializePage(){
		var initialItem = null;
		var urlIndex = $.inArray(qs, urlsArray);
		if(qs != null && qs != "" && urlIndex >= 0) {
			initialItem = $("div.items a").eq(urlIndex).attr("rel");
			moveIndicator(urlIndex);
			showSlide(initialItem);
			applyHomesIFR();
			// Initialize the carousel
			carouselApi = $("div.scrollable").scrollable({
				api: true,
				size: carouselSize,
				clickable: false,
				item: 'a',
				nextPage: ".rightControl",
				prevPage: ".leftControl"
			});
			var pageIndex = 0;
			if(urlIndex > 4) {
				pageIndex = pageIndexes[urlIndex];
				setTimeout(function(){
					for(i = 0; i < pageIndex; i++){
						carouselApi.nextPage();
					}
				},200);
			}
		} else {
			initialItem = $("div.items a:first").attr("rel");
			showSlide(initialItem);
			applyHomesIFR();
			// Initialize the carousel
			carouselApi = $("div.scrollable").scrollable({
				size: carouselSize,
				clickable: false,
				item: 'a',
				nextPage: ".rightControl",
				prevPage: ".leftControl",
				onStart: startAutoRotate()
			}).autoscroll({
				api: true,
				steps: 1,
				interval: carouselDelay,
				autoplay: false,
				autopause: false
			});
		}
		// Click event for the scrollable items
		var clickedItem = $("div.items a").click(function(){
			// Stop autorotate
			if(qs == null || qs == "")
				carouselApi.stop();
			clearTimeout(autorotateTimer);
			// Move the active indicator
			moveIndicator(clickedItem.index(this));
			return false;
		});
		// This enables the rollover tooltip for the bottom navigation icons
		$("div.items a").tooltip({
			tip: '#bottomNavTooltip',
			delay: 0,
			predelay: 100
		});
		// Show demo video popup
		$(".showDemoPopup").live("click",function(){
			$("#demoPopup").modal();
			return false;
		});
		$(".showDemoPopup2").live("click",function(){
			$("#demoPopup2").modal();
			return false;
		});
		$(".showDemoPopup3").live("click",function(){
			$("#demoPopup3").modal();
			return false;
		});
	}// End of intializePage()
});// DOM Ready
// Initialize the autorotate behavior
function startAutoRotate() {
	autorotateTimer = setTimeout(function() {
		// Move arrow to selected item
		moveIndicator(actualItem);
		actualItem++;
		// If is the fifth element in the actual page, the move the carousel
		if((actualItem - 1)%5 == 0){
			carouselApi.play();
		}
		// Rotate while actual item is not the last item
		if(actualItem < qtyItems){
			startAutoRotate();
		} else {
			carouselApi.stop();
		}
	}, carouselDelay);
}// end startAutorotate
// Moves the arrow indicator
function moveIndicator(index){
	// Pixels to move
	var movementGap = (itemWidth * index) + 64;
	$(".activeIndicator").stop().animate({left: movementGap + "px"}, 400);
	// Get the related slide to show
	var slide = $("div.items a:eq(" + index + ")").attr("rel");
	// Show corresponding slide
	showSlide(slide);
	applyHomesIFR();
}// end moveIndicator()
// Shows a specific slide
function showSlide(id){
	if (null != id){
		$("#" + id).siblings(".homeContainer").fadeOut(400, function(){
			// Show corresponding left container
			$("#" + id).fadeIn(800);
		});
	}
}// end showSlide()
// Fires the DART Tagging
function spotlightTagging() {
	var axel = Math.random() + "";
	var a = axel * 10000000000000;
	var spotpix = new Image();
	spotpix.src = "http://ad.doubleclick.net/activity;src=1419543;type=hills544;cat=hilsh499;ord=" + a + "?";
}
function spotCookbook(href) {
    var axel = Math.random() + "";
    var a = axel * 1000000000000000000;
    document.url = href;
    var doPing = new Image();
    // the URL below is a spotlight tag for page3
    doPing.src = 'http://ad.doubleclick.net/activity;src=1419543;type=hills544;cat=hilsh499' + a + '?';
    
    return true;
}

