var current = "vote";
var imgFolder = "img/";

$(document).ready(function()
{

	//preload nav and submit button images
	$.preloadImages("vote","results","contact","about");
	$("<input>").attr("src", "img/submit-hover.png");
	$('#contact_submit').hover(
		function() { $(this).attr({ src : 'img/submit_hover.png'}); },
		function() { $(this).attr({ src : 'img/submit.png'}); }
	);
	$("#img" + current).attr("src",imgFolder+"nav-"+current+"-a.png");

	//load results
	loadResults();
	navHash();

	$("#email").blur(function(){checkEmail($("#email").val())});
	$("#email").change(function () { $("#emailcheck").empty(); });
	
	$("#b").click(function()
	{
		$.cookie("bumotome", null);
		window.location.reload();
	});

	//start slider	
	$("#slider").easySlider(
	{
		auto: false,
		continuous: false,
		numeric: true,
		speed: 100
	});
		
	$(".imgnavbuttons").hover(
		function ()
		{
			if (current != $(this).attr("name"))
			{
				var i = imgFolder+"nav-" + $(this).attr("name") + "-h.png";
				$(this).attr("src",i);
			}
	    },
		function ()
		{
			if (current != $(this).attr("name"))
			{
				var i = imgFolder+"nav-" + $(this).attr("name") + "-i.png";
				$(this).attr("src",i);
			}
		}
	);

	$(".imgnavbuttons").click(function(){ clickSlide(this); });
	//end slider

	if ($.cookie('bumotome'))
	{
		$('#mainvote').load('inc/thanks.php?i='+$.cookie('bumotome'), function () { $("#mainvote").show('fast',function () {navHash();});});
	}
	else
	{
		$("#mainvote").show('fast',function () {navHash();});
	}
	$("#poll").submit(function()
	{
		if (validate() && checkEmail($("#email").val()))
			submitForm();
	});
		
	$("#confirmform").submit(function()
	{
		confirmEmail();
	});	
	function confirmEmail()
	{
		var d = $("#confirmform").serialize();
		var r = $.ajax(
		{ 
		  	type: "POST",  
			url: "ajax/confirm.php",  
			data: d,
			async: false
		}  
		).responseText;

		if (r == "noemail")
		{
			$("#confirmemailcheck").html("Sorry, that email is not in our database. Are you sure you got it right?");
		}
		else if (r == "validna")
		{
			$("#mainvote").load("inc/thanks.php?i="+$.cookie("bumotome"), function()
			{
			  $("#mainvote").show();
			});
		}
		else
		{
			$("#mainvote").load("inc/thanks.php?i="+r, function()
			{
			  $("#mainvote").show();
			});
		}
		return false;
	}


	//start functions
	function validate()
	{ 
		$("#namecheck").empty();
		$("#emailcheck").empty();
		$("#pcheck").empty();
		$("#vcheck").empty();
		$("#captchaSuccess").empty();
		
		var tandem = 0;
		if ($("#voter_name").val() == '')
		{
			$("#namecheck").html("Please enter your name.");
			$("#voter_name").focus();
			return false;
		}

		if ($("#email").val() == '')
		{
		  	$("#emailcheck").html("Please enter your email.");
			$("#email").focus();
			return false;
		}

		if ($("#president").val() != '-1')
			tandem++;

		if ($("#vicepresident").val() != '-1')
			tandem++;
			
		if (tandem == 0)
		{
			$("#pcheck").html("No President or Vice-President? Di you bumoto!");
			$("#president").focus();
			return false;
		}

		challengeField = $("input#recaptcha_challenge_field").val();
		responseField = $("input#recaptcha_response_field").val();
		var html = $.ajax(
		{
			type: "POST",
			url: "ajax/captcha.php",
			data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
			async: false
		}).responseText;

		if(html == "success")
		{
			$("#captchaStatus").html(" ");
			return true;
		}
		else
		{
			$("#captchaStatus").html("Your captcha is incorrect. Please try again");
			Recaptcha.reload();
			return false;
		}
		return true;
		
	}	
	function checkEmail(email)
	{
		if (email.length < 5)
		{
			$("#emailcheck").html("Invalid email.");
			return false;
		}
		var html = $.ajax(
		{
			type: "POST",
			url: "ajax/email.php",
			data: "e=" + email,
			async: false
			
		}).responseText;
		
		if (html == "win")
		{
			$("#emailcheck").html("valid!");
			return true;
		}
		else if (html == "fail")
		{
			$("#emailcheck").html("Duplicate email!");
			return false;
		}
		else if (html == "invalid")
		{
			$("#emailcheck").html("Invalid email!");
			return false;
		}
	}

	function submitForm()
	{
		var d = $("#poll").serialize();
		var r = $.ajax(
		{ 
		  	type: "POST",  
			url: "ajax/poll.php",  
			data: d,
			async: false
		}  
		).responseText;
		
		if (r != "error")
		{
			successfulVote(r);
		}
		else
		{
			alert("error! PCOS compromised! JK.");
		}  
	}
	function successfulVote(voteid)
	{
		$.cookie('bumotome', voteid, { path: '/', expires: 10 });

		$('#mainvote').load('inc/step.php?i='+voteid, function()
		{
		  $("#mainvote").show(function() {navHash(); });
		});
		
		loadResults();
	}
	
	function loadResults(voteid)
	{
		$.ajax(
		{
			type: "GET",
			url: "ajax/results2.php?type=" + 1,
			success: function(msg){ loadGraph(msg, 1); }
		});		

		$.ajax(
		{
			type: "GET",
			url: "ajax/results2.php?type=" + 2,
			success: function(msg){ loadGraph(msg, 2); }
		});
	}
	function loadGraph(msg, type)
	{
		var c = [],u = [],z = [];
		var x = msg.split("-");
		for (var i=0;i<x.length;i++)
		{
			t = x[i].split("/");
			c[i] = parseInt(t[0],10);
			u[i] = parseInt(t[1],10);
			z[i] = [c[i],u[i]];
		}
		if (type == 1)
		{
			president = new Array(
				[z[0],'Noynoy','#fff100'],
				[z[1],'JC','#186495'],
				[z[2],'Erap','#ff6400'],
				[z[3],'Gordon','#800000'],
				[z[4],'Jamby','#51e100'],
				[z[5],'Perlas','#135237'],
				[z[6],'Gibo','#00ae51'],
				[z[7],'Bro. Eddie','#fddb79'],
				[z[8],'Villar','#ff8201']

			);
			$('#presidentGraph').empty();
			$('#presidentGraph').jqbargraph(
			{
				data: president,
				legend: false,
				width: 960,
				height:150,
				title: 'President'
			});
			$('.graphBarpresidentGraph div:first-child').css("background-color","rgba(0,0,0,.25)");
		}
		if (type == 2)
		{
			vice = new Array(
		   		[z[0],'Binay','#d55d20'],
		   		[z[1],'Chipeco','#bbd6ad'],
		   		[z[2],'Bayani','#fe0000'],
		   		[z[3],'Loren','#052f0b'],
		   		[z[4],'Edu','#009919'],
		   		[z[5],'Mar','#0d009c'],
		   		[z[6],'Jay','#232ba8'],
		   		[z[7],'Yasay','#348c39']);
			$('#viceGraph').empty();
			$('#viceGraph').jqbargraph({
			   data: vice,
			   legend: false,
			   width: 920,
			   height: 150,
			   title: 'Vice President'
			});
			$('.graphBarviceGraph div:first-child').css("background-color","rgba(0,0,0,.25)");
		}
	}

	function clickSlide(which)
	{
		$("#controls" + $(which).attr('rel')).click();
		$("#img" + current).attr("src",imgFolder+"nav-"+current+"-i.png");
		var i = imgFolder+"nav-" + $(which).attr("name") + "-a.png";
		$(which).attr("src",i);
		current = $(which).attr("name");
		window.location = "#" + current;
		$("#main"+current).show();
	}
	function navHash()
	{
		if (window.location.hash != '')
		{
			hash = window.location.hash;
			switch (hash)
			{
				case '#about': clickSlide($("#imgabout")); break;
				case '#contact': clickSlide($("#imgcontact")); break;
				case '#vote':  clickSlide($("#imgvote")); break;
				case '#results': clickSlide($("#imgresults")); break;
				case '#confirm': confirm(); break;
				default: clickSlide($("#imgvote"));
			}
		}
	}

	function confirm()
	{
		$('#mainvote').load('inc/confirm.php', function()
		{
		  $("#mainvote").show(function() {});
		});
	}
});//end document.ready
$.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
	$("<img>").attr("src", "img/nav-" + arguments[i] + "-h.png");
	$("<img>").attr("src", "img/nav-" + arguments[i] + "-i.png");
	$("<img>").attr("src", "img/nav-" + arguments[i] + "-a.png");
  }
}
var RecaptchaOptions = { theme : 'clean'};

