// Document Load Behaviours
$(document).ready(function()
{
	// Apply PNG Fix
	$("body").supersleight();
	
	// Position Decorations
	positionDecorations();
	
	// Handle Window Resizing
	$(window).resize(function()
	{
		// Position Decorations
		positionDecorations();
	});
});

// Extend Standard Objects
if(String.prototype.toUpperCaseWords == null)
{
	String.prototype.toUpperCaseWords = function()
	{
		return (this + '').replace(/^(.)|\s(.)/g, function ($String_Character)
		{
			return String_Character.toUpperCase();
		});
	}
}
if(Array.prototype.findInArray == null)
{
	Array.prototype.findInArray = function(String_Needle)
	{
		var Array_Indexes = false;
		
		for(Integer_Index = 0; Integer_Index < this.length; Integer_Index++)
		{
			if(typeof(String_Needle) == 'function')
			{
				if(String_Needle.test(this[Integer_Index]))
				{
					if(!Array_Indexes)
					{
						Array_Indexes = [];
					}
					Array_Indexes.push(Integer_Index);
				}
			}
			else
			{
				if(this[Integer_Index] === String_Needle)
				{
					if(!Array_Indexes)
					{
						Array_Indexes = [];
					}
					Array_Indexes.push(Integer_Index);
				}
			}
		}
		return Array_Indexes;
	}
}

// Declare Called Functions
function positionDecorations()
{
	// Determine Book Position
	var Offset_Book = $(".book").offset();
	
	// Plant Pot
	$(".pot").css("left", Math.ceil(Offset_Book.left - 280 - ($(window).width() * 0.04)) + "px");
	
	// Polaroids
	$(".polaroids").css("left", Math.ceil(Offset_Book.left - 250 - ($(window).width() * 0.04)) + "px");
	$(".polaroids").css("top", Math.ceil($(window).height() * 0.4) + "px");
}

function loadPolaroid(String_Element, String_Path, String_Label)
{
//	if(String_Path != $(String_Element + " .photo").attr("src"))
//	{
		// Halt Existing Transition
		$(String_Element + " .photo").last().stop(true, true);
		$(String_Element + " .photo").first().stop(true, true);
		$(String_Element + " .photo").first().unbind('load');
		
		if($(String_Element + " .photo").length > 1)
		{
			$(String_Element + " .photo").last().remove();
		}
		
		// Handle Both Types Of Polaroid
		if(String_Element == '.polaroid')
		{
			// Hide Current Content
			$(String_Element + " .photo").fadeOut("Slow", function()
			{
				// Duplicate Container
				$(String_Element + " .photo").clone().insertAfter(String_Element + ' .background');
				
				// Handle New Content
				$(String_Element + " .photo").first().load(function()
				{
					$(String_Element + " .photo").first().fadeIn("slow", function()
					{
						if($(String_Element + " .photo").length > 1)
						{
							$(String_Element + " .photo").last().remove();
						}
					});
				});
   				
				// Load New Content
				$(String_Element + " .photo").first().attr("src", String_Path);
			});
			
		}
		else
		{
			// Duplicate Container
			$(String_Element + " .photo").clone().prependTo(String_Element);
			
			// Handle New Content
			$(String_Element + " .photo").first().load(function()
			{
				$(String_Element + " .photo").last().fadeOut("slow", function()
				{
					$(this).remove();
				});
			});
			
			// Load New Content
			$(String_Element + " .photo").first().attr("src", String_Path);
			
			// Also Update Polaroid Label
			if(String_Label != $(String_Element + " h2").text())
			{
				// Halt Existing Transition
				$(String_Element + " h2").stop(true, true);
   
				// Hide Current Content
				$(String_Element + " h2").fadeOut("slow", function()
				{
					// Update Label
					$(String_Element + " h2").text(String_Label);
   
					applyCufon(String_Element + " h2");
   
					$(String_Element + " h2").supersleight();
   					
					// Show New Content
					$(String_Element + " h2").fadeIn("slow");
				});
			}
		}
   		

//	}
}

function highlightTab(Element_Tab)
{
	$(".menu li").removeClass('selected');
	$(Element_Tab).addClass('selected');
}

function loadContent(String_Page, String_Query)
{
	$(".content").remove();
	$(".book").append('<div class="content"></div>');
	
	if(String_Query == null)
	{
		String_Query = '';
	}
	
	loadCode($(".content"), 'content/' + String_Page + '.php' + String_Query, function(String_Status)
	{
		if(String_Status == "success")
		{
			pageTracker._trackPageview(String_Page);
			$.get("process-setpage.php", { page: String_Page });
			
			if(typeof(contentLoaded) == 'function')
			{
				contentLoaded();
			}
			
			$(".content").supersleight();
			
			attachTooltips();
		}
		else
		{
			loadContent('home');
		}		
	}, true);
}

