// String trimmer
/*
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/, '');
};
*/

/**
 * Strip tags from a string
 * From http://prototype.conio.net/
 **/
function stripTags(p_sStr) {
	return p_sStr.replace(/<\/?[^>]+>/gi, '');
}

function countObject(p_oObject) {
	var count = 0;
	for (var i in p_oObject) count++;
	return count;
}

/**
 * Convert html entities back
// * From http://prototyalertpe.conio.net/
 **/

function unescapeHTML(p_sStr) {
 var div = document.createElement('div');
 var text = "";
 div.innerHTML = stripTags(p_sStr);
 for (i = 0; i < div.childNodes.length; i++) {
	 text += div.childNodes[i].nodeValue;
 }
 return text;
}
/*
String.prototype.unescapeHTML = function() {
	var div = document.createElement('div');
	div.innerHTML = this.stripTags();
	return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
}
* */

function trim(p_sString) {
	return p_sString.replace(/^\s+|\s+$/, '');
};

//chk if an object is an array or not.
function isArray(obj) {
	//returns true is it is an array
	if(obj == null) return false;
	if (obj.constructor.toString().indexOf("Array") == -1)
	return false;
	else
	return true;
}

// Element selector
function _e(p_sID) {
	return document.getElementById(p_sID);
}

function getArrayIndex(p_aArr, p_sStr) {
	for(var l_iKey in p_aArr) {
		if (p_aArr[l_iKey] == p_sStr) return l_iKey;
	}
	return null;

}

function node() {
	this.oPrev = null;
	this.oNext = null;
	this.oData = null;

	this.add = function(p_oNode) {
		var l_oLastNode = this;
		while(this.oNext != null) {
			l_oLastNode = this.oNext;
		}

		l_oLastNode.oNext = p_oNode;
		p_oNode.oPrev = l_oLastNode;
	}

	this.setData = function(p_oData) {
		this.oData = p_oData;
	}
}

function tree(p_iID) {
	this.iID = p_iID;
	this.bOpened = false;
	this.iDepth = 0;
	this.oData = null;
	this.aSubTree = new Array();

	this.merge = function(p_oTree) {
		p_oTree.iDepth = this.iDepth + 1;
		this.aSubTree.push(p_oTree);
	}

	this.setData = function(p_oData) {
		this.oData = p_oData;
	}

	this.search = function(p_iID) {
		if (this.iID == p_iID) {
			return this;
		} else {
			if (this.aSubTree.length > 0) {
				for(i = 0; i < this.aSubTree.length; i++) {
					var result = this.aSubTree[i].search(p_iID);
					if (result != null) return result;
				}
			}
		}

		return null;
	}

	this.open = function(p_iID) {
		if (this.iID == p_iID) {
			this.bOpened = true;
			return true;
		} else {
			if (this.aSubTree.length > 0) {
				for(var i = 0; i < this.aSubTree.length; i++) {
					if (this.aSubTree[i].open(p_iID)) return true;
				}
			}
		}
		return false;
	}

	this.close = function(p_iID) {
		if (this.iID == p_iID) {
			this.bOpened = false;
			return true;
		} else {
			if (this.aSubTree.length > 0) {
				for(var i = 0; i < this.aSubTree.length; i++) {
					if (this.aSubTree[i].close(p_iID)) return true;
				}
			}
		}
		return false;
	}

	this.print = function(p_sPrefix) {
		var l_sStr = '' + p_sPrefix;

		l_sStr += '- ' + this.oData.toJSONString() + '<br>';
		if (this.aSubTree.length > 0) {
			for(var i = 0; i < this.aSubTree.length; i++) {
				l_sStr += this.aSubTree[i].print(p_sPrefix + '&nbsp;&nbsp;');
			}
		}

		return l_sStr;
	}
}

