$(function()
{ 
    //$(document).pngFix(); 
    
    
    /**
    * Logout 
    * 
    */
    $('#logout').click(function()
    {
        $.prompt(
            'Are you sure you want to logout?', 
            { 
                buttons: { Ok: true, Cancel: false }, 
                callback: function (v) 
                    { 
                        if (v) { location.href = '/logout.html'; } 
                    }
            });
        return false;
    });
    
    
    /**
    * Add answer form to the current comment
    * 
    */
    $('#comment li.reply span').click(function() 
    {
        // action for all
        $('.comment').css('display', 'none'); // hide any form in the comments
        $('.reply').css('display', 'inline'); // refresh "reply" link for all the comments
        
        // action for item
        var base = $(this).parent().parent().parent(); // base for our item
        base.find('.comment').css('display', 'inline'); // make working form visiable
        base.find('.comment textarea').focus(); // set focus on textarea 
        
        base.find('li.reply').css('display', 'none'); // hide "reply" link
        base.find('.error_color').css('display', 'none'); // also hide erro comment
        
        $('#comment_id_qouted').val(base.find('textarea').attr('id')); // set reply comment id
    });
    
    $('#comment input.discard').click(function() 
    {
        $('#comment_id_qouted').val(0); // set zerofill reply comment id
        $('.comment').css('display', 'none'); // hide any comment form
        $('.reply').css('display', 'inline'); // refresh "reply" link 
    });
    
    
    /**
    * Add to the form action quoted comment if it's needed
    * 
    */
    $('form#comments_form').submit(function()
    {
        var quoted_comment = $('#comment_id_qouted').val();
        var form_action = $('form#comments_form').attr('action');
        
        if (0 == quoted_comment) {
            var pos = form_action.indexOf('#');
            if (-1 != pos) {
                $('form#comments_form')
                    .attr('action', form_action.substr(0, pos));
            }
        } else {
            $('form#comments_form')
                .attr('action', form_action + '#comment_' + quoted_comment);
        }
        
        return true;
    });
    
        
    /**
    * Rate comment
    * 
    */
    $('.thumbs_up a, .thumbs_down a').click(function() 
    {
        var li = $(this).parent();
        switch (li.attr('class')) 
        {
            case 'thumbs_up': 
                var rating = '+1';
                break;
            
            case 'thumbs_down': 
                var rating = '-1';
                break;
            
            default: alert('What is it?');
        }
        
        $.post($(this).attr('href'), 
            {rating: rating},
            function(response)
            {
                li.parent().find('li.num_rate').text(response.rating);
                var thumb_down = li.parent().find('li.thumbs_down');
                var thumb_up = li.parent().find('li.thumbs_up');
                thumb_down.remove();
                thumb_up.remove();
            }, 
            'json');
        
        return false;
    });
    
    
    // this incredible css properties we set with aid of jquery, 
    // cause we too lazy and know nothing about old browsers which don't support CSS3
    $(':checkbox').css('width', 'auto');
    $(':radio').css('width', 'auto');
    
    // Zend Framework can't solve this problem on the "server" level :)
    // it's need to write self extended component, cause fo now it's kludge
    $('#favorite:checkbox').click(function()
    {
        $(this).val($(this).attr('checked') ? 1 : 0);
    });
    
    
    /**
    * Embeded video
    * 
    */
    $('.url_embed #url, .url_embed #embed').click(function (){
        $(this).select();
    });
    
    
    // this sets up the progress bar
    $('#uploadprogressbar').progressBar();
    
    
    
    
    
    /**
    * Network
    * 
    */
    
    // role filter
    $('#network_role_filter').change(function()
    {
        document.location.href = $('#network_role_filter option:selected').val();
    });
    
    // user info details
    $('#myNetCont span.restore, #myNetCont span.maximize').click(function()
    {
        var control = $(this);
        
        control.parent().parent().parent().slideUp('slow', function()
        {
            switch(control.attr('class')) 
            {
                case 'maximize' : 
                    var container_class_name = 'myNet_smallbox';
                    var control_class_name = 'restore';
                    var user_details_display = 'none';
                    
                    var image_method = 'prev';
                    break;
                
                case 'restore' : 
                    var container_class_name = 'myNet_bigbox';
                    var control_class_name = 'maximize';
                    var user_details_display = 'inline';
                    
                    var image_method = 'next';
                    break;
                
                default: alert('Unkonwn action');
            }
            
            control.attr('class', control_class_name);
            $(this).attr('class', container_class_name);
            $(this).find('img.visible').attr('class', 'hidden')[image_method]()
                .attr('class', 'visible');
            $(this).find('#user_links').css('display', user_details_display);
            $(this).find('#user_info_details .grayfont').css('display', user_details_display);
            
            $(this).slideDown();
        });
    });
    
    
    /**
    * Profile reception location followes ceremony location
    * 
    */
    
    // copy data from ceremony items to receprion
    $('input[name=is_location_same]').click(function()
    {
        $('.ceremony').each(function(){
            var opposite = $('input[name=' + 
                $(this).attr('name').replace('ceremony', 'reception') + ']');
            opposite.val($(this).val());
        });
    });
    
    // synchronize ceremony and receprion sections
    $('.reception, .ceremony').keyup(function()
    {
        var findstring, newstring;
        
        $.each($(this).attr('class').split(' '), function()
        {
            if ('ceremony' == this) {
                findstring = this;
                newstring = 'reception';
            }
            if ('reception' == this) {
                findstring = this;
                newstring = 'ceremony';
            }
        });
        
        var opposite = $('input[name=' + 
            $(this).attr('name').replace(findstring, newstring) + ']');
        
        if ($(this).val() != opposite.val()) {
            $('input[name=is_location_same]').attr('checked', false);
        }
    });
    
    // "Allow users to find me via search" checkbox
    $('form[name=privacy_settings] input[name=allow_to_find_me]').click(function()
    {
        $(this).val($(this).attr('checked') ? 1 : 0);
    });
    
    
    /**
    * Sign up
    * 
    */
    function date_control() 
    {
        var wedding_date_m = $('#sign_up select[name=wedding_date_m]');
        var wedding_date_d = $('#sign_up select[name=wedding_date_d]');
        var wedding_date_y = $('#sign_up select[name=wedding_date_y]');
        
        if ($('#sign_up input[name=no_special_day_yet]').is(':checked') ||
            $('#sign_up input[name=not_getting_married]').is(':checked')) 
        {
            wedding_date_m.attr('disabled', true);
            wedding_date_d.attr('disabled', true);
            wedding_date_y.attr('disabled', true);
        } else {
            wedding_date_m.attr('disabled', false);
            wedding_date_d.attr('disabled', false);
            wedding_date_y.attr('disabled', false);
        }
    }
    date_control();
    $('#sign_up input[name=no_special_day_yet], \
    #sign_up input[name=not_getting_married]').click(function()
    {
        date_control();
    });
    $('#sign_up #no_special_day_yet, \
        #sign_up #not_getting_married').click(function()
    {
        $(this).val($(this).attr('checked') ? 1 : 0);
    });
    
    
    /**
    * Public categories depending on the privacy setting
    * 
    */
    $('#mywedding_video_upload select[name=privacy]').change(function()
    {
        var W_PUBLIC = 1;
        var current_privacy = $('option:selected', this).val();
        var category_select_row = $('select[name=category_id]').parents('tr');
        
        current_privacy == W_PUBLIC 
            ? category_select_row.show()
            : category_select_row.hide();
    }).change();
    
    
    /**
    * Remove music songs
    * 
    */
    $('.music_uplist_cont li.remove a, \
        #photogal_subpage ul#actions li.remove a')
    .click(function()
    {
        if (confirm('Are you sure you want to delete this song?')) {
            document.location($(this).attr('href'));
        }
        return false;
    });
    
    /**
    * Decline requests
    * 
    */
    $('a.decline_request').click(function(e)
    {
        if (confirm('Are you sure you want to decline current request?')) {
            document.location($(this).attr('href'));
        }
        
        return false;
    });
    
}); 

