/**
 * @author jleeder
 */

if(location.hostname == 'www.energypluscoffee.com') {
	var api_key = '86b8acc7d49390776438cd058c2f4d99';
}
else {
	var api_key = '425b318e7f13ed307f3e101c9635b883';
}
var prefix = location.protocol + "//" + location.hostname + "/";

var game_id; 

$(document).ready(function(){
	$('#checkBtn').bind("click", pushCheck);
	$('#loginBtn').bind("click", pushLogin);
	$('#registerBtn').bind("click", pushRegister);
});

function pushCheck(){
	$('#register').animate({height: "575px"}, 'slow', 'jswing').removeClass('check').addClass('reg');
	$('#register.reg .outerBox').animate({height: "539px"}, 'slow', 'jswing');
	$('#register.reg .innerBox').animate({height: "461px"}, 'slow', 'jswing', function(){
		$('.swappable').show('slow');	
	});
	$('#check_control').hide();
	$('#reg_control').show();
	$('#register p.directions').text('Please fill out the form below');
}
function pushRegister(){}

//standard pfc login check
function pushLogin(){
	$.ajax({
		type: "POST",
		dataType: 'json',
		url: prefix+"ajax/request.php?login",
		data: $('#pepsiLogin').serialize(),
		success: function(msg){
			if (msg.result) {
				loginOverlay.close();
				$('#login_span').hide();
				$('#logout_span').show();
				nextAlert = "<strong>Success</strong><br />You have successfully logged in.";
				alertOverlay.load();
			} else {
				nextAlert = '<strong>Error</strong><br />Invalid email/password';
				alertOverlay.load();
			}
		}
	})	
}

// fb login check
function doFbConnect() {
	$.getJSON(prefix+"ajax/request.php?fb_connect", function(msg) {
		if (msg.result) {
			loginOverlay.close();
			$('#login_span').hide();
			$('#logout_span').show();
			nextAlert = "<strong>Success</strong><br />You have successfully logged in.";
			alertOverlay.load();
		} else {
			$('#header_copy').html("<strong>Register Now</strong><br/><br/>Create an account now so we can keep track of your top scores in Cell Break and Meeting Blocks.");
			$('#fb_login').hide();
			$('#fb_registration').show();
			$("#fb_registration").load(prefix+"fb_registration.form.php");
			// get name from fb
			getFbuser()
			$("#pepsi_tab").hide();
			$('.fbCreate').show();
			doFbRegAnimation('login');
		}
	});
}

function getFbuser() {
	FB.ensureInit(function() {
    	FB.Facebook.get_sessionState().waitUntilReady(function () {
        	FB.Facebook.apiClient.users_getLoggedInUser(function(result) { 
        		FB.Facebook.apiClient.users_getInfo(result, ['first_name', 'last_name', 'current_location', 'sex'], function(data) { 
        			$('#first_name').val(data[0].first_name);
        			$('#last_name').val(data[0].last_name);
        			$('#city').val(data[0].current_location.city);
        			$('#postal_code').val(data[0].current_location.zip);
        			$('#state').val(data[0].current_location.state);
        			$('#country').val(data[0].current_location.country);
        			$('#'+data[0].sex).attr('checked', 'checked');
            	});
        	});
    	});
    });
}