function Tree(p_sIdentifier, p_sFrame) {
	this.sIdentifier = p_sIdentifier;
	this.oRoot = new tree(0);
	this.oRoot.bOpened = true;
	this.oRoot.setData({id: 0});

	this.sFrame = p_sFrame;

	this.open = function(p_iID) {
		if (this.oRoot.open(p_iID)) this.refresh(p_iID);
	}

	this.close = function(p_iID) {
		if (this.oRoot.close(p_iID)) this.refresh(p_iID);
	}

	this.fill = function() {
		for (i = 0; i < 10; i++) {
			var subTree = new tree(10 + i);
			subTree.setData({name: 'category ' + i, id: 10 + i, treeContents: function() { return this.id + ': ' + this.name; } });
			this.oRoot.merge(subTree);
		}

		currentTree = this.oRoot.search(14);
		for (i = 50; i < 60; i++) {
			var subTree = new tree(i);
			subTree.setData({name: 'subcategory ' + i, id: i, treeContents: function() { return this.id + ': ' + this.name; } });
			currentTree.merge(subTree);
		}

		currentTree = this.oRoot.search(52);
		for (i = 30; i < 35; i++) {
			var subTree = new tree(i);
			subTree.setData({name: 'subsubcategory ' + i, id: i, treeContents: function() { return this.id + ': ' + this.name; } });
			currentTree.merge(subTree);
		}
	}

	this.refresh = function(p_iID) {
		var l_oDiv = _e(this.sFrame);
		var l_oReference = this;

		// It si t3h rewt
		if (p_iID == 0) {
			// Clear the div
			while (l_oDiv.childNodes.length > 0) l_oDiv.removeChild(l_oDiv.childNodes[0]);

			// If it is opened, create rows
			if (this.oRoot.bOpened && this.oRoot.aSubTree.length > 0) {
				for (var i in this.oRoot.aSubTree) {
					var l_oSubTree = this.oRoot.aSubTree[i];
					var l_oData = l_oSubTree.oData;

					// If there is no data, don't show it
					if (l_oData == null) continue;

					// Create row
					l_oRow = document.createElement('div');
					l_oRow.id = this.sIdentifier + '_' + l_oSubTree.iID;
					l_oRow.subTreeID = l_oSubTree.iID;
					l_oRow.parent = '0';

					// Apply onclick functions
					if (l_oSubTree.aSubTree.length > 0) {
						if (l_oSubTree.bOpened) {
							l_oRow.onclick = function() { l_oReference.close(this.subTreeID); }
						} else {
							l_oRow.onclick = function() { l_oReference.open(this.subTreeID); }
						}
					}

					// Show contents
					l_oRow.innerHTML = l_oData.treeContents();
					l_oDiv.appendChild(l_oRow);

					// If this subtree is opened and has subtrees, show it too
					if (l_oSubTree.bOpened && l_oSubTree.aSubTree.length > 0) {
						this.refresh(l_oSubTree.iID);
					}
				}
			}
			// It si n0t t3h r3wt
		} else {
			var l_iPosition = 0;
			var l_aDivs = l_oDiv.getElementsByTagName('div');

			for (var i = 0; i < l_aDivs.length || l_iPosition == 0; i++) {
				if (l_aDivs[i].subTreeID == p_iID) l_iPosition = i;
			}

			var l_oCurrentDiv = l_aDivs[l_iPosition];
			var l_oNextDiv = (l_iPosition + 1 == l_aDivs.length ? null : l_aDivs[l_iPosition + 1]);

			var l_oTree = this.oRoot.search(p_iID);

			// The tree is opened and has subtrees
			if (l_oTree.bOpened && l_oTree.aSubTree.length > 0) {
				l_oCurrentDiv.onclick = function() { l_oReference.close(this.subTreeID); }

				for (i = 0; i < l_oTree.aSubTree.length; i++) {
					var l_oSubTree = l_oTree.aSubTree[i];
					var l_oData = l_oSubTree.oData;

					if (l_oData == null) continue;

					l_oRow = document.createElement('div');
					l_oRow.id = this.sIdentifier + '_' + l_oSubTree.iID;
					l_oRow.subTreeID = l_oSubTree.iID;
					l_oRow.parent = l_oCurrentDiv.parent + '_' + l_oTree.iID;

					if (l_oSubTree.aSubTree.length > 0) {
						if(l_oSubTree.bOpened) {
							l_oRow.onclick = function() { l_oReference.close(this.subTreeID); }
						} else {
							l_oRow.onclick = function() { l_oReference.open(this.subTreeID); }
						}
					}

					l_oRow.innerHTML = l_oData.treeContents();
					if (l_oNextDiv == null) {
						l_oDiv.appendChild(l_oRow);
					} else {
						l_oDiv.insertBefore(l_oRow, l_oNextDiv);
					}

					if (l_oSubTree.bOpened && l_oSubTree.aSubTree.length > 0) {
						this.refresh(l_oSubTree.iID);
					}
				}

				// The tree is closed
			} else {
				l_oCurrentDiv.onclick = function() { l_oReference.open(this.subTreeID); }

				l_oNode = l_oDiv.firstChild;
				while (l_oNode.nextSibling != null) {
					l_oNextSibling = l_oNode.nextSibling;

					l_oMatch = new RegExp('^' + l_oCurrentDiv.parent + '_' + p_iID);
					l_sParent = new String(l_oNode.parent);
					l_aResults = l_sParent.match(l_oMatch);

					if (l_aResults != null) l_oDiv.removeChild(l_oNode);

					l_oNode = l_oNextSibling;
				}
			}
		}
	}
}

