// Init global variables
var isInTransition = false;
var currentPage = '';
var targetURL = '';
var currentJSON = null;
var contentAjax = $A();
var content = $A();
var lastAjaxCall;
var t;
var scrollToElem;
var test = 1;

// Set up the ajax responders to monitor ajax calls
Ajax.Responders.register({
	onComplete: function(ajaxCall) {
		// Checks if all ajax calls are completed with a 200, and updates the content
		if (ajaxCall.transport.status == 200) {
			if (Ajax.activeRequestCount == 0) {
				updateContent();
				_gaq.push(['_trackPageview', '/' + History.get('p') + '/']);
			}
		} else {
			// Displays the 404 page, if anything other than 200 is returned
			var notFoundURL = '/?p=404';
			if (targetURL != notFoundURL)
				getNewPage(notFoundURL);
			else {
				window.location  = targetURL;
			}
		}
	}
});

// redirect to root if not there, and set the hash to the page they were on
var p = location.toString().toQueryParams().p
if (p) window.location = '/#p=' + p

// Google Analytics
var _gaq = _gaq || $A();
_gaq.push(['_setAccount', 'UA-3064065-8']);
($$('head')[0] || $$('body')[0]).insert(new Element('script', { type:'text/javascript', async:true, src:('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'}));

// display the correct page for the hash on load
if (History.get('p')) {
	ajaxHistoryRequest(History.get('p'));
} else {
	History.set('p', 'index');
	_gaq.push(['_trackPageview', '/index/']);
}
History.Observer.start();

// Set handler for 'page' parameter
History.Registry.set({
	id: 'p',
	onStateChange: function(value) {
		if (value != currentPage) {
			ajaxHistoryRequest(value);
		}
	},
	defaultValue: 'index'
});

// When the dom has loaded
document.observe('dom:loaded', function() {

	$$('#topNav > li a').each(function(elem) {
		var subNav = elem.next('.subNav');
		if (subNav) {
			elem.observe('mouseover', function(event) {
				event.stop();
				clearTimeout(t);
				$$('#topNav > li .subNav').each(function(elem) {
					var id = elem.identify();
					if (id == subNav.identify()) {
						showSubNav(id);
					} else {
						hideSubNav(id);
					}
				});
			});
			elem.observe('mouseout', function(event) {
				event.stop();
				t = hideSubNav.delay(0.2, subNav.identify());
			});
			subNav.select('a').each(function(elem) {
				elem.observe('mouseover', function(event) {
					event.stop();
					clearTimeout(t);
				});
				elem.observe('mouseout', function(event) {
					event.stop();
					t = hideSubNav.delay(0.2, subNav.identify());
				});
			});
		}
	});

	// Update all the event handlers on the page.
	updateEventHandlers();

});

function showSubNav(id) {
	var elem = $(id);
	if (!elem.hasClassName('active')) {
		elem.up('li').addClassName('active');
		var height = elem.getHeight() + 'px';
		elem.setStyle({ height: '0px' });
		Effect.Queues.get(id).invoke('cancel');
		new Effect.Morph(elem, {
			style: { 'height':height },
			duration: 0.2,
			queue: id
		});
	}
}

function hideSubNav(id) {
	var elem = $(id);
	Effect.Queues.get(id).invoke('cancel');
	new Effect.Morph(elem, {
		style: { 'height':'0px' },
		duration: 0.2,
		afterFinish: function() {
			elem.setStyle({ height: '' });
			elem.up('li').removeClassName('active');
		},
		queue: id
	});
}

/***************************************************************************************************
* updateEventHandlers - Adds click events to all the anchors on the page
***************************************************************************************************/
function updateEventHandlers() {
	$$('a').each(function(elem) {
		if (elem.href.search(/mailto:/i) == -1 && elem.href.search(/lastar.com/i) != -1) {
			elem.stopObserving('click');
			elem.observe('click', function(event) {
				event.stop();
				elem.blur();
				if (elem.href.search(/#/i) != -1) { 
					scrollToElem = elem.href.split('#')[1];
				}
				var p = elem.href.toString().toQueryParams().p || 'index';
				if (p != History.get('p')) {
					ajaxHistoryRequest(p);
				} else {
					scrollToEffect();
				}
			});
		}
	});
}

function scrollToEffect() {
	scrollToElem = $(scrollToElem);
	if (scrollToElem) {
		new Effect.ScrollTo(scrollToElem, {
			duration: 0.5,
			offset: -12,
			afterFinish: function() {
				scrollToElem = null;			
			}
		});
	}
}

function ajaxHistoryRequest(myState) {
	currentPage = myState;
	History.set('p', myState);
	var url = '/?p=' + myState;
	if (contentAjax[myState]) {
		new Ajax.Cache(contentAjax[myState]);
	} else {
		contentAjax[myState] = new Ajax.Request(url, {
			method: 'get',
			parameters: { 'ajax': 'true' },
			onComplete: function(transport, json) {
				if (json.content) {
					currentJSON = json;
					json.content.each(function(url) {
						if (content[url] == undefined) updateContentSpot(url);
					});
					if (json.sidebar) {
						if (content[json.sidebar] == undefined) updateContentSpot(json.sidebar);
					}
				} else {
					window.location = url;
				}
			}
		});
	}
}


function getNewPage(url) {
	targetURL = url;
	new Ajax.Request(targetURL, {
		method: 'get',
		parameters: { 'ajax': 'true' },
		onSuccess: function(transport, json) {
			if (json.content) {
				currentJSON = json;
				json.content.each(function(url) {
					if (content[url] == undefined) updateContentSpot(url);
				});
				if (json.sidebar) {
					if (content[json.sidebar] == undefined) updateContentSpot(json.sidebar);
				}
			}
		}
	});
}

function updateContentSpot(url) {
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			content[url] = transport.responseText;
		}
	});
}

