﻿

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function (from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};


var rwIsAdmin = false;
var rwIsLoggedIn = false;
var rwIsTwitterEnabled = false;
var rwIsFacebookEnabled = false;
var rwFacebookUID = null;

var fbLoggedInResponse = null;

function rwPageLoad() {

    //hook up fancyboxes
    $("a.fancyAnchor")
    .fancybox(
        {
            'transitionIn': 'elastic',
            'transitionOut': 'elastic'
        }
    );

    //see what the DILLY is
    GetLoggedInStatus();

    //watch for notification
    StartNotePoller();

    //Get an exhibitor list
    GetExhibitors();

    //Facebook connect initializer
    try {
        FB.init({
            appId: '113603458665278', //stp.com app id
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });

        FB.getLoginStatus(function (response) {
            if (response.session) {
                fbLoggedInResponse = response;
                rwFacebookUID = response.session.uid;
                //alert('got a session');
            } else {
                //alert('fb was all like WHUT');
            }
        });
    } catch (e) {
        //stupd facebook
    }
}

function ShowTweetBox() {
    $("#tboxContainer").toggle();
}

function ToolTipResponseError(sender, args) {
    args.set_cancelErrorAlert(true);
    //alert('alert killed');
}

function FireAlert(msg) {
    $("#lblAlertBoxMessage").html(msg);
    $('#AlertBox').animate({ "height": "50" }, "fast").css("height", "auto").delay(3000).animate({ "height": "0" }, "slow");
}


function FieldDarken(input, defaultstring) {
    if (input.value == defaultstring) {
        input.value = '';
    }
    input.style.color = 'black';
}

function FieldDefaultulate(input, defaultstring) {
    if (input.value == '' | input.value == defaultstring) {
        input.value = defaultstring;
        input.style.color = 'silver';
    }
}

var notifications = new Array();

function StartNotePoller() {

    $(window).scroll(function () {
        $('#AlertBox').css('top', window.scrollY);
    })

    PollNotes();
}

function PollNotes() {
    //FireAlert("Asking for notes");
    RedwoodWebServices.RedwoodService.GetNotifications(GotNotes, AjaxFail);
    window.setTimeout(PollNotes, 20000);
}

function GotNotes(result) {
    //FireAlert('got ' + result.length + ' notes');
    if (result.length == 0) {
        return;
    }
    $.each(result, function (index, note) {
        notifications.push(note);
    });
    SlogNotes();
}




var exhibitors = new Array();

function GetExhibitors() {
    //FireAlert("Asking for notes");
    RedwoodWebServices.RedwoodService.GetExhibitors(GotExhibitors, AjaxFail);
    window.setTimeout(PollNotes, 20000);
}

function GotExhibitors(result) {
//    FireAlert('got ' + result.length + ' exhibitors');
    if (result.length == 0) {
        return;
    }
    $.each(result, function (index, exhibitor) {
        exhibitors.push(exhibitor);
    });

    //show an exhibitor or something
}





function AjaxFail(result) {
//    if (rwIsAdmin) {
//        FireAlert('Ajax Failure: ' + result._message);
//    }
}


function SlogNotes() {
    if (notifications.length > 0) {
        var note = notifications[0];
        notifications.remove(0);
        var msg = '';
        if (note.icon != "") {
            msg = "<img src='" + note.icon + "' align='absmiddle' /> ";
        }
        msg = msg + note.message;

        if (note.points != "") {
            if (note.points == 1) {
                msg = msg + " You got a point!";
            }
            else {
                msg = msg + " You got " + note.points + " points!";
            }
        }

        FireAlert(msg);

        window.setTimeout(SlogNotes, 5000);
    }
}


function DoCommentSize(textbox) {

    var content = $('#txtNewComment').attr('value');

    var height = (content.length / 23) * 9;

    if (height < 46) {
        height = 46;
    }

    $('#txtNewComment').css('height', height);


}

