var pageid = jQuery.url.param("id");

$(document).ready(function () {
    initialize();

var reg101_status = 0;

if (pageid == '1028') {
	reg101Start();
} 

if (pageid == '1025' || pageid == '1148') {
	Custom_Webform_Validate(pageid);
}

if (pageid == '1186') {
	ExploreStart();
}

if (pageid == '1122') {
	EarlyAdmStart();
}


// Custom jQuery Validation Methods

jQuery.validator.addMethod("alpha", function(value, element) {return this.optional(element) || value == value.match(/^[a-zA-Z ]+$/);},"Only Characters Allowed.");
jQuery.validator.addMethod("alphaspecial", function(value, element) {return this.optional(element) || value == value.match(/^[-a-zA-Z,_ ]+$/);}, "Only letters & Space/underscore/comma Allowed.");

jQuery.validator.addMethod("wordCount",
   function(value, element, params) {
      var typedWords = jQuery.trim(value).split(' ').length;
 
      if(typedWords <= params[0]) {
         return true;
      }
   },
   jQuery.format("Only {0} words allowed.")
);	
});

function initialize() {
	$(".expand-info").hide();
	$(".collapse").hide();

	$(".expand").bind("click",  function () { 
		var index = $(".expand").index(this);
		$("div.expand-info").eq(index).toggle('fast');
		$(this).hide();
		$("a.collapse").eq(index).toggle();
	} );

	$(".collapse").bind("click",  function () { 
		var index = $(".collapse").index(this);
		$("div.expand-info").eq(index).toggle('fast');
		$(this).hide();
		$("a.expand").eq(index).toggle();
	} );

	$("a.PaymentLink").click(function () {
		$("div.expand-info:eq(3)").toggle();
		$(".expand:eq(3)").toggle();
		$(".collapse:eq(3)").toggle();
	});

	
	var anchor = jQuery.url.attr("anchor");
	if (anchor != null) {
		$("div[id=" + anchor + "]").toggle();
		$("div[id=" + anchor + "]").prev("p").children(".expand").toggle();
		$("div[id=" + anchor + "]").prev("p").children(".collapse").toggle();
	}

	if (pageid == '157') {
		
		$.fn.clearField = function() {
			return this.focus(function() {
				if( this.value == this.defaultValue ) {
					this.value = "";
				}
			}).blur(function() {
				if( !this.value.length ) {
					this.value = this.defaultValue;
				}
			});
		};	

		$("#getcountry").submit(function () {
			/*alert('test');*/
			$.post('http://www.registrar.ualberta.ca/country_req.cfm', $("#getcountry").serialize(), function(data,status){
				$("div#country_results").remove();
				$("#getcountry").after(data);
				/*alert('test');*/

			});
			return false
		});

		//Change this to the ID of the country input you want to be autocompleted
		//make sure to update the CSS for this ID as well
		var ac_country = "#ac_country";

		//options are the same as the JQuery Autocomplete plugin
		$(ac_country).autocomplete(countries, {
			minChars: 2,
			width: 320,
			matchContains: true,
			scroll: true,
			max:0,
			formatItem: function(row, i, max, term) {
				return "<img src='../javascript/jquery/countries_images/flags/" + row.code.toLowerCase() + ".gif'> " + row.name;
			},
			formatResult: function(row) {
				return row.name;
			},
			formatMatch: function(row, i, max) {
				return row.name;
			}
		});

		$(ac_country).after($(ac_country).clone().attr('value','').attr('size','2').attr('id', $(ac_country).attr('id') + '_hidden'));
		$(ac_country).removeAttr('name', '').clearField();
		$(ac_country).result(function(event, data, formatted) {
			if(data) {
				$(ac_country + '_hidden').val(data.code);
			}
			var src = '../javascript/jquery/countries_images/flags/' + data.code.toLowerCase() + '.gif';
			$(ac_country).css('backgroundImage', 'url(' + src + ')');
		});

		/*function sendForm() {
		 $.post('http://www.registrar.ualberta.ca/country_req.cfm', $("#getcountry").serialize(), function(data,status){
			$("#result").html(data)
		
			});
			return false
		}*/
	}

	
}

/* CUSTOM WEB FORM */

