// Starting markup code of the tooltip
var tooltipCode01 = '<div class="tooltip"><div class="tooltip-lft png-fix"><div class="tooltip-ctn png-fix">';
// Ending markup code of the tooltip
var tooltipCode02 = '</div><div class="tooltip-rgt png-fix"></div><div class="tooltip-arrow png-fix"></div></div></div>';
// Array that contains all the posible rel attributes for each one of the products
var relAttrs = new Array();
// Array that contains all the tooltips content fro each one of the products, these should correspond to the rel attributes of the above array
var tooltipsCtn = new Array();
// Array with the classes of the external controls used for carousel go to functionality
var externalControls = new Array();
// Quantity of products in the carousel
var qtyProducts = 0;
// Base url for ie bug with href attribute.
var loc = window.location.href;
// sIFR initialization code
var cooperBlack = { src: 'swf/saraLeesIFR.swf' };
var popupStatus2 = 0;
var popupStatus = 0;
var selectProduct;
var productId;
var counter = 0;

//loading popup with jQuery magic!
function loadPopup(){
	//loads popup only if it is disabled
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("slow");
		$("#popupContact").fadeIn("slow");
		popupStatus = 1;
	}
}

//disabling popup with jQuery magic!
function disablePopup(){
	//disables popup only if it is enabled
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("slow");
		$("#popupContact").fadeOut("slow");
		popupStatus = 0;
	}
}

//centering popup
function centerPopup(){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupContact").height();
	var popupWidth = $("#popupContact").width();
	//centering
	$("#popupContact").css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	
	$("#backgroundPopup").css({
		"height": windowHeight
	});
	
}



function loadPopup2(){
	//loads popup only if it is disabled
	if(popupStatus2==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("slow");
		$("#popupContact2").fadeIn("slow");
		popupStatus2 = 1;
	}
}

//disabling popup with jQuery magic!
function disablePopup2(){
	//disables popup only if it is enabled
	if(popupStatus2==1){
		$("#backgroundPopup").fadeOut("slow");
		$("#popupContact2").fadeOut("slow");
		popupStatus2 = 0;
	}
}



function centerPopup2(){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupContact2").height();
	var popupWidth = $("#popupContact2").width();
	//centering
	$("#popupContact2").css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	
	$("#backgroundPopup").css({
		"height": windowHeight
	});
	
}



function popup(){
	
	$("div.popupContact").show();	
}


