// Toureen Scripts

var pageWidth = 980;
var navWidth = 980;
var nodeWidth;
var numPages;
var animSpeed = 500;
var animTransition = "easeOutExpo";
var containerMarginTop = 0;
var servicesMarginStart = 774;
var servicesAnimSpeed = 500;
var servicesAnimTransition = "easeOutExpo";
var servicesFirst = true;
var nextNum = 0;
var firstPage = null;
var xmlInitComplete = false;
var linkInitComplete = false;
var sectionName;
var isBelowIE8 = false;
var isBelowIE9 = false;
var currentPageNum = 0;
var commercialGallery = null;

var xmlPath = "storage/xml/pages.xml";
var pathPrefix = "http://www.toureenmangan.co.uk/p/page.htm?cpi_id=";
//var pathPrefix = "page.htm?cpi_id=";
var itemXML;
var verboseTitleArray;
var totalPages = 0;

var isContactPage = false;


var init = function(newID)
{
	isBelowIE8 = checkBelowIE8();
	isBelowIE9 = checkBelowIE9();
	
	
	if(newID == "news")
	{
		initScreenCenter();
		
		//$('.navTrack').width(980);
		
		$.ajax({
			type: "GET",
			url: encodeURI(xmlPath),
			dataType: "xml",
			success: function(xml) {
				$(xml).find('xml').each(function(){
					
					var i = 0;
					
					$(this).find('newsItem').each(function(){
						
						var title = $(this).attr("title");
						var thumb = $(this).attr("thumbnail");
						var excerpt = $(this).attr("excerpt");
						var content = $(this).attr("content");
						
						var newsEntry = $('<div class="newsItem"><img src="'+thumb+'" width="137" height="101" /><H2>'+title+'</H2><P>'+excerpt+'</P></div>').appendTo('.scrollWrapper');
						
						newsEntry.click( function() {
							showNewsItem(title, content);
						});
						
					});
					
						
					var newHeight = $(".scrollWrapper").height();	
				
					$(".scrollWrapper").jScrollPane({height:newHeight, dragMaxHeight: 92, dragMinHeight: 92, scrollbarWidth: 23, scrollbarMargin: 40, animateTo: true, showArrows: false });
						
				});
			}
		});
		

	}
	else
	{
		if(newID == "contact")
		{
			isContactPage = true;
		}
	
		deepLinkInit();
		
		
		initScreenCenter();
		
		sectionName = newID.charAt(0).toUpperCase() + newID.slice(1);
		
		$.ajax({
			type: "GET",
			url: encodeURI(xmlPath),
			dataType: "xml",
			success: function(xml) {
				$(xml).find('xml').each(function(){
						
					var found = false;
					$(this).find('section').each(function(){
														  
					
						if(!found)
						{
								
							var sectionID = $(this).attr("id");
							
							if(sectionID == newID)
							{
								found = true;
								itemXML = $(this);
							}
						}
							
					});
						
					if(found)
					{
						initPage();
					}
					else
					{
						alert("ID '" + newID + "' could not be found in the xml.");
					}
						
				});
			}
		});
	}
	
}

var initScreenCenter = function()
{
	updateContainerMargin();
	//window.onresize = updateContainerMargin();
}

var deepLinkInit = function()
{
	$.address.crawlable(true)
	$.address.strict(false);
	
	$.address.init(function(event) {
		//console.log('init: "' + event.value + '"');
		deepLinkEvent(event, true);
	}).change(function(event) {
		//console.log('internalChange: "' + event.value + '"');
		deepLinkEvent(event, false);
	}).externalChange(function(event) {
		//console.log('externalChange: "' + event.value + '"');
		deepLinkEvent(event, false);
	});
	
}

var deepLinkEvent = function(E, external) {
	//console.log('deepLinkEvent fired');
	if(!xmlInitComplete)
	{
		firstPage = E.value;
		//console.log('firstPage set to: ' + E.value );
		linkInitComplete = true;
		//console.log('linkInitComplete = true');
	}
	else
	{
		//console.log('xmlInitComplete true, firing handleLink with value: ' + E.value );
		handleLink(E.value, external);
	}
}

