﻿var commentAction = null;
var currentCommentId = null;
var ErrorMask1 = 0;
var ErrorMask2 = 0;
var _fckInit = false;
var NastyMessage = "";
var waiterId;

String.prototype.pad = function(l, s, t) {
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
		        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
		        + this + s.substr(0, l - t) : this;
};

function buildCommentAction() {
    var KeepLoggedinForSession = true;
    var userName = null;
    var email = null;
    var password = null;
    var quickRegister = false;
    var commentText = null;

    var oEditor = CKEDITOR.instances.commentEntryBox;


    if (oEditor.checkDirty() == false) {
        $get("validError").style.display = "";
        $get("validError").innerHTML = "You have not entered a comment. Please try again.";

        return false;
    }

    commentText = oEditor.getData(true);

    if (commentText.length < 10) {
        $get("validError").style.display = "";
        $get("validError").innerHTML = "Sorry, it seems that you did not enter a comment. Please try again.";
        return false;
    }

    if (commentText.length > 10240) {
        $get("validError").style.display = "";
        $get("validError").innerHTML = "Sorry, your comment must be 10240 characters or less. Please try again.";
        return false;
    }

    var theCheckBox = $get("chkKeepLoggedIn");
    var KeepLoggedinForever = false;
    if (theCheckBox) {
        KeepLoggedinForever = (theCheckBox.value == 'on' ? true : false);
        //if (KeepLoggedinForever) alert("Keeping you logged in forever");
    }

    // validate the comment before proceeding
    if (typeof isLoggedInX != 'undefined' && isLoggedInX != null && isLoggedInX == true) {
        userName = tvgUserName;
    }
    else if ($get("qrEmail").value.length > 0) {
        quickRegister = true;
        isLoggedInX = false;
        userName = $get("qrUserName").value;
        email = $get("qrEmail").value;
        password = $get("qrPassword").value;
    }
    else if ($get("regUserName").value.length > 0) {
        isLoggedInX = false;
        userName = $get("regUserName").value;
        password = $get("regPassword").value;
    }
    else {
        $get("validError").style.display = "";
        $get("validError").innerHTML = "You must be logged in to comment. Please log in or register above.";
        return false;
    }

    commentAction = new Object();
    commentAction.Version = 2;
    commentAction.Action = CommentActionType.Validate;
    commentAction.ContentKeyInfo = contentKeyInfo;
    commentAction.UserEmail = email;
    commentAction.UserName = userName;
    commentAction.UserPassword = password;
    commentAction.AlreadyLoggedIn = isLoggedInX;
    commentAction.KeepLoggedInForever = KeepLoggedinForever
    commentAction.KeepLoggedInSession = KeepLoggedinForSession;
    commentAction.UserType = UserType.Registered;
    commentAction.UserHostAddress = clientIPAds;
    commentAction.UserAgent = clientUserAgent;
    commentAction.Comment = commentText;
    commentAction.QuickRegister = quickRegister;

    return true;
}

function checkBrowser() {
    var browserName = navigator.appName;
    if (browserName != "Microsoft Internet Explorer") return;
    $get("commentEntryBlock").style.width = "610px";
}

function clearErrors() {
    $get("cmtError").style.display = "none";
    $get("cmtError").innerHTML = "";

    $get("validError").style.display = "none";
    $get("validError").innerHTML = "";
}

function commentEntry_HideBlock() {
}

function commentEntry_PageLoad() {
    var theCookie = null;

    checkBrowser();

    if (validateContentKeyInfo()) {
        initFCKEditor();
        
        if ((typeof (commentReadProxy) != 'undefined' && commentReadProxy == null) && (typeof (px_cr_ajaxUrl) != 'undefined' && px_cr_ajaxUrl.length > 1))
            px_cw_createReadProxy(px_cr_ajaxUrl);       

        if (typeof (commentWriteProxy) != 'undefined' && commentWriteProxy == null)
            px_cw_createWriteProxy(px_cw_ajaxUrl);

        if (typeof (mapProxy) != 'undefined' && mapProxy == null)
            px_map_createMapProxy(px_map_ajaxUrl);
            
        if (typeof commentWriteProxy != null) {
            toggleCommentLoginArea();

            theCookie = getCookieComment("commentsendfb");
            
            if (typeof theCookie != 'undefined' && theCookie != null) {
                if (theCookie == 'true')
                    $get("chkSendToFacebook").checked = true;
                else
                    $get("chkSendToFacebook").checked = false;
            }
            else
                $get("chkSendToFacebook").checked = true;

            $get("commentEntryBlock").style.display = "";
        }
    }
    else {
            $get("cmtError").style.display = "";
            $get("cmtError").innerHTML = "We are sorry, we have encountered an issue initializing the comment entry area.";
    }
}

