/*global show_error, show_message */

//Various comment/discussion utilities
function display_new_comment(comment) {
    // FIXME: Need consistent escaping scheme for project names in URL
    $('#discussion').load($('#discussion h2').attr('link'));
}

function process_comment(data, success) {
    if (data['errors']) {
        var error_list = '<ul class="error">';
        for (var message in data.errors) {
	    if (data.errors.hasOwnProperty(message)) {
		error_list += '<li>' +message+ ' -- ' + data.errors[message] +'</li>';
	    }
	}
        error_list += '</ul>';
        $("#comment_form").prepend(error_list);
    } 
    else 
    {
        display_new_comment(data[0].fields);
    }
}

function show_reply_form(comment_id, url, reply_to_name, user_name) {
    var comment_reply = $('#' + comment_id);
    var to_add = $(['<div class="response"><p>Reply to ' + reply_to_name + ':</p>',
    '<form id = "comment_form_'+comment_id+'"method="POST" action="#">',
    '<label for="id_name">Comment:</label>',
    '<textarea name="comment" cols="60" rows="10" id="id_comment_' + comment_id + '"/>',
    '<li><input type="submit" value="Submit Comment" /></li>',
    '</ul>', '</form>', '</div>'].join(''));
    to_add.css("display", "none");
    comment_reply.after(to_add);
    to_add.slideDown(function() {
        comment_reply.replaceWith(['<a id="',
        comment_id,'" href="javascript:hide_reply_form(\'',
        comment_id, '\',\'', url, '\',\'', reply_to_name,
        '\')">Stop Replying</a>'].join(''));
        $('#comment_form_'+comment_id +' input').click(function(event) {
            $.post(url, {comment: $('#id_comment_'+comment_id).val(), name: user_name}, process_comment, 'json');
            event.preventDefault();
        });
    });
}

function new_comment() {
    // Clear comment field ASAP - appears to be the most productive 
    // guard against dup submission due to dup clicks
    var comment = $('#id_comment').val();
    $('#id_comment').val('');
    $.post($('#comment_form').attr('action'), {comment: comment, name: $('#id_name').val()}, process_comment, 'json');
    return false;
}

function hide_reply_form(comment_id, url, person_name) {
    var comment_reply = $('#' + comment_id);
    comment_reply.next().slideUp(function (){
        comment_reply.next('.response').remove();
        comment_reply.replaceWith(['<a id="',
        comment_id,'" href="javascript:show_reply_form(\'',
        comment_id, '\',\'', url, '\',\'', person_name,
        '\')">Reply</a>'].join(''));
    });
}

$(document).ready(function() {
	$('.screen').fancybox({ 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'overlayShow': true, 'overlayOpacity': 0.8 });
	$('.focus h4').prepend('<span>&rarr;</span>');
	$('.focus h4').toggle(function(){
		$(this).next('.hide').show();
		$(this).find('span').html('&darr;');
		$(this).addClass('tog');
	},
	function(){
		$(this).next('.hide').hide();
		$(this).find('span').html('&rarr;');
                $(this).removeClass('tog');
	});



//Show comments
$('#discussion h2 a').click(function(event) {
    $('#discussion').load($('#discussion h2 a').attr('href'));
    event.preventDefault();
    }
);

//screenshot moving
$('.media a.screen:gt(0)').hide();
$('.media a.screen:eq(0)').prependTo('#description').css('float','right').css('margin','0 1em 3em 3em').css('display','block');
$('.media a.screen:eq(0)').show().prependTo('#bene').css('float','left').css('margin','0 2em 2em 0').parent('#bene').find('.frame').css('float','right').css('width','27em');

$('#description br').next('br').css('margin-bottom','.5em');

$('.software a.screen').each(function() {
        var subtxt = $(this).attr('title');
        $(this).append('<span class="subtext">'+subtxt+'</span>');
});

    $('a#more_reviews').toggle(
        function() {
            $('#reviews_shortlist .review').show();
            $('a#more_reviews').text('Fewer Reviews');
        },
        function() {
            $('#reviews_shortlist .review').not(':first').hide();
            $('a#more_reviews').text('More Reviews');
        }
    );

    $('#review_cancel').click(function() {
        $('#review_input').hide();
    });
    $('#review_input form').submit(function() {
        if ($.trim($('textarea', this).val()) === '') {
            show_error($(this), "You need to type something if you want to post a review.  If not, just click 'Skip' to close it");
            return false;
        }
    });
    var review_input = function($emotion) {
        $('#review_emotion_text').text($('h1').text() + ' is ' + $emotion.text().toLowerCase());
        $('#review_input').show();
        $('#review_input textarea').focus();
    };
    
    $('.emotion').click(function() {
        var $this = $(this);
        var emotion;
        if ($this.hasClass('love')) {
            emotion = 'love';
        } else if ($this.hasClass('hate')){
            emotion = 'hate';
        }
        var url = '/software/tag/' + window.project_id;
        if ($this.hasClass('selected')) {
            if ($this.is('.has_review') == 1) {
                if (!confirm('If you deselect your rating, your review will be deleted also.  Do you want to do that?')) {
                    return false;
                } else {
                    $this.removeClass('has_review');
                }
            }
            url += '/remove/emotion';
        } else {
            var $other_with_review = $('.emotion.selected.has_review');
            if ($other_with_review.length == 1) {
                if (!confirm('If you change your rating, your previous review will be deleted.  Do you want to do that?')) {
                    return false;
                } else {
                    $other_with_review.removeClass('has_review');
                }
            }
            url += '/add/emotion';
        }
        $.ajax({
            type: 'POST',
            url: url,
            data: {value: emotion},
            error: function(xhr, textStatus, errorThrown) {
                show_error($this, "Error saving.<br/>" + textStatus + " " + xhr.statusText);
            },
            success: function(data, textStatus) {
                //show_message($this, 'Successfully saved.');
                // if selecting this, unselect all others
                if (!$this.hasClass('selected')) {
                    $('.emotion.selected').removeClass('selected');
                }
                $this.toggleClass('selected');
                $('#review_input').hide();
                if ($this.hasClass('selected')) {
                    review_input($this);
                }
            }
        });
        return false;
    });
});
