/**
 * Executa tarefas comuns durante a carga da página,
 * como por exemplo, setar o foco em uma caixa de texto e
 * criar controles para calendário.
 * Requer prototype.js e calendar.js.
 * A caixa de texto que receberá o foco tem a classe CSS
 * igual a classFocus; para os calendários, classCalendar
 */
function commonTasksOnLoad(classFocus, classCalendar) {
    var elems = $$(classFocus)
    if (elems && elems.length) { elems[0].focus()}

    elems = $$(classCalendar)
    for (i = 0; i < elems.length; i++) {
        Calendar.setup({inputField : elems[i].id, ifFormat: "%d/%m/%Y",
            displayArea:"show_e", daFormat : "%d/%m/%Y",
            button: elems[i].id + "Cal", singleClick:true, weekNumbers:false });
    }

    /* Para desabilitar/habilitar os botões durante ações AJAX*/
    Ajax.Responders.register({
        onCreate: function() {
            $$('.disabledAjax').each(function(elem) {
                elem.disabled = true
            })
            $$('.invisibleAjax').each(function(elem) {
                elem.addClassName('invisible')
            })
        },
        onComplete: function() {
            $$('.disabledAjax').each(function(elem) {
                elem.disabled = false
            })
            $$('.invisibleAjax').each(function(elem) {
                elem.removeClassName('invisible')
            })
        }
    });

}
function escreverEmailProtegido(usuario, dominio) {
    var endereco = usuario + "@" + dominio
    document.write("<a href='mailto:" + endereco + "'>" + endereco + "</a>")
}
/**
 * Mostra animação para indicar processamento Ajax
 */
function showProgress(e) {
    var s = $('spinner')
    s.show()
}
function finishProgress(e) {
    $('spinner').hide()
}

function showSpinner(id) {
    jQuery('#'+id).show();
}
function hideSpinner(id) {
    jQuery('#'+id).hide();
}

function timeout(e) {
    alert("O tempo limite de resposta foi excedido.")
    window.location.reload()
}

/**
 * A partir do cep digitado, preenche campos relativos ao endereço
 */
function preencheEndereco(url, cepElem, endereco, bairro, cidade, uf) {
    $(endereco).value = ''
    $(cidade).value = ''
    $(bairro).value = ''
    $(uf).selectedIndex = ''
    url += '?cep=' + $(cepElem).value
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(transport) {
            var info = eval(transport.responseJSON)
            $(endereco).value = info.logradouro
            $(cidade).value = info.cidade
            $(bairro).value = info.bairro
            // Seleciona a uf pesquisada
            $(uf).select(' ').each(function(control, index) {
                if (control.value == info.uf) {
                    $(uf).selectedIndex = index
                    throw $break;
                }
            });
        }
    });
}

/*
 * Função utilizada para verificar os limites de tamanho de um determinado campo
 */
function validaLimite(campo, limA, limB) {
    var fld = $(campo).value
    if (fld) {
        if (fld.length < limA || fld.length > limB) {
            alert('O ' + campo + ' deve ter entre ' + limA + ' e ' + limB + ' caracteres!')
            return false
        }
    }
    return true
}


/* Modifica o tamanho da fonte*/
var tam = 14;
function mudaFonte(tipo, elemento) {
    if (tipo == "mais") {
        if (tam < 17) {
            tam += 1;
        }
        createCookie('fonte', tam, 365);
    } else {
        if (tam > 11) {
            tam -= 1;
        }
        createCookie('fonte', tam, 365);
    }
    $$('.mudaFonte').each(function(elem) {
        elem.style.fontSize = tam + 'px';
    })
}

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;
}

// Create a Youtube style text indicator underneath the stars,
// using starbox custom events
function starboxChangedText(event) {
    var indicator = this.down('.indicator'),
        pick = (event.memo.rating || 0).round() - 1,
        indicator = this.down('.indicator');

    // for restoring, store the indicator text on the star if it was not set before.
    this.starboxResetText = this.starboxResetText || indicator.innerHTML;

    this.down('.indicator').update([
        'Pobre',
        'Nada de especial',
        'Vale a pena',
        'Muito legal',
        'Excelente!'
    ][pick]);
}