function scrollTo(Element_Target)
{	
	if($('html, body').scrollTop() != ($(Element_Target).offset().top - 20))
	{
		var Integer_Distance = $('html, body').scrollTop() - ($(Element_Target).offset().top - 20);

		if(Integer_Distance > 0)
		{
			var Integer_Duration = Integer_Distance * 3;
		}
		else
		{
			var Integer_Duration = 100;
		}
		
		$('html, body').animate({ scrollTop: $(Element_Target).offset().top - 20 }, Integer_Duration, "easeInOutQuad");
	}
}

function setColumns(Element_Container, Integer_Columns, Integer_Spacing, Integer_Indentation)
{
	// Obtain Content
	var Integer_ColumnHeight = parseInt($(Element_Container).height());
	var Integer_ColumnWidth = parseInt(($(Element_Container).width() - Integer_Spacing) / 2);
	var Integer_MarginLeft = parseInt($(Element_Container).css('margin-left').replace('px', ''));
	var Integer_MarginTop = parseInt($(Element_Container).css('margin-top').replace('px', ''));
	var Integer_Column = 0;
	var Element_Parent = $(Element_Container).parent();
	
	// Adjust Container Width (Forcing Correct Element Heights)
	$(Element_Container).width(Integer_ColumnWidth);
	
	// Create Additional Columns
	var Array_ColumnElements = new Array();
	while(Integer_Column < Integer_Columns)
	{
		// Position Column
		Array_ColumnElements[Integer_Column] = $(Element_Container).clone().appendTo($(Element_Parent));
		$(Array_ColumnElements[Integer_Column]).css('margin-left', (Integer_MarginLeft + ((Integer_Spacing + Integer_ColumnWidth) * Integer_Column)) + 'px');
		$(Array_ColumnElements[Integer_Column]).html('');
		$(Array_ColumnElements[Integer_Column]).width(Integer_ColumnWidth);
		
		// Apply Indentation On Following Columns
		if(Integer_Column > 0)
		{
			if(Integer_Indentation == 'auto')
			{
				Integer_Indentation = $(Element_Parent).find("h1:first, h2:first").outerHeight(true);
			}
			
			$(Array_ColumnElements[Integer_Column]).css('margin-top', (Integer_MarginTop + Integer_Indentation) + 'px');
			$(Array_ColumnElements[Integer_Column]).height(Integer_ColumnHeight - Integer_Indentation);
		}

		Integer_Column ++;
	}

	// Assign Content To Columns
	var Integer_Column = 0;
	
	// Strip CMS Rubbish
	var String_HTML = $(Element_Container).html();
	
	String_HTML = String_HTML.replace('<P>&nbsp;</P>', '');
	String_HTML = String_HTML.replace('<P>&nbsp;</P>', '');
	String_HTML = String_HTML.replace('<p>&nbsp;</p>', '');
	String_HTML = String_HTML.replace('<p>&nbsp;</p>', '');
	String_HTML = String_HTML.replace('<p> </p>', '');
	String_HTML = String_HTML.replace('<p> </p>', '');
	String_HTML = String_HTML.replace('<p></p>', '');
	String_HTML = String_HTML.replace('<p></p>', '');
	String_HTML = String_HTML.replace('<hr />', '<SPLIT>');
	String_HTML = String_HTML.replace('<hr/>', '<SPLIT>');
	String_HTML = String_HTML.replace('<hr>', '<SPLIT>');
	String_HTML = String_HTML.replace('<HR>', '<SPLIT>');
	
	// Look For HR Splitter
	var Array_Content = String_HTML.split('<SPLIT>');

	for( var Integer_Content = 0, Integer_Blocks = Array_Content.length; Integer_Content < Integer_Blocks; ++Integer_Content )
	{
		$(Array_ColumnElements[Integer_Column]).append(Array_Content[Integer_Content]);
		
		Integer_Column ++;
	}
	
	// Destroy Original Container Element
	$(Element_Container).remove();
}

function loadCode(Element_Container, String_Source, Function_Loaded, Boolean_Clear)
{
	// Store Existing Code (Where Specified)
	var String_Code = '';
	if(!Boolean_Clear)
	{
		var String_Code = $(Element_Container).empty();
	}
	
	// Load Content
	$(Element_Container).load(String_Source, function(String_Response, String_Status)
	{
		// Prepend Existing Code
		$(Element_Container).prepend(String_Code);

		// Execute Callback Function
		if(typeof(Function_Loaded) == 'function')
		{
			Function_Loaded(String_Status);
		}
	});
}

