var sfdc_campaignid = '70150000000Eq7dAAC';
var student_account_base = 'www.gowithcea.com/Account/';

var default_base = 'http://' + student_account_base;
var secure_base = 'https://' + student_account_base;

var redirect_url = '';
var referrer_url = document.referrer;
var current_url = location.href;

var is_student = false;

if (current_url.indexOf('?') > -1)
{
	var temp = new Array();
	temp = current_url.split('?');
	query_string = '?' + temp[1];
	
	is_student = (query_string.indexOf('s=1') > -1) ? true : false;
	query_string = query_string.replace('?s=1','').replace('&s=1','')
}

$(document).ready(function() {
	$('#accountForm').attr('action', secure_base + 'ProcessAccount.aspx' + query_string);
//MULTI-SELECT
	//$("#session_of_interest").attr("multiple", "multiple");
	//$("#destination_of_interest").attr("multiple", "multiple");
//VALIDATION
	jQuery.validator.addMethod("inuse", function(value, element, params) {
		return !check_email(value);
	}, $.format("Email already in use. Please enter another"));

	$('#accountForm').validate({  
		wrapper: 'div class=errorMessage',  
		/*    errorElement: 'div',  
		wrapper: 'div',  
		errorPlacement: function(error, element) {  
			offset = element.offset();              
			error.insertBefore(element)              
			error.addClass('message');  // add a class to the wrapper              
			error.css('position', 'absolute');              
			error.css('left', offset.left + element.outerWidth());              
			error.css('top', offset.top);       
		},   */  
		//errorLabelContainer: '#errorBox',  
		//wrapper: 'li',  
		rules: {  
			account_type: { required: true },
			first_name: { required: true },  
			last_name:  { required: true },  
			email: {  
				required: true,  
				email: true,  
				inuse: {  
					email: "#email"  
				}
			},
			password: "required",
			password_confirm: {
				equalTo: "#password"
			},
			phone: { required: true },
			year_in_school: { required: true },
			state_of_institution: { required: true },
			institution: { required: true },
			destination_of_interest: { required: true },
			session_of_interest: { required: true },   
			user_specified_referrer: { required: true }
		},
		messages: {  
			account_type: ' Please select an account type',
			first_name: ' Please enter your first name',  
			last_name: ' Please enter your last name',  
			email: {  
				required: ' Please enter your email address',  
				email: ' Please enter a valid email address'  
			},
			password: ' Please enter your password',
			password_confirm: {
				equalTo: ' Passwords did not match. Please re-confirm password.'
			},
			phone: ' Please enter your complete phone number',
			year_in_school: ' Please indicate your year in school',
			state_of_institution: ' Please select the location of your University',
			institution: ' Please select your College/University',
			destination_of_interest: ' Please select your primary study abroad destination of interest',
			session_of_interest: ' Please select your primary study abroad session of interest',
			user_specified_referrer: ' Please select how you heard about CEA'
		}
	});
//Redirect back to student from a selected account type form prevents visitor from having to select Student again
	if (is_student)
	{
		$('#account_type_student').attr("checked","checked");
	}
	
//Redirect to login page based on selected account type
	$(".account_type").click(function(){
		var file = '';
		
		university = (current_url.indexOf('newhaven')>-1) 
						? 'Newhaven'
						: (current_url.indexOf('arizona')>-1) 
							? 'Arizona'
							: (current_url.indexOf('utk')>-1) 
								? 'utk'
								: false;

		switch($("input[@name='account_type']:checked").val())
		{
			case '50':
				if (typeof(non_student_form) != 'undefined')
				{
					//Kelly Mart did not want student selected by default.  To compenate for a switch from a non student page it will pass a S=1 on the query string to 
					//inform the reload that it needs to select the student option.  It is striped off on the reload.  If this were not in place the selected student option would be lost on reload.
					query_string = (query_string) ? query_string + '&s=1' : '?s=1';
					file = (!university) ? 'MyCEA_Account' : university;					
					location.href = '/' + file + '.html' + query_string;
				}
				break;
			case '51':
				file = (!university) ? 'foreign-create' : 'MyCEA_Account';
				location.href = '/' + file + '.html' + query_string;
				break;				
			case '52':
				file = (!university) ? 'parent-create' : university + '-parents';
				location.href = '/' + file + '.html' + query_string;
				break;
			case '53':
				file = (!university) ? 'advisor-create' : university + '-educators';
				location.href = '/' + file + '.html' + query_string;
				break;
		}
	});	
	
//Compensates for IE's 	lack of expansion for options wider than the width of the select
	if (window.ActiveXObject)
	{
		$(function() {  
			$("#institution")
				.focus(function(){  
					$(this)  
						.data("origWidth", $(this).css("width"))  
						.css("width", "auto");  
				})  
				.blur(function(){  
					$(this).css("width", $(this).data("origWidth"));  
				});  
		});
	}
//AJAX Validation  
	$('#state_of_institution').bind('change', function(event) {
		var sel = this[this.selectedIndex].value;
		if (sel != '') {
			load_institutions(sel);
		}
		else {
			$('#institution').empty().append($('<option></option>').val('').html('[Choose One]'));
			//$('#institution').append($('<option></option>').val('-1').html('Other'));
			$('#institution').append($('<option></option>').val('-2').html('Not In School'));
		}
	});

//MASKS 9 = [0-9] a = [A-Za-z] * = [0-9A-Za-z]
	$('#phone').mask('(999) 999-9999');
//LOAD HIDDEN FIELDS
	$('#referrer_url').val(referrer_url);  
	$('#redirect_url').val(redirect_url);
	$('#current_url').val(current_url);
	$('#sfdc_campaignid').val(sfdc_campaignid);

	collectValues($('#accountForm input:hidden'), $('#hidden_fields'), 'hidden');
	collectValues($('#accountForm :input'), $('#multi_select'), 'multi');

	collectValues($('#state option'), $('#state_values'), 'option');
	collectValues($('#gpa_range option'), $('#gpa_range_values'), 'option');
	collectValues($('#country option'), $('#country_values'), 'option');
	collectValues($('#destination_of_interest option'), $('#destination_of_interest_values'), 'option');
	collectValues($('#session_of_interest option'), $('#session_of_interest_values'), 'option');
	collectValues($('#state_of_institution option'), $('#state_of_institution_values'), 'option');
	collectValues($('#year_in_school option'), $('#year_in_school_values'), 'option');
	collectValues($('#major_1 option'), $('#major_1_values'), 'option');
	collectValues($('#user_specified_referrer option'), $('#user_specified_referrer_values'), 'option');
});
      