function registerTabChanger() {
    if ($$('.aba.selected').size() > 0) {
        $$('.aba.selected')[0].show()
        $$('.aba').without($$('.aba.selected')[0]).each(function(o1) {
            o1.removeClassName("selected")
            $(o1.id.sub(/aba\-/, '')).hide()
        })
    } else if ($$('.aba').size() > 0) {
        $$('.aba')[0].addClassName("selected")
        $$('.aba')[0].show()
        $$('.aba').without($$('.aba')[0]).each(function(o1) {
            o1.removeClassName("selected")
            $(o1.id.sub(/aba\-/, '')).hide()
        })
    }
    $$('.aba').each(function(o) {
        o.observe('click', function(e) {
            changeTab(o.id.sub(/aba\-/, ''))
        })
    });
}

function changeTab(element) {
    var tab = null
    if (typeof element == 'string') {
        tab = $('aba-' + element)
    } else {
        tab = element
    }
    tab.addClassName("selected")
    $(tab.id.sub(/aba\-/, '')).show()
    $$('.aba').without(tab).each(function(o1) {
        o1.removeClassName("selected")
        $(o1.id.sub(/aba\-/, '')).hide()
    })

}

function registerInputMessage(element, message) {
   var el = null
   if (typeof element == 'string') {
       el = $(element)
   } else {
       el = element
   }
   if (el.value == "") {
       el.value = message
   }
   if(el == null){
       return;
   }
   var f = el.form

    jQuery(el).focus(function() {
        if (el.value == message) {
            el.value = ""
        }
    });
    jQuery(el).blur(function() {
        if (el.value == "") {
            el.value = message
        }
    });
    jQuery(f).submit(function() {
        if (el.value == message) {
            el.value = ""
        }
    });
}

/*
* Simula labels em campos de texto
* Para usar, basta colocar a classe css ghosted e o texto que deseja utilizar como label no tittle
* */
Form.GhostedField = Class.create({
  initialize: function(element, title, options) {
    options = options || {};

    this.element = $(element);
    this.title = title;

    this.isGhosted = true;

    if (options.cloak) {

      // Wrap the native getValue function so that it never returns the
      // ghosted value. This is optional because it presumes the ghosted
      // value isn't valid input for the field.
      this.element.getValue = this.element.getValue.wrap(this.wrappedGetValue.bind(this));
    }

    this.addObservers();

    this.onBlur();
  },

  wrappedGetValue: function($proceed) {
    var value = $proceed();
    return value === this.title ? "" : value;
  },

  addObservers: function() {
    this.element.observe('focus', this.onFocus.bind(this));
    this.element.observe('blur',  this.onBlur.bind(this));

    var form = this.element.up('form');
    if (form) {
      form.observe('submit', this.onSubmit.bind(this));
    }

    // Firefox's bfcache means that form fields need to be re-initialized
    // when you hit the "back" button to return to the page.
    if (Prototype.Browser.Gecko) {
      window.addEventListener('pageshow', this.onBlur.bind(this), false);
    }
  },

  onFocus: function() {
    if (this.isGhosted) {
      this.element.setValue('');
      this.setGhosted(false);
    }
  },

  onBlur: function() {
    var value = this.element.getValue();
    if (value.blank() || value == this.title) {
      this.setGhosted(true);
    } else {
      this.setGhosted(false);
    }
  },

  setGhosted: function(isGhosted) {
    this.isGhosted = isGhosted;
    this.element[isGhosted ? 'addClassName' : 'removeClassName']('ghosted');
    if (isGhosted) {
      this.element.setValue(this.title);
    }
  },

  // Hook into the enclosing form's `onsubmit` event so that we clear any
  // ghosted text before the form is sent.
  onSubmit: function() {
    if (this.isGhosted) {
      this.element.setValue('');
    }
  }
});

document.observe('dom:loaded', function() {

  var searchField = $('texto');  

  new Form.GhostedField(searchField, searchField.getAttribute('title'),
    { cloak: true });
});


