/**
 * WMA JavaScript library
 * Composed 2006 by Waldek Mastykarz
 * All rights reserved  
 * @created		2006-11-03 18:00:00
 * @modified	2006-11-03 18:00:00
 * @version		1.0
 */		 		 		
var WMA = WMA || {} // Declare the WMA namespace

/****** GENERAL ******/

/**
 * is... functions
 */
WMA.isArray = function(a) {
	return isObject(a) && a.constructor == Array;
}

WMA.isFunction = function(a) {
	return typeof a == 'function';
}

WMA.isNull = function(a) {
	return a === null;
}

WMA.isObject = function(a) {
	return (a && typeof a == 'object') || WMA.isFunction(a);
}
		 				
WMA.isString = function(a) {
	return typeof a ==  "string";
}

/****** USER AGENT ******/

/**		
 * User Agent detection.
 * Invoke using WMA.userAgent.init();
 * Available properties:
 * - name - User Agent name
 * - version - User Agent version
 * - OS - User Agent OS
 * 
 * Quirksmode
 * http://www.quirksmode.org/js/detect.html		 		 
 */	 		 		 		 		
WMA.userAgent = {	 			 			
	init: function() {
		this.name = this.searchString(this.dataBrowser) || "Unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "unknown version";
		this.OS = this.searchString(this.dataOS) || "unknown OS";
	},
	
	searchString: function(data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	
	searchVersion: function(dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
}
WMA.userAgent.init();

/****** VISUAL ******/

/**
 * Sets equal height|width to given elements
 * Takes as parameters both objects and objects' ID (string)		 
 * @author	Waldek Mastykarz
 * @param	string	height|width
 * @dependency	WMA.isFunction
 * @dependency	WMA.isObject   
 * @dependency	WMA.getStyle  
 */ 		
WMA.equalSize = function(sDim) {
	// control whether the required functions are available and the dimension
	// is set correctly
	if (WMA.equalSize.arguments.length < 2 ||
		(sDim != 'height' && sDim != 'width') ||
		!WMA.isFunction ||
		!WMA.isObject ||
		!WMA.isFunction(WMA.getStyle) ||
		!document.getElementById)
		return;
	
	// set variables
	var iMax = 0; // max height
	var iCurrent = 0; // current height
	var obj; // object
	
	// process the parameters to obtain the height of the highest element	
	for (var i = 1; i < WMA.equalSize.arguments.length; i++) {
		obj = WMA.equalSize.arguments[i];
		if (WMA.isObject(obj))
			iCurrent = WMA.getStyle(obj, sDim);
		else if (document.getElementById(obj))
			iCurrent = WMA.getStyle(document.getElementById(obj), sDim);
		
		iCurrent = parseInt(iCurrent);
		iMax = (iCurrent > iMax) ? iCurrent : iMax;
	}
	
	// set the height to all elements
	for (var i = 1; i < WMA.equalSize.arguments.length; i++) {
		obj = WMA.equalSize.arguments[i];
		if (WMA.isObject(obj))
			obj.style[sDim] = iMax + "px";
		else if (document.getElementById(obj))
			document.getElementById(obj).style[sDim] = iMax + "px";
	}
}

/**
 * Returns all elements with the given attribute="value" within the given parent
 * @param	object	parent object
 * @param	string	tag name
 * @param	string	attribute
 * @param	string	attribute's value
 * @return	array	found objects
 * 
 * Copyright Robert Nyman, http://www.robertnyman.com
 * Free to use if this text is included		 		 
 */		 		 		 		 		 		 		
WMA.getElementsByAttribute = function(oElm, strTagName, strAttributeName, strAttributeValue) {
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
    var oCurrent;
    var oAttribute;
    for(var i=0; i<arrElements.length; i++){
        oCurrent = arrElements[i];
        oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
        if(typeof oAttribute == "string" && oAttribute.length > 0){
            if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                arrReturnElements.push(oCurrent);
            }
        }
    }
    return arrReturnElements;
}

/**
 * Returns elements of the given class
 * @param	string	class name		 
 * @param	object	parent object; default document
 * @param	string	tag name; * for any tag (default)
 * @return	array	found objects
 * 
 * Written by Jonathan Snook, http://www.snook.ca/jonathan
 * Add-ons by Robert Nyman, http://www.robertnyman.com
 * Updated by Waldek Mastykarz		 		 		 		 
 */		 			 		 		 		
WMA.getElementsByClassName = function(strClassName, oElm, strTagName) {
	// WMA: 2006-11-03 | Set defaults
	oElm = oElm || document;
	strTagName = strTagName || "*";
	
	if (!strClassName.replace)
		return false;
	
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++) {
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)) {
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements);
}	

/**
 * Returns rendered style of the given object
 * @param	object	object
 * @param	string	CSS rule
 * @return	string	rendered CSS value
 * @dependency	WMA.isObject 
 * @dependency	WMA.userAgent  
 * 
 * Written by Robert Nyman, http://www.robertnyman.com
 * Updated by Waldek Mastykarz	 		 		  		 
 */		 		 		 		 		
