if (jQuery.validator != undefined) {
var lang = 'ES';
var validator_ES = {
  required: "Este campo es obligatorio.",
  remote: "Por favor, rellena esta campo.",
  email: "Por favor, escribe una dirección de correo válida",
  url: "Por favor, escribe una URL válida.",
  remote: "El valor introducido ya existe en la base de datos.",
  check_domain: "Por favor, escribe una URL válida.",
  date: "Por favor, escribe una fecha válida.",
  dateISO: "Por favor, escribe una fecha (ISO) válida.",
  number: "Por favor, escribe un número entero válido.",
  digits: "Por favor, escribe sólo dígitos.",
  creditcard: "Por favor, escribe un número de tarjeta válido.",
  equalTo: "Por favor, escribe el mismo valor de nuevo.",
  accept: "Por favor, escribe una valor con una extensión aceptada.",
  maxlength: jQuery.validator.format("Por favor, no escribas más de {0} caracteres."),
  minlength: jQuery.validator.format("Por favor, no escribas menos de {0} caracteres."),
  rangelength: jQuery.validator.format("Por favor, escribe un valor entre {0} y {1} caracteres."),
  range: jQuery.validator.format("Por favor, escribe un valor entre {0} y {1}."),
  max: jQuery.validator.format("Por favor, escribe un valor igual o menor que {0}."),
  min: jQuery.validator.format("Por favor, escribe un valor igual o mayor que {0}.")
};

jQuery.extend(jQuery.validator.messages, window['validator_' + lang]);
}

var Init = {
    object: null,
    base: function(){
        $('#form_categorias :checkbox').click(function(){
            $(this).closest('ul').find('li:last-child').show().end().find(':checkbox').unbind('click');
        });
        
        $('#randomize').randomize();
        
        $('#select_year').change(function(){
            var $select = $(this);
            var new_year = $('option:selected', $select).val();
            
            $('#calendar_' + $select.data('year')).addClass('hidden');
            
            $('#calendar_' + new_year).removeClass('hidden');
            
            $select.data('year', new_year);
            
        }).data('year', new Date().getFullYear());
    },
    
    exchange: function(){
        this.base();
        
        $('#exchange_form').validate({
            rules: {
                'email': {
                    required: true,
                    email: true
                },
                'text': {
                    required: true
                },
                'url': {
                    required: true,
                    url: true
                }
            }
        });
    },
    
    contact: function(){
        this.base();
        
        $('#contact_form').validate({
            rules: {
                'email': {
                    required: true,
                    email: true
                },
                'name': {
                    required: true
                },
                'message': {
                    required: true
                }
            }
        });        
    },
    
    front: function(){
        
        var ref = this;
        
        this.base();
        
        this.sub_votes();
        
        $('li.comentar a, li.comen a').click(function(){
            var $div = $(this).closest('div');
            var id = $div.attr('id').substr(5);
            var $comments = $('#comentarios_' + id);
            
            $.get(this.href, function(data){
                if ($comments.length) {
                    $comments.replaceWith(data).slideDown('fast');
                } else {
                    $div.addClass('activo').after(data);
                }
                
                $div.addClass('activo').find('li.comentar a').addClass('actualizar');
                
                ref.sub_comment_form('comentarios_' + id);
            });
            
            return false;
        });
        
        $('#order_select').change(function(){
            $(this).parent().submit();
        });
        
        $('div.comentarios div.paginado a').live('click', function(){
            var $div_comments = $(this).closest('div.comentarios');
            
            $.get(this.href, function(data){
                $div_comments.replaceWith(data);
                
                ref.sub_comment_form($div_comments.attr('id'));
            });
            
            return false;
        });
        
        $('div.comentarios a.cerrar').live('click', function(){
            // Remove class "active" from the div post. The rel attr contains the post id
            $('#post_' + $(this).attr('rel')).removeClass('activo').find('li.comentar a').removeClass('actualizar');
            
            // Hide the comments 
            $(this).closest('div').slideUp('fast');            
            
            return false;
        });
        

    },
    
    frame: function() {
        $('a.roto').click(function(){
            $.getJSON(this.href, function(data){
                alert('Muchas gracias por avisar. Revisaremos el enlace tan pronto como sea posible.');
            });
            
            return false;
        });
        
        this.sub_votes();
    },
    
    post: function() {
        this.base();
        
        $('img.footer').each(function(){
            var $img = $(this);
            
            $img.load(function(){
                var img_class = this.width > 350 ? 'big' : 'little';
                
                $img.wrap('<div class="'+ img_class +'"></div>');
                    
                if (this.title.length) {
                    $img.after('<br/><p/>').parent().find('p').text(this.title).width(this.width - 12);
                }
            });
            
            if (this.complete) {
                $img.triggerHandler('load');
            }
            
        });
        
        this.sub_comment_form($('div.comentarios').attr('id'));
        this.sub_votes();
    },
    
    sub_comment_form: function(id){
        var $div = $('#' + id);
        var $form = $div.find('form');
        var ref = this;
        
        $form.validate({
            rules: {
                'nick': {
                    required: true
                },
                'comment': {
                    required: true
                },
                'response': {
                    required: false
                },
                'url': {
                    url: true
                }
            },
            submitHandler: function(form){
                $form.ajaxSubmit({
                    dataType: 'json',
                    success: function(data){
                        if (data.success) {
                            $div.replaceWith(data.html);
                            
                            ref.sub_comment_form(id);
                        } else {
                            var $ul = $div.find('ul.error').empty();
                            
                            $(data.errors).each(function() {
                                $('<li>' + this + '</li>').appendTo($ul);
                            });
                            
                            $ul.removeClass('hidden');
                        }
                    }
                });
            }
        });
    },
    
    sub_votes: function(){
        $('a.si,a.no').click(function(){
            var $link = $(this);
            var $ul = $link.closest('ul');
            
            if (! $link.hasClass('si_ya') && ! $link.hasClass('no_ya') && ! $ul.hasClass('ya')) {
                $.getJSON(this.href, function(data){
                    var css_class = data.votes > 0 ? 'posi' : 'nega';
                    var text = data.votes;

                    if ($ul.hasClass('valorar')) {
                        $ul.addClass('ya');
                    } else {
                        $ul.find('li.votar a').addClass(function(){
                            return $(this).hasClass('si') ? 'si_ya' : 'no_ya';
                        });
                    }
                    
                    if (data.votes > 0) {
                        text = '+' + data.votes;
                    } 
                    
                    $ul.find('li.votos').text(text).addClass(css_class);
                });
            }
            
            return false;
        });
        
        $('a.si_ya, a.no_ya').click(function(){return false});        
    }
};

$(function() {
    var type = $('#type').val();
    
    if (type != undefined) {
        Init[type]();
    }
});