sIFR.activate(cooperBlack);
/** jQuery code start */
$(document).ready(function(){
	$.ajax({
		type: "GET",
		url: "xml/products.xml",
		dataType: "xml",
		success: function(xml) {
			// Markup of the product information
			var productInfoMarkup = "";
			// Markup of the bottom navigation carousel
			var carouselMarkup = "<ul>\n";
			// Markup of dynamic css rules
			var cssRules = "<style type='text/css'>\n";
			$(xml).find('product').each(function(index){
				relAttrs[index] = $(this).attr('name');
				tooltipsCtn[index] = $(this).find('tooltipTitle').text();
				url =  $(this).attr('name');
				switch(url)
				{
				case "cocktails":
					hname = 'cocktails';
					break;	
				
				case "pigs":
					hname = 'homelitlsmokies';
					break;				
				
				case "KielbasaSauerkraut":
					hname = 'KielbasaSauerkraut';					
					break;
				
				case "MammaJamma":
					hname = 'MammaJamma';
					
					break;
			
					
				case "cookbook":
					hname = 'cookbook';
					break;
			
				
				case "beer-brats":
					hname = 'homebeerbrat';
					break;
				
				case "uttb":
					hname = 'homesandwich';
					break;
					
				case "save-55":
					hname = 'homecoupon';
					break;
								
				default:
					hname = 'homecoupon';
					break;
				
				}
				productInfoMarkup += '<div id="' + $(this).attr('name') + '-ctn" class="left-ctn">\n<div class="left-column">\n'
				+ $(this).find('subheader').text() + '\n<div class="left-divider png-fix"></div>\n'
				+ $(this).find('copy').text() + '\n</div>\n<div class="product-headline">'
				+ $(this).find('header').text() + '</div>\n</div>\n<span class="' + (index + 1) + '"></span>';
				externalControls[index] = "." + (index + 1);
				carouselMarkup += '<li class="' + (index + 1) +'"><a href="' + hname + '" rel="' + $(this).attr('name') + '" class="' + url +'">'+ '<img class="png-fix" src="' + $(this).find('thumbnail').text() + '" onclick="javascript:urchinTracker(\'/clicks/homepage/scroll/'+$(this).find('trackingTag').text()+'\');" alt="'
				+ $(this).find('tooltipTitle').text() + '" /></a></li>\n';
				 cssRules += '#' + $(this).attr('name') + '-ctn {'
				+ 'background-image:url(' + $(this).find('largeImage').text() + '); }\n';
				qtyProducts++;

			});
			carouselMarkup += '</ul>\n';
			cssRules += "</style>";
			$("head").append(cssRules);
			$(productInfoMarkup).insertBefore("#carousel");
			$("#main-carousel").append(carouselMarkup);
			initializePage();
		},
		error: function(e){
			$('<div class="error-msg">We&rsquo;re sorry.<br/>Error loading the info!</div>').appendTo('#main-section');
			$('#carousel').hide();
		}
	});
	autoFill($("#search-term"), "Search");
}); // DOM ready
// Initialize all the events in the page
function initializePage(){
	$('#main-section').css({'overflow':'hidden'});
	// Get the first element in the carousel and use the related style for the body
	var relAttr = $('#main-carousel ul li:first').next().next().find('a').attr('rel');
	if(relAttr) {
		// Show corresponding content
		$('#' + relAttr + '-ctn').show();
	}
	applysIFR();
	$.address.change(function(event) {
			var sectionName = event.value;
			var product = '';
			switch(sectionName)
			{
			case "/cocktails":
				product = 'cocktails';
				break;
				
			case "/homelitlsmokies":
				product = 'pigs';
				break;
				
			case "/KielbasaSauerkraut":
				hname = 'KielbasaSauerkraut';		
				break;	
			
			case "/MammaJamma":
				hname = 'MammaJamma';		
				break;		
			
			case "/cookbook":				
				product = 'cookbook';
				break;
				
				
	
			
			case "/homebeerbrat":
				product = 'beer-brats';
				break;
			
			case "/homesandwich":
				product = 'uttb';
				break;
				
			case "/homecoupon":
				product = 'save-55';
				break;
				
			default:
				product = 'homecoupon';
				break;
			}
				showProductInfo(product);
			});
	// Initialize jCarousel	

	$('#main-carousel').jCarouselLite({
		btnNext: ".btn-next",
		btnPrev: ".btn-prev",
		visible: 6,
		auto: 8000,
		speed: 500,
		start:8,
		beforeStart: function(){
			$('.tooltip').hide();
		},
		afterEnd: function(visibleElements){
			var product = $("a", visibleElements[2]).attr('rel');
			if(product) {
				showProductInfo(product);
			}
			$.address.value($('.' + product).attr('href').replace(loc, ''));
			$('.tooltip').remove();
			applysIFR();
		},
		btnGo:externalControls
	});

	
	// This removes the auto scroll of the carousel
	$('.btn-prev, .btn-next').click(function(){
		clearInterval(jCarouselIntervalId);
	});
	clickCarouselItem();
	// Product rollover effect
	hoverCarouselItem();
	
	$("#viewdemo01").click(function(){
		//centering with css
		centerPopup();
		//load popup
		loadPopup();
	});
				
	//CLOSING POPUP
	//Click the x event!
	$("#popupContactClose").click(function(){
		disablePopup();
	});
	//Click out event!
	$("#backgroundPopup").click(function(){
		disablePopup();
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});
	
	
	//------Second Functionality-------
	$("#viewdemo012").click(function(){
		//centering with css
		centerPopup2();
		//load popup
		loadPopup2();
	});
				
	//CLOSING POPUP
	//Click the x event!
	$("#popupContactClose2").click(function(){
		disablePopup2();
	});
	//Click out event!
	$("#backgroundPopup2").click(function(){
		disablePopup2();
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus2==1){
			disablePopup2();
		}
	});
	
	
}

