$(document).ready(function() {
    /**********************************
    * Zamykanie/otwieranie popupa
    *
    *
    ************************************/
    $('.x').click(function() {
        $(this).parent().fadeOut();
        return false;
    });
    
    $('td.clickable').find('a').bind('click',function(event){
        event.stopPropagation();
    })
    
    $('td.clickable').click(function(event) {
        event.stopPropagation();
        $('.popUpCalendar').fadeIn();
        $('#popUpDatePanel').html($(this).attr('id'));
    });

    /**********************************
    * nowe wydarzenie 
    * dodawane przez popUpa
    *
    *
    ************************************/    
    $('#add_new_event').click(function() {
        var $this = $(this);
        var date = $('#popUpDatePanel').html();
        var description = $('input[name=popup_event_description]').val();
        var hour_start = $('select[name=popup_hour_start]').val();
        var hour_end = $('select[name=popup_hour_end]').val();
        var event_status = $("input[name=event_status]:checked").length?'1':'0';
        //alert(date + hour_start + hour_end + description);

        if (!date || !description || !hour_start || !hour_end) {
            alert('Wypełnij wszystkie pola');
            return false;
        }
        // walidacja wpisanych godzin
        var start_hour_hour = parseInt(hour_start.substring(0,2),10);
        var start_hour_min = parseInt(hour_start.substring(3,5),10);
        
        var end_hour_hour = parseInt(hour_end.substring(0,2),10);
        var end_hour_min = parseInt(hour_end.substring(3,5),10);
        
        if (end_hour_hour < start_hour_hour ) {
            alert('Niepoprawnie wprowadzone godziny');
            return false;
        }
        
        if (end_hour_hour == start_hour_hour ) {
            if (end_hour_min <= start_hour_min ) {
                alert('Niepoprawnie wprowadzone godziny');
                return false;
            }
        }
        // koniec walidacji
        
        $.ajax({
            url: '/calendar_events/ajx_add_event/',
            type: 'POST',
            datatype: 'text',
            data: 'date_start='+date+'&title='+description+'&description='+description+'&date_start_hour='+hour_start+'&date_end_hour='+hour_end+'&status='+event_status,
            beforeSend: function() {
                
            },
            success: function(data, textStatus) {
                $('.popUpCalendar').fadeOut();
                //$('input[name=popup_event_description]').val('');
                //$('select[name=popup_hour_start]').val('');
                //$('select[name=popup_hour_end]').val('');
                //$("input[name=event_status]").attr('checked','');
                window.location = window.location.href;
                
                // w zaleznosci od typu kalednarza roznie dodajemy
                if ($this.hasClass('month')) {
                    var color = (event_status == '1')?'blue':'pink';
                    $('#'+date).append('<div class="textAlignLeft event"><span class="'+color+'">'+hour_start +' '+ '<a href="/calendar_events/show/'+data+'">'+description +'</a></span></div>');
                }
                else {
                    window.location = window.location.href;
                };
            }
        });
        
        return false;
    });
    
    /**********************************
    * Filtr zdarzen: 
    * publiczne, prywatne, ulubione
    *
    *
    ************************************/
    $('.events_filter').click(function() {
        // pogrubianie
        $('.events_filter').removeClass('fontBold');
        $(this).addClass('fontBold');
        
        var event_type = $(this).attr('rel');
        var $events = $('.event').children('span');
        var $events_back = $('.evt');
        var $events_long = $('.longEvt');
        var $events_long_children = $events_long.children('span');;
        
        if ('all' == event_type) {
            $events.css('display','block');
            $events_back.css('display','block');
            
            $events_long_children.css('display','block');
            $events_long.css('background','#DFEFE6');
            return false;
        }
        
        $events.not('.'+event_type).css('display','none');
        $events_back.not('.'+event_type).css('display','none');
        $events_long_children.not('.'+event_type).css('display','none');
        $events_long.not('.'+event_type).css('background','#FFF');
        
        $events.filter('.'+event_type).css('display','block');
        $events_back.filter('.'+event_type).css('display','block');
        $events_long_children.filter('.'+event_type).css('display','block');
        $events_long.filter('.'+event_type).css('background','#DFEFE6');

        
        return false;
    });
    
    /**********************************
     * Dodajemy publiczne zdarzenie
     *
     *
     ************************************/
    $('.calendar_subscribe_event').click(function() {
        var $this = $(this);
        $.ajax({
            url: '/calendar_events/ajx_subscribe_event/',
            type: 'POST',
            datatype: 'text',
            data: 'id='+$this.attr('rel'),
            beforeSend: function() {
                
            },
            success: function(data, textStatus) {
                $this.replaceWith('<div class="redButtonNonClick">Dodano</div>');
                window.location = window.location.href;
            }
        });
        return false;
    });
    
    /**********************************
     * standardowy submit formularza
     *
     *
     ************************************/
    $('.calendar_std_submit a').click(function() {
        var form_name = $(this).attr('rel');
        $('form[name="'+form_name+'"]').submit();
        return false;
    });
    
    $('.calendar_std_submit').click(function() {
        var form_name = $(this).attr('rel');
        $('form[name="'+form_name+'"]').submit();
        return false;
    });    
    
    /**********************************
     * dodawanie/odejmowanie z ulubionych
     *
     *
     ************************************/
    $('.calendar_favorite_status').click(function() {
        var $this = $(this);
        var event_id = $this.attr('rel');
        event_id = event_id.replace('event_','');
        var sign = $this.html();
        var status = 1;
        if (sign == '-') {
            status = 0;
        }
        $.ajax({
            url: '/calendar_events/ajx_favorite_status/',
            type: 'POST',
            datatype: 'text',
            data: 'id='+event_id+'&status='+status,
            beforeSend: function() {
                
            },
            success: function(data, textStatus) {
                window.location = window.location.href;
                /*
                if (sign == '-') {
                    $('.'+$this.attr('rel')).removeClass('orange');
                    $this.html('+');
                    $this.parent().parent().parent().find('a[rel='+ $this.attr('rel') +']').html('+');
                }
                else {
                    $('.'+$this.attr('rel')).addClass('orange');
                    $this.html('-');
                    $this.parent().parent().parent().find('a[rel='+ $this.attr('rel') +']').html('-');
                };
                */
            }
        });
        return false;
    });
    /**********************************
     * popup z podgladem wydarzenia
     *
     *
     ************************************/
    $('.event').hover(
            function() {
                var $this = $(this);
                //alert('test');
                $this.css('zIndex','9999999');
                $this.parent().css('zIndex','9999999');
                $this.parent().parent().css('zIndex','9999999');
                var $popup = $this.children('.popUpEventPreview');
                if ($this.hasClass('leftPop')) {
                    $popup.css('left','-238px');
                }
                
                if ($this.hasClass('topPop')) {
                    $popup.css('top','-120px');
                }
                $popup.show();
            },
            function() {
                var $this = $(this);
                if ( $.browser.opera ){
                $this.children('.popUpEventPreview').fadeOut("0.0001");
                $this.css('zIndex','0');
                $this.parent().css('zIndex','5000');
                $this.parent().parent().css('zIndex','5000');
                }
                else{
                $this.children('.popUpEventPreview').hide();
                $this.css('zIndex','0');
                $this.parent().css('zIndex','5000');
                $this.parent().parent().css('zIndex','5000');
                }

            }
    );
    /**********************************
     * automatyczne ustawianie daty
     * w drugim select'cie
     *
     *
     ************************************/
    $('.date_start_clicker').change(function() {
        if ( ($('input[name=date_start]').val() == $('input[name=date_end]').val())) {
            var newIndex = $('.date_start_clicker').attr("selectedIndex") + 1;
            var newSel = $('select[name=date_end_hour] option').get(newIndex);
            $(newSel).attr('selected','selected');
        }
    });
    $('.date_start_clicker_popup').change(function() {
        var newIndex = $('.date_start_clicker_popup').attr("selectedIndex") + 1;
        var newSel = $('select[name=popup_hour_end] option').get(newIndex);
        $(newSel).attr('selected','selected');
    });
    
    /**********************************
     * spraedzamy poprawna dlugosc komentarza
     *
     *
     ************************************/
    $('.add_new_comment').click(function() {
        var text = $('textarea[name="text"]').val();

        if (text.length > 500) {
            alert('Za długi tekst komentarza');
            return false;
        }

        var form_name = $(this).attr('rel');
        $('form[name="'+form_name+'"]').submit();
        return false;
    });
    
    $('.calendar_search_submit').click(function() {
        var text = $('input[name="exp"]').val();

        if (text.length <= 0) {
            alert('Wpisz wyrażenie do wyszukania');
            return false;
        }

        var form_name = $(this).attr('rel');
        $('form[name="'+form_name+'"]').submit();
        return false;
    });
    
    /**********************************
     * blokowanie/odblokowywnnie mozliwosci
     * wysylania zaproszen (w zaleznosci od statusu prywatny/publiczny)
     *
     *
     ************************************/
    var invitationBlocker = function() {
        var $input = $('input[name="status"]:checked');
        //alert($input.val());
        if ($input.val() == 0) {
            
            $('#leftC').css('color','#DDD');
            $('#add_new_invitation').css('visibility','hidden');
            $('input[name="invitation_name_panel"]').css('display','none');
            $('input[name="invitation_name_panel"]').val('');
            $('input[name="invitation_email_panel"]').css('display','none');
            $('input[name="invitation_email_panel"]').val('');
        }
        else {
            $('#leftC').css('color','#000');
            $('#add_new_invitation').css('visibility','visible');
            $('input[name="invitation_name_panel"]').css('display','block');
            $('input[name="invitation_email_panel"]').css('display','block');
        }
    };
    invitationBlocker();
    $('input[name="status"]').change(function(){
        invitationBlocker();
    });
    // IE6
    $('input[name="status"]').click(function(){
        invitationBlocker();
    });
    
    /**********************************
     *potwierdzenie
     *
     *
     ************************************/
    $('.confirm').click(function() {
        var conf = confirm('Na pewno usnuąć? Operacji nie da sie cofnąć');
        if (!conf) {
            return false;
        }
    });

    
});