var General = {
	Interface : {
		Calendar : {
			calendarObj : null,
			frame : null,
			focus : {
				day : null,
				month : null,
				year : null,
				display : null,

				clear : function() {
					this.day = null;
					this.month = null;
					this.year = null;
					this.display = null;
				}
			},

			init : function(p_sFrame) {
				if (!_e(p_sFrame)) {
					alert('Non-existent calendar frame ' + p_sFrame + '!');
					return;
				}

				this.frame = p_sFrame;
				this.calendarObj = new YAHOO.widget.Calendar('YAHOO_calendar', p_sFrame + '_content');
				this.calendarObj.render();
			},

			setFocus : function(p_oFields) {
				this.focus.clear();
				if(typeof p_oFields.day == "string" || typeof p_oFields.day == "String"){
					this.focus.day = _e(p_oFields.day);
				}
				if(typeof p_oFields.month == "string" || typeof p_oFields.month == "String"){
					this.focus.month = _e(p_oFields.month);
				}
				if(typeof p_oFields.year == "string" || typeof p_oFields.year == "String"){
					this.focus.year = _e(p_oFields.year);
				}
				if(typeof p_oFields.display == "string" || typeof p_oFields.display == "String"){
					this.focus.display = _e(p_oFields.display);
				}
			},

			open : function(p_oObj) {
				var l_oCalendar = _e(this.frame);
				if (!l_oCalendar) return;

				l_oCalendar.style.display = '';

				var l_aPos = { X : 0, Y : 0 };
				var l_aOffset = { X : 25, Y : 0 };

				if (!isNaN(p_oObj.x) && !isNaN(p_oObj.y)) {
					l_aPos.X = p_oObj.x;
					l_aPos.Y = p_oObj.y;
				} else {
					var l_aYahooPos = YAHOO.util.Dom.getXY(p_oObj);
					l_aPos.X = l_aYahooPos[0];
					l_aPos.Y = l_aYahooPos[1];
				}

				if (p_oObj.offsetWidth) {
					l_aOffset.X = p_oObj.offsetWidth;
				}
				l_aPos.X += l_aOffset.X;
				l_aPos.Y += l_aOffset.Y;

				YAHOO.util.Dom.setXY(l_oCalendar, [l_aPos.X, l_aPos.Y]);

				General.Interface.Calendar.calendarObj.selectEvent.subscribe(function() {
					var l_oYahooDate = General.Interface.Calendar.calendarObj.getSelectedDates()[0];
					var l_oDate = {
						day:   l_oYahooDate.getDate(),
						month: l_oYahooDate.getMonth() + 1,
						year:  l_oYahooDate.getFullYear()
					};
					l_sDisplay = l_oDate.year + '-' + pad(l_oDate.month, '0', 2) + '-' + pad(l_oDate.day, '0', 2);

					if (General.Interface.Calendar.focus.day != null)     General.Interface.Calendar.focus.day.value =     l_oDate.day;
					if (General.Interface.Calendar.focus.month != null)   General.Interface.Calendar.focus.month.value =   l_oDate.month;
					if (General.Interface.Calendar.focus.year != null)    General.Interface.Calendar.focus.year.value =    l_oDate.year;
					if (General.Interface.Calendar.focus.display != null) General.Interface.Calendar.focus.display.value = l_sDisplay;

					General.Interface.Calendar.close();
				});
			},

			clear : function() {
				if (General.Interface.Calendar.focus.day != null)     General.Interface.Calendar.focus.day.value =     null;
				if (General.Interface.Calendar.focus.month != null)   General.Interface.Calendar.focus.month.value =   null;
				if (General.Interface.Calendar.focus.year != null)    General.Interface.Calendar.focus.year.value =    null;
				if (General.Interface.Calendar.focus.display != null) General.Interface.Calendar.focus.display.value = null;
			},

			close : function() {
				var l_oCalendar = _e(this.frame);
				if (!l_oCalendar) return;

				l_oCalendar.style.display = 'none';
				General.Interface.Calendar.focus.clear();
			}
		}
	}
};