WMA.getStyle = function(oElm, strCssRule) {
	var strValue = "";
	// WMA: 2006-11-03 | IE fix
	if (WMA.isObject &&
		WMA.isObject(WMA.userAgent) &&
		WMA.userAgent.name == "Explorer" &&
		(strCssRule == "height" || strCssRule == "width")) {
		var firstLetter = strCssRule.substring(0,1);
		firstLetter = firstLetter.toUpperCase();
		strValue = oElm["offset" + firstLetter + strCssRule.substring(1,strCssRule.length)];
	}
	else if(document.defaultView && document.defaultView.getComputedStyle) {
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

/**
 * Toggles object
 * @author	Waldek Mastykarz		 
 * @param	string|object	Object to toggle
 * @dependency	WMA.isObject 
 */		 		 		
WMA.toggle = function(obj) {
	if (WMA.isObject &&
		document.getElementById) {
		if (!WMA.isObject(obj)) {
			if (!document.getElementById(obj))
				return;
			else
				obj = document.getElementById(obj);
		}
		
		obj.style.display = (obj.style.display == "none") ? "" : "none";					
	}
}

/****** BEHAVIOUR ******/

/**
 * Cross-browser event listener attacher
 * @author	Waldek Mastykarz		 
 * @param	string		event: lowercase without "on"
 * @param	function	function_name without() or function() {<your function>}
 * @param	object		object where the event listener will be attached to; default window
 * @version	1.1		 
 * 
 * CHANGES LOG:
 * 1.1		- obj param added.  		 		 		 	 
 */		 		 		 
WMA.attachEvent = function(sEvent, rFunction, obj) {
	// set defaults
	obj = obj || window;
	
	if (typeof obj.addEventListener != "undefined") {
	   obj.addEventListener(sEvent, rFunction, false);
	}
	if (typeof document.addEventListener != "undefined") {
	   document.addEventListener(sEvent, rFunction, false);
	}
	else if (typeof obj.attachEvent != "undefined") {
	   obj.attachEvent('on' + sEvent, rFunction);
	}
	else
		return false;
}

/**
 * Cross-browser event listener detacher
 * @author	Waldek Mastykarz		 
 * @param	string		event: lowercase without "on"
 * @param	function	function_name without() or function() {<your function>}
 * @param	object		object where the event listener will be detached from; default window
 * @version	1.1		 
 * 
 * CHANGES LOG:
 * 1.1		- obj param added.  		 		 		 	 
 */		 		 		 
WMA.detachEvent = function(sEvent, rFunction, obj) {
	// set defaults
	obj = obj || window;
	
	if (typeof obj.removeEventListener != "undefined") {
	   obj.removeEventListener(sEvent, rFunction, false);
	}
	if (typeof document.removeEventListener != "undefined") {
	   document.removeEventListener(sEvent, rFunction, false);
	}
	else if (typeof obj.detachEvent != "undefined") {
	   obj.detachEvent('on' + sEvent, rFunction);
	}
	else
		return false;
}

/****** CONTENT ******/

/**
 * Removes HTML tags from the given string. Optionally replaces
 * brackets entities with their HTML equivalents
 * @author	Waldek Mastykarz		 
 * @param	string	string containing HTML tags
 * @param	boolean	set to true to replace &lt; and &gt; with < and >; default false
 * @return	string	string without HTML tags		 
 */		 		 		 		 		
WMA.stripHTML = function(sHTML, escapeBrackets) {
	escapeBrackets = escapeBrackets || false;
	
	// replace brackets entities
	if (escapeBrackets)
		sHTML = sHTML.replace(/&(lt|gt);/g, function (sMatch, p) {
			return (p == "lt") ? "<" : ">";
		});
	
	// strip all HTML
	sHTML = sHTML.replace(/<\/?[^>]+(>|$)/g, "");
	return sHTML;
}

/**
 * Converts given HTML to valid XHTML
 * @author	http://robertnyman.com/roblab/javascript-html-to-xhtml.htm
 * @param	string	string containing HTML
 * @return	string	string containing valid XHTML
 */		 		 		 		 		
WMA.convertToXHTML = function(sHTML) {
	// Replaces uppercase tags and attribute names with lowercase characters
	sHTML = sHTML.replace(/<\/?[A-Z]+|[A-Z]+=/g, function (sMatch) {
		return sMatch.toLowerCase();
	});
		
	// Replaces single quotes with double ones
	sHTML = sHTML.replace(/='[^']*'/g, function (sMatch) {
		return sMatch.replace(/'/g, "\"");
	});
	
	// Replaces attribute values without quoutes with double quotes
	sHTML = sHTML.replace(/=([\w\d\s]*)(\s\w+=|>)/g, "=\"$1\"$2");
		
	// Closes unclosed tags
	// WMA: 2006-11-03 | Extra tags added
	sHTML = sHTML.replace(/(<(meta|link|input|img|br)[^>]*)([^\/]|\b)>/gi, "$1$3 />");
}

WMA.setListItems = function(oList, aItems) {
	var list = $(oList);
	if (list !== false) {
		for (i = 0; i < list.options.length; i++) {
			for (j = 0; j < aItems.length; j++) {
				if (list.options[i].value == aItems[j])
					list.options[i].selected = true;
			}
		}
	}
	else
		return false;
}

WMA.setRadioItem = function(oForm, sRadio, sValue) {
	var form = document.forms[oForm];
	if (form !== false) {
		if (form[sRadio]) {
			for (var i = 0; i < form[sRadio].length; i++)
				if (form[sRadio][i].value == sValue)
					form[sRadio][i].checked = true;
		}
	}
	else
		return false;
}

// Examples:
// WMA.attachEvent("load", function() {alert(WMA.getElementsByClassName("abc"))});
// WMA.attachEvent("load", function() {WMA.equalSize("width", document.getElementById("a"), "b", "c")});

// set current namespace
WMA.Validator = WMA.Validator || {}

WMA.Validator = {
	isValidEmail: function(sEmail) {
		var reg = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
		
		return reg.test(sEmail);
	},
	
	isValidURL: function(sURL) {
		var reg = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
		
		return reg.test(sURL);
	} 
}
