﻿/*
tools.js

This file contains generic code that could be used in any web app (see 3dss.js for javascript code specific to 3DSS)

Since 2009 some of this code uses jQuery (Google it if you don't know about it yet).

*/



// hide submit button (prevent double submission)
// apparently a later version of ASP.NET will include a Button attribute DisableOnSubmit="true"
// if so delete this and use that.
function HideButton(Button) {
	// hide
	Button.className += " unpressable";

	// bring it back (if not submitted because of client-side validators etc) after 10 secs
	setTimeout("ShowHiddenButtons();", 15000);
}
function ShowHiddenButtons() {
	$(".unpressable").removeClass("unpressable");
}

/*
multiline textboxes ignore MaxLength. So you need this. You have to put it on the onblur event 
and the onkeypress event, so they can't paste or type beyond the given limit. Note that 
because the two events work differently, onKeyPress has to be one less than the limit.

Usage example: 
someTextBox.Attributes.Add("onBlur", "KeepToMaxLength(this, 250);")
someTextBox.Attributes.Add("onKeyPress", "KeepToMaxLength(this, 249);")
*/
function KeepToMaxLength(textArea, maxLength) {
	textArea.value = textArea.value.substring(0, maxLength);
}


//find x (TOP), y (LEFT) coordinates of an HTML element
//PARAM 
//obj: HTML element to find the x, y coordinates of
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft, curtop];
}

//this method trims blanks from start and end of string
//PARAM
//s: the string to have the white spaces removed
function trim(s) {
	if ((s == null) || (typeof (s) != 'string') || !s.length) {
		return '';
	}
	return s.replace(/^\s+/, '').replace(/\s+$/, '')
}

//gets the query string from the URL
//PARAM
//variable: the query string that you want retrieve the value for
function GetQueryString(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		//make search case insensitive
		if (pair[0].toLowerCase() == variable.toLowerCase()) {
			return pair[1];
		}
	}
}

//get mouse coordinates relative to a supplied parent control reference
//PARAM
//event: the mouse click event
//reference: the parent object
function getRelativeCoordinates(event, reference) {
	var x, y;
	event = event || window.event;
	var el = event.target || event.srcElement;

	if (!window.opera && typeof event.offsetX != 'undefined') {
		// Use offset coordinates and find common offsetParent
		var pos = { x: event.offsetX, y: event.offsetY };

		// Send the coordinates upwards through the offsetParent chain.
		var e = el;
		while (e) {
			e.mouseX = pos.x;
			e.mouseY = pos.y;
			pos.x += e.offsetLeft;
			pos.y += e.offsetTop;
			e = e.offsetParent;
		}

		// Look for the coordinates starting from the reference element.
		var e = reference;
		var offset = { x: 0, y: 0 }
		while (e) {
			if (typeof e.mouseX != 'undefined') {
				x = e.mouseX - offset.x;
				y = e.mouseY - offset.y;
				break;
			}
			offset.x += e.offsetLeft;
			offset.y += e.offsetTop;
			e = e.offsetParent;
		}

		// Reset stored coordinates
		e = el;
		while (e) {
			e.mouseX = undefined;
			e.mouseY = undefined;
			e = e.offsetParent;
		}
	}
	else {
		// Use absolute coordinates
		var pos = getAbsolutePosition(reference);
		x = event.pageX - pos.x;
		y = event.pageY - pos.y;
	}
	// Subtract distance to middle
	return { x: x, y: y };
}

//method used to replace line breaks \n with <br> so that it renders as a line break on web form
//PARAM
//str: the string to be replaced with <br> tags
function ReplaceLineBreaksWithHTMLTag(str) {
	//replace user entered line breaks \n with HTML line break tag </br>
	var index = str.indexOf('\n');
	// Loop over the string value replacing out each matching substring.
	while (index != -1) {
		// Relace out the current instance.
		str = str.replace('\n', '<br>')
		// Get the index of any next matching substring.
		index = str.indexOf('\n');
	}
	return str;
}

//method used to replace line breaks <br> with \n for persistance
//PARAM
//str: the string to be replaced with \n 
function ReplaceHTMLTagWithLineBreak(str) {
	//replace user entered line breaks \n with HTML line break tag </br>
	var index = str.indexOf('<br>');
	// Loop over the string value replacing out each matching substring.
	while (index != -1) {
		// Relace out the current instance.
		str = str.replace('<br>', '\n')
		// Get the index of any next matching substring.
		index = str.indexOf('<br>');
	}
	return str;
}

//method used to replace saces with &nbsp; so that spaces will be rendered in the web browser
//PARAM
//str: the string to be replaced &nbsp; literals
function EscapeHTMLWhitespace(str) {
	//replace user entered line breaks \n with HTML line break tag </br>
	var index = str.indexOf('&nbsp;');
	// Loop over the string value replacing out each matching substring.
	while (index != -1) {
		// Relace out the current instance.
		str = str.replace('&nbsp;', ' ')
		// Get the index of any next matching substring.
		index = str.indexOf('&nbsp;');
	}
	return str;
}

//method used to encode all < and > as they are black listed chars
//PARAM
//str: the string to be be stripped of < and > characters
function UrlEncode(str) {
	//replace user entered line breaks \n with HTML line break tag </br>
	var index = str.indexOf('<');
	// Loop over the string value replacing out each matching substring.
	while (index != -1) {
		// Relace out the current instance.
		str = str.replace('<', '%3C')
		// Get the index of any next matching substring.
		index = str.indexOf('<');
	}

	var index2 = str.indexOf('>');
	// Loop over the string value replacing out each matching substring.
	while (index2 != -1) {
		// Relace out the current instance.
		str = str.replace('>', '%3E')
		// Get the index of any next matching substring.
		index2 = str.indexOf('>');
	}
	return str;
}

//triggered when there is an error
//this can be hooked up to the window.onerror event if need be
//PARAM
//intStatus: error code
//strStatusText: error description
function error(intStatus, strStatusText) {
	var message = "An expected error has occurred while attempting to process this AJAX request. \r\n";
	message += "Please try again, and if the problem persists, contact support and supply the following information. \r\n";
	message += "Error code: [" + intStatus + "], error message: [" + strStatusText + "].";
}


//method used to create a new cookie
//PARAM
//c_name: the name of the cookie
//value: the value of the cookie
//expireddays: in days when will the cookie expire from the creation date
function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + value + ";expires=" + exdate.toGMTString();
}


//method used to create a new AJAX XMLHTTP object
function GetXmlHttpObject() {
	var objXMLHttp = null;
	if (window.XMLHttpRequest) {
		objXMLHttp = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
} 