function ToggleReplyVis(CommentID) {
    if ($('#commentReply_' + CommentID).is(':visible')) {
        $('#commentReply_' + CommentID).fadeOut();

        $('#commentReplyHide_' + CommentID).fadeOut(
            'fast', function () {
                $('#commentReplyShow_' + CommentID).fadeIn();
            }
        );

    }
    else {
        $('#commentReply_' + CommentID).fadeIn();
        $('#commentReplyShow_' + CommentID).fadeOut(
            'fast', function () {
                $('#commentReplyHide_' + CommentID).fadeIn();
            }
        );
    }
}



////////////////////////////////////////////////////
////////////////////  COMMENTS  ////////////////////
////////////////////////////////////////////////////

var rwCommentEntityId = '';
var rwCommentEntityType = '';

function DrawCommentsFromScratch() {
//    $('#commentSpace').empty();
    RedwoodWebServices.RedwoodService.GetComments(rwCommentEntityType, rwCommentEntityId, function (result) {

        $('#commentSpace').empty();

        if (result == null) { return; }

        NewCommentForm($('#commentSpace'), rwCommentEntityType, rwCommentEntityId);
        GotComments(result, $('#commentSpace'));
    }, AjaxFail);
    
}

function GotComments(result, container) {
    //FireAlert('got ' + result.length + ' comments');

    if (result == null) { return; }
    if (result.length == 0) { return; }

    $.each(result, function (index, comment) {
        DrawComment(comment, container);
    });
}


function DrawComment(comment, container) {

    //Comment Container
    var divComment = $("<div>");
    divComment.attr('id', 'commentDiv_' + comment.CommentID);
    divComment.addClass('comment');

    if (comment.ParentCommentID != 0) {
        divComment.appendTo($('#commentDiv_' + comment.ParentCommentID));
        divComment.css('margin-top', '18px');
    }
    else {
        divComment.appendTo(container);
    }

    //Commenter photo, hooked to PersonTooltip ;)
    var imgThumb = $("<img />");
    imgThumb.attr('src', comment.PersonThumbURL);
    imgThumb.css('float', 'right');
    imgThumb.attr('id', comment.UserID);
    imgThumb.attr('onmouseover', 'showPersonToolTip(this)');
    imgThumb.appendTo(divComment);

    //Commenter name
    var h3Name = $("<h3>");
    h3Name.text(comment.PersonName);
    h3Name.appendTo(divComment);

    //comment date
    var spanDt = $("<span>");
    spanDt.text(comment.CreatedAt.format('M/d/yy h:mm:ss tt'));
    spanDt.css('font-size', '10px');
    spanDt.css('color', 'gray');
    spanDt.appendTo(divComment);
    AddBrTo(divComment);

    //comment latest reply
//    var spanDtLatest = $("<span>");
//    spanDtLatest.text(comment.LatestReply.format('M/d/yy h:mm:ss tt'));
//    spanDtLatest.css('font-size', '10px');
//    spanDtLatest.css('color', 'orange');
//    spanDtLatest.appendTo(divComment);
//    AddBrTo(divComment);

    //comment content
    var spanComment = $("<span>");
    spanComment.html(nl2br(linkify(comment.Content)));
    spanComment.appendTo(divComment);
    AddBrTo(divComment);
    AddBrTo(divComment);



    //Thread value
//    var spanThreadValue = $("<span>");
//    spanThreadValue.text(comment.ThreadValue);
//    spanThreadValue.appendTo(divComment);
//    AddBrTo(divComment);





    //comment tools
    var divCommentTools = $("<div style='float:right'></div>");
    divCommentTools.attr('id', 'commentDiv_' + comment.CommentID);
    divCommentTools.appendTo(divComment);



    //show replies button, if there are any
//    if (comment.Ancestors != 0) {
//        var spanAncestors = $("<a href='javascript:void(0)'>");
//        spanAncestors.attr("id", "viewRepliesOf_" + comment.CommentID);
//        spanAncestors.text("View " + comment.Ancestors + " replies");
//        spanAncestors.css('padding-right', '4px');

//        spanAncestors.click(function () {
//            RedwoodWebServices.RedwoodService.GetComments('comment', comment.CommentID, GotComments, AjaxFail);
//            spanAncestors.attr("viewRepliesOf_" + comment.CommentID);
//            $("#viewRepliesOf_" + comment.CommentID).fadeOut();
//        });

//        spanAncestors.appendTo(divCommentTools);
//    }
    
    //if they're logged in, show the reply link with attached call to new comment form.
    if (rwIsLoggedIn) {

        var aReply = $("<a href='javascript:void(0)'>Reply</a>");
        aReply.attr('id', 'replyTo_' + comment.CommentID);
        aReply.click(function () {
            NewCommentForm(divComment, 'comment', comment.CommentID);
            $(this).hide();
        });
        aReply.appendTo(divCommentTools);
    }

    //if an admin, give them a delete button
    if (rwIsAdmin) {

        var aDelete = $("<a href='javascript:void(0)'>Delete</a>");
        aDelete.css('padding-left', '4px');
        aDelete.click(function () {
            if (confirm('This will delete this comment and ALL REPLIES to this comment. There is NO UNDO.')) {
                DeleteComment(comment.CommentID);
            }
        });
        aDelete.appendTo(divCommentTools);

    }

    //rating tools
    var divCommentRateSpace = $("<div style='float:left'></div>");
    divCommentRateSpace.attr('id', 'RatingContainer_comment_' + comment.CommentID);
    divCommentRateSpace.appendTo(divComment);
    NewRatingForm(divCommentRateSpace, "comment", comment.CommentID);

    AddBrClearAllTo(divComment);

    //go get child comments REEEEEEEcurse
    if (comment.Ancestors > 0) {
        for (var i = 0; i < comment.SubComments.length; i++) {
            DrawComment(comment.SubComments[i], divComment);
        }
        //RedwoodWebServices.RedwoodService.GetComments('comment', comment.CommentID, GotComments, AjaxFail);
    }
}

