var windowH = $(window).height(), headerHeight, footerHeight, contentHeight, navHeight, navOffset, page = location.hash;

window.onError = function(message, url, lineNumber) {  
    var params = [];  
    params[0] = 'browser=' + Core.Client.browser;  
    params[1] = 'data=' + navigator.userAgent + '|' + navigator.vendor + '|' + navigator.platform;  
    params[2] = 'lineNumber=' + Core.Client.message;  
    params[3] = 'message=' + Core.Client.lineNumber;  
    params[4] = 'os=' + Core.Client.OS;  
    params[5] = 'url=' + Core.Client.url;  
    params[6] = 'version=' + Core.Client.version;  
      
    try { 
    	console.log(params);
        //YAHOO.util.Connect.asyncRequest('GET', 'logJavaScriptError.event?' + params.join('&'), function() {}, null);  
    }  
    catch(e) {  
        // squelch, because we don't want to prevent method from returning true  
    }  
      
    return true;  
};  

function validate(input) {
	var valid = false, error = '', regex, validEmail;
	if (input.hasClass('required')) {
		if (!input.val()) {
			error = '<p class="error">Please enter your ' + input.attr('id') + '.</p>';
		} else if (input.val() && input.attr('id') == 'email') {
			regex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
			validEmail = regex.test(input.val());
			if (!validEmail) {
				error = '<p class="error">Please enter a valid email address.</p>';
			} else {
				input.animate({color: '#666'}, 500);
				return true;
			}
		} else {
			input.animate({color: '#666'}, 500);
			return true;
		}
		if (input.next('p.error').length == 0) {
			input.after(error);
		}
		input.next('p.error').fadeIn('normal', function () {
			$(this).css('filter', 'alpha(opacity=80)');
		}); 
		input.keydown(function () {
			$(this).next().fadeOut('normal', function () {
				$(this).remove();
			});
			input.unbind('keydown');
		});
		return false;
	}
	return true;
}

function updateNav(page) {
	if (page.indexOf('#') === 0) {
		page = page.substring(1);
	}
	$('div#nav ul li').children().each(function () {
		if ($(this).text() === page) {
			$(this).addClass('current');
			return false;
		}
	});
}

function AJAXload(e, initial) {
	if (e.text) {
		page = e.text();
	} else {
		page = e.substring(1);
	}
	var title = $('#title span'), quip = $('#title').parent().next(), currentPage = e, content = $('#content'); 
	
	$('#nav ul li a.current').removeClass('current');
	if (_gaq) {
		_gaq.push(['_trackEvent', 'pageViews', 'newPage', page]);
	}
	if (!initial) {
		window.location.hash = page;
	}
	updateNav(page);
	$.ajax({
		method: 'GET',
		data: 'page=' + page,
		dataType: 'html',
		cache: false,
		success: function (data) {
			if (window.location.hash) {
				page = window.location.hash;
			}
			title.animate({opacity: 0}, 500);
			quip.animate({marginTop: '-3em'}, 500);
			content.animate({opacity: 0}, 700, function () {
				var numImages = $(data).find('img').not('[class="logo noscript"]').length, i = 0;
				content.html(data);
				title.text($('#page_title').clone().children().remove().end().text())
					.animate({opacity: 1}, 500);
				quip.text($('#page_title span').text())
					.animate({marginTop: '0em'}, 500);
				$('body').css('cursor', 'auto');
				content.css('paddingTop', (windowH - headerHeight - footerHeight - $('#content').height()) / 2 + 'px')
					.animate({opacity: 1}, 500, function () {$('#loading').fadeOut('fast', function () {$(document).unbind('mousemove'); }); });
				setInterval(pollHash, 1000);
			});
		}
	});
	return false;
}

function pollHash() {
	if (page.length !== 0) {
		if (page.indexOf('#') === -1) {
			page = '#' + page;
		}
		if (location.hash.length === 0) {
			location.hash = page;
			updateNav(page.substring(1));
		}
	}
	if (location.hash !== page) {
		clearInterval(pollHash);
		AJAXload(location.hash, false);
    }
}

$.ajaxSetup({
	url: 'page_request.php',
	beforeSend: function () {
		var loading = $('#loading');
		$('body').css('cursor', 'none');
		loading.fadeIn('fast');
		$(document).bind('mousemove', function(e) { 
			loading.css({top: e.pageY - 8, left: e.pageX - 8});
		});
	},
	cache: false,
	error: function (xhr, status, error) {
		$('#loading').fadeOut('fast', function () {$(document).unbind('mousemove'); });
		$('#error_dialog').dialog("open");
	}
});

$(document).ready(function () {
	if (window.location.hash) {
		if ($.support.opacity) {
			$('#content').css('opacity', 0);
		}
		AJAXload(window.location.hash, true);
	} else {
		setInterval(pollHash, 250);
		$('h2#quip').animate({marginTop: '0em'}, 500);
	}
	//$('h1')﻿.textShadow();
	headerHeight = $('#header').height();
	footerHeight = $('#footer').height();
	contentHeight = $('#content').height();
	navHeight = $('#nav').height();
	page = $('h1').attr('title');
	
	var offset = (windowH - headerHeight - footerHeight - contentHeight) / 2;
	if (offset > 0) $('#content').css('paddingTop',  offset + 'px');
	if (windowH / 2 > 320) $('#nav').css('top', windowH / 2);
	else $('#nav').css('top', 320);
	$('a.ajax').live('click', function (e) {
		e.preventDefault();
		$('#loading').css({top: e.pageY, left: e.pageX});
		if (!$(this).hasClass('current')) {
			AJAXload($(this), false);
		} else {
			return false;
		}
	});
	
	$('input').live('blur', function () {
		validate($(this));
	});
	
	$('textarea').live('blur', function () {
		$(this).animate({color: '#666'}, 500); 
	});
	 
	$('input, textarea').live('focus', function () {
		$(this).animate({color: '#333'}, 300);
		if ($(this).parent().children('p.error').length != 0) {
			$('p.error').fadeOut();
		}
		return false;
	});
	
	$('input[type="button"], input[type="submit"]').live('click', function (e) {
		e.preventDefault();
		var inputs = $('input, textarea'), valid = false;
		inputs.each(function (i) {
			valid = validate($(this));
			if (!valid) {
				return false;
			}
		});
		if (valid) {
			$.ajax({
				type: 'POST',
				url: 'http://www.vestigefilmworks.com/contact_form.php',
				data: $('form').serialize(),
				success: function (data) {
					$('#wrap').append(data);
					$('#dialog').css({
						display: 'block', 
						left: ($('body').width() - $('#dialog').width()) / 2,
						top: 0,
						zIndex: 4
					})
					.animate({
						top: '140px'
					}, 600, function() {
						var t = setTimeout(function() {
							$('#dialog').animate({top: '-20px'}, 600, function() {
								//$(this).remove();
							});
						}, 5000);
					});
					
					$('body').css('cursor', 'auto');
					$('#loading').fadeOut();
					if ($('#dialog').hasClass('success')) {
						inputs.each(function () {
							if ($(this).attr('type') != 'hidden' && $(this).attr('type') != 'button') {
								$(this).val('');
							}
						});
					}
				}
			});
		}
		return false;
	});
	
	$('div.close').live('click', function () {
		$(this).parent().fadeOut();
		if ($(this).parent().attr('id') == 'movie') stopMovie($(this));
		return false;
	});
	
	$('#overlay').click(function (e) {
		if (e.target.id == 'overlay') {
			$(this).fadeOut();
			stopMovie($(this).children().children());
			return false;
		}
	});
});