function attachTooltips()
{
	// Disable Tooltips For Now
	$("*[title!='']").attr('title', '');

	// Locate Title Attributes
	/*
	$("*[title!='']").each(function(Count)
	{
		// Determine Text
		var String_Text = $(this).attr('title');
		var Integer_Start = String_Text.indexOf('[') + 1;
		var Integer_End = String_Text.indexOf(']', Integer_Start);

		String_Title = String_Text.substring(Integer_Start, Integer_End);
		String_Text = String_Text.substring(Integer_End + 1);
		
		// Apply Behaviours
		$(document).unbind('mousemove');
		$(this).unbind('mouseover');
		$(this).unbind('mouseout');
		$(this).mouseover(function()
		{
			// Destroy Existing Tooltip
			$(".tooltip").remove();
			
			// Remove Title (Stop Browser Tooltip)
			$(this).attr('title', '');
			
			$(this).addClass('tooltipped');
			
			// Create Tooltip Element
			$("body").append('<div class="tooltip"><img class="left" src="images/cap-tooltip-left.png" alt="" /><img class="right" src="images/cap-tooltip-right.png" alt="" /><div class="content"><h1>' + String_Title + '</h1><p>' + String_Text + '</p></div></div>');
			
			// Restrict Width
			if($(".tooltip").width() > 300)
			{
				$(".tooltip p").text($(".tooltip p").text().substr(0, 40) + '...');
				$(".tooltip p").text($(".tooltip p").text().replace(' ...', '...'));
			}
			else
			{
				$(".tooltip").width(320)
			}
			
			// Replace Fonts
			applyCufon(".tooltip h1");
			applyCufon(".tooltip p");
			
			$(".tooltip").supersleight();
			
			// Position Tooltip
//			var Offset_Element = $(this).offset();
//			var Integer_XPosition = Offset_Element.left + ($(this).width() / 2);
//			var Integer_YPosition = Offset_Element.top + ($(this).height() / 2);
//			alert($(this).width() + ' ' + $(this).height() + ' ' + Offset_Element.left + ' ' + Offset_Element.top + ' ' + Integer_XPosition + ' ' + Integer_YPosition);
//			$(".tooltip").css({'top': Integer_YPosition, 'left': Integer_XPosition});
			
			
			$(document).unbind('mousemove');
			$(document).mousemove(function(Mouse)
			{
				$(".tooltip").css({'top': Mouse.pageY + 3, 'left': Mouse.pageX + 10});
				
				var Offset_Element = $(".tooltipped").offset();

				Integer_YExtent = parseInt(Offset_Element.top) + parseInt($(".tooltipped").height());
				Integer_XExtent = parseInt(Offset_Element.left) + parseInt($(".tooltipped").width());
				
				if((Mouse.pageY < Offset_Element.top) || (Mouse.pageY > Integer_YExtent) || (Mouse.pageX < Offset_Element.left) || (Mouse.pageX > Integer_XExtent))
				{
					$(".tooltipped").mouseout();
				}
			});

		}).mouseout(function(e)
		{

			var x = e.pageX - this.offsetLeft;
			var y = e.pageY - this.offsetTop;

			if((x < $(this).width()) && (x > 0))
			{
				if((y < $(this).height()) && (y > 0))
				{
					return false;
				}
			}

			// Remove Movement Adjustment
			$(document).unbind('mousemove');
		
			// Restore Title
			$(this).attr('title', String_Text);
			
			$(this).removeClass('tooltipped');
			
			// Destroy Tooltip
			$(".tooltip").remove();
		});

	});
	*/
}

function loadOverlay(String_Page, String_Query)
{
	if($(".overlay").length < 1)
	{
		$(".page").before('<div class="overlay"></div>');
	}

	if($(".pop").length < 1)
	{
		$(".page").before('<div class="pop"></div>');
	}
		
	loadCode($(".pop"), 'content/' + String_Page + '.php' + String_Query, function(String_Status)
	{
		if(String_Status == "success")
		{
			$(".overlay").fadeTo(1000, 0.75);
			$(".pop").fadeIn(1000, function()
			{

			});
			
			if(typeof(contentLoaded) == 'function')
			{
				contentLoaded();
			}
		}
		else
		{
			hideOverlay();
		}		
	}, true);
}

function hideOverlay()
{
	if($(".overlay").length > 0)
	{
		$(".overlay").fadeOut(500, function()
		{
			$(".overlay").remove();
		});
	}

	if($(".pop").length > 0)
	{
		$(".pop").fadeOut(500, function()
		{
			$(".pop").remove();	
		});
	}
}





// Cookie Functions
function setCookie(String_Cookie,String_Value,Integer_Days)
{
var Date_Expiry=new Date();
Date_Expiry.setDate(Date_Expiry.getDate()+Integer_Days);
document.cookie=String_Cookie+ "=" +escape(String_Value)+
((Integer_Days==null) ? "" : ";expires="+Date_Expiry.toUTCString());
}

function getCookie(String_Cookie)
{
if (document.cookie.length>0)
{
Integer_Start=document.cookie.indexOf(String_Cookie + "=");
if (Integer_Start!=-1)
{
Integer_Start=Integer_Start + String_Cookie.length+1;
Integer_End=document.cookie.indexOf(";",Integer_Start);
if (Integer_End==-1) Integer_End=document.cookie.length;
return unescape(document.cookie.substring(Integer_Start,Integer_End));
}
}
return "";
}