function collectValues(items, outField, fieldType)  
{  
	var x = ''
	for(i = 0;i < items.length;i++)
	{
		switch(fieldType)
		{
			case 'option':
				if (i>0)
					x += items[i].value + ',' + items[i].text + '|';
				break;
			case 'hidden':
				x += items[i].id + ','
				break;
			case 'multi':
				if (items[i].type == 'select-multiple')
					x += items[i].id + ','
				break;
		}
	}
	outField.val(x.substring(0,x.length-1));
}  

function load_institutions(sel) {
	var options = {
		type: 'POST',
		url: default_base + 'Ajax.aspx/ReturnInstitutions',
		data: "{state : '" + sel + "'}",
		contentType: 'application/json; charset=utf-8',
		dataType: 'json',
		success: function(response) {
			var data = eval('(' + response.d + ')');
			$('#institution').empty().append($('<option></option>').val('').html('[Choose One]'));
			//$('#institution').append($('<option></option>').val('-1').html('Other'));
			$.each(data.opts, function(index, items) {
				$('#institution').append('<option value="'
					+ items.val
					+ '">' + items.text
					+ '</option>');
			});
			$('#institution').append($('<option></option>').val('490500').html('Not In College'));
			collectValues($('#institution option'), $('#institution_values'), 'option');
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			//alert(XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText);
		}
	};
	$.ajax(options);
}  
 
function check_email(sel) {
	var options = {
		type: 'POST',
		url: default_base + 'Ajax.aspx/LoginExists',
		data: "{email : '" + sel + "'}",
		contentType: 'application/json; charset=utf-8',
		dataType: 'json',
		async: false,
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			//alert(textStatus);  
		}
	}
	var inuse = eval('(' + $.ajax(options).responseText + ')');  
	return inuse.d  
}