function AddBrTo(container) {
    $("<br />").appendTo(container);
}

function AddBrClearAllTo(container) {
    $("<br clear='all' />").appendTo(container);
}

function NewCommentForm(container, entityType, entityID) {

    if (rwIsLoggedIn) {

        $('#commentSpaceLoginRequired').hide();

        var divCommentReply = $("<div>");
        divCommentReply.attr('id', 'commentReplyDiv_' + entityID);
        divCommentReply.appendTo(container);
        divCommentReply.hide();

        AddBrTo(divCommentReply);

        var txtComment = $("<textarea>");
        txtComment.attr('id', 'newCommentText_' + entityType + '_' + entityID);
        txtComment.css('width', '99%');
        txtComment.appendTo(divCommentReply);

        AddBrTo(divCommentReply);

        var btnPost = $("<input type='button' />");
        btnPost.css('width', '250px');
        btnPost.attr('value', 'Post Your Message');
        btnPost.attr('id', 'newCommentBtn_' + entityType + '_' + entityID);
        btnPost.click(function (event) {
            PostComment(event);
        });

        btnPost.appendTo(divCommentReply);

        if (entityType == 'comment') {

            var aCancelReply = $("<a href='javascript:void(0)'>Cancel Reply</a>");
            aCancelReply.attr('id', 'cancelReplyTo_' + entityID);
            aCancelReply.click(function () {

                var commentID = this.id.replace('cancelReplyTo_', '');

                $('#replyTo_' + commentID).show();
                $('#commentReplyDiv_' + commentID).slideUp('fast', function () {
                    $('#commentReplyDiv_' + commentID).remove();
                });
            });

            aCancelReply.appendTo(divCommentReply);
        }

        divCommentReply.slideDown();
        if (entityType == 'comment') {
            txtComment.focus();
        }
    }
}

