var squish;
var saving = false;

$(document).ready(function(){
    soundManager.url = GLOBALS.contextPath + '/js/soundmanager/swf/';
    soundManager.onload = function() {
        squish = soundManager.createSound({
            id: 'preloadSound',
            url: GLOBALS.contextPath + '/sounds/squish.mp3'
        });

        squish.load(); // load the sound ahead of time
    }

    soundManager.onerror = function() {
    }

    $('#saveBlurb').click(function(){
        if (GLOBALS.uid < 0) {
            window.location = GLOBALS.loginUrl + '?subjectId=' + GLOBALS.sid + '&next=viewSubject';
            return;
        }
        if(!saving){
            saving = true;
            createBlurb();
        }
        return false;
    });

    $('#blurbTags').bind("keydown", function(e){
    if(!(e.keyCode in keyCodesWithNoAffect)){
        var forward = !(e.keyCode == 46 || e.keyCode == 8);
        var sizer = $("#sizer");
        var jqTarget = $(e.target);
        var id = jqTarget.attr("id");
        var newWidth = 0;

        if(forward){
            newWidth = sizer.html((jqTarget.val() + String.fromCharCode(e.keyCode)).replace(/\s/g, ".")).width() + 5;
        } else {
            var selectedText = "";

            if (document.selection) {
                selectedText = document.selection.createRange().text
            } else if (jqTarget[0].selectionStart !== undefined && jqTarget[0].selectionStart !== undefined) {
                selectedText = jqTarget.val().substring(jqTarget[0].selectionStart, jqTarget[0].selectionEnd);
            }

            newWidth = sizer.html(jqTarget.val().replace(selectedText, "").replace(/\s/g, ".")).width();
        }

        newWidth +=50;

        jqTarget.width(newWidth >= 50 ? newWidth : 50);
    }
});


});

function createBlurb(){
    if(!document.getElementById('blurbText').value)
        return;

    var action = GLOBALS.contextPath+'/ajax/createBlurb?subjectId=' + GLOBALS.sid + '&content=' + encodeURIComponent($('#blurbText').val()) + '&tags=' + encodeURIComponent($('#blurbTags').val());

    $.ajax({
        type: 'POST', dataType: 'json', cache: false, url: action, data: [],
        success: function(data, textStatus) {
          saving = false;
          if(!data.error){
            //window.location.href = window.location.href;
            squish.play();
            lessBlurbsAbout();
            loadBlurbsAbout();
            document.getElementById('blurbText').value = '';
            document.getElementById('blurbText').focus();
            document.getElementById('blurbText').blur();
            document.getElementById('blurbTags').value = '';
          }
          else {
            if (data.errors['_GLOBAL_'] && data.errors['_GLOBAL_'].length) {
              formatErrors(data.errors['_GLOBAL_']);
            }
            else {
              formatErrors(['an unknown error occurred']);
            }
          }
        },
        error: function(ajaxRequest, textStatus, errorThrown) {
          formatErrors(['an internal error occurred (' + ajaxRequest.status + ' - ' +  ajaxRequest.statusText + ')']);
        }
      });
}

var blurbsAboutExpanded = false;
var blurbsByExpanded = false;

function loadBlurbsAbout(){
    var action = GLOBALS.contextPath + '/ajax/loadBlurbs?aboutSubject&subjectId=' + GLOBALS['sid'] + '&sortAscending=false&sortField=BLURB_DATE&pageSize=10000&formatted=true';

    $.ajax({
        type: 'POST', dataType: 'json', cache: false, url: action, data: [],
        success: function(data, textStatus) {
          if(!data.error){
            //window.location.href = window.location.href;
            displayBlurbsAbout(data.blurbs);
          }
          else {
            if (data.errors['_GLOBAL_'] && data.errors['_GLOBAL_'].length) {
              formatErrors(data.errors['_GLOBAL_']);
            }
            else {
              formatErrors(['an unknown error occurred']);
            }
          }
        },
        error: function(ajaxRequest, textStatus, errorThrown) {
          formatErrors(['an internal error occurred (' + ajaxRequest.status + ' - ' +  ajaxRequest.statusText + ')']);
        }
      });
}

