$(document).ready(function() {
    
    // SUBNAV
    
    $('.subnav').hide()
                .parent('li')
                .hover(
        function() {
            $(this).children('.subnav').show();
        },
        function() {
            $(this).children('.subnav').hide();
        }
    );
    
    
    // PHOTO CYCLE
    $('#photo-carousel').after('<div id="p-nav"></div>').cycle({fx: 'fade', pager: '#p-nav', pause: 1, delay: 1000});
    
    // center images vertically and horizontally
    $('#photo-carousel li img').each(function() {
        f_height = 350;
        f_width = 400;
        i_height = $(this).attr('height');
        i_width = $(this).attr('width');
        t_margin = (f_height - i_height) / 2;
        l_margin = (f_width - i_width) / 2;
        $(this).css({'margin-top' : t_margin, 'margin-left' : l_margin});
    });
    
    initPage();
    
})

function initPage() {
    // EDIT IN PLACE
    $('.auth:not(.manage-photos)').click(function(e) {
       e.preventDefault();
       url = $(this).attr('href');
       if ($('#authcontainer').length) {
           container = $('#authcontainer');
       } else {
           container = $(this).parent('div');
       }
       $.get(url, function(data) {
           container.html(data);
           initPage();
       });
    });
    
    $('.cancel-button').click(function(e) {
       e.preventDefault();
       url = $(this).val();
       o = confirm("Are you sure you want to discard any changes you've made?");
       if (o) {
           window.location = url.split('#')[0];
       }
    });
    
    $('.delete').click(function(e) {
        e.preventDefault();
        url = $(this).attr('href');
        o = confirm("Are you sure you want to delete this item?");
        if (o) {
            window.location = url;
        }
    });
    
    $('#id_content_type').change(function() {
        
        switch($(this).val()) {
            case 'NewsLink':
                type = 'text';
                label = 'Link URL';
            break;
            case 'NewsFile':
                type = 'file';
                label = 'File';
            break;
            case 'NewsText':
                type = 'textarea';
                label = 'Content';
            break;
        };
        if (type=='textarea') {
            html = "<tr class='news-item-type'><td><label>" + label + "</label></td><td><textarea name='news-item'></textarea></td></tr>";
        } else {
            html = "<tr class='news-item-type'><td><label>" + label + "</label></td><td><input type='"+ type +"' name='news-item' /></td></tr>";
        };
        
        $('tr.news-item-type').remove();
        $('tr.submit').before(html);
    });
}
