/*************************************************
	Name: fastapps.js
	Purpose: javascript (including ajax) for fastapps application system. makes extensive use of jquery.
	Author: Barbara Hui
	Date: 2 January 2010
	ChangeLog: 
		1/15/2010-M Dailey-updated messages users see when revising or submitting on review page, 
		1/15/10-MDailey--updated text user sees when they complete registration
	
	
**************************************************/

/************************************************************************************
* create XMLHttpRequest object
************************************************************************************/
/*
var request = null;

function createRequest() {
	try {
		request = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(failed) {
				request = null;
			}
		}
	}
	if (request==null)
		alert("Error creating request object!");
}
*/

/****************************
* authenticate user
****************************/
function authenticate() {
	//tell IE not to cache ajax
	$.ajaxSetup ({
		cache: false
	});
	
	//use ajax to see if user is logged in
	$(function() {
		$.ajax({
			type: "GET",
			url: "includes/authenticate.php", 
			dataType: "xml",
			success: function(xmlData)
			{
				xmlDataSet = xmlData;
				processAuthData();
			},
			error: function()
			{
				alert("ajax error in fastapps/js/fastapps.js, authenticate()");
			}
		});
	});
	
	function processAuthData() {
		isAuthenticated = $(xmlDataSet).find("loggedIn").text();  
		if(isAuthenticated!=1) {
			//if not authenticated, login first
			/* alert('about to run login() from inside processAuthData()'); */
			login();
		} else {
			//if authenticated, start fastapps
			display_logout_btn();
			start_fastapps();
		}
	}
}

/**************************************
* display application
**************************************/
function display_application(){
	//load preliminary application
	
	// @todo: display the correct form depending on configuration (round?)
	// $("div#fastapps_content").load("forms/prelim_form.php");
	$("div#fastapps_content").load("forms/round2_form.php", function()
	{
		embed_video();
	});
}

/**************************************
* embeded linked video
**************************************/
var last_video_key;
function embed_video() {
	var input = $("[name=videouri]");
	var container = $(".video-container");
	var error = $(".video-error");
	
	var re_youtube = /youtube\.com\/watch\?v=([A-Za-z0-9._%-]+)[&\w;=\+_\-]*/i;
	var re_yahoo = /video.yahoo.com\/watch\/(\d+)\/(\d+)/i;
	
	if(!input.val())
		return;
	
	var matches = re_youtube.exec(input.val());
	if(matches = re_youtube.exec(input.val()))
	{
		if(matches[1] == last_video_key)
			return;
		
		container.show();
		error.hide();
		
		last_video_key = matches[1];
		container.show();
		container.show().html(
			'<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/' + matches[1] + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + matches[1] + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>'
		);
	}
	else if(matches = re_yahoo.exec(input.val()))
	{
		if(matches[1] == last_video_key)
			return;
		
		container.show();
		error.hide();
		
		last_video_key = matches[1];
		container.show();
		container.show().html(
			'<object width="480" height="385"><param name="movie" value="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.46" /><param name="allowFullScreen" value="true" /><param name="AllowScriptAccess" VALUE="always" /><param name="bgcolor" value="#000000" /><param name="flashVars" value="id=' + matches[2] + '&vid=' + matches[1] + '&embed=1" /><embed src="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.46" type="application/x-shockwave-flash" width="480" height="385" allowFullScreen="true" AllowScriptAccess="always" bgcolor="#000000" flashVars="id=' + matches[2] + '&vid=' + matches[1] + '&embed=1" ></embed></object>'
		);
	}
	else
	{
		// Invalid video uri.
		container.html("").hide();
		last_video_key = null;
		if(!input.val())
			error.hide();
		else
			error.show();
	}
}