function trackError( err )
{
	var msg = 'Unknown error';
	if ( err.message )
	{
		msg = err.number;
	}
	else if ( typeof err == 'string' || typeof err == 'String' )
	{
		msg = err;
	}
	//alert("hola lindos" + msg);
	// Msg for over stack error
	if (msg == 'Out of stack space; http://dtaspsara.avventa.co.cr/hillshirefarm/; 20')
	{
		//alert("hola lindos");
		window.location.reload();
		//location.reload(true);
	}
};

window.onerror = function( msg, url, lineNo ) 
{ 
	trackError( [ msg, url, lineNo ].join('; ') );
	// return true to stop error from propogating, false to allow propogation
	return true;
};

// click carousel effect
function clickCarouselItem(){
$('#main-carousel ul li a').click(function(){
		//Load Background content function
		selectProduct = $(this).attr('rel');
			showProductInfo(selectProduct);
		// Bounce effect
		$('img',this).stop().animate({ marginTop: "-20px" }, 300).animate({ marginTop: "0px" }, 300);
		// This clear the setInterval used for the autorotate functionality, the provided ID was added by us in the jCarouselLite library, so it is always the same
		clearInterval(jCarouselIntervalId);
		// Get the product to show
		productId = parseInt($(this).parent().attr('class'));
		// Apply some arithmetic rules to mantain the cyclic carousel
		productId = productId + qtyProducts - 2;
		if(productId > qtyProducts)
			productId = productId % qtyProducts;
		// Go to the product
		$("." + productId).trigger('click');                                       
	});
}

// Product rollover effect
function hoverCarouselItem(){
	$('#main-carousel li').hover(
		function(){
			// Get the position of the product
			var position = $(this).offset();
			// Get rel attribute
			var rel = $("a", this).attr('rel');
			// Get index of the rel attribute
			var indexRel = $.inArray(rel, relAttrs);
			var text = tooltipCode01;
			// Get content of the tooltip
			if(indexRel >= 0) {
				text += tooltipsCtn[indexRel];
			} else {
				text += "___";
			}
			text += tooltipCode02;
			// Add tooltip to product
			$('#main-section').append(text);
			setTimeout( function() {
				$('#main-section .tooltip').show();
				}, 600 );
			// This center the tooltip
			var all_windows = $(window).width();
			var mainSectionWidth = ($('#main-section').width()) + 8;
			var sectionTooltips = (all_windows - mainSectionWidth); 
			var tooltipWidth = $('#main-section .tooltip').width();
			if (all_windows > mainSectionWidth) {
				$('.tooltip').css('left',position.left + 60 - (tooltipWidth/2) - (sectionTooltips/2)).css('top',position.top - 100);
			}
			else {
				$('.tooltip').css('left',position.left + 60 - (tooltipWidth/2)).css('top',position.top - 100);
			}
		},
		function(){
			// This removes the tooltip
			$('#main-section .tooltip').hide().remove();
		}
	);
	}

// This shows a specific product information
function showProductInfo(product){
	// Hide any product information
	$('#' + product + '-ctn').siblings('.left-ctn').fadeOut(400, function(){
		// Show corresponding left container
		$('#' + product + '-ctn').fadeIn(900);
	});
}

// Apply sIFR replacing
function applysIFR (){
	sIFR.replace(cooperBlack, {
		selector: '.left-column h3.red-hdr, .product-headline h1.red-hdr'
		,css: '.sIFR-root {color:#b52e18; font-weight:bold;}'
		,wmode: 'transparent'
	});
	sIFR.replace(cooperBlack, {
		selector: '.left-column h3.green-hdr, .product-headline h1.green-hdr'
		,css: '.sIFR-root {color:#005944; font-weight:bold;}'
		,wmode: 'transparent'
	});
}

// Autofill function
function autoFill(id, v){
	$(id).attr({ value:v })
	.focus(function(){
			if($(this).val() == v){
				$(this).val("");
			}
	})
	.blur(function(){
		if($.trim($(this).val()) == ""){
			$(this).val(v);
		}
	});
}


