﻿
/*
Contains general javascript functions.
*/

// Tests a string for being null, empty, or whitespace.
function isNullOrWhitespace(str) {
	if (!str)
		return true;
	else if (str.replace(/\s/g, '') == '') {
		return true;
	}

	return false;
}


// Used by ASP.NET CustomValidator controls that need to validate a string in a textbox.
function CustomValidateIsNullOrWhitespace(source, arguments) {
	arguments.IsValid = !isNullOrWhitespace(arguments.Value);
}


// Used by ASP.NET CustomValidator controls that need to validate the MaxLength property of an asp:textbox with TextMode set to MultiLine (i.e. a <textarea> tag).
function CustomValidateMaxLength(source, args) {

	var maxLen = source.MaxLength; // source.MaxLength should be set server-side via call to Page.ClientScript.RegisterExpandoAttribute(Me.cvField.ClientID, "MaxLength", Me.txtField.MaxLength.ToString(), True)

	if (args.Value != null && args.Value.length > 0 && args.Value.length <= maxLen)
		args.IsValid = true;
	else
		args.IsValid = false;
}


// Used by ASP.NET CustomValidator controls that need to validate that a textbox's text has changed from the DefaultText.
function CustomValidateBlurField(source, args) {

	var defaultText = source.DefaultText; // source.DefaultText should be set server-side via call to Page.ClientScript.RegisterExpandoAttribute(Me.cvField.ClientID, "DefaultText", Me.txtField.Text, True)

	if (args.Value != null && args.Value.length > 0 && args.Value != defaultText)
		args.IsValid = true;
	else
		args.IsValid = false;
}


// Validates a string is a valid email address.
function isEmailAddress(str) {
	if (str.replace(' ', '') == '')
		return false;

	var filter = /^.+@.+\..{2,10}$/;
	return (filter.test(str));
}


// Used by ASP.NET CustomValidator controls that need to validate an email address in a textbox.
function CustomValidateEmailAddress(source, arguments) {
	arguments.IsValid = isEmailAddress(arguments.Value);
}


// Used by ASP.NET CustomValidator controls that need to validate a RadComboBox's item values.
// Reason being, RadComboBox normally gets validated against its items' text.
// Assumes the invalid item's value is '' or '0'.
// See this for details: http://www.telerik.com/help/aspnet-ajax/validate-combobox-value.html
function CustomValidateRadComboBox(source, args) {
	var controlToValidate;
	if (source.controltovalidate)
		controlToValidate = source.controltovalidate;
	else
		controlToValidate = source.attributes.getNamedItem('controltovalidate').value;
	args.IsValid = false;
	var combo = $find(controlToValidate);
	var text = combo.get_text();
	if (text.length < 1) {
		args.IsValid = false;
	}
	else {
		var node = combo.findItemByText(text);
		if (node) {
			var value = node.get_value();
			//if (value.length > 0 && value > 0) {
			if (value.length > 0 && (isNaN(value) || value > 0)) {
				args.IsValid = true;
			}
		}
		else {
			args.IsValid = false;
		}
	}
}


// Used by ASP.NET CustomValidator controls that need to validate a RadNumericTextBox's item values.
// Assumes the invalid item's value is '' or '0'.
// CustomValidator must have its ValidateEmptyText property set to true.
function CustomValidateRadNumericTextBox(source, args) {
	if (args.Value == '' || args.Value <= 0) {
		args.IsValid = false;
	}
}


// Sets each of the specified jQuery DOM objects to the same CSS height, based on the tallest of the 4.
// $id3 and $id4 are optional.
// Dependant on jQuery being available.
function EnsureSameHeight($id1, $id2, $id3, $id4) {
	var height1 = $id1.height();
	var height2 = $id2.height();
	var height3 = $id3 ? $id3.height() : null;
	var height4 = $id4 ? $id4.height() : null;

	var maxHeight = Math.max(height1, height2, height3, height4);

	$id1.height(maxHeight);
	$id2.height(maxHeight);

	if ($id3)
		$id3.height(maxHeight);

	if ($id4)
		$id4.height(maxHeight);
}


function getRadWindow() {
	var oWindow = null;
	if (window.radWindow)
		oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog       
	else if (window.frameElement && window.frameElement.radWindow)
		oWindow = window.frameElement.radWindow; //IE (and Moz as well)
	return oWindow;
}


//function closeRadWindow() {
//	var wnd = getRadWindow();
//	wnd.Close();
//}

function closeRadWindow(argument) {
	var wnd = getRadWindow();

	if (!wnd) {
		//window.alert('Cannot find RadWindow');
		return;
	}

	if (argument != undefined) {
		// Set the RadWindow's argument property so we can inspect it in RadWindow's OnClientClose event handler to see if we need to reload a RadGrid etc.
		wnd.argument = argument;
	}
	wnd.Close();
}


function reloadOpener() {
	if (window.opener) {
		window.opener.location = window.opener.location;
		window.close();
	}
}


function reload(queryKvp) {

	var key;
	if (queryKvp && queryKvp.indexOf('=') > 0)
		key = queryKvp.split('=')[0];

	if (window.parent) {
		//var url = appendQueryKvp(window.parent.location.href, queryKvp);
		var url = window.parent.location.href;
		if (key) {
			url = removeParameterFromUrl(url, key);
			url = appendQueryKvp(url, queryKvp);
		}
		window.parent.location.href = url;
	}
	else {
		//var url = appendQueryKvp(window.location.href, queryKvp);
		var url = window.location.href;
		if (key) {
			url = removeParameterFromUrl(url, key);
			url = appendQueryKvp(url, queryKvp);
		}
		window.location.href = url;
	}
}


