/* Commons */
/*Forms*/
//classForm.setModalDivAux('DV_alternada');
//classForm.setModalDiv('DV_poperror');

var _POST       = new Array();
var _errors     = new Array();

function abre_foto( x , largura , altura ){
	foto = window.open("","_____","width="+largura+", height="+altura);
	foto.document.write("<html><body leftmargin='0' topmargin='0'>");
	foto.document.write("<img src='"+x+"' onclick='window.close()' />");
	foto.document.write("</body></html>");
}

function dateBr2Us(sData) {
	var split = sData.split("/");
	return split[1] +"/"+ split[0] +"/"+ split[2];
}

function HideShowText(strDIVText,len) {
	var ObjTexto = classObjetos.findObj(strDIVText);
	
	if (ObjTexto.innerHTML.length >len) {
		ObjTexto.setAttribute('RealText', ObjTexto.innerHTML);
		ObjTexto.innerHTML = ObjTexto.innerHTML.substring(0,len-3) +"...";
	} else {
		if (ObjTexto.getAttribute('RealText')) {
			ObjTexto.innerHTML = ObjTexto.getAttribute('RealText');
		}
	}
}

function ShowHideDiv(strObj) {
	var Obj = classObjetos.findObj(strObj);
	if (!Obj) return false;

	if (Obj.style.display == '' || Obj.style.display == 'block') {
		Obj.style.display = 'none';
	} else {
		Obj.style.display = 'block';
	}
}

function fields2Array(objElements, arrayData) {
	arrayData = (arrayData != null) ? arrayData : new Array();

	for (var i = 0; i < objElements.length; i++) {
		if (objElements[i] == undefined) continue;

		if (objElements[i].type == 'checkbox') {
			arrayData.push((!objElements[i].checked ? 'N' : 'S'));
		} else if (objElements[i].type != 'radio' || (objElements[i].type == 'radio' && objElements[i].checked)) {
			arrayData.push(objElements[i].value.convertUTF8Chars());
		}
	}

	return arrayData;
}

function TextAreaMaxLength(obj) {
	var len = obj.getAttribute('maxlength');
	if (obj.value.length >len) {
		obj.value = obj.value.substring(0,len);
	}
}

function SetCookie(cookieName,cookieValue,nDays) {
	 var today = new Date();
	 var expire = new Date();
	 if (nDays==null || nDays==0) nDays=30;
	 expire.setTime(today.getTime() + 3600000*24*nDays);
	 document.cookie = cookieName+"="+escape(cookieValue)
	                 + ";expires="+expire.toGMTString();
}

function GetCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ){
		return null;
	}
	
	if ( start == -1 ) return null;
	
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function ModalDialog(url, width, height, target, scroll) {
	if (document.getElementById && !document.all) {
		window.open(url,target,"width="+width+",height="+height+", scrollbars="+scroll);
	} else {
		window.showModalDialog(url, target,'status:no;dialogWidth:"+width+";dialogHeight:"+height+";dialogHide:true;help:no;scroll:'+scroll);
	}
}

function centerWindow(_url, _target, _width, _height) {
	var left = (screen.width - _width) / 2;
	var top  = (screen.height - _height) / 2;
	
	window.open( _url, _target, "width=" +_width+ ", height=" +_height+ ", left=" +left+ ", top=" +top+ ", scrollbars=1" );
}

function PassaValor(valor, campo) {
	campo = classObjetos.findObj(campo);
	campo.value = valor;
}

function AllChecks(check,id){
	var inputs = document.getElementsByTagName('input');
	for (var x = 0; x < inputs.length; x++) {
		if (check.type == inputs[x].type && id == inputs[x].id) {
			inputs[x].checked = check.checked;
		}
	}	
}

/* Emoteicons & URL/bold/italic/underline */

/******************************
 * Selection functions for IE *
 ******************************/

// Returns the selection end position
function getSelectionEnd(input) {
	var range = document.selection.createRange();
	var isCollapsed = range.compareEndPoints("StartToEnd", range) == 0;

	if (!isCollapsed)
		range.collapse(false);

	var b = range.getBookmark();
	return b.charCodeAt(2) - 2;
}

// Makes a new selection
function setSelectionRange(input, start, end) {
	var range = input.createTextRange();
	range.collapse(true);
	range.moveStart("character", start);
	range.moveEnd("character", end - start);
	range.select();
}


/*******************
 * HCode functions *
 *******************/

// Places a emote into the textarea
function placeEmote(description, field)
{
	placeString(description, field);
	field.focus();
}

// Places a Youtube Link
function placeYoutube(msg1, field)
{
	var url = getString(field, msg1) == "" ? prompt(msg1,"http://www.youtube.com/watch?v=") : getString(field, msg1);
	url = youtube(url);
	
	if (url)
	{
		url = '[utube]' + url + '[/utube]';

		placeString(url, field);
	}
	
	field.focus();
}

