$(document).ready(function(){
	
	
	$("#photos").hover(
		function () {$("#tap_photo").animate( { color:"#FFFFFF"}, "fast" );},
		function () {$("#tap_photo").animate( { color:"#898989"}, "fast" );});
	$("#Video").hover(
		function () {$("#tap_video").animate( { color:"#FFFFFF"}, "fast" );},
		function () {$("#tap_video").animate( { color:"#898989"}, "fast" );});
		
			
		$("#LoginButton").hover(
		function () {$("#LoginButton").animate( { opacity:".8"}, "fast" );},
		function () {$("#LoginButton").animate( { opacity:"1.0"}, "fast" );});
		
	$.preloadImages("/images/big1_s.jpg","/images/big2_s.jpg","/images/big3_s.jpg","/images/big4_s.jpg");
	
});



jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}



AppMenu = 0
function SwitchApplicationMenu(button) {
	if (AppMenu == 0) {
		$(button).removeClass('redButton').addClass('blackButton'); 
		$(button).html("Cancel")
		$('#ApplyForm').toggle('slide', { direction: 'left' }, 800);
		AppMenu = 1
	} else {
		$(button).removeClass('blackButton').addClass('redButton'); 
		$(button).html("<span style='margin-top:6px; ; margin-right:15px'>Get Invited</span>")
		$('#ApplyForm').toggle('slide', { direction: 'left' }, 800);
		AppMenu = 0
	}
}
/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}

function VerifyForm(button) {
	$('#first_name_error').hide()
	$('#last_name_error').hide()
	$('#email_error').hide()
	$('#phone_error').hide()
	$('#location_manual_error').hide()
	$('#password_error').hide()
	$('#device_id_error').hide()
	$('#terms_error').hide()
	error = 0
	
	if ($('#first_name').val().length < 2) {
		$('#first_name_error').show()
		$('#first_name_error').html('First name required')
		$('#first_name').focus()
		error = 1
	}
	if ($('#last_name').val().length < 2) {
		$('#last_name_error').show()
		$('#last_name_error').html('Last name required')
		$('#last_name').focus()
		error = 1
	}
	if ($('#email').val().length < 2) {
		$('#email_error').show()
		$('#email_error').html('Email required')
		$('#email').focus()
		error = 1
	} else {
		if (echeck($('#email').val())==false) {
			$('#email_error').show()
			$('#email_error').html('Enter valid e-mail')
			$('#email').focus()
			error = 1
		}
	}
	if ($('#phone_os').val() == 'Please choose...') {
		$('#phone_error').show()
		$('#phone_error').html('Phone OS required')
		$('#phone').focus()
		error = 1
	
	}
	if ($('#location_manual').val().length < 2) {
		$('#location_manual_error').show()
		$('#location_manual_error').html('Home city required')
		$('#location_manual').focus()
		error = 1
	}
	if ($('#password').val() == '') {
		$('#password_error').show()
		$('#password_error').html('Password required')
		$('#password').focus()
		error = 1
	} else {
		if ($('#password').val().length < 4) {
			$('#password_error').show()
			$('#password_error').html('Needs 4+ characters')
			$('#password').val('')
			$('#password').focus()
			error = 1
		}
	}

	
	 if (document.theForm.terms.checked == false) {
		$('#terms_error').show()
		$('#terms_error').html('Please agree')
		$('#terms_error').focus()
		error = 1
	}
	
	interests = ''
	if (document.theForm.create_content.checked == true) {
		interests = interests + '{Create Content} '
	}
	if (document.theForm.solve_missions.checked == true) {
		interests = interests + '{Solve Missions}'
	}
		
	if (error == 0) {
		if ($(button).text() == 'Register') {
			$(button).html('<div id="Spinner" class="RedSpinner" style="margin-top:10px;">&nbsp;&nbsp;</div>')
			$(button).css({opacity:.8})
	
				$.post("/register", { email: document.getElementById("email").value, password: document.getElementById("password").value, first_name: document.getElementById("first_name").value, last_name: document.getElementById("last_name").value, phone_os: document.getElementById("phone_os").value, homecity: document.getElementById("location_manual").value, lng: document.getElementById("lng").value, lat: document.getElementById("lat").value, account_status: 1, interest:  interests}, 
				function(data){
					var error = data.getElementsByTagName("error")[0].childNodes[0].nodeValue;
					$(button).html('Register')
					$(button).css({opacity:1})
					if(error == 0) {	
						
						location.reload(true);
						
						//var UserID = data.getElementsByTagName("user_id")[0].childNodes[0].nodeValue;
						//$('#user_id').val(UserID)
						//$("#RegisterFormLayer").hide()
						//$("#RegisterThanksLayer").show()
						//createCookie('Registered',1,60)
					} else {
						$('#email_error').show()
						$('#email_error').html('Email already in use')
						$('#email').focus()
					}
				});
		}
	}
	
}
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
	Login($('#LoginButton'))
   return false;
   }