function commentFailure() {
    $(pnlSubmissionConfirmText).innerHTML = "<p>Unknown Error in posting.  Please try again later.</p>";
    setTimeout("hidePopup();", 5000);
}

function compareEmailAddresses() {
    $get("cmtError").style.display = "none";
    var email = $get("qrEmail").value;
    var confirm = $get("qrConfEmail").value;

    if (email != confirm  || email.length == 0 || confirm.length == 0) {
        ErrorMask1 |= 2;
        //       $get("cmtError").innerHTML = "The emails you entered do not match.  Please try again.";
        //     $get("qrConfEmail").focus();        
    }
    else {
        ErrorMask1 &= (~2);
        validateEmail();
        //   $get("cmtError").innerHTML = "";
    }
}

function doCmtUserArea() {
    updateMultiLoginState(0);
    updateMultiLoginState(1);
}

function formatDateTime(timestamp) {

    var formattedDate = null;
    
    var monthNames = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    ];

    var dayNames = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday"
    ];

    formattedDate = dayNames[timestamp.getDay()].substring(0, 3) + ", " + monthNames[timestamp.getMonth()].substring(0, 3) + " " + timestamp.getDate().toString() + ", " + timestamp.getFullYear().toString();
    formattedDate += " at " + ((timestamp.getHours() % 12) ? timestamp.getHours() % 12 : 12).toString() + ":" + timestamp.getMinutes().toString().pad(2, '0', 0) + " ";
    formattedDate += (timestamp.getHours() < 12 ? 'am' : 'pm') + " ";
    formattedDate += timestamp.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");

    return formattedDate;    
}

function hidePopup() {
    $(document).trigger('close.facebox');
}

function initFCKEditor() {
    if (!_fckInit) {
        _fckInit = true;

        // Load changes to Menu
        var oFCKeditor = CKEDITOR.replace('commentEntryBox',
			{
			    //				extraPlugins : 'uicolor',
			    //				uiColor: '#CCCCCC',
			    toolbar:
				[
				    ['Cut', 'Copy', 'Paste', 'PasteText', '-', 'Bold', 'Italic', 'Underline', 'SpellChecker', 'Scayt', 'Smiley']
				]
			});

			oFCKeditor.basePath = "/FCK/ckeditor_3.0/";
							
			/* var ver = GetInternetExplorerVersion();
			if (ver > -1 && ver >= 7.0) {
			    oFCKeditor.config.startupFocus = true;
			    setTimeout("window.location.href='#'", 1000);
			} */
						
        // Custom Skins that can be used for the menu and dialogs
    }
}

function methodFailed(errorInfo, context, methodName) {
    var href = window.top.location.href.toLowerCase();

    if (href.indexOf("qa") != -1 || href.indexOf("localhost") != -1) {
        $(pnlSubmissionConfirmText).innerHTML = "<p>" + String.format("Execution of method {0} failed because of the following:\r\n{1}", methodName, errorInfo.get_message()) + "</p>";
        setTimeout("hidePopup();", 5000);
    } else {
        setTimeout("hidePopup();", 10);
    }
    //alert('There was a problem connecting to the server.  Click OK to refresh the page.');
    //window.setTimeout('window.location.href=window.location.href;',10);
}

function saveComment() {

    ErrorMask2 = ErrorMask1;
    ErrorMask1 = 0;

    if (ErrorMask2 != 0) {
        var errors = "";

        errors = testMask(1, errors, "An account with this email address already exists. Please try another email address.");
        errors = testMask(2, errors, "The email addresses you have entered do not match.  Please try again.");
        errors = testMask(4, errors, "Your password must include [enter password requirements here]. Please try again.");
        errors = testMask(8, errors, "The username you have selected is already in use. Please enter another username.");
        errors = testMask(16, errors, "Your username must include [enter username requirements here]. Please try another username.");
        errors = testMask(32, errors, NastyMessage); //"This email address is already in use. Please try another email address.");
        errors = testMask(64, errors, "The specified username does not exist. Please register this username.");

        $get("cmtError").style.display = "";
        $get("cmtError").innerHTML = errors;
        return;
    }


    $get("pnlSubmissionConfirmText").innerHTML = "<p>Thank you. Your comment is being posted.</p>";
    jQuery.facebox($get("pnlSubmissionConfirm").innerHTML);
    $('#facebox .footer').css('display', 'none');

    if (waiterId != null) clearTimeout(waiterId);
    waiterId = setTimeout("CommentFailure();", 10000);
    commentAction.Action = CommentActionType.Save;
    px_cw_saveComment(commentAction, saveCommentCompleted, methodFailed);
    return;
}