/**************************************
* finalize prelim app
**************************************/
function finalize_prelimForm(app_id){

	$("div#fastapps_feedback").empty();
	$("div#fastapps_content").html("Processing finalization of prelim form...");
	
	//tell browser not to cache ajax
/*
	$.ajaxSetup ({
		cache: false
	});
*/

/*
	$.post(
		"database/finalize_prelim_form.php", 
		{
			app_id: app_id
		},
		function(xmlData){
			finalizePrelimXml = xmlData;
	  		confirm_finalize_prelim();
	  	}
	);
*/
	
	$(function() {
		$.ajax({
			url: "database/finalize_prelim_form.php",
			data: "app_id=" + app_id,
			dataType: "xml",
			success: function(xmlPrelimData)
			{
				finalizePrelimXml = xmlPrelimData;
				confirm_finalize_prelim();
			},
			error: function(xhr,ajaxOptions,thrownError)
			{
				/* alert("xhr.responseText: " + xhr.responseText + " xhr.status: " + xhr.status + " thrownError: " + thrownError); */
				feedbackMsg = "We're sorry, but your browser experienced an AJAX error."
				alert(feedbackMsg);
			}
		});
	});
		
	//confirm that login succeeded
	function confirm_finalize_prelim() {
		var feedbackMsg = '';
  		responseType = $(finalizePrelimXml).find("success").text();
  		/* alert('responseType: ' + responseType); */
  		if(responseType!="1"){
  			//error
  			feedbackMsg = 'Submission of application failed: ' + $(finalizePrelimXml).find("error").text();
  			$("div#fastapps_feedback").html(feedbackMsg);
  			display_application();
  		} else {
  			//start fastapps
  			display_logout_btn();
  			feedbackMsg = 'Your application was successfully submitted.';
  			$("div#fastapps_feedback").empty();
  			$("div#fastapps_content").load("forms/prelim_final_confirm.php");
  		}	
	}			
}


/**************************************
* finalize round2 app
**************************************/
function submit_round2Form(app_id)
{
	
	$(function() {
		$("div#fastapps_feedback").html("Processing...");
		
		// hide the form
		$("div#fastapps_content").hide();
		
		var xml;
		$("form#round2Form").ajaxSubmit(
		{
			url: "database/process_round2_form.php",
			data: "app_id=" + app_id,
			dataType: "xml",
			success: function(xml)
			{
				var feedbackMsg = "";
				var $xml = $(xml);
				var responseType = $xml.find("success").text();
				
				if(responseType!="1")
				{
		  			// error
		  			feedbackMsg = 'Submission of application failed: ' + $xml.find("error").text();
		  			$("div#fastapps_feedback").html(feedbackMsg);
		  		} else {
		  			// success
		  			display_logout_btn();
		  			feedbackMsg = 'Your application was successfully submitted.';
		  			$("div#fastapps_feedback").empty();
		  			$("div#fastapps_content").load("forms/round2_final_confirm.php");
		  		}	
			},
			error: function(xhr,ajaxOptions,thrownError)
			{
				feedbackMsg = "We're sorry, but your browser experienced an AJAX error."
				alert(feedbackMsg);
			},
			complete: function()
			{
				$("div#fastapps_content").show();
			}
		});
	});
}

/**************************************
* start fastapps
**************************************/
function start_fastapps(){
	$("div#fastapps_content").html("in start_fastapps");
	//determine user type, what to show user
	//if applicant, show application
	display_application();
	//if judge, show judge view
	//if public, show pligg
}

/**************************************
* log the user in to fastapps
**************************************/
function login(){
	$("div#logout_btn").html('');
	$("div#fastapps_content").load("forms/login_form.php");
}

/**************************************
* log the user out of fastapps
**************************************/
function logout(){
	//tell browser not to cache ajax
	$.ajaxSetup ({
		cache: false
	});
	
	//use ajax to see if user is logged in
	$(function() {
		$.ajax({
			url: "includes/logout.php",
			dataType: "xml",
			success: function(xmlData)
			{
				xmlDataSet = xmlData;
				processLogoutData();
			},
			error: function()
			{
				alert("ajax error in fastapps/js/fastapps.js, logout()");
			}
		});
	});
	
	function processLogoutData() {
		feedbackMsg = '';
		isLoggedOut = $(xmlDataSet).find("success").text();  
		if(isLoggedOut!=1) {
			//problem logging out; show error
			feedbackMsg = "Error: " + $(processLoginXml).find("error").text();
  			$("div#fastapps_feedback").html(feedbackMsg);
		} else {
			//logged out successfully
			feedbackMsg = "Logout was successful.";
			$("div#fastapps_feedback").html(feedbackMsg);
			/* alert('about to run login() from inside logout()'); */
			login();
		}
	}

}

