﻿// Beeline jQuery plugins/extensions
var ZipPostalCodePattern = /^([abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz]\s?[0-9][abceghjklmnprstvwxyz][0-9]|[0-9]{5})$/i;

$.fn.clearSelect = function (label) {
	return this.each(function () {
		if (this.tagName == 'SELECT')
			this.options.length = 0;
		if (label) {
			var dropdownList = this;
			var option = new Option(label, null);
			if ($.browser.msie) {
				dropdownList.add(option);
			}
			else {
				dropdownList.add(option, null);
			}
		}
	});
};
$.fn.fillSelect = function (data, label) {
	return this.clearSelect(label).each(function () {
		if (this.tagName == 'SELECT') {
			var dropdownList = this;
			$.each(data, function (index, optionData) {

				var option = new Option(optionData.Text, optionData.Value);

				if ($.browser.msie) {
					dropdownList.add(option);
				}
				else {
					dropdownList.add(option, null);
				}
			});
		}
	});
};
$.fn.valToInt = function () {
	var v = parseInt(this.val());
	if (v)
		return v;

	return 0;
};
$.fn.preventDoubleSubmit = function () {
	$(this).submit(function () {
		if (this.beenSubmitted) {
			return false;
		} else {
			// Page_IsValid comes from the ASP.NET scripts supplied via WebResource.axd
			if (Page_IsValid == 'undefined' || Page_IsValid == true)
				this.beenSubmitted = true;
			return true;
		}
	});
};

$.fn.resetDoubleSubmit = function () {
	$(this).submit(function () {
		this.beenSubmitted = false;
	});
};

jQuery.fn.exists = function () { return jQuery(this).length > 0; };

var ZipSearch_Keypress_Handler = function(event) {
	if (event.which == 13) {
		event.preventDefault(); ZipSearch_Search();
	}
};

function ZipSearch_Initialize() {

	if ($("#ZipSearch").exists()) {
		$.ajax({
			type: "POST",
			contentType: "application/json",
			url: "/Framework/Services/CategoryService.asmx/GetAllCategories",
			data: "{}",
			dataType: "json",
			success: function (data) {
				ZipSearch_InitializeDropDowns(data.d);
			}
		});

		var zipCode = $("#ZipSearch_ZipCode");
		var z = getParameterByName("z");
		if (z)
			zipCode.val(z);
		zipCode.watermark("[Zip Code or Keywords]").keypress(function(event) {
			return ZipSearch_Keypress_Handler(event);
		});
		$("#ZipSearch_Category").keypress(function(event) {
			return ZipSearch_Keypress_Handler(event);
		});
		$("#ZipSearch_SubCategory").keypress(function(event) {
			return ZipSearch_Keypress_Handler(event);
		});
		$("#ZipSearch select").watermark();
		$("#ZipSearch_Category").change(function (event) { ZipSearch_Update(); });
		$("#ZipSearch_SearchButton").click(function (event) { event.preventDefault(); ZipSearch_Search(); });
		$("#ZipSearch").removeClass("large").addClass("small");

	}

	if ($("#ZipSearchLandingForm").exists()) {

		$("#ZipSearch_ZipCode").keyup(function (event) {
			var zipCodeControl = $(this);
			var code = zipCodeControl.val();

			if (code.length == 0)
				return;

			if (code.length >= 5) {
				if (ZipPostalCodePattern.test(code))
					zipCodeControl.removeClass("invalid").addClass("valid");
				else
					zipCodeControl.removeClass("valid").addClass("invalid");
			} else {
				zipCodeControl.removeClass("valid").removeClass("invalid");
			}
		}).keypress(function () {
			if (event.which == 13) {
				event.preventDefault(); 
				$("#ZipSearchLandingForm").submit();
			}
		});
		
		$("#ZipSearchLandingForm").submit(function () {
			var code = $("#ZipSearch_ZipCode").val();
			if (code.length == 0 || ZipPostalCodePattern.test(code)) {
				return true;
			}
			return false;
		});		
	}
}

function zipSearchLandingFormIsValid() {
	
}

function ZipSearch_InitializeDropDowns(categories) {
	$("#ZipSearch_SubCategory").parent().hide();
	var categorySelect = $("#ZipSearch_Category");
	if (categorySelect) {
		categorySelect.empty();
		categorySelect.append('<option value="" class="watermark">[Choose an Area of Study]</option>');
		$.each(categories, function (index, category) {
			var element = $('<option value="' + category.ID + '">' + category.Name + '</option>');
			element.data("subs", category.SubCategories);
			categorySelect.append(element);
		});

		var categoryID = parseInt(getParameterByName("c"));
		ZipSearch_SelectCategory(categoryID, categories);
	}

	var gradYearSelect = $("#ZipSearch_GradYear");
	if (gradYearSelect) {
		var d = new Date();
		var year = d.getFullYear();
		gradYearSelect.append('<option value="" class="watermark">[Grad Year]</option>');
		var i = 0;
		for (i = year; i > (year - 100); i--) {
			gradYearSelect.append('<option value="' + i + '">' + i + '</option>');
		}
	}
}