function PostComment(event) {

    var typeAndId = event.target.id.replace('newCommentBtn_', '');
    var type = typeAndId.substring(0, typeAndId.indexOf('_'));
    var id = typeAndId.replace(type + '_', '');

    //FireAlert('Reply to: ' + type + ' ' + id);

    var comments = $('#newCommentText_' + type + '_' + id).val();

    RedwoodWebServices.RedwoodService.PostComment(type, id, comments, false, PostedComment, AjaxFail);

    //FireAlert(comments);
}


function PostedComment(result) {

    //this is bad... jquery wraps and silences the error, 
    //but drawCommentsFromScratch only works on small format comment spaces
    //FillInBoard only works on the forum page...
    // se la vi 
    DrawCommentsFromScratch();
    GetBoardComments();

}

function DeleteComment(id) {
    RedwoodWebServices.RedwoodService.DeleteComment(id, function () {
        DeletedComment(id);
    }, AjaxFail);
}

function DeletedComment(id) {
    $('#commentDiv_' + id).slideUp('fast', function () { $('#commentDiv_' + id).remove()});
}


////////////////////////////////////////////////////
///////////////////  Rating System  ////////////////
////////////////////////////////////////////////////


function NewRatingForm(container, entityType, entityID) {
    $(container).empty();
    RedwoodWebServices.RedwoodService.GetRatingInfo(entityType, entityID, function (result) {
        RatingInfoResponse(result, container, entityType, entityID);
    }, AjaxFail);
}

function RatingInfoResponse(result, container, entityType, entityID) {

    //FireAlert('got rating response');

    var divRateContainer = $("<div />");
    divRateContainer.attr('id', 'rateDiv_' + entityType + '_' + entityID);
    divRateContainer.appendTo($(container));

    //score
    var divRatingValue = $("<div class='littleRatingScore'></div>");
    divRatingValue.text(result.Value);
    divRatingValue.appendTo(divRateContainer);


    if (rwIsLoggedIn) {

        //thumbsup
        var imgRateUp = $("<img src='/images/thumbs_sm_up.gif' style='cursor:pointer;margin-right:2px;'>");
        if (result.MyVote == '1') {
            imgRateUp.attr('src', '/images/thumbs_sm_up_off.gif');
        }
        imgRateUp.click(function () {
            SendRating(1, entityType, entityID);
        });
        imgRateUp.appendTo(divRateContainer);


        //thumbsdown
        var imgRateDn = $("<img src='/images/thumbs_sm_dn.gif' style='cursor:pointer;'>");
        if (result.MyVote == '-1') {
            imgRateDn.attr('src', '/images/thumbs_sm_dn_off.gif');
        }
        imgRateDn.click(function () {
            SendRating(-1, entityType, entityID);
        });
        imgRateDn.appendTo(divRateContainer);
    }


}


function SendRating(RatingValue, entityType, entityID) {

    //FireAlert('Rated ' + entityType + ' ' + entityID + ' ' + RatingValue);
    RedwoodWebServices.RedwoodService.NewRating(entityType, entityID, RatingValue, function () {

        var container = $('#RatingContainer_' + entityType + '_' + entityID);
        NewRatingForm(container, entityType, entityID);

    }, AjaxFail);
}


////////////////////////////////////////////////////
///////////////////  CREDENTIALS  //////////////////
////////////////////////////////////////////////////

function GetLoggedInStatus() {
    RedwoodWebServices.RedwoodService.IsAdmin(AdminResponse, AjaxFail);
    RedwoodWebServices.RedwoodService.IsLoggedIn(LoggedInResponse, AjaxFail);
    RedwoodWebServices.RedwoodService.IsTwitterEnabled(TwitterEnabledResponse, AjaxFail);
    RedwoodWebServices.RedwoodService.IsFacebookEnabled(FacebookEnabledResponse, AjaxFail);
}

function LoggedInResponse(result) {
    rwIsLoggedIn = result;
}
function AdminResponse(result) {
    rwIsAdmin = result;
}
function TwitterEnabledResponse(result) {
    rwIsTwitterEnabled = result;
}
function FacebookEnabledResponse(result) {
    rwIsFacebookEnabled = result;
}