function updateContent() {
	var effects = $A();
	var numContentSpots = $$('#mainContent .w').length;
	if (numContentSpots < currentJSON.content.length) {
		for ( i = 0; i <= currentJSON.content.length - numContentSpots; i++ ) {
			var newContentWrapper = $$('#mainContent .w')[0].cloneNode(true);
			$(newContentWrapper).setStyle({height:'0px'});
			$('mainContent').insert(newContentWrapper);
		}
	}
	var contentSpots = $$('#mainContent .w');
	contentSpots.each(function(elem, i) {
		effects.push(fadeOutElem(elem.down('.content')));
	});
	var sidebar = !$('mainContent').hasClassName('nosidebar');
	if (sidebar) effects.push(fadeOutElem($('sidebar').down('.content')));
	var newBg = 'url(' + currentJSON.background + ')';
	if ($('bg').getStyle('backgroundImage') != newBg) effects.push(fadeOutElem($('bg')));
	new Effect.Parallel(effects, {
		duration: 0.5,
		afterFinish: function() {

			// Reset the effect array
			effects = $A();

			// Set the background of the page
			$('bg').setStyle({'backgroundImage':newBg});

			var mainContent = $('mainContent');
			contentSpots.each(function(elem, i) {
				elem.addClassName('last')
				if (i < currentJSON.content.length) {
					if (i != currentJSON.content.length - 1) elem.removeClassName('last');
					var tempWrapper = mainContent.down('.w').cloneNode(true);
					tempWrapper.down('.content').update(content[currentJSON.content[i]]);

					// Create variables to hold the new width/heights
					var newWidth = ''; var newHeight = '';

					// Set mainContent to how it will look after transition
					if (currentJSON.sidebar) {
						mainContent.removeClassName('nosidebar');
					} else {
						mainContent.addClassName('nosidebar');
					}

					mainContent.insert(tempWrapper);

					// grab height of wrapper after transition
					newHeight = tempWrapper.getHeight() - 26 + 'px'

					// Get mainContents newWidth, but only the first time.
					if ( i == 0) { newWidth = tempWrapper.getWidth() + 'px'; }

					tempWrapper.hide().remove();

					// Reset mainContent back to original
					if (sidebar) {
						mainContent.removeClassName('nosidebar');
					} else {
						mainContent.addClassName('nosidebar');
					}

					// Add effect to transition mainContent and the side bar, but only the first time.
					if ( i == 0) {
						effects.push(
							new Effect.Morph(mainContent, {
								sync: true,
								style: { 'width':newWidth },
								afterFinish: function() {
									if (currentJSON.sidebar) {
										mainContent.removeClassName('nosidebar');
									} else {
										mainContent.addClassName('nosidebar');
									}
									mainContent.setStyle({'width':''});
								}
							})
						);
						var sidebarWrapper = $('sidebar').down('.w');
						if (sidebar && !currentJSON.sidebar) {
							effects.push(
								new Effect.Morph(sidebarWrapper, {
									sync: true,
									style: { 'width':'0px' },
									afterFinish: function() { sidebarWrapper.hide(); }
								})
							);
						}
						if (!sidebar && currentJSON.sidebar) {
							effects.push(
								new Effect.Morph(sidebarWrapper, {
									sync: true,
									style: { 'width':'228px' },
									beforeStart: function() { sidebarWrapper.show(); }
								})
							);
						}
					}

					// Add effect to transition contentWrapper
					effects.push(
						new Effect.Morph(elem, {
							sync: true,
							style: { 'height':newHeight },
							beforeStart: function() { elem.show(); },
							afterFinish: function() {
								elem.setStyle({ height:'' });
							}
						})
					);
				} else {
					effects.push(
						new Effect.Morph(elem, {
							sync: true,
							style: { 'height':'0px' },
							afterFinish: function() {
								elem.hide();
								elem.setStyle({ height:'' });
							}
						})
					);
				}
			});
			new Effect.Parallel(effects, {
				duration: 0.5,
				afterFinish: function() {

					// Set the title of that page
					document.title = 'Lastar, Inc.';
					if (currentJSON.title) { document.title += ' | ' + currentJSON.title;	}

					// Reset the effect array
					effects = $A();

					// Fade in the bg if needed
					if ($('bg').getStyle('opacity') == 0) effects.push(fadeInElem($('bg')));

					currentJSON.content.each(function(url, i) {
						var elem = contentSpots[i];
						elem = elem.down('.content');
						elem.update(content[url]);
						effects.push(fadeInElem(elem));
					});
					if (currentJSON.sidebar) {
						elem = $('sidebar').down('.content');
						elem.update(content[currentJSON.sidebar]);
						effects.push(fadeInElem(elem));
					}
					new Effect.Parallel(effects, {
						duration: 0.5,
						afterFinish: function() {
							// Call the scrollTo function to scroll the page
							scrollToEffect();

							updateEventHandlers();
							isInTransition = false;
						}
					});
				}
			});
		}
	});
}

function fadeOutElem(elem) {
	return new Effect.Opacity(elem, {
		sync: true,
		from: 1.0,
		to: 0.0,
		beforeStart: function() {
			elem.setStyle({backgroundColor:'#FFF'});
		},
		afterFinish: function() {
			elem.setStyle({backgroundColor:''});
		}
	});
}

function fadeInElem(elem) {
	return new Effect.Opacity(elem, {
		sync: true,
		from: 0.0,
		to: 1.0,
		beforeStart: function() {
			elem.setStyle({backgroundColor:'#FFF'});
		},
		afterFinish: function() {
			elem.setStyle({backgroundColor:''});
		}
	});
}