/**
* Tab function
**/
function showTab(l_sSection, l_iTab) {
	/* Fetch elements */
	var l_oSection = document.getElementById(l_sSection);
	var l_oSectionTabs = document.getElementById(l_sSection + '_tabs');

	var l_aTabs = l_oSectionTabs.getElementsByTagName('div');
	var l_aPages = l_oSection.getElementsByTagName('div');

	/* Update tab layout */
	for (var l_iKey = 0; l_iKey < l_aTabs.length; l_iKey++) {
		var l_oTab = l_aTabs[l_iKey];
		if (l_oTab.getAttribute('action') && l_oTab.getAttribute('action').substr(0, 4) == 'tab_') {
			if (l_oTab.getAttribute('action') == 'tab_' + l_iTab) {
				l_oTab.className = 'tab_active';
			} else {
				l_oTab.className = 'tab';
			}
		}
	}

	/* Show corresponding tab page */
	for (var l_iKey = 0; l_iKey < l_aPages.length; l_iKey++) {
		var l_oPage = l_aPages[l_iKey];
		if (l_oPage.getAttribute('action') && l_oPage.getAttribute('action').substr(0, 10) == 'tabscreen_') {
			if (l_oPage.getAttribute('action') == 'tabscreen_' + l_iTab) {
				l_oPage.style.display = '';
			} else {
				l_oPage.style.display = 'none';
			}
		}
	}
}

/**
* Currency class
**/
function currency(p_aCurrency) {

	this.m_sSymbolLeft         = p_aCurrency['symbol_left'];
	this.m_sSymbolRight        = p_aCurrency['symbol_right'];
	this.m_iDecimalPlaces      = p_aCurrency['decimal_places'];
	this.m_sDecimalPoint       = p_aCurrency['decimal_point'];
	this.m_sThousandGroup      = p_aCurrency['thousands_point'];

	this.format = function(p_fPrice) {
		var str = number_format(p_fPrice, this.m_iDecimalPlaces, this.m_sDecimalPoint, this.m_sThousandGroup);
		if (this.m_sSymbolLeft != '') str = this.m_sSymbolLeft + ' ' + str;
		if (this.m_sSymbolRight != '') str = str + ' ' + this.m_sSymbolRight;
		return str;
	}

	this.symbol = function() {
		if (this.m_sSymbolLeft.length > 0) return this.m_sSymbolLeft;
		if (this.m_sSymbolRight.length > 0) return this.m_sSymbolRight;
		return 'moo';
	}
}

/**
* Number padding
*/
function pad(p_iNumber, p_sChar, p_iLength) {
	l_sStr = '' + p_iNumber;
	while (l_sStr.length < p_iLength) {
		l_sStr = p_sChar + l_sStr;
	}
	return l_sStr;
}

/**
* PRICE FORMATTER using number_format function
**/
function number_format (number, decimals, dec_point, thousands_sep)
{
	var exponent = "";
	var numberstr = number.toString ();
	var eindex = numberstr.indexOf ("e");
	if (eindex > -1)
	{
		exponent = numberstr.substring (eindex);
		number = parseFloat (numberstr.substring (0, eindex));
	}

	if (decimals != null)
	{
		var temp = Math.pow (10, decimals);
		number = Math.round (number * temp) / temp;
	}
	var sign = number < 0 ? "-" : "";
	var integer = (number > 0 ?
	Math.floor (number) : Math.abs (Math.ceil (number))).toString ();

	var fractional = number.toString ().substring (integer.length + sign.length);
	dec_point = dec_point != null ? dec_point : ".";
	fractional = decimals != null && decimals > 0 || fractional.length > 1 ?
	(dec_point + fractional.substring (1)) : "";
	if (decimals != null && decimals > 0)
	{
		for (i = fractional.length - 1, z = decimals; i < z; ++i)
		fractional += "0";
	}

	thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ?
	thousands_sep : null;
	if (thousands_sep != null && thousands_sep != "")
	{
		for (i = integer.length - 3; i > 0; i -= 3)
		integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
	}

	return sign + integer + fractional + exponent;
}

