var classErrorField = 'classErrorField';
var msgFillFieldsError = 'Preencha todos os campos corretamente';
var stAddImages = "Adicionar imagens";
var ExecFunctionAfterAjax = "";
var CancelFunctionAjax = "";
var stDescriptionFile = "Imagens JPG e PNG";
var stFileExtensions = '*.jpg;*.png';
var FocusField = "";

ShowHideMenu = function(Obj, State)
{
	if (State)
	  $(Obj).children('.classSubMenu').show();
	else
	  $(Obj).children('.classSubMenu').hide();
}

CreatePolls = function()
{
   $(".LoadPoll").each(function()
   {
	   idPoll = $(this).attr('rel');
	   RunAjax('core/manutencao/votepoll.php','idPoll=' + idPoll.toString(), "Poll" + idPoll.toString());
   });
}

PollComputeVote = function(idPoll)
{
   	idItemPoll = $("#PollOption" + idPoll.toString()).val();
	if (idItemPoll == "")
	  alert("Escolha uma alternativa para votar.");
	else
	  RunAjax('core/manutencao/votepoll.php','Action=ComputeVote&idPoll=' + idPoll.toString() + '&idItemPoll=' + idItemPoll.toString(), "Poll" + idPoll.toString());
	return false;
}

TogglePoolPartialResult = function(idPoll)
{
    $(".PollToggle" + idPoll.toString()).toggle();
}


RunAjax = function(File, DataParameters, Place)
{
	$.ajax({
		   url:File,
		   data:DataParameters,
		   cache:false,
		   success:function(contentHtml)
		   {
			  $('#' + Place).html(contentHtml);
			  if (ExecFunctionAfterAjax != "")
			    eval(ExecFunctionAfterAjax);
			  ExecFunctionAfterAjax = "";
		   }
    });	
}

AjaxForm = function(Title, File, NoAutoResize, Width, Height, CloseForm)
{
    Parametro = {
        'modal':true,
        'useNextPrev':false
    };
    
    if (NoAutoResize)
      Parametro = {
        'modal':true,
        'autoDimensions':false,
        'autoScale':false,
        'width':Width,
        'useNextPrev':false,
        'height':Height        
      };
    
    $.ajax({
      url: File,
      cache:false,
      success:function(htmlCode)
      {
         lForm = '<div class="FormPopup"><div class="FormTitle">' + Title + '</div><div class="Body">' + htmlCode + '</div>';
         lForm = lForm + '<div class="Commands">';
         if (CloseForm)
           lForm = lForm + '<input type="button" onclick="CancelPopupForm()" value="Fechar">';
         else
         {
           lForm = lForm + '<input type="button" onclick="SubmitPopupForm()" value="Salvar">';
           lForm = lForm + '<input type="button" onclick="CancelPopupForm()" value="Cancelar">';
         }
         lForm = lForm + '</div></div>';
         $.fancybox(lForm, Parametro);
 		 if (ExecFunctionAfterAjax != "")
		   eval(ExecFunctionAfterAjax);
         ExecFunctionAfterAjax = "";
         if ($("div.FormPopup div.Body form .Focus").size() != 0)
           $("div.FormPopup div.Body form .Focus").focus();
      } 
    });  
}

SubmitPopupForm = function()
{
    $("div.FormPopup div.Body form").submit();
}

CancelPopupForm = function()
{
    if (editor)
    {
        editor.destroy();
        editor = null;   
    }
    $.fancybox.close();
    if (CancelFunctionAjax != '')
      eval(CancelFunctionAjax);
}

SimpleAjax = function(File)
{
	$.ajax({
		   url:File,
		   cache:false,
		   success:function(contentHtml)
			   {
				  if (ExecFunctionAfterAjax != "")
					eval(ExecFunctionAfterAjax);
				  ExecFunctionAfterAjax = "";
			   }
		   });	
}

CheckFields = function()
{
   var Ok = CheckFieldsGeneric(CheckFields.arguments)
   if (!Ok) 
     {
		alert(msgFillFieldsError);
		$("#" + FocusField).focus();
	 }
   return Ok;
}

CheckFieldsWithoutWarning = function()
{
	return CheckFieldsGeneric(CheckFieldsWithoutWarning.arguments);
}