function doLogin(form) {
	$.ajax({
		type: "POST",
		dataType: 'json',
		url: prefix+"ajax/request.php?login",
		data: $('#'+form).serialize(),
		success: function(msg){
			if (msg.result) {
				loginOverlay.close();
				$('#login_span').hide();
				$('#logout_span').show();
				nextAlert = "<strong>Success</strong><br />You have successfully logged in.";
				alertOverlay.load();
			} else {
				nextAlert = '<strong>Error</strong><br />Invalid email/password';
				alertOverlay.load();
			}
		}
	})
}

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 doFbRegistration() {
	$.ajax({
		type: "POST",
		dataType: 'json',
		url: prefix+"ajax/request.php?fb_registration",
		data: $('#fbRegisterForm').serialize(),
		success: function(msg){
			if (msg.result) {
				loginOverlay.close();
				$('#login_span').hide();
				$('#logout_span').show();
				nextAlert = "<strong>Success</strong><br />You have successfully logged in.";
				alertOverlay.load();
				
			} else {
//				if (msg.message == 'Missing Required Fields') {
//					getNewCaptcha();
//					
//					nextAlert = "<strong>"+msg.message+"</strong><br />";
//					var errors = msg.errors;
//					
//					jQuery.each(errors, function(i, data) {
//						nextAlert = nextAlert+data+'<br /> ';
//					});
//					
//					alertOverlay.load();
//				}
//				if (msg.message == 'Invalid Captcha') {
//					$("#captcha").load(prefix+"ajax/get_captcha.php");
//					nextAlert = "<strong>"+msg.message+"</strong><br />";
//					var errors = msg.errors;
//					
//					jQuery.each(errors, function(i, data) {
//						nextAlert = nextAlert+data+'<br /> ';
//					});
//					
//					alertOverlay.load();
//				}
//				if (msg.message == 'AlreadyRegistered') {
//					$("#fb_registration").load(prefix+"ajax/already_registered_login.php");
//					$('#fbCreateBtn').attr('onClick', 'doLogin("registrationLogin")');
//					$('#fbCreateTxt').text('Login');
//					doFbLoginAnimation('login');
//				}
				if (msg.message == 'AlreadyRegistered') {
					fbAlreadyRegistered();
//					$('#header_copy').text("Looks like we already have the email address you entered on file."); 
//					$("#fb_registration").load(prefix+"ajax/already_registered_login.php");
//					$('#fbCreateBtn').attr('onClick', 'doLogin("registrationLogin")');
//					$('#fbCreateTxt').text('Login');
//					doFbLoginAnimation('login');
				} else {
					$("#captcha").load(prefix+"ajax/get_captcha.php");
					nextAlert = "<strong>"+msg.message+"</strong><br />";
					var errors = msg.errors;
					
					jQuery.each(errors, function(i, data) {
						nextAlert = nextAlert+data+'<br /> ';
					});
					
					alertOverlay.load();
				}
			}
		}
	})
}

function fbAlreadyRegistered() {
	$('.fbCreate').hide();
	$('.fbLogin').show();
	$('#header_copy').text("Looks like we already have the email address you entered on file."); 
	$("#fb_registration").load(prefix+"ajax/already_registered_login.php");
	doFbLoginAnimation('login');
}

function getNewCaptcha() {
	$("#captcha").load(prefix+"ajax/get_captcha.php");
}

function showPfcRegistration() {
	$('#header_copy').html("<strong>Register Now</strong><br />\nCreate an account now so we can keep track of your top scores in Cell Break and Meeting Blocks.");
	$('#pfc_controls').hide();
	$('#pfc_login').hide();
	$('#pfc_registration').show();
	$("#pfc_registration").load(prefix+"pfc_registration.form.php");
	
	$("#facebook_tab").hide();
	$('.pfcCreate').show();
	doPfcRegAnimation('login');
}

function doPfcRegistration() {
	$.ajax({
		type: "POST",
		dataType: 'json',
		url: prefix+"ajax/request.php?pfc_registration",
		data: $('#pfcRegisterForm').serialize(),
		success: function(msg){
			if (msg.result) {
				loginOverlay.close();
				$('#login_span').hide();
				$('#logout_span').show();
				nextAlert = "<strong>Success</strong><br />You have successfully logged in.";
				alertOverlay.load();
				
			} else {
//				if (msg.message == 'Password Mismatch') {
//					$("#captcha").load(prefix+"ajax/get_captcha.php");
//					nextAlert = "<strong>"+msg.message+"</strong><br />";
//					var errors = msg.errors;
//					
//					jQuery.each(errors, function(i, data) {
//						nextAlert = nextAlert+data+'<br /> ';
//					});
//					
//					alertOverlay.load();
//				}
//				if (msg.message == 'Missing Required Fields') {
//					$("#captcha").load(prefix+"ajax/get_captcha.php");
//					nextAlert = "<strong>"+msg.message+"</strong><br />";
//					var errors = msg.errors;
//					
//					jQuery.each(errors, function(i, data) {
//						nextAlert = nextAlert+data+'<br /> ';
//					});
//					
//					alertOverlay.load();
//				}
//				if (msg.message == 'Error') {
//					$("#captcha").load(prefix+"ajax/get_captcha.php");
//					nextAlert = "<strong>"+msg.message+"</strong><br />";
//					var errors = msg.errors;
//					
//					jQuery.each(errors, function(i, data) {
//						nextAlert = nextAlert+data+'<br /> ';
//					});
//					
//					alertOverlay.load();
//				}
				if (msg.message == 'AlreadyRegistered') {
					$('#header_copy').text("The email address you entered is already associated with a PepsiCo account."); 
					$("#pfc_registration").load(prefix+"ajax/already_registered_login.php");
					$('#pfcCreateBtn').attr('onClick', 'doLogin("registrationLogin")');
					$('#pfcCreateTxt').text('Log In');
					doPfcLoginAnimation('login');
				} else {
					$("#captcha").load(prefix+"ajax/get_captcha.php");
					nextAlert = "<strong>"+msg.message+"</strong><br />";
					var errors = msg.errors;
					
					jQuery.each(errors, function(i, data) {
						nextAlert = nextAlert+data+'<br /> ';
					});
					
					alertOverlay.load();
				}
			}
		}
	})
}