// Places a URL Image into the textarea
function placeImage(msg1, field)
{
	var url = prompt(msg1,"http://");
	
	if (url)
	{
		url = '[img]' + url + '[/img]';

		placeString(url, field);
	}
	
	field.focus();
}

// Places a URL Image2 into the textarea
function placeImage2(msg1, field)
{
	var url = prompt(msg1,"http://");
	
	if (url)
	{
		url = '[img=' + url + ']';

		placeString(url, field);
	}
	
	field.focus();
}

// Places a URL into the textarea
function placeURL(msg1, msg2, field)
{
	var url = prompt(msg1,"http://");
	var link = (url && getString(field, msg2) == "") ? prompt(msg2, "") : getString(field, msg2);
	
	if (url)
	{
		url = '[url=' + url +']' + (link ? link : url) + '[/url]';

		placeString(url, field);
	}
	
	field.focus();
}

// Places a simple tag into the textarea
function placeTag (tag, msg, field, add)
{
	add = (!add) ? "" : add;
	var text = getString(field, msg) == "" ? prompt(msg, add+"") : getString(field, msg);
	
	if (text)
	{
		text = '[' + tag + ']' + text + '[/' + tag + ']';

		placeString(text, field);
	}
	
	field.focus();
}

function placeTagClass(tag, strClass, msg, field) {
	var text = getString(field, msg) == "" ? prompt(msg) : getString(field, msg);
	
	if (text)
	{
		strClass = (strClass == '') ? "" : (" class='" +strClass+ "'");
		text     = '<' + tag + strClass + '>' + text + '</' + tag + '>';

		placeString(text, field);
	}
	
	field.focus();
}

// Places a string into into a form field
function placeString(str, field)
{
	if (str.length > 0)
	{
		if (document.selection)
		{
			field.focus();

			sel = document.selection.createRange();
			sel.text = str;

			var curPos = getSelectionEnd(field);
			setSelectionRange(field, 0, 0);
			var startPos = getSelectionEnd(field);

			curPos -= startPos;

			setSelectionRange(field, curPos, curPos);
		}
		else if (field.selectionStart || field.selectionStart == "0")
		{
			var startPos = field.selectionStart;
			var endPos   = field.selectionEnd;
			var curStr   = field.value;

			field.value = curStr.substring(0, startPos) + str + curStr.substring(endPos, curStr.length);

			field.setSelectionRange(startPos + str.length, startPos + str.length);

			field.focus()
		}
		else
		{
			field.value += str;
		}
	}
}

// Returns the selected text into this field
function getString(field, def_msg)
{
	if (field)
	{
		if (document.selection)
		{
			field.focus();
			sel = document.selection.createRange();
			field.focus();

			return sel.text;
		}
		else if (field.selectionStart || field.selectionStart == "0")
		{
			var startPos = field.selectionStart;
			var endPos = field.selectionEnd;
			var curStr = field.value;

			field.focus();

			return curStr.substring(startPos, endPos);
		}
		else
		{
			field.focus();
			return prompt(def_msg, "");
		}
	}
}

//limpa todos os campos de um redio button
function clean(arg)
{
	var radio_choice = false;
	for (counter = 0; counter < arg.length; counter++)
		arg[counter].checked = radio_choice;
	arg.checked = radio_choice;
}

function isNumberKey(evt) {
	evt = evt || window.event;

   var charCode = (evt.which) ? evt.which : evt.keyCode;

   if ((charCode > 31 && (charCode < 48 || charCode > 57)) && !(charCode >= 35 && charCode <= 40) && charCode != 46)
   	return false;

   return true;
}

function doCountChecks(strObj) {
	var objCheck = classObjetos.findObj(strObj);
	var total    = 0;

	if (objCheck[0]==null && objCheck.checked) {
		total    = 1;
	} else {
		for (var i = 0; i < objCheck.length; i++) {
			if (objCheck[i].checked) {
				total++;
			}
		}
	}
	
	return (total>0)?true:false;
}

function doPost(strForm, ObjArray) {
	var objForm    = (typeof document.forms[strForm] == 'object') ? document.forms[strForm] : document.createElement('FORM');
	var boolMethod = false;

	for (x in ObjArray) {
		if (ObjArray[x] == '______array') continue;
		if (x == 'action') {
			objForm.action = ObjArray[x]; 
			continue;
		} else if (x == 'method') {
			objForm.method = ObjArray[x]; 
			boolMethod     = true;
			continue;
		}
		
		var objInput = (typeof objForm.elements[x] == 'object') ? objForm.elements[x] : document.createElement('INPUT');
		if (typeof objForm.elements[x] != 'object') {
			objInput.type = 'hidden';
			objInput.name = x;

			objForm.appendChild(objInput);
		}

		objInput.value = ObjArray[x];
	}
	
	if (typeof document.forms[strForm] != 'object') {
		if (!boolMethod)
			objForm.method = "POST";

		objForm.style.display = 'none';
		document.body.appendChild(objForm);
	}

	objForm.submit();
}