var handleLink = function(linkValue, external) {
	if(linkValue == "/" ||linkValue == "#" || linkValue == "" || linkValue == "/home")
	{
		scrollToPage(0, external);
		
		if(verboseTitleArray[pageNum] != "")
		{
			$.address.title(verboseTitleArray[0] + ' | Toureen Mangan');
		}
		else
		{
			$.address.title(sectionName + ' | Toureen Mangan');
		}
	}
	else
	{
		//var pageTitle = linkValue.split("/");
		//pageTitle = pageTitle[pageTitle.length-1];
		var pageTitle = linkValue;
		
		var i = 0;
		var pageNum = 0;
		
		var found = false;
		
		itemXML.find('page').each(function(){
										   
			if(!found)
			{
				var newTitle = $(this).attr("pageTitle");
				
				newTitle.replace(" ", "_");
				newTitle = newTitle.toLowerCase();
				
				
				if(newTitle == pageTitle)
				{
					found = true;
					pageNum = i;
				}
			}
			
			i++;
			
		});
		
		if(verboseTitleArray[pageNum] != "")
		{
			$.address.title(verboseTitleArray[pageNum] + ' | Toureen Mangan');
		}
		else
		{
			var withCap = pageTitle.charAt(0).toUpperCase() + pageTitle.slice(1);
			
			if(sectionName != withCap)
			{
				$.address.title(withCap + ' | Toureen Mangan');
			}
			else
			{
				$.address.title(sectionName + ' | Toureen Mangan');
			}
			
		}
		
		scrollToPage(pageNum, external);
	}
}


var initPage = function()
{
	
	totalPages = itemXML.find('page').length;
	
	$('.mover').width(pageWidth * totalPages);
	
	nodeWidth = navWidth / totalPages;
	
	$('.navTrack').width(nodeWidth / 2);
	
	verboseTitleArray = new Array();
	
	var i = 0;
	
	itemXML.find('page').each(function(){
									   
		var pageTitle = $(this).attr("pageTitle");
		var verboseTitle = $(this).attr("verboseTitle");
		if(verboseTitle == null)
		{
			verboseTitle = "";
		}
		
		verboseTitleArray.push(verboseTitle);
		
		var navHoverImagePath = "style/images/nav_node_hover.png";
		
		if(isBelowIE8)
		{
			//navHoverImagePath = "style/images/nav_node_hover_ie.gif";
		}
		
		var navHTML = '<div class="navNode" id="navNode' + i + '" onclick="getPage(\'' + pageTitle + '\')"><div class="navCircle"><img src="'+navHoverImagePath+'" class="on" width="41" height="41" /></div><h4>' + pageTitle + '</h4></div>';
		
		$('.navNodeWrapper').append(navHTML);
		
		if(isBelowIE8 == false)
		{
			$('.mover').append('<div class="loadingWrapper"><div class="tempPageWrapper" style="opacity: 0;" id="newPageWrapper' + i + '"></div></div>');
		}
		else
		{
			$('.mover').append('<div class="loadingWrapper"><div class="tempPageWrapper" id="newPageWrapper' + i + '"></div></div>');
		}
		
		$('#newPageWrapper' + i).load(pathPrefix + $(this).attr("pageID") + ' .pageWrapper', function() {
			//columnLoaded();
			
			//alert(this);
			
			
			if(isBelowIE8)
			{
				$(this).css('display', 'block');
			}
			
			var newHeight = $(".scrollWrapper", this).height();	
		
			$(".scrollWrapper", this).jScrollPane({height:newHeight, dragMaxHeight: 92, dragMinHeight: 92, scrollbarWidth: 23, scrollbarMargin: 40, animateTo: true, showArrows: false });
			

			var pageWrapper = $(".pageWrapper", this);
			
			//pageWrapper.css('opacity', 0);
			
			
			var pageNum = $(this).attr('id');
			pageNum = pageNum.split("newPageWrapper")
			pageNum = pageNum[pageNum.length-1];
			//alert(pageNum);
			
			//Setup services buttons			
			$('.tabButton a.caseStudies').click( function() {
				sidewaysMoverSlideTo(this, 1);
			});			
			$('.tabButton a.services').click( function() {
				sidewaysMoverSlideTo(this, 2);
			});
			
			/*
				$('.wideButton a.back').click( function() {
					resetSidewaysMover(this);
				});
			*/
			
			//$('.caseStudyButton', this).mouseover(function(){fadeInPopupButton(this);})
			
			if($('.sendBtn', this).length > 0)
			{
				setupForm();
			}

			
			pageWrapper.attr('id', "page" + pageNum);
			
			$(this).stop().animate(
					{opacity: 1},
					300,
					function() {
						var pageWrapper = $(".pageWrapper", this);
						pageWrapper.unwrap();
						pageWrapper.unwrap();
						if(isBelowIE8)
						{
							if(pageNum != currentPageNum)
							{
								pageWrapper.css('display', 'none');
							}
							
							$('.sidewaysMoverItem', pageWrapper).hide();
							$('.sidewaysMoverItem#item1', pageWrapper).show();
						}

					});
			
			//pageWrapper.unwrap();
			//pageWrapper.unwrap();
			
		});

		i++;		
	});
	
	$('.navNode').each(function()
	{
		$(this).width(nodeWidth);
	});
	
	xmlInitComplete = true;
	//console.log('xmlInitComplete = true');
	
	if(xmlInitComplete)
	{
		//console.log('xmlInitComplete is true, firing handleLink with "firstPage" which equals: ' + firstPage);
		handleLink(firstPage, true);
	}

}