function ShowNotes() {
    $('#NoteFlow').slideDown();
}

function HideNotes() {
    $('#NoteFlow').slideUp();
}

////////////////////////////////////////////////////
///////////////////  JS ToolTip   //////////////////
////////////////////////////////////////////////////

function showPersonToolTip(element) {
    var tooltipManager = $find("rttmPersonToolTip");

    //If the user hovers the image before the page has loaded, there is no manager created
    if (!tooltipManager) return;

    //Find the tooltip for this element if it has been created
    var tooltip = tooltipManager.getToolTipByElement(element);

    //Create a tooltip if no tooltip exists for such element
    if (!tooltip) {
        tooltip = tooltipManager.createToolTip(element);
        tooltip.set_value($(element).attr('id')); //assume the id of the element is the personID..
    }

    //Let the tooltip's own show mechanism take over from here - execute the onmouseover just once
    element.onmouseover = null;

    //show the tooltip
    tooltip.show();
} 

////////////////////////////////////////////////////
/////////////////////  Boards   ////////////////////
////////////////////////////////////////////////////

function GetBoardList() {

    //FireAlert('yo');

    RedwoodWebServices.RedwoodService.GetBoards(GotBoardsResponse, AjaxFail);

}


var rwSelectedBoard = 0;


function GotBoardsResponse(result) {

    //FireAlert('got response');
    $.each(result, function (index, board) {
        var id = "handleForBoard_" + board.ID;
        var divBoardLabel = $("<a href='javascript:void(0)' style='float:left;margin-right:16px;' />");
        divBoardLabel.appendTo($('#boardList'));
        divBoardLabel.text(board.Name + " (" + board.ThreadCount + ")");
        divBoardLabel.attr('id', id);
        divBoardLabel.attr('class', "boardhandle");
        //divBoardLabel.attr('onClick', 'SelectBoard(' + board.ID + '); return false;');

        divBoardLabel.click(function () {
            SelectBoard(board.ID);
            return false;
        });
    });

    AddBrTo($('#boardList'));

    var urlBoard = gup("board");

    if (urlBoard != "") {
        SelectBoard(urlBoard);
    }
}

function SelectBoard(BoardID) {

    $(".boardhandle").css("font-weight", "normal");
    $("#handleForBoard_" + BoardID).css("font-weight", "bold");

    rwSelectedBoard = BoardID;
    GetBoardComments();
}

function GetBoardComments()
{
    RedwoodWebServices.RedwoodService.GetComments('board', rwSelectedBoard, FillInBoardComments, AjaxFail);
}

function FillInBoardComments(result) {

    $('#boardComments').empty();
    NewCommentForm($('#boardComments'), 'board', rwSelectedBoard);
    GotComments(result, $('#boardComments'));
}

//////////////////////////////////////////////////////
///////////////////  Demographics   //////////////////
//////////////////////////////////////////////////////

function toggleTextBox(checkbox) {
    var $otherTextBox = $(checkbox).parent().next().find(".otherCheckBoxTextBox");
    if ($otherTextBox != null && $otherTextBox.length > 0) {
        if (checkbox.checked == true)
            $otherTextBox.attr("disabled", false);
        else {
            $otherTextBox.attr("disabled", true);
            $otherTextBox.val("");
        }
    }
}

function linkify(text) {
    if (text) {
        text = text.replace(
            /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
            function (url) {
                var full_url = url;
                if (!full_url.match('^https?:\/\/')) {
                    full_url = 'http://' + full_url;
                }
                return '<a href="' + full_url + '">' + url + '</a>';
            }
        );
    }
    return text;
}

function nl2br(myString) {
    var regX = RegExp("\\n", "g");
    var replaceString = '<br />';
    var val = myString.replace(regX, replaceString);
    return val;
}

//gup will return the value of a URL variable
function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}
