/*jslint browser: true, white: false, onevar: false */
/*global jQuery,$,window,net */
jQuery(function(jq) {
    // Handle hiding/showing maintainers
    /* #463 - commented out until this bug is fixed
    jq('#maintainers').truncate( 50, {
        chars: /\s/,
        trail: [ " <a href='#' class='truncate_show'>&#187;</a>", " <a href='#' class='truncate_hide'>&#171;</a>" ]
    });
    */

    // Handle hiding/showing maintainers if more than five
    var moreMaintainers = document.getElementById('moreMaintainers');
    if (moreMaintainers) {
        // #337 - IE isn't properly handling jQuery's toggle() method on the
        // span. Firefox knows that it should be display: inline, but not IE.
        // So we'll just manually toggle the CSS and call it good.
        jq(moreMaintainers).css('display','none');
        var moreLink = jq('<a href="#">&#8230;</a>').click(function(e) {
            e.preventDefault();
            jq(this).remove();
            jq(moreMaintainers).css('display','inline');
        });
        jq('#maintainers').append(moreLink);
    }
        
    // Handle hiding/showing reviews
    jq('.review-txt').truncate( 250, {
        trail: [ " (<a href='#' class='truncate_show'>more</a>&#8230;)", " (&#8230;<a href='#' class='truncate_hide'>less</a>)" ]
    });
    
    // Handle hiding/showing the descriptions of related projects
    jq('#related p').truncate( 100, {
        chars: /\s/,
        trail: [ " <a href='#' class='truncate_show'>&#8230;</a>", " <a href='#' class='truncate_hide'>&#171;</a>" ]
    });
    
    // Generic method used by any box that has a filter
    var filter_change = function(e) {
        var id = e.data.id,
            url = e.data.url,
            selector = e.data.selector,
            params = e.data.params,
            selected = jq(id + ' form select option:selected').val(),
            list = jq(id + ' .list'),
            indicator = jq(new Image()),
            reveal = function() {
                indicator.fadeOut(function() {
                    indicator.remove();
                    list.slideDown('fast');
                });
            };
        
        indicator.load(function() {
            jq(this).hide();
            list.after(this);
            jq(this).fadeIn();
        }).attr('src', net.sf.cdn_url + '/img/indicator.gif').css("padding-top","0.8333em");
        
        list.slideUp('fast', function() {
            var suffix = [
                    '?',
                    selected !== 'everything' ? 'filter=' + selected : '',
                    params,
                    selector ? ' ' + selector : ''
                ],
                url_suffix = suffix.join(''); 
            list.load(url + url_suffix, reveal);
        });
    };
    
    // Setup the feed filter
    jq('#feed-filter input[type="submit"]').remove();
    jq('#feed-filter select').bind('change', { id: '#feed', url: 'feed' }, filter_change);
    
    // Setup the review filter
    jq('#review-filter input[type="submit"]').remove();
    jq('#review-filter select').bind('change', { id: '#reviews-n-ratings', url: 'project_reviews', params: '&limit=3'}, filter_change);
   
    // Load the review form, if required
    if (jq('#review-form').length) {
        jq('#review-form').reviewform();
    }
    
    // Setup screenshots modal
    var bf_display = ( $('#screenshots li').length > 5 ) ? true : false ;
    jq('#screenshots .ad-gallery').adGallery({
        loader_image: net.sf.cdn_url + '/img/gallery/loader.gif',
        slideshow: { enable: false },
        cycle: false,
        display_back_and_forward: bf_display
    });

    // Auto-open dialog if the URL contains the hash for a particular screenshot
    jq('#screenshots').dialog({
        autoOpen: (window.location.hash && window.location.hash.indexOf('#ad-image') === 0),
        bgiframe: true,
        modal: true,
        width: 634
    });

    // Click to open screenshots modal
    jq('div.b-proj__picrel a.link-more').click(function(e){
        e.preventDefault();
        jq('#screenshots').dialog('open').parent().css('left', (($(window).width() - $('#doc4').width()) / 2) );
    });
    
    // Submit review ratings via AJAX
    function rate_review_fn(e) {
        e.preventDefault();
        
        var form = jq(this).parent(),
            data = form.serialize(),
            meta = form.metadata(),
            indicator = jq(new Image());

        // Per http://dev.jquery.com/ticket/3523, we need to add in the submit that was clicked
        data += "&" + jq(this).attr('name') + "=" + jq(this).val();

        indicator.load(function() {
            jq(this).hide();
            form.hide();
            form.after(this);
            jq(this).fadeIn();
        }).attr('src', net.sf.cdn_url + '/img/indicator.gif').css({'margin-left':'8px', 'display':'inline'});
        
        jq.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: data,
            dataType: 'json',
            success: function(response, textStatus) {
                var rating = response.rating ? 'helpful' : 'unhelpful';
                indicator.stop().fadeOut(function() {
                    var container = jq('.helpfulness', form.parent());
                    if (container.length) {
                        container.html(rating);
                        container.effect('highlight', {}, 3000);
                    } else {
                        form.before('<br/>(Current rating: <span class="helpfulness">' + rating + '</span>)');
                        container.effect('highlight', {}, 3000);
                    }
                    form.show();
                    indicator.remove();
                });
            },
            error: function(xhr, textStatus, errorThrown) {
                jq('#messages').notify({status: 'error', message: "An error occurred while posting your rating of this review."});
                indicator.stop().fadeOut(function() {
                    form.show();
                    indicator.remove();
                });
            }
        });
    }
    // SFPY-366: be sure the review click handler is in place for the 
    // current and any future reviews (that is, reviews loaded up
    // via Ajax).
    jq('form.rate-review input[type=submit]').live('click', rate_review_fn);

    // Submit review spam via AJAX
    function moderate_review_fn(e) {
        e.preventDefault();
        
        var form = jq(this).parent(),
            data = form.serialize(),
            meta = form.metadata(),
            indicator = jq(new Image()),
            self = this;

        // Per http://dev.jquery.com/ticket/3523, we need to add in the submit that was clicked
        data += "&" + jq(self).attr('name') + "=" + jq(self).val();

        indicator.load(function() {
            jq(this).hide();
            form.hide();
            form.after(this);
            jq(this).fadeIn();
        }).attr('src', net.sf.cdn_url + '/img/indicator.gif').css({'margin-left':'8px', 'display':'inline'});
        
        jq.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: data,
            dataType: 'json',
            success: function(response, textStatus) {
                var new_action = (response.action === 'show') ? 'hide' : 'show',
                    new_value = (new_action === 'show') ? 'Not Spam' : 'Flag as Spam';
                indicator.stop().fadeOut(function() {
                    var container = jq(self).parents('.reviewed'),
                        review_txt = jq('.review-txt', container);
                    review_txt.toggleClass('spam');
                    jq(self).attr('name', new_action).attr('value', new_value);
                    container.effect('highlight', {}, 3000);
                    form.show();
                    indicator.remove();
                });
            },
            error: function(xhr, textStatus, errorThrown) {
                jq('#messages').notify({status: 'error', message: "An error occurred while moderating this review."});
                indicator.stop().fadeOut(function() {
                    form.show();
                    indicator.remove();
                });
            }
        });
    }
    // SFPY-366: be sure the review click handler is in place for the 
    // current and any future reviews (that is, reviews loaded up
    // via Ajax).
    jq('form.moderate-review input[type=submit]').live('click', moderate_review_fn);

    // Load up the next set of reviews via Ajax
    jq('#more-reviews').click(function(e) {
        e.preventDefault();
        
        var button = jq(this),
            indicator = jq(new Image()),
            metadata = button.metadata();

        if (!net.sf.review_offset) {
            net.sf.review_offset = parseInt(metadata.offset, 10) + parseInt(metadata.limit, 10);
        }
        if (!net.sf.review_limit) {
            net.sf.review_limit = parseInt(metadata.limit, 10);
        }

        indicator.load(function() {
            jq(this).hide();
            button.after(this);
            jq(this).fadeIn();
        }).attr('src', net.sf.cdn_url + '/img/indicator.gif').css({'margin-left':'8px', 'display':'inline'});
        
        jq.ajax({
            type: 'GET',
            url: metadata.url,
            data: { offset: net.sf.review_offset },
            dataType: 'html',
            success: function(response, textStatus) {
                indicator.stop().fadeOut(function() {
                    var container = jq('.list', button.parent());
                    container.append(response);
                    indicator.remove();
                });
                net.sf.review_offset += net.sf.review_limit;
                if (parseInt(metadata.count, 10) < net.sf.review_offset) {
                    button.fadeOut(function() {
                       jq(this).remove();
                    });
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                jq('#messages').notify({status: 'error', message: "An error occurred while loading reviews."});
                indicator.stop().fadeOut(function() {
                    indicator.remove();
                });
            }
        });
    });

    // Hide/show project details
    function hide_details_fn(e) {
        e.preventDefault();
        jq(this).text('Show project details');
        jq('#project-details').hide();
        jq.cookie('project_details', 'hide');
    }
    function show_details_fn(e) {
        e.preventDefault();
        jq(this).text('Hide project details');
        jq('#project-details').show();
        jq.cookie('project_details', 'show');
    }
    if (jq.cookie('project_details') === 'show') {
        jq('#project-details').after('<div id="project-reveal"><a href="#more">Hide project details</a></div>');
        jq('#project-reveal a').toggle(hide_details_fn, show_details_fn);
    } else if (jq.cookie('project_details') === 'hide') {
        jq('#project-details').hide().after('<div id="project-reveal"><a href="#more">Show project details</a></div>');
        jq('#project-reveal a').toggle(show_details_fn, hide_details_fn);
    } else if (net.sf.is_admin) {
        jq('#project-details').after('<div id="project-reveal"><a href="#more">Hide project details</a></div>');
        jq('#project-reveal a').toggle(hide_details_fn, show_details_fn);
    } else {
        jq('#project-details').hide().after('<div id="project-reveal"><a href="#more">Show project details</a></div>');
        jq('#project-reveal a').toggle(show_details_fn, hide_details_fn);
    }

    // Initialize editing of features and icons
    if (net.sf.is_admin) {
        if (jq('ul.features').length) {
            jq('#edit-features').remove();
        } else {
            jq('#edit-features').replaceWith('<ul class="features"></ul>');
        }
        jq('.features').listedit({
            action: 'update',
            add_value: "Add a new feature",
            html: [ net.sf.antixsrf ]
        });
        var icon_form = jq('#icon-dialog form');
        icon_form.validate({
            rules: {
                icon: {
                    required: true,
                    accept: "png|gif|jpeg|jpg"
                }
            }
        });
        jq('#icon-dialog').dialog({
            bgiframe: true,
            autoOpen: false,
            modal: true,
            width: 300,
            buttons: {
                'Save icon': function() {
                    icon_form.submit();
                },
                'Cancel': function() {
                    $(this).dialog('close');
                }
            }
        });
        $('#pd-icon .edit-button').click(function(e) {
            e.preventDefault();
            $('#icon-dialog').dialog('open');
        });
    }

    // Color the background of an editable chunk if the user is hovering over the edit link
    net.sf.editable_on = function() {
        if (jq(this).hasClass('editable')) {
            jq(this).css('background-color','#E8F5FD');
        } else {
            jq(this).parents('.editable').css('background-color','#E8F5FD');
        }
    };
    net.sf.editable_off = function() {
        if (jq(this).hasClass('editable')) {
            jq(this).css('background-color','transparent');
        } else {
            jq(this).parents('.editable').css('background-color','transparent');
        }
    };
    jq('.edit-button').hover(net.sf.editable_on, net.sf.editable_off);
    
    // Load up the full project nav if logged in, per SFPY-223
    if (jq('#nav-project').children().length === 0) {
        var nav = jq('#nav-project');
        nav.load(nav.metadata().url, function() {
            jq('#nav-project ul.b-hornav > li:last-child').addClass('last');
            jq('#nav-project ul.b-hornav > li').each(function() {
                jq('li[class!=disabled]', this).eq(0).addClass('first');
            });
            jq('#nav-project ul.b-hornav').droppy({speed: 0, delay: 0});
            jq('#menu_consume_' + document.body.id).addClass('selected');
        });
    }
});