//Extended jQuery function
//Replace text input fields from the default
(function ($) {
	$.fn.extend({
		replaceDefaultInputBoxes: function (originalTextColor, replacementTextColor) {

			//Store original input values in an array for comparison
			var inputArray = [];

			this.each(function () {
				inputArray[this.id] = this.title; //Using Title as the default state as on postback the Value property will be what we posted and would be wrong

			});


			this.each(function () {
				inputBox = $('#' + this.id); //Had to reference the control with '$' as using 'this' directly didn't affect the actual input box
                
				inputBox
                    .focus(function () {
                    	if ($(this).val() == inputArray[this.id]) { //Check the input box value to the array value
                    		$(this).css('color', '#' + replacementTextColor);
                    		$(this).val("");
                    	}
                    })
                .blur(function () {
                	if ($(this).val() == "") {
                		$(this).css('color', '#' + originalTextColor);
                		$(this).val(inputArray[this.id]);
                	}
                });

                if (!inputBox.val() == inputArray[this.id]) {
                    inputBox.css('color', '#' + replacementTextColor);
                }

			});


			return this;
		}
	});
})(jQuery);


// jQuery extension function.
// Replaces the css class name of text input fields from the default.
// Use it to show
(function ($) {
	$.fn.extend({
		replaceDefaultCssClasses: function (originalCssClass, replacementCssClass) {

			//Store original input values in an array for comparison
			var inputArray = [];

			this.each(function () {
				inputArray[this.id] = this.title; //Using Title as the default state as on postback the Value property will be what we posted and would be wrong
			});

			this.each(function () {
				inputBox = $('#' + this.id); //Had to reference the control with '$' as using 'this' directly didn't affect the actual input box

				inputBox
					.focus(function () {
						if ($(this).val() == inputArray[this.id]) { //Check the input box value to the array value
							//$(this).css('color', '#' + replacementTextColor);
							$(this).removeClass(originalCssClass).addClass(replacementCssClass);
							$(this).val("");
						}
					})
					.blur(function () {
						if ($(this).val() == "") {
							//$(this).css('color', '#' + originalTextColor);
							$(this).removeClass(replacementCssClass).addClass(originalCssClass);
							$(this).val(inputArray[this.id]);
						}
					});

				if (!inputBox.val() == inputArray[this.id]) {
					//inputBox.css('color', '#' + replacementTextColor);
					inputBox.removeClass(originalCssClass).addClass(replacementCssClass);
				}
			});

			return this;
		}
	});
})(jQuery);


// Used by CheckBoxValidator controls that need to validate an ASP.NET CheckBox control.
function CheckBoxValidatorEvaluateIsValid(val) {
	var control = document.getElementById(val.controltovalidate);
	var mustBeChecked = val.mustBeChecked == 'true' ? true : false;

	return control.checked == mustBeChecked;
}	


// Used by CheckBoxListValidator controls that need to validate an ASP.NET CheckBoxList control.
function CheckBoxListValidatorEvaluateIsValid(val) {
	var control = document.getElementById(val.controltovalidate);
	var minimumNumberOfSelectedCheckBoxes = parseInt(val.minimumNumberOfSelectedCheckBoxes);

	var selectedItemCount = 0;
	var liIndex = 0;
	var currentListItem = document.getElementById(control.id + '_' + liIndex.toString());

	while (currentListItem != null) {
		if (currentListItem.checked) selectedItemCount++;
		liIndex++;

		currentListItem = document.getElementById(control.id + '_' + liIndex.toString());
	}

	return selectedItemCount >= minimumNumberOfSelectedCheckBoxes;
}

function toggleContainer(id) {
	$('#' + id).toggle();
}

/// Ensures the given $obj is jQuery-ised.
function ensurejQueryised($obj) {
	if (!($obj instanceof jQuery))
		$obj = $($obj);

	return $obj;
}


/// Sets the given input text box's default content and text colour.
/// $textBox: jQuery-fied text input - e.g. $("*[id$=txtLoginEmail]")
/// defaultText: e.g. 'email address' - the default text to apply to the input
/// defaultClass: e.g. 'lightGrey' - the class name that will be applied to the input when default text is entered
/// altClass: e.g. 'darkGrey' - the class name that will be applied to the input when non-default text is entered
function setTextboxDefaultText($textbox, defaultText, defaultClass, altClass) {
	if ($textbox.val() == defaultText)
		$textbox.addClass(defaultClass);
	else
		$textbox.addClass(altClass);

	$textbox.focus(function () {
		$(this).removeClass(defaultClass).addClass(altClass);
		if ($(this).val() == defaultText) {
			$(this).val("");
		}
	});
	$textbox.blur(function () {
		if ($(this).val() == "") {
			$(this).val(defaultText);
			$(this).removeClass(altClass).addClass(defaultClass);
		}
	});
}

/// Configures a masked password field to appear when the clear text input field gets focus.
/// When the masked field loses focus, if its text is empty the clear field reappears in its place.
function togglePasswordFields($passwordClear, $passwordMasked) {
	if ($passwordMasked.val() == '') {
		$passwordClear.show();
		$passwordMasked.hide();
	} else {
		$passwordClear.hide();
		$passwordMasked.show();
	}

	$passwordClear.focus(function () {
		$passwordClear.hide();
		$passwordMasked.show().focus();
	});

	$passwordMasked.blur(function () {
		if ($passwordMasked.val() == '') {
			$passwordClear.show();
			$passwordMasked.hide();
		}
	});
}

