// + created by: Thiago Genuino (http://thiagogenuino.com.br)
// + email: thiago@genuino.com.br
// + email 2: thiagogenuino@coldvector.com
// + note: Javascript object with common tools
// * Coldvector Tecnologia em Informática
// * http://www.coldvector.com
// * last modified: 2011-04-12
var Cold = {
	ie : /*@cc_on!@*/false,
	
	$ : function(element) {
		return document.getElementById(element);
	},
	
	onload : function(ev) {
		Cold.drag.scan();
		Cold.tools.scan();
		
		window.onmousemove = function(ev) {
			Cold.traceMouse.scan(ev);
		}
	},
	
	onresize : function(ev) {
		
	},
	
	onmousemove : function(ev) {
		return Cold.drag.move(ev);
	},
	
	toogle : function(id) {
		var div = Cold.$(id);
		
		if (div.style.display == 'none') {
			div.style.display = 'block'
		} else {
			div.style.display = 'none'
		}
	},
	
	loading : function(obj, className) {
		obj = (typeof obj == 'object' ? obj : Cold.$(obj));
		className = className || null;
		
		var opacity = Cold.element.create('div');
		if (className) {
			opacity.className = className;
		} else {
			opacity.style.backgroundColor = '#000';
			opacity.style.opacity = '0.8';
			opacity.style.filter = 'alpha(opacity=80)';
		}
		
		opacity.style.position = 'absolute';
		opacity.style.left = obj.offsetLeft+'px';
		opacity.style.top = obj.offsetTop+'px';
		opacity.style.width = obj.offsetWidth+'px';
		opacity.style.height = obj.offsetHeight+'px';
		opacity.style.zIndex = obj.style.zIndex+1;
		opacity.style.textAlign = 'center';
		
		var img = new Image();
		img.src = 'http://www.ibertec.com.br/img/sys/ajax.gif';
		img.style.marginTop = ((obj.offsetHeight / 2) - img.height)+'px';
		
		opacity.appendChild(img);
		
		obj.parentNode.appendChild(opacity);
		
		return opacity;
	},
	
	element : {
		create : function(type, id, params, appendTo, className, styles) {
			type = type || 'div';
			id = id || Cold.uniqid('_tmp');
			className = className || null;
			styles = styles || {};
			appendTo = (typeof appendTo == 'object' ? appendTo : Cold.$('appendTo')) || document.body;
			params = params || {};
			
			if (Cold.$(id)) return Cold.$(id);
			
			var obj = document.createElement(type);
			obj.id = id;
			obj.name = obj.id;
			
			for(key in params) {
				obj.setAttribute(key, params[key]);
			}
				
			if (className) obj.className = className;
			
			for(key in styles) {
				if (obj.styles.key) obj.styles.key = styles[key];
			}
			
			appendTo.appendChild(obj);
			
			return obj;
		},
		
		location : function(obj) {
			obj = (typeof obj == 'object' ? obj : Cold.$(obj));
			
			var x = 0;
			var y = 0;
			
			while(obj) {
				x += obj.offsetLeft;
				y += obj.offsetTop;
				
				obj = obj.offsetParent;
			}
			
			return {'x':x, 'y':y};
		}
	},
	
	upload : function(form, params, callback, funError) {
		params = params || {};
		callback = (typeof callback == 'function' ? callback : function() {});
		funError = (typeof funError == 'function' ? funError : function() {});
		
		var iframe = Cold.element.create('iframe');
		iframe.src = 'about:blank';
		iframe.style.display = 'none';
		
		params['iframeid'] = iframe.id;
		
		form.action = 'http://www.ibertec.com.br/ajax.php';
		form.target = iframe.name;
		
		var input = [];
		
		for(key in params) {
			input.push(Cold.element.create('input', key, {type : 'hidden', value : params[key]}));
			form.appendChild(input[input.length-1]);
		}
		
		form.submit();
				
		for(key in input) {
			input[key].parentNode.removeChild(input[key]);
		}
		
		var interval = setInterval(function() {
			try {
				var conteudo = iframe.contentDocument;
			} catch(e) {
				try {
					var conteudo = iframe.contentWindow.document;
				} catch(e2) {
					try {
						var conteudo = window.frames[iframe.id].document;
					} catch(e3) {
						alert(e3);
					}
				}
			}
			if (conteudo.body.innerHTML) {
				clearInterval(interval);
				
				eval('var res = '+conteudo.body.innerHTML+';');
				if (res.status == true) {
					if (res.scripts) eval(res.scripts);
					
					callback();
				} else {
					funError();
				}
				
				if (res.msg) alert(res.msg);
			}
		},100);
		
		return false;
	},
	
	traceMouse : {
		x : null,
		y : null,
		
		scan : function(ev) {
			ev = ev || window.event;
			var mousePos = Cold.drag.mouseCoords(ev);
			
			Cold.traceMouse.x = mousePos.x;
			Cold.traceMouse.y = mousePos.y;
			
			return false;
		}
	},
	
	getIEVersion : function() {
	
	    var rv = -1; // Return value assumes failure.
	
	    if (navigator.appName == 'Microsoft Internet Explorer') {
	
	        var ua = navigator.userAgent;
	
	        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
	
	        if (re.exec(ua) != null)
	
	            rv = parseFloat(RegExp.$1);
	
	    }
	
	    return rv;
	
	},
	
	selectRemoveOptions : function(select) {
		select = (typeof select == 'object' ? select : Cold.$(select));
//		select.options.length = 0;
		
		var selectParentNode = select.parentNode;
		var newSelectObj = select.cloneNode(false); // Make a shallow copy
		selectParentNode.replaceChild(newSelectObj, select);
		return newSelectObj;
	},
	
	removeChars : function(string, allowedChars) {
		string = string || null;
		allowedChars = allowedChars || '';
		
		var result = '';
		
		if (string) {
			for (i=0;i<string.length;i++) {
				if (allowedChars.indexOf(string.charAt(i)) > -1) {
					result += string.charAt(i);
				}
			}
		} else {
			result = false;
		}
		
		return result;
	},
	
	moeda2float : function(value) {
		if (value) {
			value = Cold.replaceAll(value, '.', '');
			value = Cold.replaceAll(value, ',', '.');
			
			return parseFloat(value);
		} else {
			return 0;
		}
	},
	
	go : function(url) {
		window.location = url;
	},
	
	blank : function(url,target) {
		target = target || null;
		
		window.open(url,target);
	},
	
	getScreenSize : function() {
		if (window.innerWidth) {
			var w = window.innerWidth;
			var h = window.innerHeight;
		} else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
			var w = document.documentElement.clientWidth;
			var h = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			var w = document.body.clientWidth;
			var h = document.body.clientHeight;
		}
		
		return {'w' : w , 'h' : h};
	},
	
	getScrollXY : function() {
		var scrOfX = 0, scrOfY = 0;
		
		if( typeof( window.pageYOffset ) == 'number' ) {
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		
		return { x : scrOfX, y : scrOfY };
	},
	
	replaceAll : function(str, de, para){
	    var pos = str.indexOf(de);
	    while (pos > -1){
			str = str.replace(de, para);
			pos = str.indexOf(de);
		}
	    return (str);
	},
	
	rand : function(n) {
		return ( Math.floor ( Math.random ( ) * n + 1 ) );
	},
	
	uniqid : function(prefix, more_entropy) {
	    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +    revised by: Kankrelune (http://www.webfaktory.info/)
	    // %        note 1: Uses an internal counter (in php_js global) to avoid collision
	    // *     example 1: uniqid();
	    // *     returns 1: 'a30285b160c14'
	    // *     example 2: uniqid('foo');
	    // *     returns 2: 'fooa30285b1cd361'
	    // *     example 3: uniqid('bar', true);
	    // *     returns 3: 'bara20285b23dfd1.31879087'
	    if (typeof prefix == 'undefined') {
	        prefix = "";
	    }
	
	    var retId;
	    var formatSeed = function (seed, reqWidth) {
	        seed = parseInt(seed, 10).toString(16); // to hex str
	        if (reqWidth < seed.length) { // so long we split
	            return seed.slice(seed.length - reqWidth);
	        }
	        if (reqWidth > seed.length) { // so short we pad
	            return Array(1 + (reqWidth - seed.length)).join('0') + seed;
	        }
	        return seed;
	    };
	
	    // BEGIN REDUNDANT
	    if (!this.php_js) {
	        this.php_js = {};
	    }
	    // END REDUNDANT
	    if (!this.php_js.uniqidSeed) { // init seed with big random int
	        this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
	    }
	    this.php_js.uniqidSeed++;
	
	    retId = prefix; // start with prefix, add current milliseconds hex string
	    retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
	    retId += formatSeed(this.php_js.uniqidSeed, 5); // add seed hex string
	    if (more_entropy) {
	        // for more entropy we add a float lower to 10
	        retId += (Math.random() * 10).toFixed(8).toString();
	    }
	
	    return retId;
	},
	
	debug_obj : function(obj) {
		for (key in obj) {
			if (!confirm(typeof obj+'- '+key+' = '+ obj[key])) break;
			
			if (typeof obj[key] == 'object') {
				Cold.debug_obj(obj[key]);
			}
		}
	},
	
	extractScript : function(result, keep) {
		keep = keep || false;
		var objScript = document.createElement('script');
		var ini, fim, src, src_i, src_f, codigo, fim_script;
		
		ini = result.indexOf('<script', 0);
		while(ini!=-1) {
			objScript = document.createElement("script");
			fim = result.indexOf('>', ini);
			src = (result.indexOf(' src', ini) == -1 ? null : result.indexOf(' src', ini));
			
			if ((src != null) &&(src < fim)) {
				src_i = result.indexOf('"', src)+1;
				src_f = result.indexOf('"', src_i);
				
				if ((src_i < fim) && (src_f < fim)) {
					codigo = result.substr(src_i,(fim - src_i - 1));
				}
				
				objScript.src = codigo;
			} else {
				fim_script = result.indexOf('<\/script>', fim);
				codigo = result.substr((fim+1), (fim_script - (fim+1)));
				
				objScript.text = codigo;
			}
			
			document.body.appendChild(objScript);
			if (keep == false) document.body.removeChild(objScript);
			
			ini = result.indexOf('<script', fim);
		}
	},

	drag : {
		target : null,
		obj : null,
		clone : null,
		fixed : true,
		active : false,
		mouseOffset : {x:0,y:0},
		mc : {},
		
		scan : function(obj, type) {
			obj = obj || document.body;
			type = type || 'div';
			var itens = obj.getElementsByTagName(type);
			for(i=0;i<itens.length;i++) {
				if (itens[i].getAttribute('drag') == 1) {
					Cold.drag.makeDrag(itens[i]);
				}
			}
		},
		
		makeDrag : function(obj) {
			obj.id = obj.id || Cold.uniqid('ColdDrag');
			
			obj.onmousedown = function(ev) {
				return Cold.drag.start(this, ev);
			}
			
			document.onmouseup = function(ev) {
				if (Cold.drag.active) {
					return Cold.drag.stop(ev);
				}
			}
		},
		
		createClone : function(obj, full, parent) {
			parent 	= parent || obj.parentNode;
			full 	= (full == false ? false : true);
			
			var clone = obj.cloneNode(full);
			
			if (Cold.ie) {
				clone.style.filter = 'alpha(opacity=50)';
			} else {
				clone.style.opacity = 0.5;
			}
			
			clone.style.border = '2px solid #000';
			clone.style.position = 'absolute';
			clone.style.top = obj.offsetTop + 'px';
			clone.style.left = obj.offsetLeft + 'px';
			clone.style.zIndex = 1000;
			parent.appendChild(clone);
			
			return clone;
		},
		
		mouseOffset : function(obj, ev) {
			ev = ev || window.event;
			
			var mouseCoords = Cold.drag.mouseCoords(ev);
			var objCoords = Cold.drag.getPosition(obj);
			
			return {x:mouseCoords.x - objCoords.x, y:mouseCoords.y - objCoords.y};
		},
	
		getPosition : function(obj) {
			var x = 0;
			var y = 0;
			
			while(obj) {
				x += obj.offsetLeft;
				y += obj.offsetTop;
				
				obj = obj.offsetParent;
			}
			
			return {'x':x, 'y':y};
		},
		
		mouseCoords : function(ev) {
			ev = ev || window.event;
			
			if(ev.pageX || ev.pageY) {
				return {x:ev.pageX, y:ev.pageY};
			}
			return {
				x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
				y:ev.clientY + document.body.scrollTop  - document.body.clientTop
			};
		},
		
		move : function(ev) {
			ev = ev || window.event;
			var mousePos = Cold.drag.mouseCoords(ev);
			
			Cold.mc = mousePos;
			
			if (Cold.drag.active) {
				Cold.drag.target.style.position = 'absolute';
				Cold.drag.target.style.top      = (mousePos.y - Cold.drag.mouseOffset.y) + 'px';
				Cold.drag.target.style.left     = (mousePos.x - Cold.drag.mouseOffset.x) + 'px';
			}
			
			return false;
		},
		
		start : function(obj, ev) {
			ev = ev || window.event;
			Cold.drag.obj = (typeof obj == 'object' ? obj : Cold.$(obj));
			
			if (Cold.drag.obj) {
				Cold.drag.clone = (Cold.drag.obj.getAttribute('clone') == 1 ? Cold.drag.createClone(Cold.drag.obj) : null);
				Cold.drag.fixed = (Cold.drag.obj.getAttribute('free') == 1 ? false : true);
				if (Cold.drag.clone) {
					// Drag com Clone
					Cold.drag.target = Cold.drag.clone;
				} else {
					// Drag sem Clone
					Cold.drag.target = (Cold.drag.obj.getAttribute('target') ? Cold.$(Cold.drag.obj.getAttribute('target')) : Cold.drag.obj);
				}
				
				var mouseOffset = Cold.drag.mouseOffset(Cold.drag.target, ev);
				
				Cold.drag.mouseOffset.x = mouseOffset.x;
				Cold.drag.mouseOffset.y = mouseOffset.y;
				
				Cold.drag.active = true;
			}
			
			return false;
		},
		
		stop : function(ev) {
			ev = ev || window.event;
			
			if (Cold.drag.fixed) {
				if (!Cold.drag.clone) {
					Cold.drag.target.style.position = 'static';
					Cold.drag.target.style.top = '';
					Cold.drag.target.style.left = '';
				}
			} else {
				if (Cold.drag.clone) {
					Cold.drag.obj.style.position = 'absolute';
					Cold.drag.obj.style.top = Cold.drag.target.offsetTop + 'px';
					Cold.drag.obj.style.left = Cold.drag.target.offsetLeft + 'px';
				}
				
			}
			
			Cold.drag.target.style.display = 'none';
			Cold.drag.checkCall(ev);
			Cold.drag.target.style.display = 'block';
			
			Cold.drag.active = false;
			
			if (Cold.drag.clone) Cold.drag.clone.parentNode.removeChild(Cold.drag.clone);
			
			Cold.drag.obj = null;
			Cold.drag.target = null;
			
			return Cold.drag.active;
		},
		
		checkCall : function(ev) {
			ev = ev || window.event;
			var mousePos = Cold.drag.mouseCoords(ev);
			
			var aim = document.elementFromPoint(mousePos.x, mousePos.y);
			while (aim) {
				if (aim.getAttribute('drop') == 1) {
					if ((aim.getAttribute('call')) && (Cold.drag.target.getAttribute('params'))) {
						var call = aim.getAttribute('call');
						var params = Cold.drag.target.getAttribute('params');
						
						eval(Cold.replaceAll(call, '#', params));
					}
				}
				
				aim = aim.offsetParent;
			}
			
		}
	},
	
	postIframe : function(name, appendTo, display) {
		name = name || Cold.uniqid('iframe');
		display = display || 'none';
		appendTo = (typeof appendTo == 'object' ? appendTo : Cold.$(appendTo)) || document.body;
		
		var obj = document.createElement('iframe');
		obj.name = name;
		obj.id = name;
		obj.style.display = display;
		obj.src = 'about:blank';
		
		appendTo.appendChild(obj);
		
		return obj;
	},
	
	removeObj : function(obj) {
		obj = (typeof obj == 'object' ? obj : Cold.$(obj)) || null;
		
		if (obj) {
			return (obj.parentNode ? obj.parentNode.removeChild(obj) : obj.offsetParent.removeChild(obj));
		}
	},
	
	ajax : function(target, loader, script) {
		script = script || 'ajax.php';
		loader = loader || 'carregando...';
		
		var xhttp = null;
		var params = {};
		var active = false;
		var result = null;
		var call = null;
		
		try {
			xhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				try {
					xhttp = new XMLHttpRequest();
				} catch (e3) {
					xhttp = false;
				}
			}
		}
		
		var start = function() {
			active = true;	
			
			var _params = '';
			for (key in params) {
				_params += '&'+key+'='+params[key];
			}
			
			xhttp.open("POST", script, true);
			xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xhttp.setRequestHeader("Content-length", _params.length);
			xhttp.setRequestHeader("Connection", "close");
			
			xhttp.send(_params);
		}
		
		var close = function() {
			active = false;
			//result = 'Closed!';
			xhttp.close();
		}
		
		var timeout = function(time) {
			time = (time || 30) * 60;
			var timeout = setTimeout(function() {
				if (active == true) {
					close();
					//result = 'Timeout!';
				}
			}, time);
		}
		
		var funRedirect = function() {
			if (xhttp.readyState == 1) {
				timeout();
			}
			if (xhttp.readyState == 4 && xhttp.status == 200) { 
				result 	= xhttp.responseText;
				Cold.extractScript(result);
				
				//active 	= false;
				setEnd();
				
				window.location = target;
			}
		}
		
		var funAlert = function() {
			if (xhttp.readyState == 1) {
				timeout();
			}
			if (xhttp.readyState == 4 && xhttp.status == 200) { 
				result 	= xhttp.responseText;  
				Cold.extractScript(result);
				
				//active 	= false;
				setEnd();
				
				alert(result);
			}
		}
		
		var funAdd = function () {
			if (xhttp.readyState == 1) {
				timeout();
			}
			if (xhttp.readyState == 4 && xhttp.status == 200) {
				obj 			= Cold.$(target);
				result 			= xhttp.responseText;
				
				Cold.extractScript(result);
				
				if (obj.value)
					obj.value += result;
					
				if (obj.innerHTML)
					obj.innerHTML += result;
				
				//active 	= false;
				setEnd();
			}
		}
		
		var funAddSelect = function() {
			if (xhttp.readyState == 1) {
				timeout();
			}
			if (xhttp.readyState == 4 && xhttp.status == 200) { 
				obj 	= Cold.$(target);
				result 	= xhttp.responseText;
				
				Cold.extractScript(result);
				
				var itens = result.slice(0,-1).split('|');
				
				for (i=0;i<itens.length;i++) {
					var opt = document.createElement("OPTION");
					split = itens[i].split('=');
					
					opt.text = split[0];
					opt.value = split[1];
					
					obj.options.add(opt);
				}
				
				//active 	= false;
				setEnd();
				
			}
		}
		
		var funUpdate = function () {
			if (xhttp.readyState == 1) {
				timeout();
				obj = Cold.$(target);
				
				if (obj.innerHTML) obj.innerHTML = loader;
				if (obj.value) obj.value = loader;
			}
			if (xhttp.readyState == 4 && xhttp.status == 200) {
				obj = Cold.$(target);
				result = xhttp.responseText;
				
				Cold.extractScript(result);
				
				obj.value = result;
				obj.innerHTML = result;
				
				//active 	= false;
				setEnd();
			}
		}
		
		var funUpdateSelect = function() {
			if (xhttp.readyState == 1) {
				timeout();
				obj = Cold.$(target);
				
				Cold.selectRemoveOptions(obj);
				
				var opt = document.createElement("OPTION");
				opt.text = 'carregando...';
				opt.value = 'carregando...';
				
				obj.options.add(opt);
			}
			
			if (xhttp.readyState == 4 && xhttp.status == 200) {
				obj 	= Cold.$(target);
				result 	= xhttp.responseText;
				
				Cold.extractScript(result);
				
				eval('var res = '+result+';');
				
				for(key in res) {
					var opt = document.createElement("OPTION");
					
					opt.text = res[key].nome;
					opt.value = key;
					
					obj.options.add(opt);
				}
				
				//active 	= false;
				setEnd();
				
			}
		}
			
		var funHide = function () {
			if (xhttp.readyState == 1) {
				timeout();
			}
			
			if (xhttp.readyState == 4 && xhttp.status == 200) {
				result 	= xhttp.responseText;
				Cold.extractScript(result); 
				obj = Cold.$(target);
				obj.style.display = 'none';
				
				//active 	= false;
				setEnd();
			}
		}
		
		var funLoad = function () {
			if (xhttp.readyState == 1) {
				timeout();
			}
			
			if (xhttp.readyState == 4 && xhttp.status == 200) { 
				result = xhttp.responseText;
				Cold.extractScript(result);
				
				//active 	= false;
				setEnd();
			}
		}
		
		var setEnd = function() {
			active = false;
			if (call) {
				call();
			}
		}
		
		// Funções Públicas
		
		this.setScript = function(script_path) {
			script = script_path;
		}
		
		this.setParam = function(key, value) {
			params[key] = value;
		}
		
		this.setParams = function(p) {
			params = p;
		}
		
		this.setLoader = function(html) {
			loader = unescape(html);
		}
		
		this.callback = function(fun) {
			call = fun;
		}
		
		// Funcionalidades
		
		this.add = function() {
			var isSelect 	= (Cold.$(target).type ? (Cold.$(target).type == 'select-one' ? true : false) : false);
			
			if (isSelect) {
				xhttp.onreadystatechange = funAddSelect;
			} else {
				xhttp.onreadystatechange = funAdd;
			}
			
			return start();
		}
		
		this.update = function() {
			var isSelect 	= (Cold.$(target).type ? (Cold.$(target).type == 'select-one' ? true : false) : false);
			
			if (isSelect) {
				xhttp.onreadystatechange = funUpdateSelect;
			} else{
				xhttp.onreadystatechange = funUpdate;
			}
			
			return start();
		}
		
		this.hide = function() {
			xhttp.onreadystatechange = funHide;
			return start();
		}
		
		this.load = function() {
			xhttp.onreadystatechange = funLoad;
			return start();
		}
		
		this.redirect = function(url) {
			target = url;
			xhttp.onreadystatechange = funRedirect;
			return start();
		}
		
		this.alert = function() {
			xhttp.onreadystatechange = funAlert;
			return start();
		}
		
		this.end = function() {
			return (active == true ? false : true);
		}
		
		this.result = function() {
			return result;
		}
	},
	
	quick_ajax : function(script, mode, params, msg) {
		script = script || 'ajax.php';
		msg = msg || null;
		mode = mode || 'update';
		
		var ajax = new Cold.ajax(this.id, msg);
		
		if (script) {
			ajax.setScript(script);
		}
		
		ajax.setParams(params);
		
		switch(mode) {
			case 'update': ajax.update(); break;
			case 'add': ajax.add(); break;
			case 'hide': ajax.hide(); break;
			case 'alert': ajax.alert(); break;
			case 'load': ajax.load(); break;
		}
	},
	
	tools : {
		divAjuda : document.createElement('div'),
		getPosition : function(e){
			var left = 0;
			var top  = 0;
		
			while (e.offsetParent){
				left += e.offsetLeft;
				top  += e.offsetTop;
				e     = e.offsetParent;
			}
		
			left += e.offsetLeft;
			top  += e.offsetTop;
		
			return {x:left, y:top};
		},
		
		scan : function(local) {
			local = (typeof local == 'object' ? local : Cold.$(local)) || document.body;
			
			var elements = local.getElementsByTagName("*");
			for(i = 0 ; i < elements.length ; i++) {
				if (elements[i].getAttribute('tools')) {
					switch(elements[i].getAttribute('tools')) {
						case 'moeda':
							Cold.tools.setMoeda(elements[i]);
						break;
						case 'permitido':
							Cold.tools.setPermitido(elements[i]);
						break;
						case 'ajuda':
							Cold.tools.setAjuda(elements[i]);
						break;
						case 'formatar':
							Cold.tools.setFormatar(elements[i]);
						break;
					}
				}
			}
		},
		
		setMoeda : function(campo) {
			var separador_milhar = campo.getAttribute('separador_milhar') || '.';
			var separador_decimal = campo.getAttribute('separador_decimal') || ',';
			
			campo.setAttribute('onkeypress',"return Cold.tools.formatarMoeda(this,'"+separador_milhar+"','"+separador_decimal+"',event);");
		},
		
		formatarMoeda : function(campo, separador_milhar, separador_decimal, tecla) {
			var sep = 0;
			var key = '';
			var i = j = 0;
			var len = len2 = 0;
			var strCheck = '0123456789';
			var aux = aux2 = '';
			var ev = window.event || tecla;
			var whichCode = ev.which || ev.keyCode;
			
			if (whichCode == 13) return true; // Tecla Enter
			if (whichCode == 8) return true; // Tecla Delete
			if (whichCode == 0) return true; // Tecla Tab
			key = String.fromCharCode(whichCode); // Pegando o valor digitado
			if (strCheck.indexOf(key) == -1) return false; // Valor inválido (não inteiro)
			len = campo.value.length;
			for(i = 0; i < len; i++)
			if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != separador_decimal)) break;
			aux = '';
			for(; i < len; i++)
			if (strCheck.indexOf(campo.value.charAt(i))!=-1) aux += campo.value.charAt(i);
			aux += key;
			len = aux.length;
			if (len == 0) campo.value = '';
			if (len == 1) campo.value = '0'+ separador_decimal + '0' + aux;
			if (len == 2) campo.value = '0'+ separador_decimal + aux;
		
			if (len > 2) {
				aux2 = '';
		
				for (j = 0, i = len - 3; i >= 0; i--) {
					if (j == 3) {
						aux2 += separador_milhar;
						j = 0;
					}
					aux2 += aux.charAt(i);
					j++;
				}
		
				campo.value = '';
				len2 = aux2.length;
				for (i = len2 - 1; i >= 0; i--)
				campo.value += aux2.charAt(i);
				campo.value += separador_decimal + aux.substr(len - 2, len);
			}
		
			return false;
		},
		
		setAjuda : function(campo) {
			var msg = campo.getAttribute('ajuda') || null;
			
			campo.setAttribute('onfocus',"Cold.tools.mostrarAjuda(this,'"+msg+"');");
			campo.setAttribute('onblur',"Cold.tools.escondeAjuda();");
		},
		
		mostrarAjuda : function(campo,msg) {
			var pos = Cold.tools.getPosition(campo);
			
			if (!document.getElementById('toolsAjuda')) {
				Cold.tools.divAjuda.id = 'toolsAjuda';
				Cold.tools.divAjuda.style.position = 'absolute';
				Cold.tools.divAjuda.style.backgroundColor = '#fff';
				Cold.tools.divAjuda.style.border = '1px solid #000';
				Cold.tools.divAjuda.style.padding = '3px';
				Cold.tools.divAjuda.style.width = '200px';
				Cold.tools.divAjuda.style.textAlign = 'center';
				Cold.tools.divAjuda.style.display = 'none';
				Cold.tools.divAjuda.style.fontFamily = 'verdana';
				Cold.tools.divAjuda.style.fontSize = '12px';
				
				document.body.appendChild(Cold.tools.divAjuda);
			}
			
			Cold.tools.divAjuda.innerHTML = msg;
			Cold.tools.divAjuda.style.display = 'block';
			Cold.tools.divAjuda.style.top = pos['y']+'px';
			Cold.tools.divAjuda.style.left = (pos['x'] + campo.offsetWidth + 5) + 'px';
		},
		
		escondeAjuda : function() {
			Cold.tools.divAjuda.style.display = 'none';
		},
		
		setFormatar : function(campo) {
			var formatar = campo.getAttribute('formatar') || null;
			var permitido = campo.getAttribute('permitido') || null;
			
			campo.setAttribute('onkeypress',"return Cold.tools.formatar(this,event,'"+formatar+"','"+permitido+"')");
		},
		
		formatar : function(campo, ev, mask, permitido) {
			if (permitido != 'null') {
				permitido = permitido.toLowerCase();
			} else {
				permitido = false;
			}
			
			if (window.event) {
				key = window.event.keyCode;
			} else {
				key = ev.which;
			}
		
			if ((key == 8) || (key == 9) || (key == 13) || (key == 0)) {
				return true;
			}
		
			var string = campo.value;  
			var i = string.length;
			
			if (permitido) {
				var keychar = String.fromCharCode(key).toLowerCase();
				if ((permitido).indexOf(keychar.toLowerCase()) == -1) {
					return false;
				}
			}
			
			if (i < mask.length) {
				if (mask.charAt(i) == '?') {
					return (key > 47 && key < 58);
				} else {
					if (mask.charAt(i) == '!') {
						return true;
					}
					for (c = i; c < mask.length; c++) {
						if (mask.charAt(c) != '?' && mask.charAt(c) != '!') {
							campo.value = campo.value + mask.charAt(c);
						} else if (mask.charAt(c) == '!') {
							return true;
						} else {
							return (key > 47 && key < 58);
						}
					}
				}
			} else {
				return false;
			}
		},
		
		setPermitido : function(campo) {
			var permitido = campo.getAttribute('permitido') || null;
			
			campo.setAttribute('onkeypress',"return Cold.tools.permitido(this,event,'"+permitido+"');");
		},
		
		permitido : function(field,ev,permitido) {
			var key;
			var keychar;
			
			if (window.event) {
			   key = window.event.keyCode;
			} else if (ev) {
			   key = ev.which;
			} else {
			   return true;
			}
			
			var numpad_chaves = new Array(48,49,50,51,52,53,54,55,56,57);
			var numpad_valores = new Array(0,1,2,3,4,5,6,7,8,9);
			
			if ((key >= 48) && (key <= 57)) {
				for(tecla in numpad_chaves) {
					if (key == numpad_chaves[tecla]) {
						keychar = numpad_valores[tecla];
					}
				}
			} else {
				keychar = String.fromCharCode(key).toLowerCase();
			}
			
			if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)) {
			   return true;
			} else if (((permitido).indexOf(keychar) > -1)) {
				return true;
			} else {
				return false;
			}
		}
	}
}