else
   return true;
}

function ForgetPassword(link) {
	if (link.innerHTML == 'Forget your password?') {
		link.innerHTML = 'I remember my password!'
		$('#LoginButton').text('Password')
		$('#RememberCheck').hide()
		$('#login_password').hide()
		$('#login_error').hide()
		$('#HiddenPassword').hide()
		$('#HiddenReset').show()
	} else {
		link.innerHTML = 'Forget your password?'
		$('#LoginButton').text('Login')
		$('#RememberCheck').show()
		$('#login_password').show()
		$('#HiddenReset').hide()
	}
	
	
}

function Login(button) {

	if ($(button).text() == 'Login') {
				
		    email = $('#login_email').val()
			password = $('#login_password').val()
		
			if ($('#login_remember').attr('checked') == true) {
				remember = 1
			} else {
				remember = 0
			}
			if ((email != '') && (password != '')) {
				
				$(button).html('<div class="BlackSpinner" style="margin-top:10px;">&nbsp;&nbsp;</div>')
				$(button).css({opacity:.8})
				$.post("/login", { email: email, password: password, remember: remember }, 
				function(data){
					
					var error = data.getElementsByTagName("error")[0].childNodes[0].nodeValue;
					if(error == 0) {	
						window.location.reload()
					} else {
						$(button).html('Login')
						$(button).css({opacity:1})
						$('#login_error').show()
						if(error == 3) {
							$('#login_error').html('Account not yet active')
						} else {
							$('#login_error').html('Invalid email/password combination')
						}
						$('#login_email').focus()
					}
				});
			} else {
				$('#login_error').show()
				$('#login_error').html('Input email/password')	
			}
		} else {
			if ($(button).text() == 'Password') {
				$(button).html('<div id="Spinner" class="BlackSpinner" style="margin-top:10px;">&nbsp;&nbsp;</div>')
				$(button).css({opacity:.8})
				$.post("/sendpassword", { email: $('#login_email').val() }, 
				function(data){
					$('#login_error').html(data)
					ForgetPassword($('#ForgetPassword'))
					$('#ForgetPassword').text('Forget password?')
					$('#login_error').show()
					$(button).css({opacity:1})
				});
			}
		}
}
function LogOut() {
	$.post("/logout", { authenticity_token: window._token }, 
	function(data){			
			window.location.href="/splash"
	});
}


function SubmitDeviceID(button) {
	error = 0
	if ($('#device_id').val()  == '') {
		$('#device_id_error').show()
		$('#device_id_error').html('Device ID required')
		$('#device_id').focus()
		error = 1
	} else {
		if ($('#device_id').val().length < 40) {
			$('#device_id_error').show()
			$('#device_id_error').html('Invalid Device ID.')
			$('#device_id').focus()
			error = 1
		}
	}
	
	if (error == 0) {
		if ($(button).text() == 'Register') {
			$(button).html('<div id="Spinner" class="RedSpinner" style="margin-top:10px;">&nbsp;&nbsp;</div>')
			$(button).css({opacity:.8})
			$.post("/register", { user_id: document.getElementById("user_id").value, device_id: document.getElementById("device_id").value, authenticity_token: window._token}, 
			function(data){
				$("#DeviceIDLayer").hide()
				$("#ShowSuccess").show()
				$('#ApplyButton').html("Back")
				createCookie('Registered',2,60)
			});
		}
	}
}

