/* v.1.42|04.12.2010*/
/*
 * added alt name for newXMLHTTPRequest | request;
 **/
/* v.1.41|30.11.2010*/
/*
 * added: clearNode();
 **/
var cm = common = new function()
{
	var me = this;
	/***************************** Working box animation ******************************/
	var dimmers = new Array();
	this.dimmerOpacity = 0.6;
	this.dimmerColor = '#fff';
	var startWorkingBoxAnimation = this.startWorkingBoxAnimation = function()
	{
		for(var i = 0, ln = arguments.length; i < ln; i++)
		{
			var id = arguments[i];
			var owner = null;
			if(!(owner = getEl(id)))
				continue;
			if(!dimmers[id])
			{
				dimmers[id] = Node('div', {'style':'background-color:'+me.dimmerColor+';display:block;position:absolute;z-index:9000'}, cm.Node('span', {'style':'position:relative;'}, 'Loading...'));
				dimmers[id].a = new Animation(dimmers[id]);
				setOpacity(dimmers[id], 0);			
			}
			checkDimmer(owner, dimmers[id]);
			document.body.appendChild(dimmers[id]);
			dimmers[id].a.go(Array('opacity:'+me.dimmerOpacity), 200, 'simple');
		}
	};
	var stopWorkingBoxAnimation = this.stopWorkingBoxAnimation = function()
	{
		for(var i = 0, ln = arguments.length; i < ln; i++)
		{
			var id = arguments[i];
			if(!(dimmers[id] && dimmers[id].parentNode))
				continue;
			(function(){
				var dimmer = dimmers[id];
				dimmer.a.go(Array('opacity:0'), 200, 'simple', function(){
					if(dimmer.parentNode)
						dimmer.parentNode.removeChild(dimmer);
				});
			})();
		}
	}
	var checkDimmer = function(owner, dimmer)
	{
		dimmer.style.width = owner.offsetWidth + 'px';
		dimmer.style.height = owner.offsetHeight + 'px';
		
		dimmer.style.textAlign = 'center';
		dimmer.style.fontSize = '20px';
		
		dimmer.getElementsByTagName('span')[0].style.top = parseInt(owner.offsetHeight/2 - 20) + 'px';
		
		dimmer.style.top = getY(owner) + 'px';
		dimmer.style.left = getX(owner) + 'px';
	}
	/****************************** Hash function *****************************/
	var loadHashData = this.loadHashData = function()
	{
		var hash = document.location.hash.replace('#','').split('&');
		window.userRequest = {};
		for(var i = 0; hash.length > i; i++)
		{
			window.userRequest[hash[i].split('=')[0]] = hash[i].split('=')[1]; 
		}
		return true;
	}
	var reloadHashData = this.reloadHashData = function()
	{
		var hash = '#';
		for(var name in window.userRequest)
		{
			hash += name + '=' + window.userRequest[name];
		}
		document.location.hash = hash;
		return true;
	}
	/****************************** AJAX *****************************/
	var createXmlHttpRequestObject = this.createXmlHttpRequestObject = function()
	{
		var xmlHttp;
		
		try
		{
			xmlHttp = new XMLHttpRequest();
		}
		catch(e)
		{
			var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
			"MSXML2.XMLHTTP.5.0",
			"MSXML2.XMLHTTP.4.0",
			"MSXML2.XMLHTTP.3.0",
			"MSXML2.XMLHTTP",
			"Microsoft.XMLHTTP");
			for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
			{
				try
				{
					xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
				}
				catch (e) {}
			}
		}
		if (!xmlHttp)
			alert("Error creating the XMLHttpRequest object.");
		else
			return xmlHttp;
	}
	var newXMLHTTPRequest = this.request = this.newXMLHTTPRequest = function(req, params, method, handler)
	{
		var url = (method == 'POST' || method == 'post')? req : req + params;
		var httpRequestObject = createXmlHttpRequestObject();
		httpRequestObject.open(method, url, true);
		httpRequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		httpRequestObject.onreadystatechange = (handler != null)? function(){ if (httpRequestObject.readyState == 4) { handler(httpRequestObject.responseXML, httpRequestObject.readyState)}} : null;
		(method == 'POST' || method == 'post')? httpRequestObject.send(params) : httpRequestObject.send(null);
	}
	var responseInArray = this.responseInArray = function(xmldoc)
	{
		var response = xmldoc.getElementsByTagName('response')[0];
		var data = new Array();
		for(var i = 0; response.childNodes.length > i; i++)
		{
			if(response.childNodes[i].nodeType != 1)
				continue;
			var kids = response.childNodes[i].childNodes;
			var tmp = new Array();
			for(var k = 0; kids.length > k; k++)
			{
				if(kids[k].nodeType == 1)
					tmp[kids[k].tagName] = kids[k].firstChild? kids[k].firstChild.nodeValue : '';
			}
			data.push(tmp);
		}
		return data;
	}
	var getTxtVal = this.getTxtVal = function(o){return o.nodeType == 1 && o.firstChild? o.firstChild.nodeValue : '';}
	/****************************** Note *****************************/
	var showNote = this.showNote = function(txt)
	{
		if(typeof(noteDiv) == 'undefined')
		{
			noteDiv = Node('div', {'class':'notification'});
			noteAnim = new Animation(noteDiv);
			setOpacity(noteDiv, 0);
			document.body.appendChild(noteDiv);
		}
		
		noteDiv.style.display = 'block';
		noteDiv.innerHTML = txt;
		noteDiv.style.top = getBodyScrollTop() + 50 + 'px';
		noteDiv.style.left = (screen.width - noteDiv.offsetWidth)/2 + 'px';
		noteAnim.go(['opacity:0.8'], 500, 'simple', function(){
			window.setTimeout(function(){noteAnim.go(['opacity:0'], 500, 'simple', function(){noteDiv.style.display = 'none';})}, 2000);
		});
	}
	/****************************** Scroll *****************************/
	var getBodyScrollTop = this.getBodyScrollTop = function()
	{
		return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
	}

	/****************************** Events ******************************/
	var getEvent = this.getEvent = function(e){return e || event;}
	var getObjFromEvent = this.getObjFromEvent = function(e){return  e.target || e.srcElement;}
	var addEvent = this.addEvent = function(elem, type, handler){try{elem.addEventListener(type, handler, true);}catch(e){elem.attachEvent("on"+type, handler);}}
	var removeEvent = this.removeEvent = function(elem, type, handler){try{elem.removeEventListener(type, handler, true);}catch(e){elem.detachEvent("on"+type, handler);}}
	var onload = this.onload = function(handler){try{addEvent(window, 'load', handler);}catch(e){}};
	/****************************** Get Element Adjustments ******************************/
	var getX = this.getX = function(o){var x=0;while(o){x+=o.offsetLeft;o=o.offsetParent;}return x;}
	var getY = this.getY = function(o){var y=0;while(o){y+=o.offsetTop;o=o.offsetParent;}return y;}	
	/******************************** Get Element ********************************/
	var getEl = this.getEl = function(id){return document.getElementById(id);};
	var getByAttr = this.getByAttr = function(attr, value, element){
		var p = element||document;
		if(p.querySelectorAll)
			return p.querySelectorAll("[" + attr + "='" + value + "']");
		var elements = p.getElementsByTagName('*');
		var stack = [];
		for(var i = 0, ln = elements.length; i < ln; i++){
			if(elements[i].getAttribute(attr) == value)
				stack.push(elements[i]);
		}
		return stack;
	};
	var getByClass = this.getByClass = function(){
		var o = typeof(arguments[0]) == 'object' && arguments[0].nodeType == 1? arguments[0] : document;
		var str = o == arguments[0]? arguments[1] : arguments[0];
		var n = new RegExp('\\s' + str + '\\s|^' + str + '\\s|\\s' + str + '$|^' + str + '$');
		var nodes = o.getElementsByTagName('*');
		var rValue = [];
		for(var d in nodes)
		{
			
			if(nodes[d].nodeType == 1 && nodes[d].className.match(n))
				rValue.push(nodes[d]);
		}
		return rValue;
	}
	var getIFrameDOM = this.getIFrameDOM = function (o){
		return o.contentDocument ||o.document;
	}
	/******************************** Set opacity ********************************/
	var setOpacity = this.setOpacity = function(elem, val)
	{
		if(elem)
		{
			if(document.all)
				elem.style.filter = "alpha(opacity=" + (Math.floor(val * 100)) + ")";
			else
				elem.style.opacity = val;
		}
	}
	/******************************** Node builder ********************************/
	var Node = this.Node = function()
	{
		var el = document.createElement(arguments[0]);
		if(typeof arguments[1] == "object" && !arguments[1].nodeType)
		{
			for(var i in arguments[1])
			{
				if(i == 'style')
					el.style.cssText = arguments[1][i];
				else if(i == 'class')
					el.className = arguments[1][i];
				else
					el.setAttribute(i, arguments[1][i]);
			}
			i = 2;
		}
		else
			i = 1;
			
		for(var ln = arguments.length; i < ln; i++)
		{
			if(typeof arguments[i] == 'string' || typeof arguments[i] == 'number')
				el.innerHTML = arguments[i];//el.appendChild(document.createTextNode(arguments[i]));
			else
				el.appendChild(arguments[i]);
		}
		return el;
	}
	/******************************** Nodes ********************************/
	var clearNode = this.clearNode = function(o)
	{
		while(o.firstChild)
		{
			o.removeChild(o.firstChild);
		}
		return o;
	}
	/******************************** Animation ********************************/
	var Animation = this.Animation = function(o)
	{
		var obj = o;
		var processes = new Array()
		this.go = function(){
			var pId = Math.random()
			var properties = new Array();
			var ln =  arguments[0].length;
			for(var i = 0; i < ln; i++)
			{
				var tmp = new Array();
					tmp['name'] = arguments[0][i].split(':')[0];
					tmp['new'] = (tmp['name'].match(/color/i))?
							((!arguments[0][i].split(':')[1].match(/rgb/i))? hex2rgb(arguments[0][i].split(':')[1].match(/[\w\d]+/)[0])
							: 
							Array(parseInt(arguments[0][i].split(':')[1].match(/\d+/g)[0]), parseInt(arguments[0][i].split(':')[1].match(/\d+/g)[1]), parseInt(arguments[0][i].split(':')[1].match(/\d+/g)[2])))
							:
							arguments[0][i].split(':')[1].replace(/[^\-0-9\.]/g,'');
					tmp['dimension'] = arguments[0][i].split(':')[1].match(/\d+(\D*)/)[1];
					tmp['old'] = getStyle(obj, tmp);
				properties.push(tmp);
			}
			var duration = arguments[1];
			var delta = arguments[2]? eval(arguments[2]) : simple;
			var onStop = (arguments[3])? arguments[3] : function(){};
	
			var start = new Date().getTime();
			var procLn = processes.length;
			for(var i = 0; i < procLn; i++)
			{
				processes[i][1] = false;
			}
			processes.push(new Array(pId, true));
			setTimeout(function(){
				var processId = pId;
				var procLn = processes.length;
				for(var i = 0; i < procLn; i++)
				{
					if(processes[i][0] == processId && !processes[i][1])
					{
						processes.splice(i,1);
						return false;
					}
					else if(processes[i][0] == processId && processes[i][1])
						break;
				}
	
				var now = (new Date().getTime()) - start;
				var progress = now / duration;
				if(progress < 1)
				{
					for(var i = 0; i < ln; i++)
					{
						var val = (properties[i]['new'] - properties[i]['old']) * delta(progress) + properties[i]['old'];
						if(properties[i]['name'] == 'opacity')
							setOpacity(obj, val);
						else if(properties[i]['name'].match(/color/i))
						{
							var r = parseInt((properties[i]['new'][0] - properties[i]['old'][0]) * delta(progress) + properties[i]['old'][0]);
							var g = parseInt((properties[i]['new'][1] - properties[i]['old'][1]) * delta(progress) + properties[i]['old'][1]);
							var b = parseInt((properties[i]['new'][2] - properties[i]['old'][2]) * delta(progress) + properties[i]['old'][2]);
							obj.style[properties[i]['name']] = rgb2hex(r, g, b);
						}
						else
						{
							obj.style[properties[i]['name']] = parseInt(val) + properties[i]['dimension'];
						}
					}
					setTimeout(arguments.callee, 10);
				}
				else
				{
					for(var i = 0; i < ln; i++)
					{
						if(properties[i]['name'] == 'opacity')
							setOpacity(obj, properties[i]['new']);
						else if(properties[i]['name'].match(/color/i))
							obj.style[properties[i]['name']] = rgb2hex(properties[i]['new'][0], properties[i]['new'][1], properties[i]['new'][2]);
						else
							obj.style[properties[i]['name']] = properties[i]['new'] + properties[i]['dimension'];
					}
					processes.splice(i,1);
					onStop();
				}
			}, 10);
		}
		var simple = function(progress)
		{
			return progress;
		}
		var inhibition = function(progress)
		{
			return 1 - acceleration(1 - progress);
		}
		var acceleration = function(progress)
		{
			return Math.pow(progress, 3);
		}
		var smooth = function(progress)
		{
			return (progress < 0.5)? acceleration(2 * progress) / 2 : 1 - acceleration(2 * (1 - progress)) / 2;
		}
	
		var getStyle = function(o, old)
		{
			switch(old['name'])
			{
				case 'width':
				case 'height':
				case 'top':
				case 'left':
					var Name = old['name'].charAt(0).toUpperCase() + old['name'].substr(1, old['name'].length-1);
					if(old['dimension'] == '%' && !o.style[old['name']].match(/%/))
					{
						var el = (o.parentNode.tagName.match(/body/i) || Name.match(/top|left/i))? 'client' : 'offset';
						var pv = (Name.match(/width|left/i))? o.parentNode[el + 'Width'] : o.parentNode[el + 'Height'];
						return 100 * ( o['offset' + Name] / pv );
					}
					else if((old['dimension'] == '%' && o.style[old['name']].match(/%/))
							|| (old['dimension'] == 'px' && o.style[old['name']].match(/px/)))
						return parseInt(o.style[old['name']]);
					return o['offset' + Name];
				break;
				case 'opacity':
					if(document.all)
					{
						var reg = /alpha\(opacity=(.*)\)/;
						var res = reg.exec(o.style.filter);
						return (res)? res[1] / 100 : 1;
					}
					else
					{
						var val = parseFloat(o.style.opacity);
						return (!isNaN(val))? val : 1;
					}
				break;
				default:
					if(old['name'].match(/color/i))
					{
						
						if(o.style[old['name']].match(/rgb/i))
							return Array(parseInt(o.style[old['name']].match(/\d+/g)[0]), parseInt(o.style[old['name']].match(/\d+/g)[1]), parseInt(o.style[old['name']].match(/\d+/g)[2]));	
						return hex2rgb(o.style[old['name']].match(/[\w\d]+/)[0]);	
					}
					
					if(o.style[old['name']])
						return parseInt(o.style[old['name']]);
				return 0;
			}
		}
		var setOpacity = function(elem, val)
		{
			if(elem)
			{
				if(document.all)
					elem.style.filter = "alpha(opacity=" + (Math.floor(val * 100)) + ")";
				else
					elem.style.opacity = val;
			}
		}
	
		var rgb2hex = function (r, g , b) 
		{
			var rgb= new Array(r, g, b);
			for(i in rgb)
			{
				rgb[i]=Number(rgb[i]).toString(16);	
				if(rgb[i] == '0')
					rgb[i] = '00';
				else if(rgb[i].length == 1)
					rgb[i] = '0' + rgb[i];
			}
			return '#'+rgb.join('');
		}
		var hex2rgb = function(hex)
		{
			return(function(v){return [v >> 16 & 255, v >> 8 & 255, v & 255];})(parseInt(hex, 16));
		}
	
	}
	var rgb2hex = this.rgb2hex = function (r, g , b) 
	{
		var rgb= new Array(r, g, b);
		for(i in rgb)
		{
			rgb[i]=Number(rgb[i]).toString(16);	
			if(rgb[i] == '0')
				rgb[i] = '00';
			else if(rgb[i].length == 1)
				rgb[i] = '0' + rgb[i];
		}
		return '#'+rgb.join('');
	}
	/******************************** Cookie ********************************/
	this.getCookie = function(name)
	{
	    var matches = document.cookie.match(new RegExp(
	      "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
	    ))
	    return matches ? decodeURIComponent(matches[1]) : undefined 
	}
	this.setCookie = function(name, value, props)
	{
	    props = props || {}
	    var exp = props.expires
	    if (typeof exp == "number" && exp) {
	        var d = new Date()
	        d.setTime(d.getTime() + exp*1000)
	        exp = props.expires = d
	    }
	    if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
	 
	    value = encodeURIComponent(value)
	    var updatedCookie = name + "=" + value
	    for(var propName in props){
	        updatedCookie += "; " + propName
	        var propValue = props[propName]
	        if(propValue !== true){ updatedCookie += "=" + propValue }
	    }
	    document.cookie = updatedCookie
	}
	this.deleteCookie = function(name) 
	{
	    setCookie(name, null, { expires: -1 })
	}
}