if (typeof($) !== 'function') {
	function $(element) {
		return Cold.$(element);
	}
}

String.prototype.replaceAll = function(de, para) {
	return Cold.replaceAll(this, de, para);
}

var Sys = {
	produtos : {
		abas : {
			show : function(obj) {
				var pai = obj.parentNode;
				var abas = pai.getElementsByTagName('div');
				
				for(key in abas) {
					if (typeof abas[key] == 'object') {
						abas[key].className = 'item';
						Cold.$('_'+abas[key].id).style.display = 'none';
					}
				}
				
				obj.className = 'item high';
				
				Cold.$('_'+obj.id).style.display = 'block';
			}
		},
		fotos : {
			lock : false,
			load : function(srcFoto, w, h, fw, fh) {
				return false;
				Sys.produtos.fotos.lock = true;
				var preview = Cold.$('_fotosPreview');
				var zoom = Cold.$('_fotosZoom');
				var map = Cold.$('fotoMap');
				
					map.src = srcFoto;
					map.width = w;
					map.height = h;
				
				var showProd = Cold.$('foto_preview');
				if (Cold.$('loading_nova_foto')) showProd.removeChild(Cold.$('loading_nova_foto'));
				
				var limg = new Image();
				limg.src = 'http://www.ibertec.com.br/img/sys/ajax.gif';
				
				var loading = document.createElement('div');
				loading.style.top = map.offsetTop+'px';
				loading.style.left = map.offsetLeft+'px';
				loading.style.width = map.offsetWidth+'px';
				loading.style.height = map.offsetHeight+'px';
				loading.style.position = 'absolute';
				loading.style.backgroundColor = '#fff';
				loading.style.textAlign = 'center';
				loading.id = 'loading_nova_foto';
				
				map.style.visibility = 'hidden';
				
				showProd.appendChild(loading);
				
				loading.appendChild(limg);
				limg.style.marginTop = ((map.height / 2) - (limg.height / 2)) + 'px';
				
				zoom.style.width = (w + (w/1.4))+'px';
				zoom.style.height = (h + (h/1.4))+'px';
				
				var loadImg = new Image();
				loadImg.src = srcFoto;
				
				setTimeout(function() {
					
//					preview.style.width = w+'px';
	//				preview.style.height = h+'px';
			
					Cold.$('fotoW').value = fw;
					Cold.$('fotoH').value = fh;
					
					
					
					zoom.style.backgroundImage = 'url('+srcFoto+')';
					
					Sys.produtos.fotos.lock = false;
					showProd.removeChild(loading);
					map.style.visibility = 'visible';
				}, 2000);
			},
			
			zoom : {
				interval : null,
				show : function() {
					if (Sys.produtos.fotos.lock == true) return false;
					
					var painel = Cold.$('foto_preview');
					var preview = Cold.$('_fotosPreview');
					var zoom = Cold.$('_fotosZoom');
					var map = Cold.$('fotoMap');
					
					document.body.style.cursor = 'crosshair';
					
					var fotoW = Cold.$('fotoW').value;
					var fotoH = Cold.$('fotoH').value;
					
					zoom.style.display = 'block';
					zoom.style.left = (preview.offsetLeft - (Cold.ie ? 4 : 0))+'px';
					zoom.style.top = (preview.offsetTop - (Cold.ie ? 4 : 0))+'px';
					
					Sys.produtos.fotos.zoom.interval = setInterval(function() {
						var mousePos = {
							x : Cold.traceMouse.x,
							y : Cold.traceMouse.y
						}
						
						var mouseImgPos = {
							x : mousePos.x - map.offsetLeft,
							y : mousePos.y - map.offsetTop
						}
						
						var porc = {
							x : (mouseImgPos.x / map.width) * 100,
							y : (mouseImgPos.y / map.height) * 100
						}
						
						porc.x = (porc.x > 100 ? 100 : porc.x);
						porc.y = (porc.y > 100 ? 100 : porc.y);
						
						porc.x = (porc.x < 0 ? 0 : porc.x);
						porc.y = (porc.y < 0 ? 0 : porc.y);
						
						var umporc = {
							w : (fotoW / 100),
							h : (fotoH / 100)
						}
						
						var valorFinal = {
							x : (umporc.w * porc.x),
							y : (umporc.h * porc.y)
						}
						
						valorFinal.x -= (map.offsetWidth / 2);
						valorFinal.y -= (map.offsetHeight / 2);
						
						valorFinal.x = (valorFinal.x < 0 ? 0 : valorFinal.x);
						valorFinal.y = (valorFinal.y < 0 ? 0 : valorFinal.y);
						
						var offset = {
							x : (fotoW - zoom.offsetWidth) -2,
							y : (fotoH - zoom.offsetHeight) -2
						}
						
						valorFinal.x = (valorFinal.x > offset.x ? offset.x : valorFinal.x);
						valorFinal.y = (valorFinal.y > offset.y ? offset.y : valorFinal.y);

						zoom.style.backgroundPosition = -(valorFinal.x)+'px '+-(valorFinal.y)+'px';
						
					}, 30);
				},
				
				hide : function() {
					clearInterval(Sys.produtos.fotos.zoom.interval);
					
					document.body.style.cursor = '';
					
					var zoom = Cold.$('_fotosZoom');
					
					zoom.style.display = 'none';
				}
			}
		}
	},
	
	menu_js : {
		elements: {},
		pos : {},
		fix : function() {
			Cold.$('menu_js').style.display = 'block';
			Sys.menu_js.elements = Cold.$('menu').getElementsByTagName('li');
			this.pos[0] = (Sys.menu_js.elements[0].offsetLeft+30);
			for(i=1;i<=Sys.menu_js.elements.length;i++) {
				if (typeof Sys.menu_js.elements[i] == 'object') {
					this.pos[i] = (this.pos[(i-1)] + Sys.menu_js.elements[(i-1)].offsetWidth - 30);
					this.effect(Sys.menu_js.elements[i], this.pos[i]);
				}
			}
		},
		
		effect : function(obj, end) {
			obj = (typeof obj == 'object' ? obj : Cold.$(obj));
			var left = obj.offsetLeft;
			var opa = 0;
			var interval = setInterval(function() {
				left += 15;
				opa += 0.1;
				
				if (opa >= 1) {
					opa = 1;
				}
				
				if (left >= end) {
					clearInterval(interval);
					left = end;
				}
				
				Cold.$('menu_js').style.opacity = opa;
				obj.style.left = left+'px';
			}, 5);
		}
	},
	
	scrollme : function(obj) {
		if (!obj.id) obj.id = Cold.uniqid();
		
		if (Cold.$('clone_'+obj.id)) return false;
		
		var clone = obj.cloneNode(1);
		clone.id = 'clone_'+obj.id;
		clone.style.position = 'absolute';
		clone.style.top = obj.offsetTop+'px';
		clone.style.left = obj.offsetLeft+'px';
		clone.style.backgroundColor = '#fff';
		clone.style.marginTop = '-1px';
		clone.style.width = obj.offsetWidth+'px';
		clone.style.overflow = 'auto';
		clone.style.padding = '5px';
		clone.style.border = '1px solid #000';
		
		clone.onmouseover = null;
		
		clone.onmouseout = function() {
			this.parentNode.removeChild(this);
		}
		
		obj.parentNode.appendChild(clone);
	}
}

function fechar(){
			document.getElementById('popup').style.display = 'none';
		}


