﻿(function($) {
//Comment functionality
$.mmsComments = {
    services: {
        comments: 'comments.aspx?set=', 
        counts: 'counts.aspx?set='
    },
    startDate: new Date('09/24/2008'),
    endDate: new Date('10/15/2008')
};


$.mmsComments.pages = {
    header: '<div class="commentsHeader">' +
        '<img alt="Comments and Responses" src="img/commentsAndResponses.png" />' +
        '<a id="toggleView" href="#"></a></div>',
    calendar: '<div class="calendarNav"></div>',
    commentNav:
        '<p class="commentNav"><a id="previousComment"></a>' + 
        '<span id="commentNum"></span><a id="nextComment"></a></p>',
    commentList: '<div id="commentList"></div>',
    comment: '<div class="comment"><div class="inner"><div class="info"><p></p><p></p><p></p><p></p><p></p></div>' +
        '<div class="content"></div></div></div>'
};


$.fn.mmsComments = function(setName) {
    $.mmsComments.services.comments += setName + '&';
    $.mmsComments.services.counts += setName + '&';    

    $.ajax({ url: $.mmsComments.services.counts + 'field=date', 
        success: $.mmsComments.initData, dataType: 'jsonp' });
    
    return this;
};


$.mmsComments.initData = function(data) {
    $.mmsComments.comments = [];
    $.each(data, function(key, value) {
        for(var i = 0; i < value; i++)
            $.mmsComments.comments.push({ date: key });
    });

    $.mmsComments.comments.reverse();

    $.mmsComments.showComment(0);
    $('.preview').click($.mmsComments.previewComment);
    $('img.edit').click($.mmsComments.editComment);
    $('#country').change($.mmsComments.checkCountry);
    $.mmsComments.checkCountry();
    
    //Limit text fields to 100 characters
    $('.contribute input[type=text]').keyup(function() {
        this.value = this.value.substring(0, 100);
        return true; 
    });
};


$.mmsComments.checkCountry = function() {
    $('#stateList').append($('#state option'));
    $('#state').empty().attr('disabled', 'disabled');

    if($('#country').val() == 'United States')
        $('#state').append($('#stateList .us')).attr('disabled', '');
    else if($('#country').val() == 'Canada')
        $('#state').append($('#stateList .canada')).attr('disabled', '');
        
    if($('#state').length) $('#state').get(0).selectedIndex = 0;
};


$.mmsComments.editComment = function() {
    $('.contributeForm, .whoIsContributing').show();
    $('.contribute').removeClass('contributeWide');    
    $('#previewComment').hide();
    $('div.submit p.error').hide();
};


$.mmsComments.previewComment = function() {
    var data = $.mmsComments.getFormData();
    var errors = $.mmsComments.validateForm(data);
    
    $('.errorMessage, .errors').hide();
    
    if(errors.length == 0) { ntptEventTag('ev=PREPreviewComment');
        $('.contributeForm, .whoIsContributing').hide();
        $('.contribute').addClass('contributeWide');

        data.date = $.dateFormat(new Date(), "mm/dd/yyyy");
        var comment = $.mmsComments.renderComment(data);
        
        $('#previewComment .captchaFields img').attr('src', 'captcha.aspx?id=' + Math.random());
        $('#previewComment .info').empty().html(comment.find('.info').html());
        $('#previewComment .content').empty().html(comment.find('.content').html());
        $('#previewComment').show();
        
        delete data.date;
        $('#previewComment img.submit').unbind('click').click(function() {
            $('.contributeForm .errors').html('');
            $.mmsComments.submitComment(data);
        });
    }
    else {
        var errorsList = $('.contributeForm .errors').html('');
        $('.errorMessage, .errors').show();
        $.each(errors, function(i, n) { 
            errorsList.append($('<li></li>').html(n)); 
        });
    }
};


$.mmsComments.submitComment = function(data) {
    if($('div.submit input[name=captcha]').val() == '') {
        $('div.submit p.error').show();
    }
    else {    

        if($('#terms').attr('checked')) {        
            data['Editorial Comments'] = '';
            data['Better than Average'] = '';
            data['Best of Day'] = '';
            data['captcha'] = $('div.submit input[name=captcha]').val();
            delete data['Retype E-mail'];
            $.ajax({ type: 'POST', url: $.mmsComments.services.comments + '_method=PUT',
                data: data, dataType: 'jsonp', success: $.mmsComments.submitted  });
        }
        else {
            $('div.submit span').css('backgroundColor', '#ff0').animate({
                'backgroundColor': '#fbfcee'
            }, 1000);
        }
    }
};


$.mmsComments.submitted = function(data) {
    if(data.error) {    
        $('#previewComment .captchaFields img').attr('src', 'captcha.aspx?id=' + Math.random());
        $('div.submit input[name=captcha]').val('');
        $('div.submit p.error').show();
    }
    else { ntptEventTag('ev=PRESubmitComment');
        $('.contribute').removeClass('contributeWide');
        $('#previewComment').css('display', 'none');
        $('.contributeForm, .whoIsContributing').css('display', 'block');
        $('.contributeForm').replaceWith('<p class="thanks">Thank you for submitting your comment, which will be reviewed by the editors. We will post comments through October&#160;15,&#160;2008.</p>');
    }
};


$.mmsComments.getFormData = function() {
    var fields = $('#contributeForm *[name]');
    var data = {};
    $.each(fields, function() {
        data[this.name] = $(this).attr('disabled') ? '' : $(this).val();
    });
    return data;
};


$.mmsComments.validateForm = function(data) {
    var errors = [];
    
    if(data['First Name'] == '')
        errors.push('You must enter your first name');
    if(data['Last Name'] == '')
        errors.push('You must enter your last name');
    
    var emailRegex = /^([\w\d_\.\-])+\@(([\w\d\-])+\.)+([\w\d]{2,4})+$/;
    if(data['E-mail'] == '')
        errors.push('You must enter your email');
    else if(!emailRegex.test(data['E-mail']))
        errors.push('You must enter a valid email');
    else if(data['E-mail'] != data['Retype E-mail'])
        errors.push('The email fields do not match');
    
    if(data['Position'] == '')
        errors.push('You must select your position');
    if(data['City'] == '')
        errors.push('You must enter your city'); 
    
    if(data['Country'] == '')
        errors.push('You must select your country'); 
    
    var stateRequired =
        $('#country').val() == 'United States' ||
        $('#country').val() == 'Canada';
    if(stateRequired && data['State / Province'] == '')
        errors.push('You must select your state'); 
    
    if(data['Title'] == '')
        errors.push('You must enter a subject');
    
    if(data['Comment'] == '')
        errors.push('You must enter comment text');
    
    var numWords = data['Comment'].split(' ').length;
    var numChars = data['Comment'].length;
    
    if(numWords > 250)
        errors.push('Please limit your comment to 250 words <br/><em>(you have currently entered ' + numWords + ' words)</em>');    
    else if(numChars > 8000)
        errors.push('Please limit your comment to 8000 characters <br/><em>(you have currently entered ' + numChars + ' characters)</em>');

    return errors;
};


$.mmsComments.showComment = function(position) {
    $.mmsComments.getComment(position, function(comment) {
        var numComments = $.mmsComments.comments.length;
        var header = $.mmsComments.renderShortHeader(comment.date, numComments);
        var commentNav = $.mmsComments.renderCommentNav(position, numComments);
        var commentList = $($.mmsComments.pages.commentList);
        var singleComment = $.mmsComments.renderComment(comment);

        commentList.append(singleComment);
        $('#comments').empty().append(header).append(commentNav).append(commentList);
    });
};


$.mmsComments.showCommentsByDate = function(date) {
    var first = -1;
    var filtered = $.grep($.mmsComments.comments, function(n, i) {
        if(new Date(n.date).getTime() == new Date(date).getTime()) {
            first = first == -1 ? i : first; 
            return true;
        }
    });

    $.mmsComments.getComment(first, function(comment) {
        var numComments = $.mmsComments.comments.length;
        var header = $.mmsComments.renderLongHeader(first);
        var topCalendar = $.mmsComments.renderCalendar(date).addClass('calendarNavTop');
        var bottomCalendar = $.mmsComments.renderCalendar(date).addClass('calendarNavBottom');
        var commentList = $($.mmsComments.pages.commentList);
        
        $.mmsEachAsync(filtered, function() {
            commentList.append($.mmsComments.renderComment(this));
        }, null, 5, 25, function() {
            commentList.find('.comment:last').addClass('lastComment');
        });
        
        $('#comments').empty().append(header).append(topCalendar).append(commentList).append(bottomCalendar);
    });
};


$.mmsComments.renderShortHeader = function(date, numComments) {
    var header = $($.mmsComments.pages.header);
    var text = 'View All (' + numComments + ')';
    header.find('#toggleView').text(text).click(function() { ntptEventTag('ev=PREViewCommentsByDay');
        $.mmsComments.showCommentsByDate(date);
        return false;
    }); 
    return header;
};


$.mmsComments.renderLongHeader = function(position) {
    var header = $($.mmsComments.pages.header);
    header.find('#toggleView').text('Short View').click(function() { ntptEventTag('ev=PREViewComments');
        $.mmsComments.showComment(position);
        return false;
    }); 
    return header;
};


$.mmsComments.renderCalendar = function(date) {
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var calendar = $($.mmsComments.pages.calendar);
    
    var commentDates = [];
    $.each($.mmsComments.comments, 
        function(i, n) { commentDates.push(new Date(n.date).getTime()); });
    
    commentDates = $.unique(commentDates);
    
    var current = new Date($.mmsComments.startDate);
    while(current <= $.mmsComments.endDate) {
        if(current.getMonth() != month) {
            var month = current.getMonth();
            var list = $('<ul></ul>');
            var monthName = $('<p></p>').text(months[month]);
            calendar.append(monthName).append(list);
        }
 
        var day = $.mmsComments.renderDay(new Date(current));
        if(current.getTime() == new Date(date).getTime())
            day.addClass('selected');
        else if($.inArray(current.getTime(), commentDates) >= 0)
            day.addClass('active').hover(
                function() { $(this).addClass('hover'); },
                function() { $(this).removeClass('hover'); });
        else
            day.unbind('click');
                
        list.append(day);
        current = new Date(current.setDate(current.getDate() + 1));
    }
    
    calendar.find('li:last-child').addClass('last');
    return calendar;
};


$.mmsComments.renderDay = function(current) {
    return $('<li></li>').text(current.getDate()).click(
        function() { $.mmsComments.showCommentsByDate(current); });
};


$.mmsComments.renderComment = function(comment) {
    var singleComment = $($.mmsComments.pages.comment);
    var content = singleComment.find('.content');

    content.append($('<h4></h4>').text(comment["Title"]));
    $.each(comment['Comment'].split('\n'), function(i, n) {
        if(n.length > 0) content.append($('<p></p>').text(n));
    });

    var info = singleComment.find('.info');
    
    if(comment['State / Province'] == '')
        var location = comment['City'] + ', ' + comment['Country'];
    else
        var location = comment['City'] + ', ' + comment['State / Province'];
    
    var items = [
        comment['First Name'] + ' ' + comment['Last Name'],
        location,
        comment['Institution'],
        comment.date
    ];
    
    var infoParas = info.find('p');
    $.each(items, function(i, n) { infoParas.eq(i).text(n); });

    return singleComment;
};


$.mmsComments.renderCommentNav = function(position, numComments) {
    var commentNav = $($.mmsComments.pages.commentNav);
    commentNav.find('span').text((position + 1) + ' of ' + numComments);
    if(position == 0)
        commentNav.find('#previousComment').addClass('previousDisabled');
    else
        commentNav.find('#previousComment').click(function() { ntptEventTag('ev=PREBackwardScrollComments'); 
            $.mmsComments.showComment(position - 1); 
            return false; 
        });    
        
    if(position == numComments - 1)
        commentNav.find('#nextComment').addClass('nextDisabled');
    else
        commentNav.find('#nextComment').click(function() { ntptEventTag('ev=PREForwardScrollComments');
            $.mmsComments.showComment(position + 1); 
            return false; 
        });
            
    return commentNav;
};

$.mmsComments.getComment = function(position, callback) {
    var comment = $.mmsComments.comments[position];
    if(comment) {
        if(comment["Title"])
            callback(comment);
        else {
            $.ajax({ 
                url: $.mmsComments.services.comments + 'date=' + comment.date, 
                success: function(data) {
                    $.mmsComments.mergeComments(comment.date, data); 
                    callback(comment); 
                }, 
                dataType: 'jsonp'
            });
        }
    }
};


$.mmsComments.mergeComments = function(date, data) {
    var mergeIndex = 0;
    
    //Move better than avarage comments to the beginning of the array
    $.each(data.comments, function(i, n) {
        if(n['Better than Average'] == 'true') {
            data.comments.splice(i, 1);
            data.comments.splice(0, 0, n);
        }
    });    
    
    //Move best of day comments to the beginning of the array
    $.each(data.comments, function(i, n) {
        if(n['Best of Day'] == 'true') {
            data.comments.splice(i, 1);
            data.comments.splice(0, 0, n);
        }
    });
    
    $.each($.mmsComments.comments, function(i, n) {
        if($.mmsComments.comments[i].date == date)
            $.extend($.mmsComments.comments[i], data.comments[mergeIndex++]);
    });
};

})(jQuery);