/* Commons */
/*Forms*/
//classForm.setModalDivAux('DV_alternada');
//classForm.setModalDiv('DV_poperror');

function ParseHTML(texto) {
	// texto = texto.replace(/^.*'([^']*)'.*$/, "---''$1''---");
	// (\w+)
	
	texto = texto.replace(/\[b\](.*)\[\/b\]/, "<b>$1</b>");
	texto = texto.replace(/\[i\](.*)\[\/i\]/, "<i>$1</i>");
	texto = texto.replace(/\[u\](.*)\[\/u\]/, "<u>$1</u>");
	texto = texto.replace(/\[center\](.*)\[\/center\]/, "<center>$1</center>");
	texto = texto.replace(/\[url=(.*)\](.*)\[\/url\]/, "<a href=\"$1 aaaaa\" target=\"_blank\">$2</a>");
	
	return texto;
}

function HideAllAlerts(strObj) {
	var Hide   = classObjetos.findObj('DV_alertErrors');
	var objDiv = classObjetos.findObj(strObj);

	if (Hide) {
		Hide.style.display = 'none';
	}
	
	if (objDiv && (typeof __errors == '')) {
		objDiv.style.display = 'none';
	}

	if (objDiv && __errors == 'S') {
		objDiv.style.display = 'block';
	}
}

function selectAll(strObj){
	var objCheck = classObjetos.findObj(strObj);

	for (var i = 0; i < objCheck.length; i++) {
		if (!objCheck[i].checked) {
			objCheck[i].checked = true;
		}
	}

	return true;
}
function selectNone(strObj){
	var objCheck = classObjetos.findObj(strObj);

	for (var i = 0; i < objCheck.length; i++) {
		if (objCheck[i].checked) {
			objCheck[i].checked = false;
		}
	}

	return true;
}


function HideObjects() {
	var objArray = arguments;
	var Item;
	for (var i = 1; i < objArray.length; i++) {
		Item = classObjetos.findObj(objArray[i]);
		if (Item) {
			Item.style.display = objArray[0];
		}
	}
}

function Foca(strObj) {
	strObj = classObjetos.findObj(strObj);
	if (strObj && strObj.style.display != 'none' && strObj.style.visibility != 'hidden') {
		strObj.focus();
	}
}

var common_ajax, callback = {
	ToUpper    : function (result) {}, 
	doPostBack : function (result) {
		if (typeof _REQUEST != "undefined") {
			var formulario = (result!="") ? ((document.forms[result] != null) ? document.forms[result] : document.getElementById(result)) : document.forms[0];
			var campos     = _REQUEST;
		
			if (campos && formulario) {
				var elemento;
				for (x in campos) {
					if (x == '______array') continue;
					elemento       = (formulario.elements[x]!=null) ? formulario.elements[x] : document.getElementById(x);
					if (elemento != null && typeof elemento == 'object') {
						if (elemento.name != null && elemento.getAttribute('doPostBack') == 'S') {
							switch(elemento.type) {
								case 'checkbox':
								case 'radio':
										for (j in elemento) {
											if (j == '______array') continue;
											if (elemento[j].value == campos[x])
												elemento[j].checked = true;
										}
										//elemento.checked = true;
									break;
								case 'select-one':
										elemento.value = campos[x];
									break;
								case 'select-multiple':
										for (j in campos[x]) {
											if (j == '______array') continue;
											elemento[j].selected = true;
										}
									break; 
								default:						
										elemento.value = campos[x];
									break;
							}
						}
					}
				}
			}
		}
	}
}
common_ajax = new ajax_forms(callback);