CheckFieldsGeneric = function(Args)
{
   FocusField = '';
   var flCampo = true;
   var Ok = true;
   var Retorno = false;
   var Email = false;
   for (i=0;i<Args.length;i++)
       {
		  Campo = Args[i];
		  Email = false;
		  if (Campo.indexOf('@') > -1)
		    {
			   // Analisar Email
			   Campo = Campo.replace('@','');
			   Email = true;
			}
		  
		  Retorno = $("#" + Campo).val()=='';
		  $("#" + Campo).removeClass(classErrorField);
		  
		  if ((Email) && (!Retorno)) 
		     Retorno = ($("#" + Campo).val().indexOf('@') == -1);
			 
		  if (Retorno)
            $("#" + Campo).addClass(classErrorField);
		 
			 
          if (Retorno && flCampo) 
		    {
			   flCampo = false;
			   FocusField = Campo;
		    }
		  Ok = Ok && (!Retorno);
	   }
   return Ok;
}



ShowHide = function(Obj, state)
{
	if (state)
	  $(Obj).show();
	else
	  $(Obj).hide();
}

StateCSSNormal = function(CSS)
{
	$("#Centro").css('width','50%').show();
    $("#Direita, #Esquerda").css('width','25%').show();
	
	if (CSS != '')
	  {
		 var Diretivas = CSS.split('|');
		 for (i=0;i<Diretivas.length;i++)
		   {
			  Parametros = Diretivas[i].split('-');
			  Dados = Parametros[1].split(':');
			  $(Parametros[0]).css(Dados[0].toString(),Dados[1].toString());
		   }
	  }
}

OnlyNumbers = function(evt, CannotComma)
{
 if (evt.which == 0) 
   return true;

 var charCode = (evt.which) ? evt.which : event.keyCode;
 var Comma = (charCode == 44) || (charCode == 188);
 if (CannotComma)
   Comma = false;

  return ((charCode == 8) || (charCode == 9) || Comma || (charCode >= 48 && charCode <= 57));
}

OnlyLetters = function(evt)
{
 if (evt.which == 0) 
   return true;

 var charCode = (evt.which) ? evt.which : event.keyCode;
 return ((charCode == 8) || (charCode == 9) || (charCode >= 65 && charCode <= 91) || (charCode >= 97 && charCode <= 122));
}


CheckQueueFiles = function(AmountFiles)
{
  if (AmountFiles == 0)
	{
	  $("#btnUpload").attr('disabled','disabled');
	  $("#btnRemoveAllFiles").attr('disabled','disabled');
	}
  else
    {
	  $("#btnUpload").removeAttr('disabled');
	  $("#btnRemoveAllFiles").removeAttr('disabled');
	}
}

MakeUploadFile = function(ControlName, DescriptionFile, FileExtensions)
{
	var lDescriptionFile = (DescriptionFile) ? DescriptionFile : stDescriptionFile;
	var lFileExtensions = (FileExtensions) ? FileExtensions : stFileExtensions;
    $("#" + ControlName).fileUpload({
	   uploader:'core/uploadfy/uploader.swf',
	   script:'/newproject/upload.php',
	   cancelImg : 'core/uploadfy/cancel.png',
	   simUploadLimit:1,
	   multi:true,
	   fileDesc: lDescriptionFile,
	   fileExt: lFileExtensions,
	   buttonText:stAddImages,
	   displayData:'percentage',
	   onSelect:function(event, queueID, fileObj)
	   {
          CheckQueueFiles(1);
       },
	   onCancel:function(event, queueID, fileObj, data)
	   { 
          CheckQueueFiles(data.fileCount);
	   },
	   onError:function(a,b,c,d)
	   {
         if (d.status == 404)
            alert('Could not find upload script. Use a path relative to: '+'<?= getcwd() ?>');
         else if (d.type === "HTTP")
            alert('error '+d.type+": "+d.status);
         else if (d.type ==="File Size")
            alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
         else
            alert('error '+d.type+": "+d.text);
	   }
	   
	});
}

StartCascadeMenu = function(MenuParent)
{
    $('#' + MenuParent + ' > ul.classMenus > li').mouseover(function()
	{
	   $(this).children('ul.classSubMenu').show();
	}).mouseout(function() {
	   $(this).children('ul.classSubMenu').hide();	
	});
}

OpenPicture = function(idFoto)
{
	//AjaxForm('Foto', 660, 'controlpanel/exibefoto.php?idFoto=' + idFoto.toString(),1);
	window.open('controlpanel/exibefoto.php?idFoto=' + idFoto.toString(),'','scrollbars=no, width=660, height=500');
}