/**
* DATE CONVERTOR
**/
function getDate(p_sDateStr) {
	var l_iYear = parseInt(p_sDateStr.substring(0, 4));
	var l_iMonth = parseInt(p_sDateStr.substring(5, 7));
	var l_iDay = parseInt(p_sDateStr.substring(8, 10));
	var l_iHour = parseInt(p_sDateStr.substring(11, 13));
	var l_iMinute = parseInt(p_sDateStr.substring(14, 16));
	var l_iSeconds = parseInt(p_sDateStr.substring(17, 19));
	return new Date(l_iYear, l_iMonth - 1, l_iDay, l_iHour, l_iMinute, l_iSeconds);
}
/**
* DEBUG ARRAY/OBJECT
* Print out structure and contents of array and objects. Uses recursive debug_r function.
**/
function debug(p_aVars){
	var l_sUrlEncodedVars = "";
	for(l_sKey in p_aVars){
		if(typeof p_aVars[l_sKey] == "array" || typeof p_aVars[l_sKey] == "object"){
			l_sUrlEncodedVars += debug_r(p_aVars[l_sKey], 'Array['+l_sKey+']');
		}else{
			l_sUrlEncodedVars += 'Array['+l_sKey+']' + '=' + p_aVars[l_sKey] + "\n";
		}
	}
	return l_sUrlEncodedVars;
}

/**
* Walk the array recursively to encode the data capture inside
**/
function debug_r(p_aVars, p_sArrayPrefix){
	var l_sUrlEncodedVars = "";
	for(l_sKey in p_aVars){
		// Check if p_aVars[l_sKey] is an array
		if(typeof p_aVars[l_sKey] == "array" || typeof p_aVars[l_sKey] == "object"){
			l_sUrlEncodedVars += debug_r(p_aVars[l_sKey], p_sArrayPrefix + "[" + l_sKey + "]");
		}else{
			l_sUrlEncodedVars += p_sArrayPrefix + "[" + l_sKey + "]" + '=' + p_aVars[l_sKey] + "\n";
		}
	}
	return l_sUrlEncodedVars;
}

function isNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;

	var i=0;
	if (sText.charAt(0) == '-') {
		i = 1;
	}
	for (; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}

function _ev(p_oReference, p_sEventName, p_addressFunc) {
	if (!p_oReference.addEventListener && p_oReference.attachEvent) {
		p_oReference.attachEvent('on' + p_sEventName, p_addressFunc);
	}
	else {
		p_oReference.addEventListener(p_sEventName, p_addressFunc, true);
	}
}

function _dev(p_oReference, p_sEventName, p_addressFunc) {
	if (!p_oReference.removeEventListener && p_oReference.detachEvent) {
		p_oReference.detachEvent('on' + p_sEventName, p_addressFunc);
	}
	else {
		p_oReference.removeEventListener(p_sEventName, p_addressFunc, true);
	}
}

function testSupplier() {
	if (document.attachEvent) {
		// IE
		e = window.event;
		object = e.srcElement;
	}
	else {
		// rest of the world
		object = this;
	}
	str = object.id.substr(0, object.id.indexOf('line_'));
	currentLine = parseInt(object.id.substr(object.id.indexOf('line_') + 5));
	line = 0;
	while (element = _e(str + 'line_' + line++)) {
		if ((object.value == element.value) && ((line - 1) != currentLine)) {
			object.selectedIndex = oldSupplier;
			alert('This supplier was allready chosen!');
			break;
		}
	}
}

function memSupplier() {
	if (document.attachEvent) {
		// IE
		e = window.event;
		object = e.srcElement;
	}
	else {
		// rest of the world
		object = this;
	}
	oldSupplier = object.selectedIndex;
}

function emptyTable(p_sTableID, p_iStartingRow) {
	l_oTable = _e(p_sTableID);
	var	l_iCount;
	var	l_iRows = l_oTable.rows.length;
	for (l_iCount = p_iStartingRow; l_iCount < l_iRows; l_iCount++) {
		l_oTable.deleteRow(p_iStartingRow);
	}
}
