// MAIN FUNCTIONS
	function showDialogConfirm(str,strtitle,targetURL) {

		var c = $('body').append('<div></div>').find(':last');
		
		$(c).dialog('destroy');
		$(c).show();
		$(c).html(str);
		$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
		
		$(c).dialog({
			open:function() {
				$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
			},
			bgiframe: true,
			modal: true,
			title: strtitle,
			closeOnEscape: true,
			draggable: false,
			buttons: {
				Ok: function() {
					window.location.href = targetURL;
					}
			}
		});
		return false;
	}

	function showDialogError(str,strtitle) {

		var e = $('body').append('<div></div>').find(':last');
		
		$(e).dialog('destroy');
		$(e).show();
		$(e).html(str);
		
		$(e).dialog({
			open:function() {
				$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
			},
			bgiframe: true,
			modal: true,
			title: strtitle,
			closeOnEscape: true,
			draggable: false,
			buttons: {
				Ok: function() {
					$(this).dialog('destroy');
					}
			}
		});
		return false;
	}
	
	function processAjaxPost(confirmationMessage, errorMessage, post_url, formData, targetURL){
		$.post(post_url, formData, function(data){
			if (data.verify == 1) {
				if(targetURL){
					showDialogConfirm(data.msg, confirmationMessage, targetURL);							
				}
				else {
					showDialogError(data.msg, confirmationMessage);
					$(this).dialog('destroy');
				}
			}
			else {
				showDialogError(data.msg, errorMessage);
				$(this).dialog('destroy');
			}
			return false;
		},'json');
	};
	
	function processAjaxGet(confirmationMessage, errorMessage, get_url, targetURL){
		$.get(get_url, function(data){
			if (data.verify == 1) {
				if(targetURL) {
					showDialogConfirm(data.msg, confirmationMessage, targetURL);
				}
				else {
					showDialogError(data.msg, confirmationMessage);
					$(this).dialog('destroy');					
				}
			}
			else {
				showDialogError(data.msg, errorMessage);
				$(this).dialog('destroy');
			}
			return false;
		},'json');
	};
	
	function getSnippet(title, snippet_path, width, height, cb){
		snippet_dialog = $('body').append('<div></div>').find(':last');

		$(snippet_dialog).show();
		$(snippet_dialog).html('Loading...');
		$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
		
		$(snippet_dialog).dialog({
			open:function() {
				$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
			},
			bgiframe: true,
			modal: true,
			title: title,
			closeOnEscape: true,
			draggable: false,
			width: width,
			height: height
		});
		
		$.get(snippet_path, function(data) {
			$(snippet_dialog).html(data);
			if(typeof cb === 'function') {
				cb();
			}
		});
	};
	
	function userConfirmation(text){

		confirmation_dialog = $('body').append('<div></div>').find(':last');

		$(confirmation_dialog).show();
		$(confirmation_dialog).html('Loading...');
		$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
		
		$(confirmation_dialog).dialog({
			open:function() {
				$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();
			},
			bgiframe: true,
			modal: true,
			title: 'Please confirm your selection',
			closeOnEscape: false,
			draggable: false
		});
		
		$(confirmation_dialog).html(text);
	};	
	
	function saveAccount(type) {
		//SUBMITS THE FORM TO CREATE THE NEW ACCOUNT
		var form_data = {
			handle: $('#create_account_form [name=handle]').val(),
			password: $('#create_account_form [name=password]').val(),
			re_password: $('#create_account_form [name=re_password]').val(),
			firstname: $('#create_account_form [name=firstname]').val(),
			lastname: $('#create_account_form [name=lastname]').val(),
			email: $('#create_account_form [name=email]').val(),
			promo: $('#create_account_form [name=promo]').val(),
			recaptcha_challenge_field: $('#create_account_form [name=recaptcha_challenge_field]').val(),
			recaptcha_response_field: $('#create_account_form [name=recaptcha_response_field]').val(),
			agreement: $('#create_account_form [name=agreement]').attr('checked')
		};
		// required fields
		if(!form_data.handle || !form_data.password || !form_data.re_password || !form_data.firstname || !form_data.lastname || !form_data.email || !form_data.recaptcha_response_field){
			showDialogError('Please complete all fields', 'Form Error');
			return;
		}
		// password confirmation
		if(form_data.password != form_data.re_password){
			showDialogError('Your passwords must match', 'Form Error');
			return;
		}
		// checkbox agreement
		if(!form_data.agreement){
			showDialogError('You must accept EZClassSites.com License and Terms of Use to create an account', 'Form Error');
			return;
		}
		// remove plaintext password
		delete form_data.re_password;
		// hash password password
		form_data.password_sha1 = hex_sha1(form_data.password);
		// remove plaintext password
		delete form_data.password;
//		console.log(form_data);
		$.post('/main/main/save_account&type=' + type, form_data, function(data) {
			//ACCOUNT CREATION SUCCESSFUL
			if (data.verify >= 1) 
			{	
				//AJAX CALL TO LOG USER IN
				handle = data.handle;
				password_sha1 = data.password_sha1
				$.get('/main/login/login?us_handle='  + handle + '&password_sha1=' + password_sha1, function(result) {
					//THE USER WAS SUCCESSFULLY LOGGED IN
					// Verify values: 1 = Teacher, 2 = Student, 3 = Parent, 4 = Admin
					if (result.verify == 1) 
					{
						showDialogConfirm(data.msg, 'New Account Created', '/tools/classrooms/#first-login');
					}
					else if (result.verify > 1)
					{
						showDialogConfirm(data.msg, 'New Account Created', '/tools/cp/');
					}
					//THE USER COULD NOT BE LOGGED IN
					else
					{
						showDialogError(result.msg, 'Sign In Error');
					}
				}, 'json');
			}
			else //ACCOUNT CREATION ERROR
			{
				Recaptcha.create("6LdZAr4SAAAAAGFd4UsMxRkrD650EMrfJn1EW5MX", 'reCaptcha');
				//Recaptcha.create("6LfxtL4SAAAAADUOqwuab8XOcPblCpGX5X5j0zOX", 'reCaptcha'); // ezclasssites.com.local
				showDialogError(data.msg, 'Account Creation Error');
			}
		}, 'json');
	}
	
	// added below to redirect after uploaded
	function attachCallbacks(Uploader) {
		Uploader.bind('FileUploaded', function(up, file, response) {
			var obj = jQuery.parseJSON(response.response);
			if(obj.verify != 1)
		  	{
		  		up.stop();
				showDialogConfirm(obj.msg, 'File Upload Error', '/tools/billing/purchase_storage');
			}
		});
		Uploader.bind('UploadComplete', function(uploader, files) {
			showDialogError('Your files were upload successfully', 'Files Uploaded');
		});
	}
	