function ExtraiScript(texto) {
    var ini, pos_src, fim, codigo, count = 0;
    var objScript = null;
    var ObjsArray = new Array();
    ini = texto.indexOf('<script', 0)
    while (ini!=-1){
        objScript = document.createElement("script");
        //Busca se tem algum src a partir do inicio do script
        pos_src = texto.indexOf(' src', ini)
        ini = texto.indexOf('>', ini) + 1;

        //Verifica se este e um bloco de script ou include para um arquivo de scripts
        if (pos_src < ini && pos_src >=0){//Se encontrou um "src" dentro da tag script, esta e um include de um arquivo script
            //Marca como sendo o inicio do nome do arquivo para depois do src
            ini = pos_src + 4;
            //Procura pelo ponto do nome da extencao do arquivo e marca para depois dele
            fim = texto.indexOf('.', ini)+4;
            //Pega o nome do arquivo
            codigo = texto.substring(ini,fim);
            //Elimina do nome do arquivo os caracteres que possam ter sido pegos por engano
            codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">","");
            // Adiciona o arquivo de script ao objeto que sera adicionado ao documento
            if (codigo.substring(codigo.indexOf('.')) == '.php') codigo += "?client=all&stub=all";
            
            objScript.src  = codigo;
        }else{//Se nao encontrou um "src" dentro da tag script, esta e um bloco de codigo script
            // Procura o final do script
            fim = texto.indexOf('</script>', ini);
            // Extrai apenas o script
            codigo = texto.substring(ini,fim);
            // Adiciona o bloco de script ao objeto que sera adicionado ao documento
            objScript.text = codigo;
        }

        //Adiciona o script a um novo array
        ObjsArray[count] = objScript;
//        document.body.appendChild(objScript);
        
        // Procura a proxima tag de <script
        ini = texto.indexOf('<script', fim);

        //Limpa o objeto de script
        objScript = null;
        
        count++;
    }
    
    setTimeout( function () {
				    for (var x = 0; x < ObjsArray.length; x++) {
				    	if (ObjsArray[x] != null) document.body.appendChild(ObjsArray[x]);
				    	ObjsArray[x] = null;
				    }
    			}, 750);
}

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 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 HideAllDivs(strObj,attribute)
{	
	for (var i=0; i<strObj.length; i++){
  		var div = strObj[i];  		
  		var rel = div.getAttribute(attribute);
  		if (rel && rel == 'S'){
   			div.style.display='none';
  		}
	}
	
}

function ShowHideDiv(strObj) {
	var Obj = classObjetos.findObj(strObj);
	if (Obj.style.display == '' || Obj.style.display == 'block') {
		Obj.style.display = 'none';
	} else {
		Obj.style.display = 'block';
	}
}

function TextAreaMaxLength(obj) {
	var len = obj.getAttribute('maxlength');
	if (obj.value.length >len) {
		obj.value = obj.value.substring(0,len);
	}
}

function SetOneOrOther(strObj1,strObj2,strRequired) {
	var Obj1 = classObjetos.findObj(strObj1);
	var Obj2 = classObjetos.findObj(strObj2);

	if (Obj1.value == "" && Obj2.value == "") {
		Obj1.setAttribute('required',strRequired);
		Obj2.removeAttribute('required');
	} else if (Obj1.value == "" && Obj2.value != "") {
		Obj2.setAttribute('required',strRequired);
		Obj1.removeAttribute('required');
	} else if (Obj1.value != "" && Obj2.value == "") {
		Obj1.setAttribute('required',strRequired);
		Obj2.removeAttribute('required');
	}
}

function RemoveAttributes(strObj,strAttribute) {
	var Obj = classObjetos.findObj(strObj);
	Obj.removeAttribute(strAttribute);
}

function DontSetOneOrOther(strObj) {
	var Obj = classObjetos.findObj(strObj);
	
	return Obj.checked;
}

function EnableFieldByFlag(flag,strObjto,strRequired) {
	var Obj = classObjetos.findObj(strObjto);
	if (flag) {
		Obj.disabled = false;
		if (strRequired != null) Obj.setAttribute('required',strRequired);
	}
	else {
		Obj.disabled = true;
		if (strRequired != null) Obj.removeAttribute('required');
	}
}

function DisableFieldByFlag(flag,strObjto,strRequired) {
	var Obj = classObjetos.findObj(strObjto);
	if (flag) {
		Obj.disabled = true;
		if (strRequired != null) Obj.removeAttribute('required');
	}
	else {
		Obj.disabled = false;
		if (strRequired != null) Obj.setAttribute('required',strRequired);
	}
}

function Confirma(texto) {
	return confirm(texto);
}

function SendFormTag(form,tag,text) {
	form = (form.elements == null) ? document.forms[form] : form;
	tag  = form.elements[tag];
	tag.value = text;

	form.submit();
}

function SetFormTag(form,tag,text) {
	form = (form.elements == null) ? document.forms[form] : form;
	tag  = form.elements[tag];
	tag.value = text;
}

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 CloseDiv(div_id) {
	div_id = document.getElementById(div_id);
	div_id.style.display = 'none';
}

function expandcontent(id) {
	id = document.getElementById(id);
	if (id.style.display != 'none') id.style.display = 'none'
	else id.style.display = 'block';
}

function OnlyLettersBack(obj,adicionais) {
	var retorno = classStrings.stringValidation(obj.value.toLowerCase(), ('abcdefghijklmnopqrstuvxwyz'+ ((adicionais != "") ? adicionais : "") ));

	if (retorno == false) {
		obj.value = obj.value.substring(0,obj.value.length-1);
		
		if (classStrings.stringValidation(obj.value.toLowerCase(), ('abcdefghijklmnopqrstuvxwyz'+ ((adicionais != "") ? adicionais : "") )) == false) {
			obj.value = '';
		}
	}
}

function OnlyStrings(obj) {
	obj.value   = classStrings.stripNonString(obj.value);
}