function loadBlurbsBy(){
    var action = GLOBALS.contextPath + '/ajax/loadBlurbs?bySubject&subjectId=' + GLOBALS['sid'] + '&sortAscending=false&sortField=BLURB_DATE&pageSize=10000&formatted=true';
    $.ajax({
        type: 'POST', dataType: 'json', cache: false, url: action, data: [],
        success: function(data, textStatus) {
          if(!data.error){
            //window.location.href = window.location.href;
            displayBlurbsBy(data.blurbs);
          }
          else {
            if (data.errors['_GLOBAL_'] && data.errors['_GLOBAL_'].length) {
              formatErrors(data.errors['_GLOBAL_']);
            }
            else {
              formatErrors(['an unknown error occurred']);
            }
          }
        },
        error: function(ajaxRequest, textStatus, errorThrown) {
          formatErrors(['an internal error occurred (' + ajaxRequest.status + ' - ' +  ajaxRequest.statusText + ')']);
        }
      });

    return;
}

function displayBlurbsAbout(blurbs){
    var blurbsHTML = '';
    $(blurbs).each(function(blurbIndex){
        var hidden = blurbIndex>2;
            blurbsHTML +=  '<div class="box1" id="blurbAbout-' + this.id + '"' + (hidden? ' style="display:none;padding-bottom:8px;"' : ' style="padding-bottom:8px;"') + '>' +
                        '<a href="' + GLOBALS.contextPath + '/viewSubject/' + this.createdBy + '"><span class="peopleLink">' + this.creatorName + '</span></a>' +
                        '<span style="border-width: 0.5px;"> <em>' + this.description + '</em><br/><span>"</span><span>' + this.content + '</span><span>"</span>' +
                       '</div>';
    });

    if(blurbs.length>3){
        $('#moreBlurbsAbout').show();

        //var scrollingBlurbsAbout = new VerticalScrollingArea('blurbsAbout_outerFrame', 'blurbsAboutPlaceholder', 'blurbsAboutScrollUp', 'blurbsAboutScrollDown');

        var scrollUpInterval;
        var scrollDownInterval;

        $('#blurbsAboutScrollUp').mouseover(function(){
            scrollUpInterval = window.setInterval(function(){
                document.getElementById('blurbsAboutPlaceholder').scrollTop-=10;
            }, 10);
        });

        $('#blurbsAboutScrollUp').mouseout(function(){
            window.clearInterval(scrollUpInterval);
        });

        $('#blurbsAboutScrollDown').mouseover(function(){
            scrollDownInterval = window.setInterval(function(){
                document.getElementById('blurbsAboutPlaceholder').scrollTop+=10;
            }, 10);
        });

        $('#blurbsAboutScrollDown').mouseout(function(){
            window.clearInterval(scrollDownInterval);
        });
    }

    $('#moreBlurbsAbout').click(function(){
        $('#blurbsAboutPlaceholder div.box1').each(function(i, item){
            $(item).show();
        });
        $('#lessBlurbsAbout').show();
        $('#moreBlurbsAbout').hide();
        $('#blurbsAboutScrollButtons').show();

        if($('#blurbsAboutPlaceholder').height() > 450)
            $('#blurbsAboutPlaceholder').css('height', '450px');
    });

    $('#lessBlurbsAbout').click(function(){
        lessBlurbsAbout();
    });

    document.getElementById('blurbsAboutPlaceholder').innerHTML = blurbsHTML;

    $(blurbs).each(function(blurbIndex) {
        $('#blurbAbout-' + this.id).append(
            comments.include('blurbAbout-' + this.id, 'about', 'blurb', this.id)
        );
    });
}