function postAction() {
	// Create the form
	var form = document.createElement("FORM");
	form.method = "POST";
	form.style.cssText = 'display:none; ';

	// Add the form
	document.body.appendChild(form);

	// Generate the fields
	for (var i=0; i<arguments.length; i++)
	{
		// Create the input
		var input = document.createElement("INPUT");

		// Config the input
		input.type  = 'hidden';
		input.name  = arguments[i][0];
		input.value = arguments[i][1];

		// Add the input
		form.appendChild(input);
	}

	// Send the form
	form.submit();

	// Return
	return false;
}

function postForm(id) {
	var theForm = classObjetos.findObj(id);

	if (theForm['classForms'].Valida(theForm)) {
		theForm['classForms'].encodeAll(theForm);
		theForm.submit();
		theForm['classForms'].decodeAll(theForm);
	}
}

function addBoxErrors(strMensagem) {
	_errors.push(strMensagem);
}

function showBoxErrors(boxErrorsID, boxTextErrorsID) {
	var ObjBox     = classObjetos.findObj(boxErrorsID);
	var ObjBoxText = classObjetos.findObj(boxTextErrorsID);
	var res        = "<ul>";

	for (var i = 0; i < _errors.length; i++) {
		res += "<li>" +_errors[i]+ "</li>";
	}

	res += "</ul>";
	
	if (_errors.length >0) {
		ObjBox.style.display = 'block';
		ObjBoxText.innerHTML = res;

		_errors = new Array();
	}
}

function youtube(link) {
	if (!link) return false;
	var linkpos=link.indexOf('v=');
	if(linkpos >=0)
		link=link.substring(linkpos+2);

	if(link.length!=11) {
		alert('Invalid Youtube ID.');
	} else
		return link;
}

function utube(id) {
	document.write('<object width="302" height="248"><param name="movie" value="http://www.youtube.com/v/'+id+'"></param><embed src="http://www.youtube.com/v/'+id+'" type="application/x-shockwave-flash" width="302" height="248"></embed></object>');
}

function clearForm(id) {
	var theForm = document.forms[id];
	var Elem    = null;
	for (var i = 0; i < theForm.elements.length; i++) {
		Elem = theForm.elements[i];
		switch (Elem.type.toLowerCase())
		{
			case 'select-one':
					Elem.options[ Elem.options.selectedIndex ].selected = false;
				break;
			
			case 'checkbox':
			case 'radio':
					Elem.checked = false;
				break;

			case 'text':
			case 'password':
			case 'file':
					Elem.value = '';
				break;
		}
	}
}

function removeInvalidChars(strStr) {
	strStr = strStr.replace(" ", "_");
	strStr = strStr.replace(/\(/g, "");
	strStr = strStr.replace(/\)/g, "");
	strStr = strStr.replace(/\./g, "");

	strStr = strStr.replace(/ã|á|à|â|ä/g, "a");
	strStr = strStr.replace(/é|è|ê|ë/g, "e");
	strStr = strStr.replace(/í|ì|î|ï/g, "i");
	strStr = strStr.replace(/õ|ó|ò|ô|ö/g, "o");
	strStr = strStr.replace(/ú|ù|û|ü/g, "u");
	strStr = strStr.replace(/ç/g, "c");
	strStr = strStr.replace(/ñ/g, "n");

	strStr = strStr.replace(/Ã|Á|À|Â|Ä/g, "A");
	strStr = strStr.replace(/É|È|Ê|Ë/g, "E");
	strStr = strStr.replace(/Í|Ì|Î|Ï/g, "I");
	strStr = strStr.replace(/Õ|Ó|Ò|Ô|Ö/g, "O");
	strStr = strStr.replace(/Ú|Ù|Û|Ü/g, "U");
	strStr = strStr.replace(/Ç/g, "C");
	strStr = strStr.replace(/Ñ/g, "N");
	
	return strStr;
}

function redirect(url, objWindow) {
	if (String(window.opener) != 'undefined' && objWindow == null)
		objWindow = window.opener;

	if (objWindow != null)
		objWindow.location = url;
	else
		location = url;

	if (String(window.opener) != 'undefined')
		window.close();
}

if (typeof Web == 'object') {
	var classForms = new Web.Components.Forms();
	classForms.start();
}
