var selectedContent = -1;
var baseURL = "http://www.culturesalive.com.au/";
var bennyMoveSpeed = 400;
var bennyCameraSpeed = 450;
var terminatePepsinBubbles = false;
var contentPages = new Array('roomyoghurt','hotyoghurt','buttermilk','gingerbeer','kefirgrains','kombucha','vinegar','sourdough');
var scrollToViewPosition = 0;
var scrollOffset = 40;
var stomach_offset = 0;
var screenLinkHouser = 0;
var downloadSeperator = 0;
var downloadContent = 0;
var downloadContent2 = 0;
var top = 0;
var logoBenny = 0;
var stomach = 0;
var floodLight = 0;
var htmlBody = 0;
var screenViewer = 0;

var downloadPages = new Array
(
	'files/Mesophilic Yoghurts Info Sheet.pdf',
	'hotyoghurt',
	'files/Cultured Buttermilk Info Sheet.pdf',
	'gingerbeer',
	'files/Water Kefir Info Sheet.pdf',
	'files/Kombucha Info Sheet.pdf',
	'vinegar',
	'files/Sourdough Starter Info Sheet.pdf'
);

var originalBubblePosition = new Array
(
	{ left: -10, top: 10 }, // room yoghurt
	{ left: 250, top: 10 }, // hot yoghurt
	{ left: 160, top: 120 }, // buttermilk
	{ left: -160, top: 120 }, // gingerbeer
	{ left: 60, top: -120 }, // kefirgrains
	{ left: -60, top: -120 }, // kombucha
	{ left: 80, top: 30 }, // vinegar
	{ left: -80, top: 30 } // sourdough
);

var wayPoints = new Array
(
	{ left: 53, top: 0 },
	{ left: 54, top: 63 },
	{ left: 55, top: 127 },
	{ left: 57, top: 194 },
	{ left: 57, top: 270 },
	{ left: 54, top: 282 },
	{ left: 50, top: 311 },
	{ left: 44, top: 310 },
	{ left: 38, top: 306 },
	{ left: 34, top: 339 },
	{ left: 34, top: 420 },
	{ left: 36, top: 471 },
	{ left: 43, top: 461 },
	{ left: 49, top: 468 },
	{ left: 51, top: 549 },
	{ left: 50, top: 661 },
	{ left: 47, top: 701 },
	{ left: 41, top: 715 }
);

function constructMenu()
{
	var opts =
	{ 
		align: 'middle'
		, size: 70
		, labels: 'bc'
		, distance: 55
		, fadeIn: 400
	};
	$('#navBar').jqDock(opts);
}

$("div.bubble > a > img").bind({
	mouseenter:	function() {
		//$(this).removeClass('bubble');
		$(this).animate({ width:"+=10px", height:"+=10px", left:"-=5px", top:"-=5px" }, 100);
		//$(this).stop();
	},
	mouseleave: function() {
		$(this).animate({ width:"-=10px", height:"-=10px", left:"+=5px", top:"+=5px" }, 100);//, function() {
			//$(this).addClass('bubble');
		//});
	}
});

function randomValue(minVal,maxVal)
{  
	var randVal = minVal + ( Math.random() * ( maxVal - minVal ));  
	return randVal.toFixed();
}


//////////////////////////////////////////////
//            Pepsin Bubble Maker           //
//////////////////////////////////////////////

function startPepsinBubbles()
{
	stomach_offset = $(stomach).offset();
	
    $('img.pepsinBubble', $("#top")).each(
        function () 
		{
			if (!terminatePepsinBubbles) pop(this); 
        }
    );	
}

function pop(currentA) 
{
	var newspeed = randomValue(35, 45);
	newspeed = newspeed * 10;
	var zIndex = randomValue(01, 99);
	zIndex = "89" + zIndex

	$(currentA).attr('width', '9px').attr('height', '9px')
	.css(
	{    
		'z-index': zIndex,
		'top': randomValue((stomach_offset.top + stomach.height()) - 40,(stomach_offset.top + stomach.height()) - 112) + "px",
		'left': randomValue(stomach_offset.left + 165, (stomach_offset.left + stomach.width()) - 145) + "px",
		'width': "9px",
		'height': "9px",
		opacity: 0
	});
	if(navigator.userAgent.search(/msie/i)!= -1) { 
		currentA.style.removeAttribute('filter');
	}
	offset = $(currentA).offset();
	$(currentA).animate(
		{ 
			top: (offset.top - (randomValue(50, 150))) + "px",
			opacity: 1,
			width: "20px", 
			height: "20px"
		}, newspeed, 'linear')
		.fadeTo(100, 0, function(){
				if (!terminatePepsinBubbles) pop(this); 
			});
}


//////////////////////////////////////////////
//              Bounce Bubbles              //
//////////////////////////////////////////////

