poc = organic;


try {
if (!poc.exists) { throw "pocObjUndefined"; }

poc.homepage = {
    num_backgrounds:0,
    current_background:false,
	nextBg:0,
	crossfade:false,
	animationTimeout:null,
	overlayTimeout:null,
	nextTimeout:null,
	bgSpeed:250,
	fgSpeed:250,
	bgCached:false,
	fgCached:false,
	randomBool:false,
	animationAllowed:false,
	 
	init: function() {
		//console.log('Running');
		
	    //Count backgrounds
		poc.homepage.bgCached = jQuery('#bg div');
		poc.homepage.fgCached = jQuery('#fg div');
        
        if(poc.homepage.bgCached.size() != 0) {
           poc.homepage.preload();
        }
    },
    
    fadeBG: function(id, crossfade) {
        var curr_bg = poc.homepage.current_background;
		
		function fadeInBg ()
		{
			var next = id;
			//console.log("next: "+next)
			poc.homepage.bgCached.eq(next).css({'opacity':''}).fadeIn(poc.homepage.bgSpeed, function() {
				poc.homepage.fgCached.eq(next).css({'opacity':''}).fadeIn(poc.homepage.fgSpeed, function () {
					poc.homepage.current_background = next;
					poc.homepage.nextBg = poc.homepage.current_background+1;
				});
			});				
		}
		
        if(curr_bg !== false){
			//console.log("curr bg: "+curr_bg);
            poc.homepage.fgCached.eq(curr_bg).fadeOut(poc.homepagefgSpeed, function() {																
				poc.homepage.bgCached.eq(curr_bg).fadeOut(poc.homepage.bgSpeed, function (){										  
					// crossfade isnt wanted, fadeIn is queued
					if(!crossfade) { fadeInBg(); }
					jQuery(".controls").removeClass("active");
					jQuery(".controls").eq(id).addClass("active");
				});
				// crossfade required, fadeIn isn't queued
				if(crossfade) { fadeInBg(); }
            });
        }
		else { fadeInBg(); }
        //END HACK
    },
	
	preload: function () {
		
		function imageLoaded () {
			jQuery("body#homepage #flash-content").css({'background':'none'});
			poc.homepage.initRotation();			
		}
		var imgArray = new Array();
		
		for (var i=0;i<poc.homepage.bgCached.length;i++)
		{
			var bg = poc.homepage.bgCached.eq(i);
			
			var cssImage = bg.css("background-image");
			var firstSplit = cssImage.split("url(")[1];
			var imagePath = firstSplit.split(")")[0];
			//imgArray[i] = new Image();
			var cleanPath = imagePath.replace(/["']/gi,'');
			imgArray[i] = jQuery("<img>");
			if (i == 0)
			{ imgArray[0].bind("load", imageLoaded); }
			imgArray[i].attr("src", cleanPath);
		}
	},
	
	initRotation: function (){
		var animationCode = function () { poc.homepage.animationAllowed = true; }
		poc.homepage.animationTimeout = setTimeout(animationCode, 500);
		
		poc.homepage.hideOverlay();
		poc.homepage.rotateBool = true;

		// random is set, but we've already set the background, prevent a background switch.
		if (poc.homepage.randomBool == true && poc.homepage.current_background != false)
			{ poc.homepage.nextBg = -1; }

		//  
		if (poc.homepage.current_background === false)
		{
			console.log("curr: "+poc.homepage.current_background);
			if (poc.homepage.randomBool == true && poc.homepage.current_background === false)
			{
				poc.homepage.nextBg = Math.floor(Math.random()*poc.homepage.bgCached.size());
			}
			else
			{ poc.homepage.nextBg = 0; }
			
			poc.homepage.populateButtons();
			
			poc.homepage.nextBackground();
		}
		
	},
	
	nextBackground: function (){
		// id is -1 if we detect (in initRotation) that randomBool is true, and the background has already been set
		if (poc.homepage.animationAllowed == true && id != -1)
		{
			var id = poc.homepage.nextBg;
			
			// grab holdingTime from hidden input in our target div
			var holdTime = Number(poc.homepage.bgCached.eq(id).find(".holdTime").val());
			
			// a zero holdTime indicates infinite hold, trigger stopRotation()
			if (holdTime === 0)
			{ poc.homepage.stopRotation("true"); }
			
			// init actual fade, param true for crossfade
			poc.homepage.fadeBG(id, "true");
			
			// prepare the id of the next image, setTimeout to hold current background image
			if (poc.homepage.randomBool == false)
			{
				var code = function() {
					// have we reached the end of our stack?
					// reset to 0 to restart from first background
					if (id >= poc.homepage.bgCached.size())
					{ poc.homepage.nextBg = 0; }
					
					poc.homepage.nextBackground();		
				}
				poc.homepage.nextTimeout = setTimeout(code, holdTime);
			}
			else
			{
				poc.homepage.animationAllowed = false;
			}
		}
		
		// not allowed to animate, wait and try again (unless prevented by -1 scenario)
		else if (id != -1)
		{
			var code = function () { poc.homepage.nextBackground();  }
			setTimeout(code, 1000);
		}
	},
	
	immediateNext: function (id) {

		clearTimeout(poc.homepage.nextTimeout);
		
		var fgCached = poc.homepage.fgCached;
		var bgCached = poc.homepage.bgCached;
		fgCached.stop();
		bgCached.stop();		
		for (var i=0;i<bgCached.length;i++)
		{
			fgCached.eq(i).fadeOut(0, function () {
				bgCached.eq(i).fadeOut(0, function () {
					if (i == bgCached.length-1)
					{
						poc.homepage.nextBg = id;
						poc.homepage.nextBackground();
						clearTimeout(poc.homepage.nextTimeout);
					}
				});
			});
		}

	},
	
	stopRotation: function (infiniteHold){
		clearTimeout(poc.homepage.animationTimeout);
		poc.homepage.animationAllowed = false;

		
		if (!infiniteHold) { poc.homepage.showOverlay(); }
	},
	
	showOverlay: function () {
		clearTimeout(poc.homepage.overlayTimeout);
		var overlayDiv = jQuery("#overlay");
		if(overlayDiv.size() > 0)
		{
			overlayDiv
				.show()
				.fadeTo(100, 0.9)
				.addClass("visible");
			poc.homepage.fgCached.eq(poc.homepage.current_background).fadeOut('fast');
		}
		// used to layer flash on top so none of the html overlaps it
		jQuery("#main_flash_embed").css({'z-index':3});
		poc.homepage.fgCached.css({'z-index':1});
	},
	
	hideOverlay: function () {
		var code = function () {
			if (poc.homepage.current_background !== false)
			{
				poc.homepage.fgCached.eq(poc.homepage.current_background).fadeIn('fast');
				jQuery("#overlay").animate({'opacity':'0'}, 100, function () {
					jQuery(this).hide().removeClass("visible");
				});
				// used to layer html on top so none of the flash overlaps it
				jQuery("#main_flash_embed").css({'z-index':1});
				poc.homepage.fgCached.css({'z-index':3});
			}
		}
		poc.homepage.overlayTimeout = setTimeout(code, 500);
	},
	
	populateButtons: function () {
		var startingActive = Number(poc.homepage.nextBg);
		var ramTruck = jQuery("#background_controls.dots");
		var chrysler = jQuery("#background_controls.numbered");
		
		// conditional to see if the button container exists in the DOM
		if (chrysler.size() > 0 || ramTruck.size() > 0)
		{
			console.log("conditional met");


			
			for (var i=0;i<poc.homepage.bgCached.length;i++)
			{	
				if(i === startingActive) { var injectedClass = "active"; }
				else { var injectedClass = ""; }
				
				var humanNumber = i+1;		
				var newElement = jQuery("#background_controls")
									.append("<div class='controls "+injectedClass+"'><a href='#' name='&lid=image_scroll&lpos=content'>"+humanNumber+"</a></div>");
			}
			
			// generate the margin-left to center controls
			// 480 is 960/2, subtract the product of the width of the controls (21px margin/padding included) 
			// and the number of controls divided by 2 (we cut 960 in half)	
			var chryslerChildren = chrysler.find("div");
			if(chryslerChildren.length > 0)
			{
				var marginLeft = 480-((chryslerChildren.length*21)/2);
				chrysler.css({'margin-left':marginLeft});
			}
			
			var ramChildren = ramTruck.find("div");
			if(ramChildren.length > 0)
			{
				var marginLeft = 480-((ramChildren.length*15)/2);
				ramTruck.css({'margin-left':marginLeft});				
			}
			
			jQuery("#background_controls div").click(function () {
				jQuery("#background_controls div").removeClass("active");
				jQuery(this).addClass("active");
				poc.homepage.nextBg = jQuery(".controls").index(this);
				poc.homepage.immediateNext(jQuery(".controls").index(this));
				
			});
			
			jQuery("#background_controls div a").click(function (e) { e.preventDefault(); });
			
		}
	},
    
	changeFooter: function (){
		var cachedTarget = jQuery("#footer_disclaimer");
			jQuery("#footer_legal a").toggleClass("active");
			cachedTarget.toggleClass("hidden");
	}
};
jQuery(document).ready(function(){poc.homepage.init()});
} catch(e) { poc.standard_error_handler(e); }