function doFbLoginAnimation(form) {
	$('#'+form).animate({height: "300px"}, 'slow', 'jswing');
	$('#'+form+' .outerBox').animate({height: "265px"}, 'slow', 'jswing');
	$('#facebook').animate({height: "145px"}, 'slow', 'jswing', function(){
		$('.swappable').show('slow');	
	});
	$('#'+form+' .innerBox').animate({height: "245px"}, 'slow', 'jswing');
}

function doPfcLoginAnimation(form) {
	$('#'+form).animate({height: "300px"}, 'slow', 'jswing');
	$('#'+form+' .outerBox').animate({height: "265px"}, 'slow', 'jswing');
	$('#pepsi').animate({height: "130px"}, 'slow', 'jswing', function(){
		$('.swappable').show('slow');	
	});
	$('#'+form+' .innerBox').animate({height: "245px"}, 'slow', 'jswing');
}

function doFbRegAnimation(form) {
	$('#'+form).animate({height: "658px"}, 'slow', 'jswing');
	$('#'+form+' .outerBox').animate({height: "625px"}, 'slow', 'jswing');
	$('#facebook').animate({height: "449px"}, 'slow', 'jswing', function(){
		$('.swappable').show('slow');	
	});
	$('#site_register').animate({height: "475px"}, 'slow', 'jswing');
	$('#'+form+' .innerBox').animate({height: "486px"}, 'slow', 'jswing');
}

function doPfcRegAnimation(form) {
	$('#'+form).animate({height: "669px"}, 'slow', 'jswing');
	$('#'+form+' .outerBox').animate({height: "634px"}, 'slow', 'jswing');
	$('#pepsi').animate({height: "471px"}, 'slow', 'jswing', function(){
		$('.swappable').show('slow');	
	});
	$('#site_register').animate({height: "515px"}, 'slow', 'jswing');
	$('#'+form+' .innerBox').animate({height: "526px"}, 'slow', 'jswing');
}

// fb and standard logout
function doLogout() {
   	var status = FB.Connect.get_status().result;
   	if (status == FB.ConnectState.connected) {
	$.get("ajax/logout.php", function() {
		$("#logout_span").hide();
		$("#login_span").show();
	});
	FB.Connect.logout();
	} else {
		$.get("ajax/logout.php", function() {
		$("#logout_span").hide();
		$("#login_span").show();
	});
	}
}

function updateForm(cd) {
	$('#state_list').load(prefix+'ajax/get_country_subdivs.php?cd='+cd);
}

function doFbShare(score, game) {
	game_id = game;
	FB.ensureInit(function() {
        FB.Facebook.get_sessionWaitable().waitUntilReady(function () {
        	var meetris_feed_id = 82929203589;
        	var cell_break_feed_id = 82931133589;
        	var token;
        	
        	switch (game_id) 
        	{
        		case 1101:
        			//meetris
        			token = {"link":"http://www.energypluscoffee.com","score":score,"images":[{"src":"http://www.energypluscoffee.com/images/fb_meetris.jpg", "href":"http://www.energypluscoffee.com"}]};
        			var dialog = FB.Connect.showFeedDialog(meetris_feed_id, token, null, null, null, null, null, null);
        			return false;
        			break;
        		case 1102:
        			//cell break
        			token = {"link":"http://www.energypluscoffee.com","score":score,"images":[{"src":"http://www.energypluscoffee.com/images/fb_cell_break.jpg", "href":"http://www.energypluscoffee.com"}]};
        			var dialog = FB.Connect.showFeedDialog(cell_break_feed_id, token, null, null, null, null, null, null);
        			return false;
        			break;
        		default:
        			nextAlert = "share error: "+game_id+" - "+score;
        			alertOverlay.load();
        			return false;
        	} 
        });
    });
	
}

function showResults(data){
	var results = '<strong class="green">Results</strong>\n';
	for (i=0; i<data.length; i++){
		results+= '<span class="answerText">' + data[i].answerText + '</span>\n';
		results+= '<div class="barGraph"><div class="barResults" style="width: ' + data[i].answerResults + 'px"></div></div>\n';
		results+= '<span class="answerResults">' + data[i].answerResults + '%</span>\n';
	}
	return results;
}

function processPoll(purl){
	$.ajax({
		type: "POST",
		dataType: 'json',
		url: purl,
		data: $('#surveyForm').serialize(),
		success: function(data){
			$('#survey').contents().remove();
			$('#survey').append(showResults(data));
		}
	});
}
