$(function()
{
    $('a[href="#send"]').click(function()
    {
        setTimeout(function()
        {
            var nombre = $('#nombre');

            if ( nombre.val().length == 0 )
                nombre.focus();
            else
                $('#mensaje').focus();
        }, 1);
    });


    var controls = $('<div class="controls"><'+'/div>').appendTo( $('div#slideshow') );
    
    if ( $('div#slideshow div.photos img').length > 1 )
    {
        photoCurrent = 0;

        $('div#slideshow div.photos img').hide().eq(photoCurrent).fadeIn();
        
            controls.append(
            $('<a>Anterior<'+'/a>').click(function()
            {
                var photos = $('div#slideshow div.photos img');
                var photoBackup = photoCurrent;

                photoCurrent--;

                if ( photoCurrent < 0 )
                    photoCurrent = photos.length - 1;

                photos.eq(photoBackup).fadeOut('slow', function()
                {
                    photos.eq(photoCurrent).fadeIn('slow');
                });
            })
        )
        .append( $('<span>&nbsp;<'+'/span>') )
        .append(
            $('<a>Siguiente<'+'/a>').click(function()
            {
                var photos = $('div#slideshow div.photos img');
                var photoBackup = photoCurrent;

                photoCurrent++;

                if ( photoCurrent > photos.length - 1 )
                    photoCurrent = 0;

                photos.eq(photoBackup).fadeOut('slow', function()
                {
                    photos.eq(photoCurrent).fadeIn('slow');
                });
            })
        );
    }
    
    if ( isEditable ){
        controls.append(
            $('<a class="images" href="/usercp/propiedades/fotos/' + idPropiedades + '/">Modificar (' + imgCount + ')</a>')
        )
        .append(
            $('<div class="clear"><!-- --></div>')
        )
    }

    $('a.reply').click(function()
    {
        $('<div class="reply"><'+'/div>')
        .appendTo( $(this).hide().parents('div.answer') )
        .append( $('<textarea cols="69" rows="4"><'+'/textarea>') )
        .append(
            $('<a href="#replySave">Guardar<'+'/a>').click(function()
            {
                var replyDiv = $(this).parents('div.reply');
                var replyTextarea = replyDiv.children('textarea');
                var replySave = replyDiv.children('a');
                var reply = replyTextarea.val();
                var idPropiedadesPublicacionMensajes = replyDiv.parents('div.answer').find('a[name]').attr('name').substr(1);

                if ( reply.length > 0 )
                {
                    replyTextarea.remove();
                    replySave.remove();

                    $.ajax({
                        type   : 'POST',
                        url    : '/api/ApiPostReply/',
                        data   : 'id_=' + idPropiedadesPublicacionMensajes + '&reply=' + reply,
                        success: function(html){
                            replyDiv.html(html).animate({ backgroundColor: '#FFE999' }, 500)
                                               .animate({ backgroundColor: '#FFF' }, 500)
                                               .animate({ backgroundColor: "#FFF4D6" }, 500);
                        }
                    });
                }
                else
                    replyTextarea.focus();

                return false;
            })
        ).hide().show('slow');

        return false;
    });
    
    $('div#slideshow div.photos img').click(function(){
        jQuery.facebox($('<img src="' + this.src.replace('/320x240/', '/640x480/') + '" />'));
    
    
        var foot = $('#facebox td.body div.footer')
            foot.find('p').empty();
            foot.html('<p class="aLeft">' + ( this.title || '' ) + '</p><div class="jFoot">' + foot.html() + '</div>');
    
        $('#facebox td.body div.footer div.jFoot a').click(jQuery.facebox.close);
        
        $('#facebox div.popup td.body').css('width', 'auto');
        $('#facebox div.popup td.body div.content').css('text-align', 'center');
    
        return false;
    });
    
    
    if ( isEditable ){
        $('div.calendario table.calendar tbody tr td a').click(function(){
            var self = $(this);
    
            var d = self.html();
    
            var mY = self.parents('tbody').attr('id').replace(/mY/g, '');
            var toggle = self.hasClass('busy') ? 0 : 1;
    
            $.get('/api/ApiSetCalendarStatus/' + idPropiedades + '/' + d + '-' + mY + '/' + toggle + '/', function( response ){
                if ( response == 1 )
                    self.addClass('busy');
                else
                    self.removeClass('busy');
            });
    
            return false;
        });
        
        $('div.calendar-info a[href=#allMonth]').click(function(){
            var x = 0;
    
            var date = $(this).parent().next().children('tbody').attr('id').replace(/mY/g, '');
            var days = $('tbody#mY' + date + ' tr td a');
    
                days.each(function(){ if ( $(this).hasClass('busy') ) x++; });
    
            var toggle = x == days.length ? 0 : 1;
    
            $.get('/api/ApiSetCalendarStatus/' + idPropiedades + '/' + date + '/' + toggle + '/', function( response ){
                if ( response == 1 )
                    $('tbody#mY' + date + ' tr td a').each(function(){ $(this).addClass('busy'); });
                else
                    $('tbody#mY' + date + ' tr td a').each(function(){ $(this).removeClass('busy'); });
            });
    
            return false;
        });
    }
    else {
        $('div.calendario table.calendar tbody tr td a').click(function(){
    
            if ( $(this).hasClass('busy') )
                return false;
            
            var d  = $(this).html();
            
            var mY = $(this).parents('tbody').attr('id').replace(/[^\d-]/g, '').split('-');
    
            var desde = $('#desde');
            var hasta = $('#hasta');
    
            var date  = [d, mY[0], mY[1]].join('/');
    
            if ( !isDate(desde.val()) )
                desde.val(date);
    
            else if ( date != desde.val() )
            {
                hasta.val(date);
    
                var dateIni = $('#desde').val();
                var dateEnd = date;
    
                $.ajax({
                    type   : 'POST',
                    url    : '/api/ApiCheckCalendar/' + idPropiedades + '/' + dateIni.replace(/\//g, '-') + '/' + dateEnd.replace(/\//g, '-') + '/',
                    success: function( Busy ){
                        if ( Busy != 0 ){
                            alert(Busy);
                            hasta.val('');
                        }
                    }
                });
            }
    
            return false;
        });
    }
    
    $('#hasta').blur(function(){
        if ( isDate($(this).val()) )
        {
            $.ajax({
                type   : 'POST',
                url    : '/api/ApiCheckCalendar/' + idPropiedades + '/' + $('#desde').val().replace(/\//g, '-') + '/' + $(this).val().replace(/\//g, '-') + '/',
                success: function( Busy ){
                    if ( Busy != 0 ){
                        alert(Busy);
                        $('#hasta').val('');
                    }
                }
            });
        }
    });
    
    var inputs = $("#desde, #hasta");
    
    if ( 'date_input' in inputs )
        inputs.date_input();
    
    function isDate( date ){
        return /(0?[1-9]|[12][0-9]|3[01])[/](0?[1-9]|1?[012])[/](19|20)\d\d/.test(date);
    }
    
    $('a.publish-cancel').click(function(){
        return confirm('Esta Seguro?');
    });
    
    $('div.go-back a').click(function(){
        history.go(-1);
        return false;
    });
});