var getPage = function(pageName)
{
	pageName.replace(" ", "_");
	pageName = pageName.toLowerCase();
	
	$.address.value(pageName);
}

function getInternetExplorerVersion() {
	var rv = -1;
	if (navigator.appName == 'Microsoft Internet Explorer') {
		var ua = navigator.userAgent;
		var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
			rv = parseFloat(RegExp.$1);
	}
	return rv;
}

function checkBelowIE8() {
	var ver = getInternetExplorerVersion();
	if (ver > -1) {
		if (ver >= 8.0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	else
	{
		return false;
	}
}

function checkBelowIE9() {
	var ver = getInternetExplorerVersion();
	if (ver > -1) {
		if (ver >= 9.0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	else
	{
		return false;
	}
}

var scrollToPage = function(num, instant)
{
	currentPageNum = num;
	var newSpeed = animSpeed;
	
	if(instant == true)
	{
		newSpeed = 0;
	}
	
	if(isBelowIE8 == false)
	{
		$("div.mover").stop().animate(
						{marginLeft: -(pageWidth * num)},
						{duration: newSpeed,
						easing: animTransition});
	}
	else
	{
		var i;		
		for(i = 0; i < totalPages; i++)
		{
			if(i != num)
			{
				$('#page' + i).css("display","none");
				$('#newPageWrapper' + i).css("display","none");
			}
			else
			{
				$('#page' + i).css("display","block");
				$('#newPageWrapper' + i).css("display","block");
				
				//var newHeight = $('#page' + i + " .scrollWrapper").height();
				//$('#page' + i + " .scrollWrapper").jScrollPane({height:newHeight, dragMaxHeight: 92, dragMinHeight: 92, scrollbarWidth: 23, scrollbarMargin: 40, animateTo: true, showArrows: false });
			}
		}
	}


	$(".navTrack").stop().animate(
					{width: (nodeWidth / 2) + (nodeWidth * num)},
					{duration: newSpeed,
					easing: animTransition});
	
	var i = 0;
	
	$('.navNode').removeClass('active');
	
			
	$('.navNode').each(function()
	{
		if(i != num)
		{
			if(isBelowIE9)
			{
				$('img.on', this).css('display', 'none');
			}
			else
			{
				$('img.on', this).stop().animate(
								{"opacity": "0"},
								{duration: newSpeed,
								easing: "swing"});
			}
			
			
			//$('h4', this).stop().animate(
			//				{"opacity": "1"},
			//				{duration: newSpeed,
			//				easing: "swing"});
		}
		else
		{
			if(isBelowIE9)
			{
				$('img.on', this).css('display', 'block');
			}
			else
			{
				$('img.on', this).stop().delay(animSpeed * 0.5).animate(
							{"opacity": "1"},
							{duration: newSpeed,
							easing: "swing"});
			}
			
			$(this).addClass('active');
			
			//$('h4', this).stop().animate(
			//				{"opacity": "0"},
			//				{duration: newSpeed,
			//				easing: "swing"});
		}
		i++;
	});
	
}

var showServiceInfo = function(num)
{
	nextNum = num;
	
	servicesBGGallery.getImage(num+1);
	servicesBGGallery.pauseGallery();
	
	//updateLists();
	
	if(servicesFirst)
	{
		
		$("div.servicesWrapper").stop().animate(
						{marginLeft: servicesMarginStart - 92},
						{duration: servicesAnimSpeed,
						easing: servicesAnimTransition});
		showHideServices();
	}
	else
	{
		$("div.servicesWrapper").stop().animate(
						{marginLeft: servicesMarginStart},
						{duration: servicesAnimSpeed,
						easing: servicesAnimTransition})
						.animate(
						{marginLeft: servicesMarginStart - 92},
						{duration: servicesAnimSpeed,
						easing: servicesAnimTransition});
		
		var timer = setTimeout(showHideServices, 500);
	}
	
	$('.textPanel.services.main').stop().animate(
						{width: 33},
						{duration: servicesAnimSpeed,
						easing: servicesAnimTransition});
	
	$('.servicesBackArrow').stop().animate(
						{marginLeft: 0},
						{duration: servicesAnimSpeed,
						easing: servicesAnimTransition});
	
	
	servicesFirst = false;
}

var closeServices = function()
{
	$("div.servicesWrapper").stop().animate(
						{marginLeft: servicesMarginStart},
						{duration: servicesAnimSpeed,
						easing: servicesAnimTransition});
	
	$('.textPanel.services.main').stop().animate(
						{width: 196},
						{duration: servicesAnimSpeed,
						easing: servicesAnimTransition});
	
	$('.servicesBackArrow').stop().animate(
						{marginLeft: -33},
						{duration: servicesAnimSpeed,
						easing: servicesAnimTransition});
	
	//servicesBGGallery.resumeGallery();
	servicesBGGallery.getImage(0);
	
	//$('.textPanel.services ul li').removeClass('active');
	
	servicesFirst = true;
}

var showHideServices = function()
{
	
	var i = 0;
	$('.textPanel.services.moreInfo').each(function()
	{
		if(i != nextNum)
		{
			$(this).hide();
		}
		else
		{
			$(this).show();
		}
		
		i++;
	});
}

var updateLists = function()
{
	var i = 0;
	$('.textPanel.services ul li').each(function()
	{
		if(i != nextNum)
		{
			$(this).removeClass('active');
		}
		else
		{
			$(this).addClass('active');
		}
		
		i++;
	});

}

var updateContainerMargin = function(noAuto)
{
	var windowHeight = $(window).height();
	var contentHeight = 660;
	
	containerMarginTop = (windowHeight - contentHeight) / 2;
	if(containerMarginTop < 0 ) { containerMarginTop = 0; }
	$('.container').css('margin', containerMarginTop + 'px auto 0 auto');
	$('body').css('background-position', 'center ' + (containerMarginTop-8) + 'px');
	
	var menuTop = $(window).scrollTop() + windowHeight - 138;
	
	if(menuTop > containerMarginTop + contentHeight - 138)
	{
		menuTop = containerMarginTop + contentHeight - 138;
	}
	
	var newLeft = ($(window).width() - 980) / 2;
	
	$('.navWrapper').css('top', menuTop + 'px');
	$('.navWrapper').css('left', newLeft + 'px');
	$('.footer').css('top', (menuTop+81) + 'px');
	$('.footer').css('left', newLeft + 'px');
	
	if(!noAuto) {
		setTimeout(updateContainerMargin, 10);
	}
	
}

var positionMenu = function(noAuto) {
	
	var windowHeight = $(window).height();
	var contentHeight = $('#contentWrapper').height() - 3;
	var menuHeight = $('#menuWrapper').height();
	//var menuHeight = 260;
	
	var newPageTop = 50;
	
	if((contentHeight+100) < windowHeight) {
		newPageTop = (windowHeight - (contentHeight+100)) / 2;
	}
	
	var newTop = $(window).scrollTop() + windowHeight - menuHeight;
	
	if(newTop > (newPageTop + contentHeight - menuHeight)) {
		newTop = newPageTop + contentHeight - menuHeight;
	}
	
	$('#menuPaddingWrapper, #contentWrapper').css('left', newLeft + "px");
	
	$('#menuPaddingWrapper').css('top', newTop + "px");
	
	$('#contentWrapper').css('top', newPageTop + "px");
	
}

var sidewaysMoverSlideTo = function(button, itemNum)
{
	var buttonDiv = $(button).parent();
	var buttonParent = $(buttonDiv).parent();
	var parent = $(buttonParent).parent();
	parent = $('.sidewaysMover', parent);
	
	$('.tabButton', buttonParent).removeClass('on');
	buttonDiv.addClass('on');
	
	if(isBelowIE8 == false)
	{
		$('.sidewaysMoverItem', parent).show();
		
		var newMargin =  -360 * (itemNum-1);
		
		
		parent.stop().animate(
					{marginLeft: newMargin + 'px'},
					{duration: 300,
					easing: "easeOutExpo"});
	}
	else
	{
		$('.sidewaysMoverItem', parent).hide();
		$('.sidewaysMoverItem#item'+itemNum, parent).show();
	}
	
	
	
	
}

var resetSidewaysMover = function(button)
{
	var parent = $(button).parent();
	parent = $(parent).parent();
	parent = $(parent).parent();
	parent = $(parent);
	
	if(isBelowIE8 == false)
	{
		parent.stop().animate(
					{marginLeft: 0},
					{duration: 300,
					easing: "easeOutExpo"});
	}
	else
	{
		$('.sidewaysMoverStartItem', parent).show();
		$('.sidewaysMoverItem', parent).hide();
	}
}

var launchGallery = function(newPath)
{
	$('.enlargeOverlay').empty();
	
	var galleryMarginTop = containerMarginTop + 48;
	
	var element = $('<div class="galleryPopupContainer" style="margin-top:'+galleryMarginTop+'px"><div class="galleryPopupHeader"><div class="popupCloseButton" onclick="closeOverlay()"></div><h2><img src="style/images/loading.gif"></h2><div style="clear:both;"></div></div><div class="galleryPopupSidebar"><img src="style/images/loading.gif"></div><div class="galleryPopupWrapper"></div><p class="galleryCaption"></p><div style="clear:both;"></div></div>');
	
	element.prependTo('.enlargeOverlay');
	
	openOverlay(function(){
		if(commercialGallery != null)
		{
			commercialGallery.destroy();
		}
		
		commercialGallery = new Gallery({wrapper: "galleryPopupWrapper", xmlPath: "storage/xml/"+newPath, layout: "arrowsOnly", slideInterval: 0, scaleUp: true, externalData: {caption: '.galleryCaption'} });
	});
	
	$.ajax({
		type: "GET",
		url: encodeURI("storage/xml/"+newPath),
		dataType: "xml",
		success: function(xml) {
			$(xml).find('xml').each(function(){
				
				var galleryTitle = $(this).attr("title");
				var sidebarContent = $(this).attr("sidebarContent");
				
				$('.galleryPopupHeader h2').empty();
				$('.galleryPopupHeader h2').append(galleryTitle);
				
				$('.galleryPopupSidebar').empty();
				$('.galleryPopupSidebar').append(sidebarContent);
					
			});
		}
	});

}


var showNewsItem = function(title, content)
{
	$('.enlargeOverlay').empty();
	
	var galleryMarginTop = containerMarginTop + 48;
	
	var element = $('<div class="newsPopupContainer" style="margin-top:'+galleryMarginTop+'px"><div class="newsPopupHeader"><div class="popupCloseButton" onclick="closeOverlay()"></div><h6>'+title+'</h6><div style="clear:both;"></div></div><div class="scrollWrapper">'+content+'</div></div>');
	
	element.prependTo('.enlargeOverlay');
	
	openOverlay(function() {
		var newHeight = $(".newsPopupContainer .scrollWrapper").height();	

		$(".newsPopupContainer .scrollWrapper").jScrollPane({height:newHeight, dragMaxHeight: 92, dragMinHeight: 92, scrollbarWidth: 23, scrollbarMargin: 40, animateTo: true, showArrows: false });
	});
}


var openOverlay = function(callbackFunction)
{
	$('.enlargeOverlay').height($(document).height());
	$('.enlargeOverlayBG').height($(document).height());
	
	$('.enlargeOverlay').stop().fadeIn(100);
	$('.enlargeOverlayBG').stop().fadeTo(100, 0.5);
	
	if(isFunction(callbackFunction))
	{
		setTimeout(callbackFunction, 150);
	}
}

var closeOverlay = function(callbackFunction)
{
	
	$('.enlargeOverlay').stop().fadeOut(250);
	$('.enlargeOverlayBG').stop().fadeOut(250);
	
	setTimeout(function() {
		$('.enlargeOverlay').empty();
	}, 300);
	
	if(isFunction(callbackFunction))
	{
		setTimeout(callbackFunction, 300);
	}
}

var fadeInPopupButton = function(parent) {
	$(parent).unbind('mouseover');
	
	var newPos = $(parent).offset();
	var popup = $('.servicesPopupButtonWrapper', parent);
	var newPopup = $('<div class="servicesPopupButtonWrapper" id="tempPopup">' + popup.html() + '</div>');
	popup.hide();
	newPopup.prependTo('body');
	newPopup.css({left: newPos.left, top: newPos.top});
	newPopup.fadeIn(300);
	
	$(document).mousemove(function(e){mouseMovePopupButton(e, this, newPopup);});
	
	trackingMouseOver = true;
}

var mouseMovePopupButton = function(e, parent, popup){

	if(trackingMouseOver == true)
	{
		var newPos = popup.offset();
		var areaWidth = 463;
		var areaHeight = 86;
		
		var x = e.pageX;
		var y = e.pageY;
		
		$('p.mousex').html(x);
		$('p.mousey').html(y);
		$('p.boxx').html(newPos.left);
		$('p.boxy').html(newPos.top);
		
		var out = false;
		
		if(y > newPos.top + areaHeight)
		{
			out = true;
		}
		else if(y < newPos.top)
		{
			out = true;
		}
		else if(x > newPos.left + areaWidth)
		{
			out = true;
		}
		else if(x < newPos.left)
		{
			out = true;
		}
		
		if(out == true)
		{
			fadeOutPopupButton(parent, popup);
			$('p.outVal').html("true");
		}
		else
		{
			$('p.outVal').html("false");
		}
	}
	
	
	
}

var fadeOutPopupButton = function(parent, popup) {
	
		$(parent).mouseover(function(){fadeInPopupButton(this);})
		
		$('.caseStudyButton', this).mouseover(function(){fadeInPopupButton(this);})
		
		$(document).unbind('mousemove');
		trackingMouseOver = false;
		
		$(popup).fadeOut(300, function() {
			$(this).remove();
		});
	
}

var setupForm = function() {
	
	$(".sendBtn").click(function(event){
								 
		event.preventDefault();
		
		ValidateForm();
	});
	
	$('#contactForm').ajaxForm(function() { 
		formSuccess();
	});
}

function isFunction(possibleFunction) {
	return (typeof(possibleFunction) == typeof(Function));
}