function startBubbles(){
    // Bouncer animation (by Leo Xavier)
    // BASE SPEED OF BOUNCING. WILL ADD RAINDOM 0-100 TO UNSYNC BOUNCING
    var bouncespeed = 450;
    
    // SELECT ALL A'S EXCEPT... RESET BG-POSITION TO AVOID INITIAL POSITION BUG AND CALL BOUNCER
    $('div.bubble', $('#content')).each(
        function () 
		{
			var bubblePos = GetBubbleRow(this);
            $(this).css({ top: bubblePos.top + "px", left: bubblePos.left + "px" });
            bounce(this);
        }
    );
    
    // ACTUAL BOUNCER. CALLBACK OF ANIMATION IS THE BOUNCER ITSELF, TO LOOP ALL NIGHT LONG
    function bounce(currentA) {
        newx = Math.floor(10*Math.random());
        newy = Math.floor(3*Math.random());
		var bubblePos = GetBubbleRow(currentA);
        newspeed = bouncespeed + Math.floor(10*Math.random());
        $(currentA).animate({ left: (bubblePos.left + newx) + "px", top: (bubblePos.top + newy) + "px" }, newspeed, 'linear', function() { 
			bounce(this); 
		});
    }
}

/////////////////////////////////////////////
//     Bubble position Helper Function
/////////////////////////////////////////////

function GetBubbleRow(object)
{
	var objReturn = { left: 0, top: 0 };
	switch (object.id)
	{
		case "infoRoomYoghurt":
		{
			objReturn = originalBubblePosition[0];
			break;
		}
		case "infoHotYoghurt":
		{
			objReturn = originalBubblePosition[1];
			break;
		}
		case "infoButtermilk":
		{
			objReturn = originalBubblePosition[2];
			break;
		}
		case "infoGingerBeer":
		{
			objReturn = originalBubblePosition[3];
			break;
		}
		case "infoKefirGrains":
		{
			objReturn = originalBubblePosition[4];
			break;
		}
		case "infoKombucha":
		{
			objReturn = originalBubblePosition[5];
			break;
		}
		case "infoMotherOfVinegar":
		{
			objReturn = originalBubblePosition[6];
			break;
		}
		case "infoSourdoughStarter":
		{
			objReturn = originalBubblePosition[7];
			break;
		}
	}
	return objReturn;
}

//////////////////////////////////////////////
//              Start Animation             //
//////////////////////////////////////////////

$(document).ready( function(){
	// Animate Benny! Go benny Go GO!
	top = $("#top");
	logoBenny = $("#logoBenny", $("#top"));
	stomach = $("#backDrop", $("#top"));
	floodLight = $("#floodLight", $("#top"));
	htmlBody =  $('html, body');
	screenViewer = $("#screen", $("#top"));
	screenLinkHouser = $("#screenLinkHouser", $("#screen"));
	downloadSeperator = $("#downloadSeperator", $("#screenLinkHouser"));
	downloadContent = $("#downloadContent", $("#screenLinkHouser"));
	downloadContent2 = $("#downloadContent2", $("#screenLinkHouser"));
	
	$(downloadSeperator).hide();
	$(downloadContent2).hide();
	
	$(floodLight).show();
	var options = {};
	resetView();
	
	$(logoBenny).show('bounce', options, 500,
		function() 
		{
			// $("#content").fadeTo('fast', 0.01, function() 
			// {
				// $("#contentBottom").fadeTo('fast', 0.01);
			// });
			if(navigator.userAgent.search(/msie/i)!= -1) { 
				this.style.removeAttribute('filter');
				try {
					document.execCommand("BackgroundImageCache",false,true);
				} catch(e) {
					// just in case this fails .. ?
				}

			}  
			
			window.setTimeout('dropBenny()', 50);
			//setTimeout('scrollToView()', 700);
		}
	);
});

function resetView()
{
	$(htmlBody).scrollTop(0);
}

//////////////////////////////////////////////
//              dropBenny function          //
//////////////////////////////////////////////
function dropBenny()
{
	var windowHeight = $(window).height();
	var windowWidth = $(window).width();
	var floodLeft = 0;
	var floodTop = 0;
	
	var floodHeight = $(floodLight).height();
	var floodWidth = $(floodLight).width();
	var bennyHeight = $(logoBenny).height();
	var bennyWidth = $(logoBenny).width();
	
	startPepsinBubbles();
	
	$.each(wayPoints, function(index, value)
	{
		var bennyTop = this.top;
		var scrollTo = ((bennyTop) - ((windowHeight / 2) - (bennyHeight / 2))).toFixed();
		if (scrollTo < 0) scrollTo = 0;
		
		if (index == (wayPoints.length-1))
		{
			$(logoBenny).animate( { top: this.top + "px", left: this.left + "%" }, bennyMoveSpeed, 'linear', function()
			{
				scrollTo = (parseInt(scrollTo) + parseInt(scrollOffset));
				$(htmlBody).animate({ scrollTop: scrollTo + 'px' }, bennyCameraSpeed, 'easeInOutSine', function()
				{
					terminatePepsinBubbles = true;
					$(stomach).fadeTo(400, 0.25).fadeTo(300, 1).fadeTo(200, 0.15).fadeTo(150, 0.8).fadeTo(100, 0, function()
					{
						$(top).find("div.pepsinBubble").css("visibility","hidden");
						$(stomach).css("visibility", "hidden");
						scrollToViewPosition = scrollTo;
						showContents();
					});
				});
			});
		}
		else
		{
			var leftPos = ((this.left/100) * windowWidth).toFixed();
			floodLeft = (htmlBody.scrollLeft() - ((floodWidth / 2) - (parseInt(leftPos) + (bennyWidth / 2))));
			floodTop = (htmlBody.scrollTop() - ((floodHeight / 2) - (this.top + (bennyHeight / 2))));
			
			$(floodLight).animate( { top: floodTop + "px", left: floodLeft + "px" }, bennyCameraSpeed, 'linear');
			$(logoBenny).animate( { top: this.top + "px", left: this.left + "%" }, bennyMoveSpeed, 'linear', function()
			{
				$(htmlBody).animate({ scrollTop: scrollTo + 'px' }, bennyCameraSpeed, 'easeInOutSine');
			});
		}
		
	});
}