FixZIndex = function()
{
	if (parseInt($.browser.version)<8 && $.browser.msie)
	{
	  var zIndexNumber = 1000;
  
	  $('div, ul').each(function() {
		  $(this).css('zIndex', zIndexNumber);
		  zIndexNumber -= 10;
	  });
	}
}

// Album

CreateAlbum = function()
{
    if ($('a.PictureCP').size() > 0)
        $('a.PictureCP').fancybox({
         'transitionIn' : 'elastic',
         'transitionOut' : 'elastic',
         'speedIn' : 600,
         'speedOut' : 200,
         'overlayShow' : false
        });
}

// Entrada de dados

Masks = function()
{
  $(".CNPJ").mask('99.999.999/9999-99');	
  $(".CPF").mask('999.999.999-99');
  $(".DATAS").mask('99/99/9999');
  $(".CEP").mask('99999-999');
  $(".Telefone").mask('(99) 9999-9999');
  $(".OnlyNumbers").bind('keypress',checkItNumbers); 
}

checkItNumbers = function(evt) {
    evt = (evt) ? evt : window.event
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false
    return true
}

GetEndereco = function()
{
    $.ajax({
        url:'support.php',
        data:'Action=GetEndereco&CEP=' + $("#CEP").val(),
        cache:false,
        beforeSend:function()
        {
            $("input#CEP").removeClass('checkConfirmado');
			$("#CepNaoEncontrado").hide();
            $("span.GetAddress").show();
        },
        success:function(Response)
        {
            $("span.GetAddress").hide();
            if (Response != '')
            {
				eval(Response);
				Data = eval(resultadoCEP);
                $("#Endereco").val(Data.logradouro);
                $("#Bairro").val(Data.bairro);
                $("#Cidade").val(Data.cidade);
                $("#UF").val(Data.uf);
				$("input#CEP").addClass('checkConfirmado');
                $("#Numero").focus();
            }
            else
               $("#CepNaoEncontrado").show();
        } 
    })
}

ShowConfirmation = function(State)
{
   $("div.SavingData").hide();
   div = "div.ContactMessages" + (State ? 'Ok':'Error');
   $(div).slideDown();
}

IsDateNumbers = function(day, month, year) {
	//IsDate(29, 2, 2005)
	//IsDate(29, 2, 2004)
	var date = new Date();
	var blnRet = false;
	var blnDay;
	var blnMonth;
	var blnYear;

	date.setFullYear(year, month -1, day);

	blnDay   = (date.getDate()      == day);
	blnMonth = (date.getMonth()     == month -1);
	blnYear  = (date.getFullYear()  == year);

	if (blnDay && blnMonth && blnYear)
	blnRet = true;

	return blnRet;
}

IsDate = function(Date)
{
   Parts = Date.split('/');
   return IsDateNumbers(parseFloat(Parts[0]),parseFloat(Parts[1]),parseFloat(Parts[2])); 
}

CheckDataForm = function(pForm)
{
    Retorno = true;
    var Field;
    
    lFormName = '.Required:visible';
    if (pForm)
      lFormName = '#' + $(pForm).attr('id') + ' .Required:visible';

    $(".DATAS").removeClass('ErrorField');
    $(lFormName).removeClass('ErrorField').each(function() {
        chkCampo = ($(this).val() != '');
        if (chkCampo && $(this).hasClass('Email'))
          chkCampo = ($(this).val().indexOf('@') > 0);
          
        if (chkCampo && $(this).hasClass('DATAS'))
          chkCampo = IsDate($(this).val());


        Retorno = Retorno && chkCampo;
        if (!chkCampo)
        {
          $(this).addClass('ErrorField');
          if (!Field)
            Field = $(this);
        }
    });
    
    $(".DATAS").each(function() {
      if ($(this).val() != '')
      {
          chkCampo = IsDate($(this).val());
          Retorno = Retorno && chkCampo;
          if (!chkCampo)
            {
              $(this).addClass('ErrorField');
              if (!Field)
                Field = $(this);
            }
      }      
    });    
    
    if (!Retorno)
    {
      alert('Preencha os campos corretamente.')
      Field.focus();
    }
    else
    {
        $("div.SavingData").show();
    }
    return Retorno;
}