$(function() {
	
	// PROCESS SIGN IN REQUEST
	$('#sign_in').click(function() {
		$('#sign_in_form').submit(); // trigger form submission since the button they clicked is not a submit button
		return false;
	});
	$('#sign_in_form').bind('submit', function() { // when form is submited (by hitting enter when focused on a field or the above trigger)
		var temp_dialog = $('<div></div>').appendTo('body').dialog({
			modal: true
		}).text('Please wait while we log you in...');
		//$(temp_dialog).dialog('close');
		//SUBMITS THE FORM TO VALIDATE THE USER
		$.post('/main/login/login', {
			'us_handle': $('#us_handle').val(),
			'password_sha1': hex_sha1($('#us_password').val())
		}, function(data) {
			//TEACHER HAS LOGGED IN
			if (data.verify == 1) 
			{
				window.location.href = '/tools';
			}
			else if (data.verify == 2) 
			{
				window.location.href = '/tools';
			}
			else if (data.verify == 3)
			{
				window.location.href = '/tools';
			}
			else if (data.verify == 4)
			{
				window.location.href = '/admin';
			}
			else if (data.verify == 5)
			{
				window.location.href = '/tools/billing/manage_profile';
			}
			else
			{
				$(temp_dialog).dialog('close');
				showDialogError(data.msg, 'Sign In Error');
			}
		}, 'json');
		return false; // must return false to stop event propagation (which often will cause a page reload)
	});
	
	// PROCESS SIGN OUT REQUEST
	$('#sign_out').click(function() {
			$.get('/main/login/logout', function(data) {				
					window.location.href = '/';		
			});
	});
	
	// PROCESS CREATE NEW TEACHER ACCOUNT REQUEST
	$('#create_teacher').click( function() {
		type = 'T';
		saveAccount(type);
	});
	
	// PROCESS CREATE NEW PARENT ACCOUNT REQUEST
	$('#create_parent').click( function() {
		type = 'P';
		saveAccount(type);
	});
	
	// PROCESS CREATE NEW STUDENT ACCOUNT REQUEST
	$('#create_student').click(function() {
		type = 'S';
		saveAccount(type);
	});
	
	$('#create_lead').click(function() {
		$.post('/main/main/save_lead', $('#create_lead_form').serialize(), function(data) {
			//LEAD CREATION SUCCESSFUL
			if (data.verify == 1) 
			{	
				showDialogConfirm(data.msg, 'Information Saved', '/main/main/district_and_school_websites');
			}
			//ACCOUNT CREATION ERROR
			else
			{
				Recaptcha.create("6LdZAr4SAAAAAGFd4UsMxRkrD650EMrfJn1EW5MX", 'reCaptcha');
				// Recaptcha.create("6LfxtL4SAAAAADUOqwuab8XOcPblCpGX5X5j0zOX", 'reCaptcha'); // ezclasssites.com.local
				showDialogError(data.msg, 'Lead Creation Error');
			}
		}, 'json');
	});
	
	$("#user_list").autocomplete({
		minLength: 2,
		source: "/tools/search/search_existing_partnerships",
		select: function(event, ui) {
			if(ui.item.id != 0) {
				window.location = '/tools/whiteboard?id=' +  ui.item.id;				
			}
		}
	});
	
	$('#user_list').focus(function() {
		$(this).val('');
	});
	
	//Legacy login processing
	$('#legacy_login').click(function() {
		//Get users login info
		$.get('/tools/legacy', function(data) {
			if (data.verify == 1) 
			{
				var form_data = {
					login_user_name: data.us_handle,
					login_user_password: data.us_password
				};
				
				//Redirect user
				window.open('http://legacy.ezclasssites.com/teacher?_func=login&login_user_name=' + data.us_handle + '&login_user_password=' + data.us_password);
			}
			else
			{
				showDialogError('There was a problem logging you into our legacy account.  Please try again and if the problem persist contact customer support', 'Legacy Login In Error');
			}
		}, 'json');		
	});

	// check hash tags for directives
	var g = $('body').append('<div></div>').find(':last');
	
	$(g).dialog({
		bgiframe: true,
		modal: true,
		autoOpen: false,
		title: 'Classroom Requirement Not Met',
		buttons: {
			'Okay': function() {
				$(this).dialog('close');
			}
		}
	});
	
	var hash = window.location.hash.split(':'); // example http://ezclasssites.local/library#view-details:analytics
	switch(hash[0]){
		case '#classrooms-required':
			if(hash[1] > 1) {
				$(g).dialog('open');
				$(g).html('This tool requires you to have ' + hash[1] + ' active classrooms.  You are now being redirected to the classroom tool so that you can activate/create the classrooms required.');
			}
			else {
				$(g).dialog('open');
				$(g).html('EZClassSites.com requires you to have ' + hash[1] + ' active classroom.  You are now being redirected to the classroom tool so that you can activate/create the classrooms required.');				
			}
			break;
			
		case '#first-login':
			$(g).dialog('open');
			$(g).html('Welcome to EZClassSites.com!  The site requires you to have at least 1 active classroom.  You will now be directed to the classroom tool so that you can create your first classroom!');
			break;
			
		case '#billing-suspended':
			$(g).dialog('open');
			$(g).html('Your account is currently suspended because we were unable to process your credit card.  You will now be redirected to the billing center where you can review the charges and update your credit card.');
			break;			
	}
	
	// show selected classroom
	$('#preview_classroom').bind('change', function() {
		var cr_url = $('#preview_classroom option:selected').val()
		if(cr_url != 0)
		{
			window.open('http://'+window.location.hostname+'/'+cr_url);
			$('#preview_classroom').val(0);
		}
	})
	
	// attempt to view classroom with generic login info
	$('#site_login').click(function() {
		var url = $('#site_login_form [name=url]').val();
		$.post()
		processAjaxPost('Site Login Successful', 'Site Login Error', '/main/login/site_login', $('#site_login_form').serialize(), '/'+url);
		return false;
	});
	
	//Process forgot password form
	$('#submit_forgot_password_form').click(function() {
		//Set variables
		var form_data = {
			us_handle: $('#forgot_password_form [name=us_handle]').val()
		};
		
		processAjaxPost('Password Reset Email Sent', 'Error', '/main/main/send_password_reset_email', form_data, '/');
	});
	
	//Process password reset form
	$('#submit_password_reset_form').click(function() {
		var form_data = {
			password: $('#forgot_password_form [name=password]').val(),
			re_password: $('#forgot_password_form [name=re_password]').val(),
			token: $('#forgot_password_form [name=token]').val()
		};
		
		var errors = new Array();

		// required fields
		if(!form_data.password) {
			errors = errors + 'You must enter in a new password.<br />';
		}
		if(!form_data.re_password) {
			errors = errors + 'You must enter a confirmation password.<br />';
		}
		if(form_data.password != form_data.re_password) {
			errors = errors + 'Your password and confirmation password must match.<br />';
		}
		//Check for errors and proceed accordingly
		if(errors.length != 0) {
			showDialogError(errors, 'Error Processing Request');
			$(this).dialog('destroy').empty();
		}
		else {
			processAjaxPost('Password Reset', 'Error', '/main/main/reset_password', form_data, '/');
		}
		return false
	});
	
	//Prevent IE from caching ajax calls
	$.ajaxSetup({ cache: false });
});