function OnlyNumbers(obj) {
	obj.value   = classStrings.stripNonNumeric(obj.value);
}

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;
		}
	}	
}

function DisableByCheck(objCheck,strObj) {
	find = classObjetos.findObj(strObj);
	find.disabled = objCheck.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://");
	
	var varHttp = url.indexOf("http://");
	
	if(varHttp < 0){
		url = "http://"+url;	
	}
	
	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://");
	
	var varHttp = url.indexOf("http://");
	
	if(varHttp < 0){
		url = "http://"+url;	
	}
	
	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);
	
	var varHttp = url.indexOf("http://");
	
	if(varHttp < 0){
		url = "http://"+url;	
	}
	
	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();
}

// 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 = document.forms[strForm];

	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]; 
			continue;
		}
		
		var objInput = objForm.elements[x];
		if (objInput) {
			objInput.value = ObjArray[x];
		}
	}
	
	objForm.submit();
}

function sleep(millisecondi)
{
    var now = new Date();
    var exitTime = now.getTime() + millisecondi;

    while(true)
    {
        now = new Date();
        if(now.getTime() > exitTime) return;
    }
}


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 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 HideZipcode(obj,ids) {
	var tb_zip  = document.getElementById(ids);

	if (obj.options[obj.selectedIndex].value != 'US') {
		tb_zip.style.display  = 'none';
	} else {
		tb_zip.style.display  = 'block';
	}
}

function HideCity(obj,ids) {
	var tb_city  = document.getElementById(ids);

	if (obj.options[obj.selectedIndex].value != 'US') {
		tb_city.style.display  = 'block';
	} else {
		tb_city.style.display  = 'none';
	}
}

/*
	msg = mensagem a ser exibida
	func = função a ser executada caso clique em OK
	obj = objeto que executou a função
	btn = true exibe botão ok/cancelar e false exibe botão close
*/
function Del(Word) {
	a = Word.indexOf("<");
	b = Word.indexOf(">");
	len = Word.length;
	c = Word.substring(0, a);
	if(b == -1)
		b = a;
		d = Word.substring((b + 1), len);
		Word = c + d;
		tagCheck = Word.indexOf("<");
	if(tagCheck != -1)
		Word = Del(Word);
	return Word;
}
function ShowDivMsg( msg , func , obj , btn )
{
	if(btn){
		if(confirm(Del(msg))){
			eval(func);
		}
	}else{
		alert(Del(msg));
	}
	
/*	
	document.getElementById('LI_Msgs').innerHTML = msg+"<br />";
	
	if ( btn )
	{
		document.getElementById('nok_div').innerHTML = 'Cancel';
		document.getElementById('ok_div').style.display = 'inline';
	}
	else
	{
		document.getElementById('nok_div').innerHTML = 'Close';
	}
	
	document.getElementById('DV_Msgs').style.display = 'block';
	location = classForm.getAncora();
	
	document.getElementById('ok_div').onclick = function(){
		eval(func);
		document.getElementById('DV_Msgs').style.display = 'none';
	};

	document.getElementById('moc_alert_hidden').focus();
*/
}



// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   
   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   
   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}


/* AJAX */
// Get a new instance of a HTTP Object
function getHTTPObject()
{
	var httpobj = false;

	if (window.XMLHttpRequest) {
		httpobj = new XMLHttpRequest();
		if (httpobj.overrideMimeType) {
			httpobj.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) {
		try {
			httpobj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				httpobj = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {

			}
		}
	}

	if (!httpobj) {
		alert("Error creating HTTP Object.");
		return false;
	}

	return httpobj;
}

// Send a post request
function makePOSTRequest(url, parameters, callback)
{
	// Get HTTP Object
	var http_request = getHTTPObject();

	// Register callback function if any
	if (callback != null)
	{
		http_request.onreadystatechange = function()
		{
			if (http_request.readyState == 4)
			{
				try
				{
					if (http_request.status == 200)
					{
						eval(callback + "(http_request);");
					}
				}
				catch (e)
				{
					eval(callback + "(null);");
				}
			}
		};
	}

	// Init
	http_request.open('POST', url, true);

	// Set headers
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");

	// Send request
	http_request.send(parameters);
}

// Send a get request
function makeGETRequest(url, parameters, callback)
{
	// Get HTTP Object
	var http_request = getHTTPObject();

	// Register callback function if any
	if (callback != null)
		http_request.onreadystatechange = function()
		{
			if (http_request.readyState == 4) {
				try
				{
					if (http_request.status == 200)
					{
						eval(callback + "(http_request);");
					}
				}
				catch (e)
				{
					eval(callback + "(null);");
				}
			}
		};

	// Init
	http_request.open('GET', url + '?' + parameters, true);

	// Send
	http_request.send(null);
}