/**
* Rating stars
* 
*/
$.extend($.fn.rating, { options: 
{
    required: true, 
    callback: function(value, link)
    {
        var target = $(this).parent();
        var link = target.find('.rating_link').val()
        
        $.post(link, {rating: value},
            function(response)
            {
                $.getScript('js/jquery/jquery.MetaData.js');
                $.getScript('js/jquery/jquery.rating.pack.js');
                target.html(response);
            }, 
        'html');
    }
}});


/**
* Video progress bar
* 
*/
// uses ajax to poll the uploadprogress.php page with the id
// deserializes the json string, and computes the percentage (integer)
// update the jQuery progress bar
// sets a timer for the next poll in 750ms
function showUpload() 
{
    var progress_key = document.getElementById('progress_key').value;
    $.get('video/file-upload-status.html?id=' + progress_key, function(data) {
        if (!data)
            return;
 
        var response;
        eval ("response = " + data);
 
        if (!response)
            return;
 
        var percentage = Math.floor(100 * parseInt(response['bytes_uploaded']) / parseInt(response['bytes_total']));
        $("#uploadprogressbar").progressBar(percentage);
 
    });
    setTimeout("showUpload()", 1500);
}

// fades in the progress bar and starts polling the upload progress after 1.5seconds
function beginUpload() 
{
    if ('development' != APPLICATION_ENVIRONMENT) {
        $("#uploadprogressbar").fadeIn();
        setTimeout("showUpload()", 1500);
    }
}