/**************************************
* remind user of forgotten password
**************************************/
function passwd_remind() {
	$("div#fastapps_feedback").empty();
	$("div#fastapps_content").load("forms/passwd_remind_form.php");
}

/**************************************
* process login form
**************************************/
function process_login_form(email,password) {
	$("div#fastapps_feedback").empty();
	$("div#fastapps_content").html("Processing login form...");

	//check values against database
	
	//tell browser not to cache ajax
	$.ajaxSetup ({
		cache: false
	});

	$.post(
		"database/process_login_form.php", 
		{
			email: email,
			password: password
		},
		function(xmlData){
			/* alert('back from process_login_form.php'); */
			processLoginXml = xmlData;
	  		confirm_login();
	  	}
	);

	//confirm that login succeeded
	function confirm_login() {
		var feedbackMsg = '';
  		responseType = $(processLoginXml).find("success").text();
  		/* var responseType = processLoginXml.getElementsByTagName("success")[0].childNodes[0].nodeValue; */
  		/* alert('responseType: ' + responseType); */
  		if(responseType!="1"){
  			//error
  			feedbackMsg = 'Login Failed: ' + $(processLoginXml).find("error").text();
  			$("div#fastapps_feedback").html(feedbackMsg);
  			/* alert('about to run login() from inside process_login()'); */
  			login();
  		} else {
  			//start fastapps
  			display_logout_btn();
  			feedbackMsg = 'Welcome to the DMLC Application System.';
  			$("div#fastapps_feedback").html(feedbackMsg);
  			$("div#fastapps_content").html("login successful...");
  			start_fastapps();	
  		}	
	}	
}

/**************************************
* process password reminder form
**************************************/
function process_passwd_remind_form(email) {
	$("div#fastapps_feedback").empty();
	$("div#fastapps_content").html("Processing password reminder form...");
	
	//tell browser not to cache ajax
	$.ajaxSetup ({
		cache: false
	});

	$.post(
		"database/process_passwd_remind_form.php", 
		{
			email: email
		},
		function(xmlData){
			processPasswdRemindXml = xmlData;
	  		confirm_passwd_remind();
	  	}
	);

	//confirm that login succeeded
	function confirm_passwd_remind() {
		var feedbackMsg = '';
  		responseType = $(processPasswdRemindXml).find("success").text();
  		if(responseType!="1"){
  			//error
  			feedbackMsg = 'Password retrieval failed: ' + $(processPasswdRemindXml).find("error").text();
  			$("div#fastapps_feedback").html(feedbackMsg);
  			$("div#fastapps_content").load("forms/passwd_remind_form.php");
  		} else {
  			feedbackMsg = 'Your password has been emailed to ' + $(processPasswdRemindXml).find("email").text();
  			$("div#fastapps_feedback").html(feedbackMsg);
  			$("div#fastapps_content").html("password reminder successful...");
  			login();	
  		}	
	}	

}

/**************************************
* process preliminary round 1 application form
**************************************/
function process_prelim_form(revision,awardtype,collab1_firstname,collab2_firstname,collab3_firstname,collab4_firstname,collab5_firstname,institution,annual_operating_budget,proj_title,proj_brief_desc,proj_long_desc,tag1,tag2,tag3,tag4,tag5,req_budget,signature) {

	if(revision==1) {
		revise = 1;
	} else {
		revise = 0;
	}

	//write values to database
	//tell browser not to cache ajax
	$.ajaxSetup ({
		cache: false
	});
	
	$.post(
		"database/process_prelim_form.php", 
		{
			revise: revise,
			awardtype: awardtype,
			collab1_firstname: collab1_firstname,
			collab2_firstname: collab2_firstname,
			collab3_firstname: collab3_firstname,
			collab4_firstname: collab4_firstname,
			collab5_firstname: collab5_firstname,
			institution: institution,
			annual_operating_budget: annual_operating_budget,		
			proj_title: proj_title,
			proj_brief_desc: proj_brief_desc,
			proj_long_desc: proj_long_desc,
			tag1: tag1,
			tag2: tag2,
			tag3: tag3,
			tag4: tag4,
			tag5: tag5,
			req_budget: req_budget,
			signature: signature
		},
		function(xmlData){
			processPrelimFormXml = xmlData;
	  		confirm_prelim();
	  	}
	);
		
	//confirm
	function confirm_prelim() {
		var feedbackMsg = '';
  		responseType = $(processPrelimFormXml).find("success").text();
  		/* alert(responseType); *///for testing
  		if(responseType!="1"){
  			feedbackMsg = "Error: " + $(processPrelimFormXml).find("error").text();
  		} else {
  			if(revise==1){
  				feedbackMsg = "Your application has been updated, but IT HAS NOT YET BEEN SUBMITTED. Please take a moment to thoroughly review your application. NO changes to your application can made after final submittal. After thorough review, please click 'FINISH' below to finalize your application. You should receive a confirmation email upon successful application.";
  			} else {
  				feedbackMsg = "Your application has been saved, but IT HAS NOT YET BEEN SUBMITTED. Please take a moment to thoroughly review your application. NO changes to your application can made after final submittal. After thorough review, please click 'FINISH' below to finalize your application. You should receive a confirmation email upon successful application.";
  			}		
  		}
  		$("div#fastapps_feedback").html(feedbackMsg);	
  		$("div#fastapps_content").html("Done processing preliminary app form...");
  		display_application();
	}	
}

