﻿
/*
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.MaxLength 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 % 2 == 0) {
			if (value.length > 0 && 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.radWindow)
		oWindow = window.frameElement.radWindow; //IE (and Moz as well)       
	return oWindow;
}


function closeRadWindow() {
	var wnd = getRadWindow();
	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]);
                	}
                });
			});


			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 EnsurejQuerised($obj) {
	if (!($obj instanceof jQuery))
		$obj = $($obj);

	return $obj;
}

