﻿
// BEGIN :: VALIDATION METHODS =======================
function IsValid(_hookClass, _contextID, _msgObj) {
	
	var _response = true;
	_msgObj.html("");
	_msgObj.hide();

	$('[id*="error_"]').each(function () { $(this).remove(); });

	try {
		$('#' + _contextID + ' [class*="' + _hookClass + '"]').each(function () {
			$(this).removeClass("error");
			//
			// Validate by control type
			// ================================
			// Validate text boxes
			if ($(this).is("input:text")) {
				if (IsNullOrEmpty($(this).val())) {
					AppendErrorItemToMessage($(this), _msgObj);
					InsertFormFieldErrorMessage($(this));
					_response = false;
				}
			}
			// Validate drop down lists
			if ($(this).is("select")) {
				if ($(this).val() == -1) {
					AppendErrorItemToMessage($(this), _msgObj);
					InsertFormFieldErrorMessage($(this));
					_response = false;
				}
			}
			// Validate checkboxes
			if ($(this).is("input:checkbox")) {
				if (!$(this).is(":checked")) {
					_msgObj.html(_msgObj.html() + " - Please check the box for: " + $('label[for="' + $(this).attr("id") + '"]').html(), _msgObj);
					_response = false;
				}
			}
			// Validate textareas
			if ($(this).is("textarea")) {
				if (IsNullOrEmpty($(this).val())) {
					AppendErrorItemToMessage($(this), _msgObj);
					if ($(this).attr("rel")) { $("#" + $(this).attr("rel")).addClass("bgError"); }
					_response = false;
				}
			}
			//
			// Sub-validation methods
			// ================================
			// validate email addresses
			if (!IsNullOrEmpty($(this).val()) && $(this).hasClass("valEmail") && !IsEmailValid($(this).val())) {
				_msgObj.html(_msgObj.html() + " - " + $(this).attr("title") + " (use proper email format)<br />");
				InsertFormFieldErrorMessage($(this));
				_response = false;
			}
			// Validate numbers
			if (!IsNullOrEmpty($(this).val()) && $(this).hasClass("valInt") && isNaN($(this).val())) {
				_msgObj.html(_msgObj.html() + " - " + $(this).attr("title") + " - numbers only.<br />");
				InsertFormFieldErrorMessage($(this));
				_response = false;
			}
		});

		if (!_response) {
			_msgObj.html("Please correct the following errors:<br /><br />" + _msgObj.html());
			_msgObj.show();
		}
	}
	catch (err) { ThrowAlertError(err, "IsValid"); }
	return _response;
}

function InsertFormFieldErrorMessage(_obj) {
	$("<div id=\"error_" + _obj.attr("id") + "\" class=\"formMsgError\">This is a required field</div>").insertAfter(_obj);
	_obj.addClass("error");
}

function AppendErrorItemToMessage(_obj, _msgObj) {
	_msgObj.html(_msgObj.html() + " - " + _obj.attr("title") + "<br />");
}
// END :: VALIDATION METHODS =======================

function ThrowAlertError(_err, _functionName) {
	txt = "There was an error on this page.\r\n";
	txt += "Function: " + _functionName + "\r\n";
	txt += "Error description: " + _err + "\r\n";
	txt += "Click OK to continue.\r\n";
	alert(txt);
}

// AJAX calls to web method repository
function DoPostback(_url, _data, _successFunc, _errorFunc) {
	$.ajax({
		type: "POST",
		url: _url, //'<%= URLStuff.GetClientURL("~/WebServices/WebMethodRepository.aspx/' + _method + '") %>'
		data: _data,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		cache: false,
		error: _errorFunc,
		success: _successFunc,
		complete: PostbackComplete
	});
	return false;
}


// Pass in object to be covered by the loader
// Call this a second time to remove the loader
function SetLoading(_obj, _pos, _imgPath) {
	if (!_obj) {
		// Remove all loaders on the page
		$('[id*="loaderFor_"]').each(function () { $(this).remove(); });
	}
	else {
		if (!$("#loaderFor_" + _obj.attr("id")).length) {
			// Build the loader
			var _loader = $("<div/>", {
				id: "loaderFor_" + _obj.attr("id"),
				css: {
					width: _obj.outerWidth(),
					height: _obj.outerHeight()
				},
				"class": "dynaLoader"
			});
			if (_imgPath == null) { _loader.html("<img src=\"https://d3goy0w6lca30i.cloudfront.net/throbber.gif\" alt=\"Loading...\" />"); }
			else { _loader.html("<img src=\"" + _imgPath + "\" alt=\"Loading...\" />");  }

			switch (_pos) {
				case 0: // insert before
				default: // none specified
					_loader.insertBefore(_obj);
					break;
				case 1: // insert after
					_loader.insertAfter(_obj);
					break;
				case 2: // prepend (insert as first child)
					_obj.prepend(_loader);
					break;
				case 3: // append (insert as last child)
					_obj.append(_loader);
					break;
			}
		}
		else { $("#loaderFor_" + _obj.attr("id")).remove(); }
	}
	return false;
}