function saveCommentCompleted(results, context, methodName) {
    var resultStruct = results;
    var daze = 365;
    var commentSaved = false;
    var sendToFB = true;
    var cmtTxtForShare = "";

    sendToFB = $get("chkSendToFacebook").checked;
    setCookieComment("commentsendfb", sendToFB, 365);

    clearTimeout(waiterId);
    commentSaved = resultStruct.Saved;
    if (!commentSaved) {
        var mesg;
        if (!resultStruct.ValidErrorMsg.PassedValidation)
            mesg = resultStruct.ValidErrorMsg.ReasonForFailure;

        if (mesg == 'undefined' || mesg == null) {
            mesg = resultStruct.ErrorMsg;
        }
        if (mesg == 'undefined' || mesg == null) {
            mesg = "Server could not validate login.  Please correct and try again.";
        }
        $get("pnlSubmissionConfirmText").innerHTML = mesg;
    } else {
        $get("commentEntryBlock").style.height = "0px";
        $get("commentEntryBlock").style.display = "none";

        currentCommentId = resultStruct.CommentId;

        $get("pnlSubmissionConfirmText").innerHTML = "<p>Thank you. Your comment has been posted.</p>";
    }
    

    // has the comment be saved on our side and is the user logged into Facebook
    if (commentSaved && sendToFB) {
        hidePopup();
        // remove the opening and closing paragraph tags that the FCK includes.
        cmtTxtForShare = Encoder.htmlDecode(commentAction.Comment);

        // send to face book
        sendCommentNewsFeedToAllFriends(cmtTxtForShare, socialImage, socialTitle, socialDescription);
    }
    else {
        setTimeout("hidePopup();", 5000);
    }
    
    // we are trying to stall to give replication time to get the comment across to the other servers.
    if (commentSaved) {
        var cookieValue = resultStruct.CookieValue;
        if (cookieValue != null && cookieValue != "") {
            isLoggedInX = true;
            setCookieComment("MAPCookie", cookieValue, daze);
            tvgUserName = $get("regUserName").value;
            doCmtUserArea();
        }

        updateCommentDisplay();
    }
}

function submitComment() {

    clearErrors();

    // build the structure to pass for validation and submit.
    if (buildCommentAction() == true && commentAction != null) {
        verifyComment();
    }
}

function testMask(v, errors, mesg) {
    if ((ErrorMask2 & v) == v) {
        if (errors.length > 0) return errors + "<br />" + mesg;
        return mesg;
    }
    return errors;
}

function toggleCommentLoginArea() {

    // see if the user is logged in, and if so, hide the login boxes.
    if (typeof isLoggedInX != 'undefined' && isLoggedInX != null && isLoggedInX == true) {
        $get("logPerson").innerHTML = tvgDisplayName;
        if (isFBCAuthenticated == 1) {
            $get("logImage").src = "http://www.tvguide.com/images/global/facebook_share_icon.gif";
            $get("logImage").alt = "Facebook";
        }

        $get("cmtAlreadyLoggedin").style.display = "";
        $get("cmtLoginDiv").style.display = "none";

        if (isFBCAuthenticated == 1)
            $get("cmtLoginFacebook").style.display = "none";

    } else {
        $get("cmtLoginDiv").style.display = "";
        $get("cmtLoginFacebook").style.display = "";
    }
}

function updateCommentDisplay() {
    totalComments++;
    showCommentCounts();

    if (sortChoice == null)
        sortChoice = SortDirections.CreateTimeAscRN;

    // $get("BLKcommentCount").innerHTML = "<h3>Comments (" + (totalComments + 1) + ")</h3>";
    var totalPages = Math.ceil((totalComments) / commentsPerPage);
    px_cr_getCommentPage(contentKeyInfo, commentsPerPage, totalPages, sortChoice, updateCommentDisplayCompleted, updateCommentDisplayError);
}

function updateCommentDisplayError(errorInfo, context, methodName) {
    //    alert("Could not get comment counts");
    //    alert(errorInfo._message);
}

function updateCommentDisplayCompleted(results, context, methodName) {
    var timestamp = new Date();
    var currentItem = null;
    var found = false;

    if (results != null) {
        var commentItem = new Object();

        commentItem.UserTypeId = commentAction.UserType;
        commentItem.UserName = commentAction.UserName;
        commentItem.CommentId = currentCommentId;
        commentItem.CommentText = commentAction.Comment;
        commentItem.AgreeCount = 0;
        commentItem.Status = "pending";

        commentItem.CommentTimeStampAsString = formatDateTime(timestamp);

        // we need to make sure that this comment is not in the array before we add it.
        for (var it = 0; it < results.length; it++) {
            currentItem = results[it];
            if (currentItem.CommentId == currentCommentId) {
                found = true;
                break;
            }
        }

        // add the new comment to the end of the list.
        if (!found)
            results[results.length] = commentItem;
    }
    $get("spottoputcomments").innerHTML = generateComments(results);
    generatePager();
    checkBrowser();
}