function Custom_Webform_Validate(pageid) {

	
	if (pageid == 1025) {
		$("#custom_webform").validate({
			debug : true,
			rules: {
				fullname: "required",
				studentnumber: {
					required: true,
					digits: true
				},
				scholarship: {
					required: true,
					minlength: 1
				},
				resident: {
					required: true,
					minlength: 1
				}
			},
			messages: {
				fullname: "Please enter your fullname",
				studentnumber: "Please enter your Student Number",
				scholarship : "Please choose to accept or decline the scholarship",
				resident: "Please select one Residence option"
			},
			submitHandler: function() { Custom_Webform_Submit() }
		});
	}	
	
	if (pageid == 1148) {
		$("span#augustana_major_minor").hide();
		$("div#resources_expenses").hide();
		$("#datepicker").datepicker({ defaultDate: -6205, dateFormat: 'yy-mm-dd' });
		
		$("select#firstchoice").change(function () {
			if ($("select#firstchoice").val() == "Augustana") {
				$("span#augustana_major_minor").show();
			} else {
				$("span#augustana_major_minor").hide();
			}
		});
		
		$("#awardsfinancialneedcriteria").click(function () {
		if ($(this).is(":checked")) {
			$("div#resources_expenses").show();
		} else {
			$("div#resources_expenses").hide();
		}
		
		});
		
		$("#custom_webform").validate({
			debug : false,
			rules: {
				firstname: "required",
				lastname: "required",
				uofaid: {
					required: true,
					maxlength: 7,
					number: true,
					digits: true
				},
				dateofbirth: {
					required: true
				},
				gradhighschool: "required",
				gradcityprov: "required",
				hometown: "required",
				livedhometown: "required"
			},
			messages: {
				firstname: "Please enter your first name",
				lastname: "Please enter your last name",
				uofaid: "Please enter your U of A ID (a maximum of seven numbers)"
			},
			submitHandler: function() { Custom_Webform_Submit() }
		});
	}
}

function Custom_Webform_Submit() {

$("#custom_webform").css("display","none");

$("#custom_webform input").removeAttr("disabled");

$("#custom_webform input[type=checkbox]:not(:checked)").each(function() {
           $(this).val("no");
           $(this).attr("checked", true);
});


//values = $("#custom_webform").serializeArray();

/*values = values.concat(
	$("#custom_webform input[type=checkbox]:not(:checked)").map(
		function() {
			return {"name": this.name, "value": this.value}
		}).get()
	);*/

//alert(values);
// debug
//var checkdata = $("#custom_webform").serialize();
//alert(checkdata);

$.ajax({
	url: '/custom_webform.cfm',
	type: 'POST',
	data: $("#custom_webform").serialize(),
	dataType: 'text',
	error: function(){

	},
	success: function(text){
	//alert(text);
//	alert('Thank you for your submission.');
	//$("div#custom_webform").hide();
	}
});

$("#confirmation").show();


}


/* REG101 WEBFORM JQUERY */