/**************************************
* process registration form
**************************************/
function process_reg_form(revision) {
	
	if(revision==1) {
		revise = 1;
	} else {
		revise = 0;
	}
	
	//get values from signupForm
	firstname = $("#firstname").val();
	lastname = $("#lastname").val();
	email = $("#email").val();
	password = $("#password").val();
	country = $("#country").val();
	phone = $("#phone").val();
	
	//tell browser not to cache ajax
	$.ajaxSetup ({
		cache: false
	});
	//write values to database
	$.post(
		"database/process_reg_form.php", 
		{
			revise: revise,
			firstname: firstname,
			lastname: lastname,
			email: email,
			password: password,
			country: country,
			phone: phone
		},
		function(xmlData){
			processRegFormXml = xmlData;
	  		confirm_reg();
	  	}
	);
	
	function confirm_reg() {
		var feedbackMsg = '';
  		responseType = $(processRegFormXml).find("success").text();
  		/* alert(responseType); *///for testing
  		if(responseType!="1"){
  			//error
  			feedbackMsg = "Error: " + $(processRegFormXml).find("error").text();
  			$("div#fastapps_feedback").html(feedbackMsg);
  		} else {
  			if(revise==1) {
  				feedbackMsg = "Your application has been updated. Please click 'Submit' at bottom of page to finalize.";
  				$("div#fastapps_feedback").html(feedbackMsg);
  				display_application();
  			} else {
	  			feedbackMsg = "Thank you for registering with the Digital Media and Learning Competition. ";
	  			feedbackMsg += "We greatly appreciate your interest in this year's Competition. ";
	  			feedbackMsg += "A confirmation email has been sent to the account you used to register. ";
	  			feedbackMsg += "You may now log into the system to fill out an application.";  	
	  			$("div#fastapps_feedback").html(feedbackMsg);	
  				login();		
  			}		
  		}
  		
	}	  		
}

/**************************************
* revise password info
**************************************/
function revise_password() {
	$("div#fastapps_feedback").empty();
	$("div#fastapps_content").html("in revise password - Still working on this. BLH.");
}

/**************************************
* revise prelim info
**************************************/
function revise_prelim_form() {
	$("div#fastapps_feedback").empty();
	$("div#fastapps_content").html("loading. please wait...");
	$("div#fastapps_content").load("forms/prelim_form.php?revise=1");
}

/**************************************
* revise registration info
**************************************/
function revise_reg_form() {
	$("div#fastapps_feedback").empty();
	$("div#fastapps_content").html("loading. please wait...");
	$("div#fastapps_content").load("forms/reg_form.php?revise=1");
}

/**************************************
* user registration
**************************************/
function registration() {
	$("div#fastapps_feedback").empty();
	$("div#fastapps_content").load("forms/reg_form.php");
}

/**************************************
* display logout button
**************************************/
function display_logout_btn() {
	$("div#logout_btn").html('<a href="#" onclick="logout();">LOGOUT</a>');
}

/**************************************
* on entering page, do this
**************************************/
$(document).ready(function(){
	authenticate();
});