﻿/* ===========================================================================
GAIA - SCRIPTS - FUNÇÕES DE CORE
PROGRAMADOR: RAFAEL PIRES DE FREITAS
DATA: 04/07/2006
ULTIMA REVISAO: 15/12/2008 02:41 [RAFAEL PIRES DE FREITAS]
============================================================================ */
function using(file){
    var head = document.getElementsByTagName("HEAD").item(0);
    var script = document.createElement("SCRIPT");
    script.src = file;
    script.type = "text/javascript";
    head.appendChild(script);
}

/* ===========================================================================
CONSTANTES
PROGRAMADOR: RAFAEL PIRES DE FREITAS
DATA: 26/07/2006
ULTIMA REVISAO: 29/07/2006 02:52 [RAFAEL PIRES DE FREITAS]
============================================================================ */
var AjaxTimeOut = 600;

// includes
using("scripts/Gaia.Messages.js");
using("scripts/Gaia.Config.js");
using("scripts/Gaia.UI.JavaScript.js");
using("scripts/Gaia.UI.WebControls.DropDownListBuilder.js");
//using("scripts/Gaia.UI.Page.js");

/* ===========================================================================
FUNÇÕES DE CONVERSAO DE VALORES (
PROGRAMADOR: RAFAEL PIRES DE FREITAS
DATA: 04/07/2006
ULTIMA REVISAO: 29/07/2006 02:30 [RAFAEL PIRES DE FREITAS]
============================================================================ */
function Convert()
{
    // Retorna a data no formato especificado
    this.ToDate = function(str, format)
    {
        try
        {
            var MM = str.substring(0, 2);
            var dd = str.substring(3, 5);
            var yyyy = str.substring(6, 10);
            var hh = str.substring(11, 13);
            var mm = str.substring(14, 16);
            var output;
            var date_ref = new Date(2009, 6, 01, 0, 0, 0, 0);
            
            if (format == "dd/MM/yyyy hh:mm")
            {
                output = new Date(yyyy, dd - 1, MM, hh, mm);
            }
            if (format == "dd/MM/yyyy")
            {
                output = new Date(yyyy, dd - 1, MM);
            }

            if ((date_ref.getTimezoneOffset() / 60) - (output.getTimezoneOffset() / 60) > 0)
                output.setHours(output.getHours() + 1);
            
            return output;
        }
        catch (e)
        {
            return null;
        }
    }

    // Retorna a string no formato especificado
    this.ToString = function(exp, format)
    {
        if (isDate(exp)) // converte a partir de uma data
        {
            var date = new Date();
            date.setTime(exp.valueOf());
            var date_ref = new Date(2009, 6, 01, 0, 0, 0, 0);

            if ((date_ref.getTimezoneOffset() / 60) - (date.getTimezoneOffset() / 60) > 0)
                date.setHours(date.getHours() - 1);

            var MM = date.getMonth() + 1;
            var dd = date.getDate();
            var yyyy = date.getFullYear();
            var hh = date.getHours();
            var mm = date.getMinutes();
            var output;
            if (format == "dd/MM/yyyy hh:mm")
                output = dd + "/" + MM + "/" + yyyy + " " + hh + ":" + mm;
            if (format == "dd/MM/yyyy")
            {
                output = this.FormatLength(dd, 2) + "/" + this.FormatLength(MM, 2) + "/" + yyyy;
            }
            if (format == "hh:mm")
                output = this.FormatLength(hh, 2) + ":" + this.FormatLength(mm, 2);
            return output;
        }
        else if (format == "money")
        {
            var n = exp;
            var c = 2;
            var d = ",";
            var t = ".";
            var s = n < 0 ? "-" : "";
            var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "";
            var j = (j = i.length) > 3 ? j % 3 : 0;
            return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
        }
    }
    
    this.ToInt = function(exp)
    {
        var texto2 = exp.split('');
        var texto3 = "";
        
        for(x=0; x < texto2.length; x++)
        {
            if(isNumeric(texto2[x]) == false)
                texto2[x] = null;
        }
        for(x=0; x < texto2.length; x++)
        {
            if(texto2[x] != null)
                texto3 += texto2[x];
        }
        
        return texto3;
    }

    this.ToDecimal = function(exp) {
        var texto2 = exp.split('');
        var texto3 = "";

        for (x = 0; x < texto2.length; x++) {
            if (isNumeric(texto2[x]) == false)
                texto2[x] = null;
        }
        for (x = 0; x < texto2.length; x++) {
            if (texto2[x] != null)
                texto3 += texto2[x];
        }

        return texto3;
    }
    
    // Formata o número de casas de um valor
    this.FormatLength = function(numero, casas)
    {
	    numero = numero.toString();
    	
	    if(numero.length < casas)
	    {
		    for(var i = numero.length; i < casas; i++)
			    numero = "0" + numero;
	    }
	    else
	    {
		    numero = numero.toString().substring(numero.length - 2);
	    }
	    return numero;
    }
}

function isDate(expression)
{
    try
    {
        expression.getYear();
        return true;
    }
    catch(e)
    {
        return false;
    }
}

function isNumeric(expression, pointer)
{
    var ValidChars = "";
    if(pointer == true)
        ValidChars = "0123456789.";
    else
        ValidChars = "0123456789";
        
    var IsNumber=true;
    var Char;
 
    for (i = 0; i < expression.length && IsNumber == true; i++) 
    { 
        Char = expression.charAt(i);
        if (ValidChars.indexOf(Char) == -1) 
        {
            IsNumber = false;
        }
    }
      
   return IsNumber;
}

var Convert = new Convert();

// Função que chama a função Adicionar aos Favoritos do navegador --------------------------------------------------------------------------------------
function AddFavorite(titulo)
{
	if(browser.isIE)
	{
		window.external.AddFavorite(document.location, titulo);
	}
	else if(browser.isNS || browser.isNSCompatible)
	{
		try
		{
			window.sidebar.addPanel(titulo, document.location, '' );
		}
		catch(e)
		{
			alert ("Pressione Crtl+D para adicionar esta página em seus favoritos.");
		}
	}
	else
	{
		alert("Seu navegador não suporta esta função de maneira automática. Por favor, tente manualmente.")
	}
}

// Funções para gerenciamento de cookies --------------------------------------------------------------------------------------
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/* ===========================================================================
CÓDIGO RESPONSÁVEL PELA DELEÇÃO DE MINIATURAS DE IMAGENS
PROGRAMADOR: MARCILIO CANEDO GONÇALVES
DATA: 05/01/2007
ULTIMA REVISAO: 05/01/2007 11:30 [MARCILIO CANEDO GONÇALVES]
============================================================================ */
function DeleteImage(obj, hdf_campo, imgCad)
{
    obj.src = "images/ico_imagem.jpg";
    if(imgCad == true)
    {
        document.getElementById("txt_nuTamanho").value = "";
        document.getElementById("txt_nuAltura").value = "";
        document.getElementById("txt_nuLargura").value = "";
    }
    else
        hdf_campo.value = -1;
}

function LimTextArea(field, maxlimit, countfield, e) 
{
    /* Conta o total de caracteres restantes. */
    if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
    else
        countfield.value = maxlimit - field.value.length;

    /* Bloqueia o textArea ao chegar no limite de caracteres. */
    valor = field.value;

    if (valor.length >= countfield) 
    {
        var whichCode = (window.Event) ? e.which : e.keyCode;

        if (whichCode == 8 || whichCode == 0) return true; /* Aceita Tab e Back Space. */  
        return false;
    }
    else
        return true;
}

if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