function Geocode() {
	if (document.getElementById("location_manual").value != '') {
		$('#location_manual_error').hide()
		$.post("/geocode.js", { location_manual: document.getElementById("location_manual").value}, 
		function(data){
			eval(data)
			if (Lat == 0 ) {
				$('#geocoded').hide()
				$('#location_manual_error').show()
				$('#location_manual_error').html('Could not geocode')
				$('#location_manual').focus()
			} else {
				$('#lat').val(Lat)
				$('#lng').val(Lng)
				$('#geocoded').show()
				$('#geocoded').html(' ['+Lat+'] , ['+Lng+']')
			}
		});
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


currentButton = 'EditGame_Info';
FirstTime = 0;
function SwitchSubMenu(id) {

	$('#SubMenuEditGame > * ').each(
			function( intIndex ){			  
				$(this).addClass("SubMenuButton");
				$(this).removeClass("SubMenuButtonOver");
				}
			);
			
		$("#EditGame_Info_Layer").hide();
		$("#EditGame_Missions_Layer").hide();
		$("#EditGame_Missions_Layer_HACK").hide();
		$("#EditGame_Files_Layer").hide();
		$("#EditGame_Resources_Layer").hide();
		
		
		
		if (id.id == "EditGame_Missions") {
			$("#EditGame_Missions_Layer_HACK").show();
		}
	 $(id).addClass("SubMenuButtonOver");
	 $(id).removeClass("SubMenuButton");
	$("#"+id.id+"_Layer").show();
	
	if (id.id == "EditGame_Files") {
		if ($('#FileLoader').attr('src') == '') {
			game = $('#game_id').text();
			$('#FileLoader').attr('src', 'http://file.urbansleuth.net/?gameid='+game)
		}
	}
	
	if ($("#"+id.id+"_Layer").css("visibility") == "hidden") {
		$("#"+id.id+"_Layer").css("visibility","visible")
	}
	
	 currentButton=id;



		//ugly hack for Firefox
		if (id.id == "EditGame_Missions") {
			$("#EditGame_Missions_Layer").hide();
			$("#EditGame_Missions_Layer_HACK").hide();
			$("#EditGame_Missions_Layer_HACK").show();
			$("#EditGame_Missions_Layer").show();
			editAreaLoader.CursorAtStart();
		}
	
		
}



function ValidateGame() {
	
	if (EditAreaChanged == 1) {
		game = $('#game_id').text();
		content = editAreaLoader.getValue("mission_xml");
		$.post("/games/"+game, { _method: "put", mission_xml:content }, 
		function(data){
			document.EditGameForm.submit();
		});
	} else {
		document.EditGameForm.submit();
	}
	
	
}

function Publish(pub) {
	yes = 0;
	if (pub==0) {
		var x=window.confirm("Are you sure you want to publish this game?  It will be downloadable by everyone.")
		if (x) {
			$('#game_published').val(1)
			yes = 1;
		} 
	} else {
		var x=window.confirm("Are you sure you want to hide this game?  It will be no longer be viewable or downloadable by the public")
		if (x) {
			$('#game_published').val(0)
			yes = 1;
		}
	}
	if(yes == 1) {
		ValidateGame();
	}
	
}

function DeleteGame(id) {
	yes = 0;
	
	var x=window.confirm("Are you SURE you want to DELETE this game?  No traces will remain.")
	
	if (x) {
		$.post("/games/"+id, {  _method:"delete" }, 
		function(data){
		
			window.location.href="/authors";
		});
		
	} 
	
}




function GeoCodeAddress() {
	street = $('#game_venue_address').val();
	city = $('#game_venue_city').val();
	state = $('#game_venue_state').val();
	country = $('#game_venue_country').val();
	
	full_address = street + ' ' + city + ' ' + state + ' ' + country
	if (state != '' && city != '') {
			
			$.post("/geocode.js", { location_manual: full_address }, 
			function(data){
			
				eval(data)
				if (Lat == 0 ) {
					$('#Geocode').html('Could not geocode')
					$('#game_venue_address').focus()
				} else {
					$('#game_lat').val(Lat)
					$('#game_lng').val(Lng)
					$('#Geocode').html(' ['+Lat+'] , ['+Lng+']')
				}
			});
		
	}
}

function ToggleGameInfoOn() {
	$('#LearnMore').hide();
	$('#HiddenGameInfo').show();
}
function ToggleGameInfoOff() {
	$('#LearnMore').show();
	$('#HiddenGameInfo').hide();
}

