(function($) { // hide the namespace
    $(function () {
        // date picker
        $('.page form .item.element input[name*=date]').datepicker({
            numberOfMonths: 1,
            //minDate: server_now,
            dateFormat: 'dd/mm/yy',
            //appendText: '(dd/mm/yyyy)',
            showOn: 'both', // focus + button click
            buttonImage: '/img/datepicker.gif',
            buttonText: 'Choose the date with a calendar',
            buttonImageOnly: true,
            showStatus: true
        });

        // action confirm
        $('a.delete.confirm-it').click(function () {
            return confirm('Are you sure you want to ' + $(this).attr('title').toLowerCase() + '?');
        });
        
        // search autocomplete

        // On photographer name
        $('.zone.bloc#search input#photographer').autocomplete(
            '/photo/search/photographer'
        );

        // On photographer name - admin
        $('.page.admin.photo#list input#photographer').autocomplete(
            '/admin/photo/photographer'
        );

        // Sub categeries name 
        if ( $('select#category').val() == 0 )
            $('select#sub_category').parent('.item.element').hide();
            
        $('select#category').change(function () {
            $.ajax({
               type     : 'GET',
               url      : '/photo/search/subcategories',
               data     : 'category=' + $(this).val(),
               dataType : 'json',
               success  : function ( subcategories ) {
                              var select = $('select#sub_category');

                              cache_value = select.val();
                              
                              // Hide or show
                              select.parent('.item.element')[subcategories.length == 0 ? 'hide': 'fadeIn']();

                              // Populate (or remove) all options
                              var options = '<option value="0"></option>';
                              
                              for ( var i = 0; i < subcategories.length; i++ )
                                  options += '<option value="' + subcategories[i].ID + '"' + (cache_value == subcategories[i].ID ? ' selected="selected"' : '') + '>' + subcategories[i].name + '</option>';
                              
                              select.html(options);
                           }
             });
        })
//        .change()
        ;

    });
})(jQuery);