//////////////////////////////////////////////
//            Show Contents                 //
//////////////////////////////////////////////
function showContents()
{
	$(floodLight).css( "visibility", "hidden");
	
	$("#logoContainer", $("#contentBottom")).fadeIn( 1200, function (){
		$("div.bubble", $("#content")).fadeIn( 800, function (){ 
			startBubbles();
			constructMenu();
			setupFrames();
			$("#navBar").fadeIn( 1500, function() {
				$("#floater").fadeTo(1000, 0.3);
				$("#floater").hover(function(){$(this).fadeTo(50, 1.0);},function(){$(this).fadeTo(200, 0.3);});
			});
		});
	});
}

//////////////////////////////////////////////
//            Scroll to View                //
//////////////////////////////////////////////

function scrollToView()
{
	// Scroll to view
	$(htmlBody).animate({ scrollTop: scrollToViewPosition + 'px' }, 800, 'easeInOutQuint', function() {
		showContents();
	});
}

function scrollToViewWithSpeed(speed)
{
	// Scroll to view
	$(htmlBody).animate({ scrollTop: scrollToViewPosition + 'px' }, speed, 'easeInOutQuint');
}

//////////////////////////////////////////////
//              Screen Text                 //
//////////////////////////////////////////////

function screenText(index)
{
	$(".screenHouserInfoBox:eq(" + index + ")", $("#screenHouser")).show();
	if (index == 4) // if kefir
	{
		$(downloadSeperator).show();
		$(downloadContent2).show();
		$(downloadContent).text('Water Kefir Info Sheet');
		$(downloadContent2).text('Milk Kefir Info Sheet');
	}
	else
	{
		$(downloadSeperator).hide();
		$(downloadContent2).hide();
		$(downloadContent).text('Download Info Sheet');
		$(downloadContent2).text('Download Info Sheet 2');
	}
	
	$(htmlBody).animate({ scrollTop: '0px' }, 1500, 'easeInQuint', function(){
		$(screenViewer).fadeIn(600);
	});
}

//////////////////////////////////////////////
//              Show Content                //
//////////////////////////////////////////////

function showContent(object, content)
{
	var index = -1;
	for ( var i = 0; i < contentPages.length; i++ )
	{
		if (contentPages[i] == content)
		{
			index = i;
			break;
		}
	}
	if (index >= 0)
	{
		// fade out text
		selectedContent = index;
		screenText(index);
	}
}

//////////////////////////////////////////////
//              Download Files              //
//////////////////////////////////////////////

function downloadContent()
{
	var url = baseURL + escape(downloadPages[selectedContent]);
	window.open(url,'_blank','location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes')
}

//////////////////////////////////////////////
//              Hide Contents               //
//////////////////////////////////////////////

function hideContent()
{
	$("div.screenHouserInfoBox:eq(" + selectedContent + ")", $("#screenHouser")).hide();
	selectedContent = -1;
	$(screenViewer).fadeOut('fast');
	
	scrollToViewWithSpeed(500);
}


//////////////////////////////////////////////
//              doAction Handler            //
//////////////////////////////////////////////
function setupFrames()
{
	// 1 = clinic, 2 = contact, 3 = _blank, 4 = raw milk, 5 = recipes

	$("#clinicForm").fancybox({
		'width'				: 615,
		'height'			: 515,
		'autoScale'			: false,
		'transitionIn'		: 'fade',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});

	$("#contactPage").fancybox({
		'width'				: 615,
		'height'			: 515,
		'autoScale'			: false,
		'transitionIn'		: 'fade',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});

	$("#rawMilk").fancybox({
		'width'				: '75%',
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'fade',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});

	$("#recipeCollection").fancybox({
		'width'				: 615,
		'height'			: 515,
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'fade',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});
	
	$("#infoPage").fancybox({
		'width'				: 615,
		'height'			: 515,
		'height'			: '75%',
		'autoScale'			: false,
		'transitionIn'		: 'fade',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});
	

}

window.onerror = function(message, url, line)
{
	err='';
	for (var i = 0; i < message.length; i++) 
	{ 
		if (message.charAt(i)!="'") 
		{ 
			err=err+message.charAt(i); 
		} 
	} 
}