function ShowClipboard(_text, _obj) {
	RemoveClipboard();
	_obj = $("#" + _obj);
	if (_text.length) {
		var _contents = "Copy the link below to link directly to this comment:<br />\n\n";
		_contents += "<textarea id='copyMe' rows='4' style='width: 97%;'>" + _text + "</textarea><br />\n\n";
		_contents += "<a href='javascript:RemoveClipboard()'>Close</a>";
		var _container = $("<div/>", {
			id: "copyMeContainer",
			"class": "copyMe"
		});
		_container.html(_contents);
		var _pos = _obj.position();
		_container.css("top", _pos.top);
		_container.css("left", _pos.left);
		_container.insertAfter(_obj);
		_container.fadeIn();
		$("#copyMe").select();
	}
}

function RemoveClipboard() {
	$("#copyMeContainer").remove();
}

/*============================================
	FROM FORMMAGIC
============================================*/
function escapeQuotes(_str) {
	return _str.replace(/\"/g, '&quot;').replace(/\'/g, '&rsquo;');
}

function ShowTooltip(_object, _message, _loc, _hideType, _topOffset) {
	// _loc values
	// - 0 = append to right column
	// - 1 = show to the right of the control
	// - 2 = show on the mouse
	// _hideType
	// - 0 = hide on mouseleave
	// - 1 = hide on blur
	var _div = $("<div/>", {
			id: "hoverTooltip_" + _object.attr("id"),
			"class": "hoverTooltip",
			css: { display: "none" },
			html: _message
		});

	var _pos = _object.offset();
	_div.css("top", _pos.top + _topOffset);

	switch (_loc) {
		case 1: // right of the control
			_div.css("left", _pos.left + _object.width() + 10);
			_div.insertAfter(_object);
			_div.fadeIn("fast");
			break;
		case 2: // on mouse
			break;
		case 0: // in the right column
		default:
			var _placeholder = null;
			if ($("#divContentRight").length) { _placeholder = $("#divContentRight"); }
			else if ($(".wizardRightColumn").length) {
				_placeholder = $(".wizardRightColumn");
				_div.css("width", _placeholder.width());
			}

			if (_placeholder != null) {
				_div.css("left", _placeholder.offset().left - 5);
				_placeholder.append(_div);
				_div.fadeIn("fast");
			}
			break;
	}

	switch (_hideType) {
		case 1:
			_object.blur(function () {
				_div.stop().fadeOut("fast", function () { $(this).remove() });
			});
			break;
		case 0:
		default:
			_object.stop().bind({
				mouseleave: function () { _div.fadeOut("fast", function () { 
					$('[id*="hoverTooltip_"]').each(function () { $(this).remove(); }); }); 
				}
				//mouseout: function () { _div.fadeOut("fast", function () { $('[id*="hoverTooltip_"]').each(function () { $(this).remove(); }); }); }
			});
			break;
	}
	return false;
}

// VALIDATE SPECIFIC FIELD TYPES
//==========================================================

function validateNonHTML(_obj) {
	var _errorID = _obj.attr("id") + "-e1";
	$("#" + _errorID).remove();
	if (HasHTMLTags(_obj.val())) {
		_obj.addClass("error");
		$("<div id=\"" + _errorID + "\" class=\"formMsgError\">This field cannot have HTML tags in it</div>").insertAfter(_obj);
		return false;
	}
	else {
		_obj.removeClass("error");
		return true;
	}
}

// Validate length of text in a textarea
function validateTextAreaLength(_str, _max) {
	if (_str == null) return true;
	if (_str.length > _max) return false;
}
// Validates a required textbox field given a textbox object
// This will change the class and focus as well
function validateRequiredTextbox(_obj) {
	var _errorID = _obj.attr("id") + "-e1";
	$("#" + _errorID).remove();

	if (IsNullOrEmpty(_obj.val()) || _obj.val() == '(   )    -    ') {
		_obj.addClass("error");
		$("<div id=\"" + _errorID + "\" class=\"formMsgError\">This is a required field</div>").insertAfter(_obj);
		return false;
	}
	else {
		_obj.removeClass("error");
		return true;
	}
}
// Validate url in a textbox
// This will change the class and focus as well
function validateURLTextbox(_obj) {
	var _errorID = _obj.attr("id") + "-e2";
	$("#" + _errorID).remove();
	if (IsURLValid(_obj.val())) {
		_obj.removeClass("error");
		return true;
	}
	else {
		_obj.addClass("error");
		$("<span id=\"" + _errorID + "\" class=\"formMsgError\">Invalid web address <br />(<i>Example: http://www.yoursite.com</i>)</span>").insertAfter(_obj);
		return false;
	}
}
// Validate email textbox field
// This will change the class and focus as well
function validateEmailTextbox(_obj) {
	var _errorID = _obj.attr("id") + "-e3";
	$("#" + _errorID).remove();
	if (IsEmailValid(_obj.val())) {
		_obj.removeClass("error");
		return true;
	}
	else {
		_obj.addClass("error");
		$("<span id=\"" + _errorID + "\" class=\"formMsgError\">Invalid email address</span>").insertAfter(_obj);
		return false;
	}
}
// Validates a zipcode field given a textbox object
// This will change the class and focus as well
function validateZipcodeTextbox(_obj) {
	var _errorID = _obj.attr("id") + "-e4";
	$("#" + _errorID).remove();
	if (IsZipCodeValid(_obj.val())) {
		_obj.removeClass("error");
		return true;
	}
	else {
		_obj.addClass("error");
		$("<span id=\"" + _errorID + "\" class=\"formMsgError\">Invalid zipcode</span>").insertAfter(_obj);
		return false;
	}
}
// Validates dropdown boxes, initial value should be -1
function validateRequiredDropdown(_obj) {
	var _errorID = _obj.attr("id") + "-e5";
	$("#" + _errorID).remove();
	if (IsNullOrEmpty(_obj.val()) || _obj.val() == "-1") {
		_obj.addClass("error");
		$("<div id=\"" + _errorID + "\" class=\"formMsgError\">This is a required field</div>").insertAfter(_obj);
		return false;
	}
	else {
		_obj.removeClass("error");
		return true;
	}
}

// Validate password rules
function validatePasswordRules(_obj) {
	var pattern = new RegExp(/^\w{6,16}$/);
	var _errorID = _obj.attr("id") + "-e6";
	$("#" + _errorID).remove();
	if (IsNullOrEmpty(_obj.val())) {
		_obj.addClass("error");
		$("<div id=\"" + _errorID + "\" class=\"formMsgError\">This is a required field</div>").insertAfter(_obj);
		return false;
	}
	else if (!pattern.test(_obj.val())) {
		_obj.addClass("error");
		$("<div id=\"" + _errorID + "\" class=\"formMsgError\">Invalid password format</div>").insertAfter(_obj);
		return false;
	}
	else {
		_obj.removeClass("error");
		return true;
	}
}

// Validate password rules
function validatePasswordsMatch(_objPW, _objPWC) {
	var _errorIDPW = _objPW.attr("id") + "-e7";
	var _errorIDPWC = _objPWC.attr("id") + "-e8";
	$("#" + _errorIDPW).remove();
	$("#" + _errorIDPWC).remove();
	if (_objPW.val() != _objPWC.val()) {
		_objPW.addClass("error");
		$("<div id=\"" + _errorIDPW + "\" class=\"formMsgError\">Passwords do not match</div>").insertAfter(_objPW);
		_objPWC.addClass("error");
		$("<div id=\"" + _errorIDPWC + "\" class=\"formMsgError\">Passwords do not match</div>").insertAfter(_objPWC);
		return false;
	}
	else {
		_objPW.removeClass("error");
		_objPWC.removeClass("error");
		return true;
	}
}
// Validates a zipcode field given a textbox object
// This will change the class and focus as well
function validateNumberTextbox(_obj) {
	var _errorID = _obj.attr("id") + "-e9";
	$("#" + _errorID).remove();
	if (!isNaN(_obj.val())) {
		_obj.removeClass("error");
		return true;
	}
	else {
		_obj.addClass("error");
		$("<span id=\"" + _errorID + "\" class=\"formMsgError\">Invalid number</span>").insertAfter(_obj);
		return false;
	}
}
//==========================================================


// CORE VALIDATION METHODS
//==========================================================

function HasHTMLTags(_str) {
	if (_str == null) return false;
	var pattern = new RegExp(/<(.|\n)+?>/);
	return pattern.test(_str);
}

// Validate email address
function IsURLValid(_str) {
	if (_str == null) return false;
	var pattern = new RegExp(/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i);
	return pattern.test(_str);
}

// Validates that the string is not null or empty (required field)
function IsNullOrEmpty(_str) {
	_str = $.trim(_str);
	if (_str == null || _str.length == 0) { return true; }
	else { return false; }
}

// Validate email address
function IsEmailValid(_str) {
	if (_str == null) return false;
	var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
	return pattern.test(_str);
}

// Validate zip codes
function IsZipCodeValid(_str) {
	if (_str == null) return false;
	var re = new RegExp(/^\d{5}([\-]\d{4})?$/);
	return (re.test(_str));
}

function IsPhoneValid(_str) {
	if (_str == null) return false;
	var stripped = _str.replace(/[\s()+-]|ext\.?/gi, "");
	// 10 is the minimum number of numbers required
	return ((/\d{10,}/i).test(stripped));
}

//==========================================================
// RANDOM FORM STUFF
//==========================================================
// Pass in the textbox object and the original string
// This will remove the string on
function toggleGhostText(_obj, _str, _focused) {
	//alert(_obj.attr("id") + " " + _obj.val());
	if (_focused) {
		//alert('test');
		// Remove ghost text and class
		if (_obj.val() == _str) { _obj.val(""); }
		_obj.removeClass("ghostText");
	}
	else {
		if (IsNullOrEmpty(_obj.val()) || _obj.val() == _str) {
			_obj.val(_str);
			_obj.addClass("ghostText");
		}
		else {
			_obj.removeClass("ghostText");
		}
	}

	return false;
}

// Validates a textarea, forces max length
function textAreaMaxLength(_obj, _max, _noteID) {
	// Concat the string if they've put more then _max characters in
	if (_obj.val().length > _max) { _obj.val(_obj.val().substr(0, _max)); }
	// Update the note so they know how much room they have
	_obj.parent().find("#" + _noteID).html('You have ' + (_max - _obj.val().length) + ' characters remaining');
	return false;
}

// This will make a text area taller as content is added
function resizeTextarea(taID, spanID) {
	var textarea = document.getElementById(taID);

	// add a new row every 52 characters after the first 6 lines
	var intChars = 312; // 52 x 6

	var intBreaks = lineBreakCount(textarea.value);

	if (textarea.value.length > intChars) {

		var intAddRows = ((textarea.value.length - intChars) / 52) + 6 + intBreaks;

		// Add an extra row for IE cause it's stupid
		if (browserVersion() == "Microsoft Internet Explorer") {
			intAddRows = intAddRows + 1;
		}

		// Add a new row for every 52 chars over intChars
		textarea.rows = intAddRows;
	}
	else {
		textarea.rows = 6;
	}

	// Set the textarea count if a span ID was passed
	if (spanID.length > 0) {
		setCount(taID, spanID)
	}
}

function setCount(taID, spanID) {
	var textarea = document.getElementById(taID);
	var span = document.getElementById(spanID);
	var browser = '';
	var lineBreaks = lineBreakCount(textarea.value);
	var intTotalCount = textarea.value.length;

	// We're doubling the count for browsers != IE
	if (browserVersion() != "Microsoft Internet Explorer") {
		//lineBreaks = lineBreaks * 2;
		intTotalCount = intTotalCount + lineBreaks;
	}

	span.innerHTML = '(character count: ' + intTotalCount + ')';

	if (intTotalCount < 1000) {
		span.style.color = '#999999';
	}

	if (intTotalCount == 1000) {
		span.style.color = '#669933';
	}

	if (intTotalCount > 1000) {
		span.style.color = '#F47321';
	}
}

// Counts line breaks in a string
function lineBreakCount(str) {
	/* counts \n */
	try {
		return ((str.match(/[^\n]*\n[^\n]*/gi).length));
	} catch (e) {
		return 0;
	}
}

function browserVersion() {
	var browser = navigator.appName;
	var b_version = navigator.appVersion;
	var version = parseFloat(b_version);

	return browser;
}

// This will run a function at a set interval
function setTimer(funct, ms) {
	var timer = null;
	timer = setInterval(funct, ms);
}

// Warn the user when their session is about to timeout
function startSessionTimeoutWarning() {
	var timer = null;

	// Set the timeout for 25 minutes
	timer = setInterval("timeoutWarning()", 1500000);
}

// Just show an alert for now
function timeoutWarning() {
	alert('WARNING!!!\n\nYour browsing session is about to expire due to inactivity.\n\nPlease save your progress in the next couple minutes or it will be lost.\n\nIf you\'re not finished editing you can come back to this page after saving and continue.');
}

function getSafeHTML(_obj) {
	var _response = _obj.val();

	_response = _response.replace(/</g, "&lt;");
	_response = _response.replace(/>/g, "&gt;");
	//_response = _response.replace(/\"/g, "&quot;");
	//_response = _response.replace(/\&/g, "&amp;");

	return _response;
}

//==========================================================