function validateContentKeyInfo() {
    var validContentInfo = false;

    if (contentKeyInfo.Version == 2) {
        if (contentKeyInfo.ContentId > 1 && contentKeyInfo.ContentTypeId > 0 && contentKeyInfo.WriteServerId > 0)
            validContentInfo = true;
    }
    else if (contentKeyInfo.Version == 1) {
        if (contentKeyInfo.ContentType.length > 4 && contentKeyInfo.ContentTypeKey.length > 4)
            validContentInfo = true;
    }
    
    return validContentInfo;
}

function validateEmail() {
    var email = $get("qrEmail").value;
    if (email.length == 0) return;
    clearErrors();
    px_map_checkEmailUniqueness(email, validateEmailCompleted);
}

function validateEmailCompleted(results, context, methodName) {
    if (results == false) {
        ErrorMask1 |= 1;
        $get("cmtError").innerHTML = "The email address you have entered is already in use.";
        $get("cmtError").style.display = "";        
        $get("qrEmail").focus();        
    }
    else {
        ErrorMask1 &= (~1);
        clearErrors();
    }
}

function validatePassword() {
    $get("cmtError").style.display = "none";
    var userName = $get("qrUserName").value;
    var password = $get("qrPassword").value;
    if (userName.length > 0) {
        if (password.length == 0) {
            $get("cmtError").innerHTML = "A password is required.";
            $get("cmtError").style.display = "";
            $get("qrPassword").focus();
        }
        else {
            px_map_checkPassword(password, validatePasswordCompleted);
        }
    }
}

function validatePasswordCompleted(results, context, methodName) {
    if (results == false) {
        ErrorMask1 |= 4;
        $get("cmtError").innerHTML = "The password is not acceptable.";
        $get("cmtError").style.display = "";
        $get("qrPassword").focus();        
    }
    else {
        ErrorMask1 &= (~4);
        clearErrors();
    }
}

function validateUsername() {
    $get("cmtError").style.display = "none";
    var userName = $get("qrUserName").value;
    if (userName.length == 0) return;
    px_map_checkUserName(userName, validateUsernameCompleted);
}

function validateUsernameCompleted(results, context, methodName) {
    ErrorMask1 &= (~64);
    switch (results) {
        case CheckUserNameResult.NotUnique:
            ErrorMask1 |= 8;
            $get("cmtError").innerHTML = "This username is already in use.";
            $get("cmtError").style.display = "";
            $get("qrUserName").focus();        
            break;

        case CheckUserNameResult.Inappropriate:
            ErrorMask1 |= 16;
            $get("cmtError").innerHTML = "This username is inappropriate.";
            $get("qrUserName").focus();        
            break;

        default:
            clearErrors();
            break;
    }
}

function verifyUsernameExists() {
    $get("cmtError").style.display = "none";
    var userName = $get("regUserName").value;
    if (userName.length == 0) return;
    px_map_checkUserName(userName, verifyUsernameExistsCompleted);
}

function verifyUsernameExistsCompleted(results, context, methodName) {
    ErrorMask1 &= (~64);
    if (results != CheckUserNameResult.NotUnique) {
        ErrorMask1 |= 64;
        $get("cmtError").innerHTML = "The specified username does not exist. Please register this username.";
        $get("cmtError").style.display = "";
        $get("regUserName").focus();        
    }
    else {
        clearErrors();
    }
}

function verifyComment() {

    NastyMessage = "";
    px_cw_validateComment(commentAction, verifyCommentCompleted, methodFailed);
}

function verifyCommentCompleted(results, context, methodName) {
    var i;
    var words = "";
    var resultStruct = results;

    ErrorMask1 &= (~32);

    if (resultStruct == null) {
        saveComment();
        return;
    }

    if (results.PassedValidation == false) {
        ErrorMask1 |= 32;

        if (resultStruct.ReasonForFailure != "undefined" && resultStruct.ReasonForFailure != null) {
            NastyMessage = resultStruct.ReasonForFailure;
        } else {
            NastyMessage = " Contains <strong>spam.</strong>";
        }
        
        if (resultStruct.Details != null && resultStruct.Details.length > 0) {
            for (i = 0; i < resultStruct.Details.length; i++) {
                if (words != "") words += ", ";
                words += resultStruct.Details[i];
            }

            NastyMessage += ": <b>" + words + ".</b>";
        }

        clearErrors();
        $get("validError").style.display = "";
        $get("validError").innerHTML = $get("validErrorContent").innerHTML + NastyMessage;

        //$get("qrEmail").focus();        
    }
    else {
        saveComment();
    }
}

// CommentEntry.js completed