function displayBlurbsBy(blurbs){
    var blurbsHTML = '';
        $(blurbs).each(function(blurbIndex){
            var hidden = blurbIndex>0;
                blurbsHTML +=  '<div class="box1" id="blurbBy-' + this.id + '"' + (hidden? ' style="display:none;padding-bottom:8px;"' : ' style="padding-bottom:8px;"') + '>' +
                            'on <a href="' + GLOBALS.contextPath + '/viewSubject/' + this.subjectId + '"><span class="peopleLink">' + this.subjectName + '</span></a>' +
                            '<span style="border-width: 0.5px;"> <em>' + this.description + '</em><br/><span style="font-family:cursive; font-weight: 900;">	&ldquo;</span><span>' + this.content + '</span><span style="font-family:cursive;font-weight: 900;">&rdquo;</span>' +
                           '</div>';
        });

        if(blurbs.length>1){
            $('#moreBlurbsBy').show();

            //var scrollingBlurbsBy = new VerticalScrollingArea('blurbsBy_outerFrame', 'blurbsByPlaceholder', 'blurbsByScrollUp', 'blurbsByScrollDown');

            var scrollUpInterval;
            var scrollDownInterval;

            $('#blurbsByScrollUp').mouseover(function(){
                scrollUpInterval = window.setInterval(function(){
                    document.getElementById('blurbsByPlaceholder').scrollTop-=10;
                }, 10);
            });

            $('#blurbsByScrollUp').mouseout(function(){
                window.clearInterval(scrollUpInterval);
            });

            $('#blurbsByScrollDown').mouseover(function(){
                scrollDownInterval = window.setInterval(function(){
                    document.getElementById('blurbsByPlaceholder').scrollTop+=10;
                }, 10);
            });

            $('#blurbsByScrollDown').mouseout(function(){
                window.clearInterval(scrollDownInterval);
            });
        }

        $('#moreBlurbsBy').click(function(){
            $('#blurbsByPlaceholder div.box1').each(function(i, item){
                $(item).show();
            });
            $('#lessBlurbsBy').show();
            $('#moreBlurbsBy').hide();
            $('#blurbsByScrollButtons').show();

            if($('#blurbsByPlaceholder').height() > 450)
                $('#blurbsByPlaceholder').css('height', '450px');
        });

        $('#lessBlurbsBy').click(function(){
            lessBlurbsBy();
        });

        document.getElementById('blurbsByPlaceholder').innerHTML = blurbsHTML;

        $(blurbs).each(function(blurbIndex) {
            $('#blurbBy-' + this.id).append(comments.include('blurbBy-' + this.id, 'by', 'blurb', this.id));
        });
}

function lessBlurbsAbout(){
    $('#blurbsAboutPlaceholder div.box1').each(function(i, item){
        if(i>2)
            $(item).hide();
    });

    document.getElementById('blurbsAboutPlaceholder').scrollTop = 0;
    $('#lessBlurbsAbout').hide();
    $('#moreBlurbsAbout').show();
    $('#blurbsAboutScrollButtons').hide();

    $('#blurbsAboutPlaceholder').css('height', 'auto');
}

function lessBlurbsBy(){
    $('#blurbsByPlaceholder div.box1').each(function(i, item){
        if(i>0)
            $(item).hide();
    });

    document.getElementById('blurbsByPlaceholder').scrollTop = 0;
    $('#lessBlurbsBy').hide();
    $('#moreBlurbsBy').show();
    $('#blurbsByScrollButtons').hide();

    $('#blurbsByPlaceholder').css('height', 'auto');
}


/***************************************************************
 *  This next section provides a cross browser way
 *  to have dynamically expanding text fields.
 ***************************************************************/
// Keycodes that do not affect the length of inputs
var keyCodesWithNoAffect = {
    16 : "shift",
    36 : "home",
    37 : "leftArrow",
    38 : "rightArrow",
    39 : "upArrow"
}