function ZipSearch_SelectCategory(categoryID, categories) {
	if (categoryID) {
		for (var cIndex = 0; cIndex < categories.length; cIndex++) {
			var category = categories[cIndex];
			if (category.ID == categoryID) {
				$("#ZipSearch_Category").val(categoryID);
				ZipSearch_Update();
				return;
			} else {
				var subCategories = category.SubCategories;
				for (var sIndex = 0; sIndex < subCategories.length; sIndex++) {
					var subCategory = category.SubCategories[sIndex];
					if (subCategory.ID == categoryID) {
						$("#ZipSearch_Category").val(category.ID);
						ZipSearch_Update();
						$("#ZipSearch_SubCategory").val(subCategory.ID);
						return;
					}
				}
			}
		}
	}
}

function ZipSearch_Update() {
	var selected = $("#ZipSearch_Category option:selected");
	var subCategorySelect = $("#ZipSearch_SubCategory");
	if (subCategorySelect) {
		subCategorySelect.empty();
		subCategorySelect.append('<option value="" class="watermark">[Choose a Program]</option>');
		if (selected.val()) {
			$.each(selected.data("subs"), function (i, category) {
				subCategorySelect.append('<option value="' + category.ID + '">' + category.Name + '</option>');
			});
			$("#ZipSearch_SubCategory").parent().show();
			$("#ZipSearch").removeClass("small").addClass("large");
		} else {
			$("#ZipSearch_SubCategory").parent().hide();
			$("#ZipSearch").removeClass("large").addClass("small");
		}
	}
}

function ZipSearch_Search() {
	var z = $.trim($("#ZipSearch_ZipCode").val());
	if (z == "[Zip Code]" || z == "[Zip Code or Keywords]")
		z = '';

	var c = $.trim($("#ZipSearch_SubCategory").val());
	if (!c) {
		c = $.trim($("#ZipSearch_Category").val());
	}

	if (!c || c == "[Choose an Area of Study]" || c == "[Choose a Program]")
		c = '';

	var g = $.trim($("#ZipSearch_GradYear").val());
	if (!g || g == "[Grad Year]")
		g = '';
	
	if (z != "" || c != "" || g != "") {
		var url = "/Search.aspx" + $.query.set("z", z).set("c", c).set("g", g);
		window.location.href = url;
	}
}

// htt*://james.padolsey.com/javascript/bujs-1-getparameterbyname/
var getParameterByName = (function () {
	var c = {};
	return function getParameterByName(name) {
		name = String(name).replace(/[.*+?|()[\]{}\\]/g, '\\$&');
		if (name in c) { return c[name]; }

		var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);

		return match && (c[name] = decodeURIComponent(match[1].replace(/\+/g, ' ')));
	};
} ());


/** Fancy Box **/

function FancyBoxInit() {
	var fullPath = window.location.pathname.toLowerCase();
	var matches = fullPath.match("/([^/]*?)/(([^/]*?)\.aspx?)?");

	var path = "";

	if (matches != undefined) {
		if (matches.length > 1 && matches[1] != undefined) {
			path += "/" + matches[1];
		}
		if (matches.length > 3 && matches[3] != undefined) {
			path += "/" + matches[3];
		}
	}

	var options = {
		'autoScale': false,
		'titleShow': true,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic',
		'easingIn': 'easeOutBack',
		'easingOut': 'easeInBack',
		'type': 'iframe',
		'width': '35%',
		'height': '50%',
		'titlePosition': 'float',
		onStart: function () {
			dcsMultiTrack('DCS.dcsuri', path + "/PopupOpened.html", 'WT.si_n', 'Compliance Popup Scenario', 'WT.si_p', 'PopupOpened');			
		},
		onCancel: function () {
			dcsMultiTrack('DCS.dcsuri', path + "/PopupClosed.html", 'WT.si_n', 'Compliance Popup Scenario', 'WT.si_p', 'PopupClosed');			
		},
		onComplete: function () {
		},
		onCleanup: function () {
		},
		onClosed: function () {
			dcsMultiTrack('DCS.dcsuri', path + "/PopupClosed.html", 'WT.si_n', 'Compliance Popup Scenario', 'WT.si_p', 'PopupClosed');			
		}
	};

	$("a.fancybox").fancybox(options);
}

/****/
