$(document).ready(function(){
	
	var contactFields = $("#contact_name, #contact_email, #contact_msg, #contact_val");
	var signupFields = $("#formal_name, #web_address, #f_name, #l_name, #phone_1, #email, #address_1, #city, #state, #country, #zip, #username, #password, #retype_password, #ac_type, #signup_val, #readLegal");
	
	//for the links on the home page
	function loadURL(url){
		if (!url){
			//url = "home";
			window.location = "http://ucstreaming.net/#home";
		}
		//update the current link on the menu
		$(".currentPage").removeClass('currentPage');
		$("#" + url + "_li").addClass('currentPage');
		
		//page specific code
		if (url == "contact"){
			contactFields.removeClass('missingField');
		}
		if (url == "signup"){
			signupFields.removeClass('missingField');
		}
		if (url == "contactMsgSent"){
			$("#contact_li").addClass('currentPage');
		}
		if (url == "signupSent"){
			$("#signup_li").addClass('currentPage');
		}
		
		document.title = "UCstreaming:" + url.slice(0,1).toUpperCase() + url.slice(1) + " - Free video streaming for your church!";
		
		//show the proper div.page. Animation to make it look cool
		$("div.page").stop().animate({
			opacity:0,
		},200, function(){
			$("div.page").hide();
			$("div.page#"+url+"").show().stop().animate({
				opacity:1,
			},200, function(){});
		});
		
	}
	$.address.init(function(e) {
		var url = e.value.replace("/","");
		loadURL(url);
	}).change(function(e) {
		var url = e.value.replace("/","");
		loadURL(url);
	});
	
	$("#loader").hide();
	loadPage();
	
	/*
	//image pre loading
	$("#header,#bodyer,#footer").hide();
	var numOfImages = $("img").length;
	var numOfImagesLoaded = 0;
	$("img").load(function(){
		numOfImagesLoaded = numOfImagesLoaded + 1;
		if (numOfImages == numOfImagesLoaded){
			$("#header,#bodyer,#footer").show();
			$("#loader").hide();
			loadPage();
		}
	});
	
	*/
	
	function loadPage() {
		//the first time the page is loaded, I have a loading animation
		$('#help').css('opacity','0').css('margin-right','-500px');
		$('#header').css('opacity','0').css('height','0px').animate({
			opacity:1,
			height:'150px',
		}, 750, function() {
			// Animation complete.
			$('#help').animate({
				opacity:1,
				marginRight:'100px',
			}, 500);
		});
		$('#bodyer_menu').css('opacity','0').css('width','0px').animate({
			opacity:1,
			width:'225px',
		}, 750, function() {
			// Animation complete.
		});
	
	}
	
	/*home page */
	//for the twitter feed
	$("#twitterFeed").tweet({
		join_text: false,
		username: "ucstreaming",
		avatar_size: 0,
		count: 3,
		/*
		auto_join_text_default: "we said,",
		auto_join_text_ed: "we",
		auto_join_text_ing: "we were",
		auto_join_text_reply: "we replied",
		auto_join_text_url: "we were checking out",
		*/
		loading_text: "loading tweets..."
	});
	
	/* contact page */
	$("#contact_submit").click(function(){
		$(this).attr('disabled','disabled');
		var valid = true;
		contactFields.each(function(){ contactFormValid(this); });
		if(contactFields.hasClass('missingField')){
			valid = false;
		}
		if (valid){
			$.post('/www/welcome/sendmsg', {
				'name' : $("#contact_name").val(),
				'email' : $("#contact_email").val(),
				'msg' : $("#contact_msg").val()
			}, function(text){
				if (text == 1){
					_gaq.push(['_trackEvent', 'User', 'Message', $("#contact_name").val() + '<' + $("#contact_email").val() + '>']);
					contactFields.val('').removeClass('missingField');
					loadURL('contactMsgSent');
				}else{
					alert('Something went wrong! Please refresh the page and try again.');
				}
				$("#contact_submit").removeAttr('disabled');
			});
		}else{
			$(this).removeAttr('disabled');
		}
	});
	
	contactFields.change(function(){ contactFormValid(this); }).blur(function(){ contactFormValid(this); });
	
	function contactFormValid(elem){
		var valid = true;
		if ($(elem).val() == ""){
			valid = false;
		}
		if ($(elem).attr('id') == "contact_email" && !validateEmail($(elem).val())){
			valid = false;
		}
		if ($(elem).attr('id') == "contact_val" && $(elem).val() != "6"){
			valid = false;
		}
		if (valid){
			$(elem).removeClass('missingField');
		}else{
			$(elem).addClass('missingField');
		}
	}
	
	/*signup page */
	$("#signupSubmit").click(function(){
		$(this).attr('disabled','disabled');
		var valid = true;
		signupFields.each(function(){ signupFormValid(this); });
		if(signupFields.hasClass('missingField')){
			valid = false;
		}
		if (valid){
			var signupFormVals = $("#signupForm").serializeArray();
			//console.log(signupFormVals);
			$.get('/www/welcome/signup', signupFormVals, function(text){
				if (text == 1){
					/* Google Analytics Tracking */
					userID = 0;
					acType = $("#ac_type").val();
					_gaq.push(['_trackEvent', 'User', 'Signup', acType + ':' + userID]);
					/*  */
					signupFields.val('').removeClass('missingField');
					loadURL('signupSent');
				}else{
					alert('Something went wrong! Please refresh the page and try again.');
				}
				$("#signupSubmit").removeAttr('disabled');
				console.log(text);
			});
		}else{
			$(this).removeAttr('disabled');
		}
		
	});
	
	signupFields.change(function(){ signupFormValid(this); }).blur(function(){ signupFormValid(this); });
	
	function signupFormValid(elem){
		var valid = true;
		if ($(elem).val() == ""){
			valid = false;
		}
		if ($(elem).attr('id') == "signup_val" && $(elem).val() != "6"){
			valid = false;
		}
		if (($(elem).attr('id') == "email" || $(elem).attr('id') == "extra_emails" ) && !validateEmail($(elem).val())){
			valid = false;
		}
		if (($(elem).attr('id') == "password" || $(elem).attr('id') == "retpye_password")){
			if ($(this).val().length >= 6){
				valid = false;
			}
		}
		if ($(elem).attr('id') == "retype_password" && $(elem).val() != $("#password").val()){
			valid = false;
		}
		if ($(elem).attr('id') == "readLegal"){
			if(!$(elem).is(':checked')){
				valid = false;
			}
			elem = $("#readLegalErrorArea");
		}
		
		if ($(elem).attr('id') == "username"){
			var cleanUser = cleanStr($(this).val());
			$(this).val(cleanUser);
			if ($(this).val().length >= 6){
				valid = false;
			}
			//maybe wanna make sure it isn't in use
		}
		if (valid){
			$(elem).removeClass('missingField');
		}else{
			$(elem).addClass('missingField');
		}
	}
});

function validateEmail(x){
	var atpos=x.indexOf("@");
	var dotpos=x.lastIndexOf(".");
	if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
		//not a valid email
		return false;
	}else{
		//valid email
		return true;
	}
}

function cleanStr(str){
	var str = str.replace(" ","");
	return str;
}