function reg101Start() {

	$("#reg101_confirmation").hide();
	$("#reg101_errormsg").hide();

	$.ajax({
		url: 'reg101_form.cfm',
		type: 'GET',
		data: { action: 'getcities' },
		dataType: 'html',
		error: function(){
			$("#reg101_errormsg").show();
			$("#reg101_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
		},
		success: function(html){
			$(".reg101_cities").remove();
			$("#reg101_cities").append(html);
			reg101_unbind();
			reg101_bind();
		}
	});	
}

function reg101_unbind() {
	$("#reg101_cities").unbind();
}

function reg101_bind() {
		
		$("#reg101_city_select").change(function () {

			$.ajax({
				url: 'reg101_form.cfm',
				type: 'POST',
				data: { action : 'getfaculty', city : $("select#reg101_city_select").val() },
				dataType: 'html',
				error: function(){
					$("#reg101_errormsg").show();
					$("#reg101_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
				},
				success: function(html){
					$(".reg101_faculty").remove();
					$(".reg101_dates").remove();
					$(".reg101_times").remove();
					$(".reg101_questions").remove();
					$("#reg101_dates").append(html);
					reg101_unbind();
					reg101_bind();
				}
			});				
		});
		
		$("#reg101_faculty_select").change(function () {
			$.ajax({
				url: 'reg101_form.cfm',
				type: 'POST',
				data:  { action : 'getdates', city : $("select#reg101_city_select").val(), date : $("select#reg101_date_select").val(), faculty : $("select#reg101_faculty_select").val() },
				dataType: 'html',
				error: function(){
					$("#reg101_errormsg").show();
					$("#reg101_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
				},
				success: function(html){
					$(".reg101_dates").remove();
					$(".reg101_times").remove();
					$(".reg101_questions").remove();
					$("#reg101_times").append(html);
					reg101_unbind();
					reg101_bind();				
				}
			});				
		});

		$("#reg101_date_select").change(function () {
			$.ajax({
				url: 'reg101_form.cfm',
				type: 'POST',
				data:  { action : 'gettimes', city : $("select#reg101_city_select").val(), date : $("select#reg101_date_select").val(), faculty : $("select#reg101_faculty_select").val(), type : $("select#reg101_date_select option:selected").attr("type") },
				dataType: 'html',
				error: function(){
					$("#reg101_errormsg").show();
					$("#reg101_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
				},
				success: function(html){
					$(".reg101_times").remove();
					$(".reg101_questions").remove();
					$("#reg101_times").append(html);
					reg101_unbind();
					reg101_bind();
				}
			});
			//var test = $("select#reg101_date_select option:selected").attr("type");
			//alert(test);
		});

		$("#reg101_time_select").change(function () {
			$.ajax({
				url: 'reg101_form.cfm',
				type: 'POST',
				data:  { action : 'getquestions', city : $("select#reg101_city_select").val(), date : $("select#reg101_date_select").val(), time : $("select#reg101_time_select").val(), faculty : $("select#reg101_faculty_select").val() },
				dataType: 'html',
				error: function(){
					$("#reg101_errormsg").show();
					$("#reg101_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
				},
				success: function(html){
					$(".reg101_questions").remove();
					$("#reg101_questions").append(html);
					reg101_unbind();
					reg101_bind();				
				}
			});							
		});
		
	$("#reg101_form").validate({
		rules: {
			firstname: "required",
			lastname: "required",
			email: {
				required: true,
				email: true
			},
			phonenumber: {
				required: true,
				phoneUS: true
			},
			highschool: "required"
		},
		messages: {
			firstname: "Please enter your firstname",
			lastname: "Please enter your lastname",
			email: {
				required: "Please enter a valid e-mail address",
				minlength: "Please enter a valid e-mail address"
			},
			phonenumber: "Please enter a valid phone number",
			highschool: "Please enter your high school"
		},
		submitHandler: function() {
				$.ajax({
					url: 'reg101_form.cfm',
					type: 'POST',
					data:  $("#reg101_form").serialize(),
					dataType: 'html',
					error: function(){
						$("#reg101_errormsg").show();
						$("#reg101_errormsg").append('There was a problem submitting the registration form.');
					},
					success: function(html){
						$("#reg101_group").hide();
						$("#reg101_confirmation").append(html);	
						$("#reg101_confirmation").show();			
					}
				});
			//alert('After Validate');
		}
	});
	
}

/* EXPLORE YOUR U! WEBFORM JQUERY */

function ExploreStart() {

	$("#explore_confirmation").hide();
	$("#explore_errormsg").hide();

	$.ajax({
		url: 'explore_form.cfm',
		type: 'GET',
		data: { action: 'getTours' },
		dataType: 'html',
		error: function(){
			$("#explore_errormsg").show();
			$("#explore_errormsg").append('There was a problem loading the form.');
		},
		success: function(html){
			$("#explore_tours").append(html);
			ExploreBind();
		}
	});
	
}

function ExploreBind() {


	$("#explore_tours_select").change(function () {
		$.ajax({
			url: 'explore_form.cfm',
			type: 'POST',
			data:  { action : 'getDetails', title : $("select#explore_tours_select").val() },
			dataType: 'html',
			error: function(){
				$("#explore_errormsg").show();
				$("#explore_errormsg").append('There was a problem loading the form.');
			},
			success: function(html){
				$(".explore_details").remove();
				$("#explore_details").append(html);
				ExploreBind();
			}
		});
	});

	$("#explore_form").validate({
		rules: {
			firstname: "required",
			lastname: "required",
			email: {
				required: true,
				email: true
			},
			highschool: "required"
		},
		messages: {
			firstname: "Please enter your firstname",
			lastname: "Please enter your lastname",
			email: {
				required: "Please enter a valid e-mail address",
				minlength: "Please enter a valid e-mail address"
			},
			highschool: "Please enter your high school"
		},
		submitHandler: function() {
				$.ajax({
					url: 'explore_form.cfm',
					type: 'POST',
					data:  $("#explore_form").serialize(),
					dataType: 'html',
					error: function(){
						$("#explore_errormsg").show();
						$("#explore_errormsg").append('There was a problem submitting the registration form.');
					},
					success: function(html){
						$("#explore_intro").hide();
						$("#explore_tours").hide();
						$("#explore_details").hide();
						$("#explore_confirmation").append(html);	
						$("#explore_confirmation").show();			
					}
				});
			//alert('After Validate');
		}
	});
	
	
}

/* EARLY ADMISSION WEBFORM JQUERY */

function EarlyAdmStart() {

	$("#earlyadm_confirmation").hide();
	$("#earlyadm_errormsg").hide();

	$.ajax({
		url: 'earlyadm_form.cfm',
		type: 'GET',
		data: { action: 'getcities' },
		dataType: 'html',
		error: function(){
			$("#earlyadm_errormsg").show();
			$("#earlyadm_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
		},
		success: function(html){
			$(".earlyadm_cities").remove();
			$("#earlyadm_cities").append(html);
			earlyadm_unbind();
			earlyadm_bind();
		}
	});	
}

function earlyadm_unbind() {
	$("#earlyadm_cities").unbind();
}

function earlyadm_bind() {
		
		$("#earlyadm_city_select").change(function () {

			$.ajax({
				url: 'earlyadm_form.cfm',
				type: 'POST',
				data: { action : 'getdates', city : $("select#earlyadm_city_select").val() },
				dataType: 'html',
				error: function(){
					$("#earlyadm_errormsg").show();
					$("#earlyadm_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
				},
				success: function(html){
					$(".earlyadm_dates").remove();
					$(".earlyadm_faculty").remove();
					$(".earlyadm_times").remove();
					$(".earlyadm_questions").remove();
					$("#earlyadm_dates").append(html);
					earlyadm_unbind();
					earlyadm_bind();
				}
			});				
		});
		
		$("#earlyadm_date_select").change(function () {
			$.ajax({
				url: 'earlyadm_form.cfm',
				type: 'POST',
				data:  { action : 'getfaculty', city : $("select#earlyadm_city_select").val(), date : $("select#earlyadm_date_select").val() },
				dataType: 'html',
				error: function(){
					$("#earlyadm_errormsg").show();
					$("#earlyadm_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
				},
				success: function(html){
					$(".earlyadm_faculty").remove();
					$(".earlyadm_times").remove();
					$(".earlyadm_questions").remove();
					$("#earlyadm_faculty").append(html);
					earlyadm_unbind();
					earlyadm_bind();
				}
			});				
		});

		$("#earlyadm_faculty_select").change(function () {
			$.ajax({
				url: 'earlyadm_form.cfm',
				type: 'POST',
				data:  { action : 'gettimes', city : $("select#earlyadm_city_select").val(), date : $("select#earlyadm_date_select").val(), faculty : $("select#earlyadm_faculty_select").val(), group : $("select#earlyadm_faculty_select option:selected").attr("group") },
				dataType: 'html',
				error: function(){
					$("#earlyadm_errormsg").show();
					$("#earlyadm_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
				},
				success: function(html){
					$(".earlyadm_times").remove();
					$(".earlyadm_questions").remove();
					$("#earlyadm_times").append(html);
					earlyadm_unbind();
					earlyadm_bind();				
				}
			});				
		});

		$("#earlyadm_time_select").change(function () {
			$.ajax({
				url: 'earlyadm_form.cfm',
				type: 'POST',
				data:  { action : 'getquestions', city : $("select#earlyadm_city_select").val(), date : $("select#earlyadm_date_select").val(), time : $("select#earlyadm_time_select").val(), faculty : $("select#earlyadm_faculty_select").val(), group : $("select#earlyadm_faculty_select option:selected").attr("group") },
				dataType: 'html',
				error: function(){
					$("#earlyadm_errormsg").show();
					$("#earlyadm_errormsg").append('There was a problem loading the Registration 101 Workshop webform.');
				},
				success: function(html){
					$(".earlyadm_questions").remove();
					$("#earlyadm_questions").append(html);
					earlyadm_unbind();
					earlyadm_bind();				
				}
			});							
		});
		
	$("#earlyadm_form").validate({
		rules: {
			firstname: "required",
			lastname: "required",
			email: {
				required: true,
				email: true
			},
			phonenumber: {
				required: true,
				phoneUS: true
			},
			highschool: "required"
		},
		messages: {
			firstname: "Please enter your firstname",
			lastname: "Please enter your lastname",
			email: {
				required: "Please enter a valid e-mail address",
				minlength: "Please enter a valid e-mail address"
			},
			phonenumber: "Please enter a valid phone number",
			highschool: "Please enter your high school"
		},
		submitHandler: function() {
				$.ajax({
					url: 'earlyadm_form.cfm',
					type: 'POST',
					data:  $("#earlyadm_form").serialize(),
					dataType: 'html',
					error: function(){
						$("#earlyadm_errormsg").show();
						$("#earlyadm_errormsg").append('There was a problem submitting the registration form.');
					},
					success: function(html){
						$("#earlyadm_group").hide();
						$("#earlyadm_confirmation").append(html);	
						$("#earlyadm_confirmation").show();			
					}
				});
			//alert('After Validate');
		}
	});
	
}

