﻿//-------------------------Enums-------------------------
var PostType = { Book: "Book", Lesson: "Lesson", Talkie: "Talkie" };
var FaultType = {
    NotAuthenticated: "NotAuthenticated",
    AlreadyVoted: "AlreadyVoted",
    AlreadyReviewed: "AlreadyReviewed",
    UserSiteNotExists: "UserSiteNotExists"
};
var UserAuthenticationType = { Educopark: "Educopark", Facebook: "Facebook" };

//-------------------------Vote-------------------------

function vote(postId, votingCounterId) {
    animateVotingCounter(votingCounterId);

    var voteParams = new Object();
    voteParams.postId = postId;
    
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/WebServices/EducoparkService.asmx/VoteForLesson",
        data: JSON.stringify(voteParams),
        dataType: "json",
        success: function(result, textStatus) {
            if (result.d.IsSuccess == 1) {
                onVoteSuccess(result.d.Result, textStatus, { votingCounterId: votingCounterId })
            }
            else {
                handleFault(result.d.FaultType, result.d.FaultMessage);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            handleError(JSON.parse(XMLHttpRequest.responseText));
        }
    });
}

function animateVotingCounter(votingCounterId) {
    if (!isThisBrowserIE6()) {
        $("#" + votingCounterId + " a:first").css({ 'background': 'url(/css/Images/flower_animated.gif)' });
        setTimeout(function() {
            $("#" + votingCounterId + " a:first").removeAttr('style');
        }, 1200);
    } 
}

function onVoteSuccess(result, textStatus, voteContext) {    
    $("#" + voteContext.votingCounterId + " a:first").html(result);    
}

//-------------------------Comment-------------------------

function initComments(postType) {
    if (postType == PostType.Book) {
        rater_initDynamicBehaviour('comment_container');    
    }
    $("#lblCommentsCount").text($("div.user_comment").length + (postType == PostType.Talkie ? 1 : 0));
    $("div.user_comment").each(
        function(i) {
            var lblRepliesCount = $("#lblRepliesCount:first", this);
            var repliesCount = $("div.user_comments_first_child:first > div.user_comment", this).length;
            lblRepliesCount.text(repliesCount);
            if (repliesCount == 0) {
                lblRepliesCount.parent().removeAttr('href')
                .parent().removeClass('reply_child').addClass('reply_0');
                $("div.user_comments_first_child:first > div.arrow_comments", this).hide();
            }
            else {
                lblRepliesCount.parent().attr('href', 'javascript:void(0);')
                .parent().removeClass('reply_0').addClass('reply_child');
            }
        }
    );
    $("textarea.write_reply").maxLength(5000);
}

function toggleChildCommentItems(commentContainerId, childCommentsPanelId) {
    $("#" + commentContainerId).toggleClass('user_comment_expand');
    $("#" + childCommentsPanelId).toggle('normal'); ;
}


function submitComment(postType, parentCommentId, postId, textBoxId, commentsHolderId, addCommentPanelId, repliesPanelId) {    
    var body = $("#" + textBoxId).val();
    if (body == "") {
        showInfo("Please enter your comment", false);
        return;
    }

    showProcessing();

    var commentParams = new Object();
    commentParams.postType = postType;
    commentParams.postId = postId;
    commentParams.parentCommentId = parentCommentId;
    commentParams.body = body;

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/WebServices/EducoparkService.asmx/SubmitComment",
        data: JSON.stringify(commentParams),
        dataType: "json",
        success: function(result, textStatus) {
            if (result.d.IsSuccess == 1) {
                closeProcessing();
                onSubmitCommentSuccess(result.d.Result, textStatus, { postType: postType, textBoxId: textBoxId, commentsHolderId: commentsHolderId, addCommentPanelId: addCommentPanelId, repliesPanelId: repliesPanelId });
            }
            else {                
                closeProcessing();
                handleFault(result.d.FaultType, result.d.FaultMessage);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {            
            closeProcessing();
            handleError(JSON.parse(XMLHttpRequest.responseText));
        }
    });
}

function onSubmitCommentSuccess(result, textStatus, commentContext) {
    $("#" + commentContext.textBoxId).val("");
    $("#" + commentContext.commentsHolderId).html($("#" + commentContext.commentsHolderId).html() + result);
    if (commentContext.addCommentPanelId != "") {
        $("#" + commentContext.addCommentPanelId).hide();
    }
    $("#" + commentContext.commentsHolderId).show();
    if (commentContext.repliesPanelId != "") {
        $("#" + commentContext.repliesPanelId).show();
    }
    $('abbr[class*=timeago]').timeago();
    initComments(commentContext.postType);
}

function submitReview(postId, textBoxId, commentsHolderId, raterId) {    
    var body = $("#" + textBoxId).val();
    if (body == "") {
        showInfo("Please enter your review", false);
        return;
    }    

    var reviewParams = new Object();    
    reviewParams.postId = postId;
    reviewParams.body = body;
    reviewParams.rate = rater_classToRate($("#" + raterId).attr("class"));

    if (reviewParams.rate == 0) {
        submitComment(PostType.Book, 0, postId, textBoxId, commentsHolderId, "", "");
        return;
    }

    showProcessing();

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/WebServices/EducoparkService.asmx/SubmitReview",
        data: JSON.stringify(reviewParams),
        dataType: "json",
        success: function(result, textStatus) {
            if (result.d.IsSuccess == 1) {
                closeProcessing();
                $("#" + textBoxId).val("");
                rater_flush($("#" + raterId).get(0));
                $("#" + commentsHolderId).html($("#" + commentsHolderId).html() + result.d.Result);
                $('abbr[class*=timeago]').timeago();
                initComments(PostType.Book);
            }
            else {
                closeProcessing();
                rater_flush($("#" + raterId).get(0));
                handleFault(result.d.FaultType, result.d.FaultMessage);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            closeProcessing();
            handleError(JSON.parse(XMLHttpRequest.responseText));
        }
    });
}

//-------------------------User Sites-------------------------

function addSite() {    
    var siteDetails = new Object();
    siteDetails.name = $("#txtSiteName").val();
    siteDetails.url = $("#txtSiteUrl").val();

    if (siteDetails.name == "") {
        showInfo("Please enter the name for your site", false);
        return;
    }
        
    var urlRegEx = new RegExp("^http://[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$");
    if (!urlRegEx.test(siteDetails.url)) {
        showInfo("Please enter a valid url", false);
        return;
    }    

    showProcessing();
    
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/WebServices/EducoparkService.asmx/AddSite",
        data: JSON.stringify(siteDetails),
        dataType: "json",
        success: function(result, textStatus) {
            if (result.d.IsSuccess == 1) {
                closeProcessing();
                $("#lstSites").html($("#lstSites").html() + result.d.Result);
                $("#txtSiteName").val("");
                $("#txtSiteUrl").val("http://");
            }
            else {
                closeProcessing();
                handleFault(result.d.FaultType, result.d.FaultMessage);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            closeProcessing();
            handleError(JSON.parse(XMLHttpRequest.responseText));
        }
    });
}

function deleteSite(siteId, invocationElement) {    
    var siteDetails = new Object();
    siteDetails.userSiteId = siteId;            

    showProcessing();

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/WebServices/EducoparkService.asmx/DeleteSite",
        data: JSON.stringify(siteDetails),
        dataType: "json",
        success: function(result, textStatus) {
            if (result.d.IsSuccess == 1) {
                closeProcessing();
                $(invocationElement).parent().remove();
            }
            else {
                closeProcessing();
                handleFault(result.d.FaultType, result.d.FaultMessage);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            closeProcessing();
            handleError(JSON.parse(XMLHttpRequest.responseText));
        }
    });
}

//-------------------------Info/Fault-------------------------

function handleFault(faultType, faultMessage) {    
    if (faultType == FaultType.NotAuthenticated) {
        showInfo(faultMessage, true);
    }
    else if (faultType == FaultType.AlreadyVoted || faultType == FaultType.AlreadyReviewed || faultType == FaultType.UserSiteNotExists) {
        showInfo(faultMessage, false);
    }
    else {
        showInfo("The unknown error occured at the server. Sorry for the inconvineince. Please reopen your web browser", false);
    }
}

function handleError(error) {    
    showInfo("The unknown error occured at the server. Sorry for the inconvineince. Please reopen your web browser", false);  
}

function showInfo(text, showLogin) {
    $("#pnlInfo").dialog({
        autoOpen: false,
        bgiframe: true,
        resizable: false,
        width: 330,
        height: 130,
        minHeight: 130,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        }
    });
    
    if (showLogin) {
        $("#pnlInfo").dialog('option', 'buttons',
                {
                    'Login': function() {
                        $(this).dialog('close');
                        location.href = '/Users/Login';
                    },
                    Cancel: function() {
                        $(this).dialog('close');
                    } 
                });
    }
    else {
        $("#pnlInfo").dialog('option', 'buttons',
                {                   
                    Ok: function() {
                        $(this).dialog('close');
                    }
                });
    }
    
    $("#pnlInfoText").text(text);
    $("#pnlInfo").dialog('open');
}

//-------------------------Facebook Connect-------------------------

function fbConnect() {
    FB.ensureInit(function() {
        FB.Connect.requireSession(function() {
            FB.Connect.showPermissionDialog("offline_access", function(permissions) {                
                var fbUser = { fbUserId: FB.Connect.get_loggedInUser() };

                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/WebServices/EducoparkService.asmx/IsFBUserRegistered",
                    data: JSON.stringify(fbUser),
                    dataType: "json",
                    success: function(result) {
                        if (result.d == true) {
                            //Reload current page
                            window.location.reload();
                        }
                        else {
                            //Redirect to 'Just one more thing page'            
                            window.location.href = '/Users/JustOneMoreThing';
                        }
                    }
                });
            });
        });
    });
}

function fbConnectExistingUser() {
    FB.ensureInit(function() {
        FB.Connect.requireSession(function() {
            FB.Connect.showPermissionDialog("offline_access", function(permissions) {
                var fbUser = { fbUserId: FB.Connect.get_loggedInUser() };

                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/WebServices/EducoparkService.asmx/ConnectExistingUserToFB",
                    data: JSON.stringify(fbUser),
                    dataType: "json",
                    success: function(result) {
                        if (result.d.IsSuccess == 1) {
                            //Reload current page
                            window.location.reload();
                        }
                        else {
                            handleFault(result.d.FaultType, result.d.FaultMessage);
                        }
                    }
                });
            });
        });
    });
}

function fbPublishToWall(title, url, description, imageSrc) {
    FB.ensureInit(function() {        
        var attachment = {
            'name': title,
            'href': url,
            'description': description
        };
            
        if(imageSrc != null) {
            attachment['media'] = [{ 'type': 'image', 'src': imageSrc, 'href': url}];
        }
            
        FB.Connect.streamPublish('', attachment);
    });
}

//-------------------------ActiveUserHeader.ascx-------------------------

function ActiveUser_Submenus() {
    var _create = "<a class='add_talkie' href='/life-lessons/create'>Lesson</a><a class='add_talkie' href='/life-talks/create'>Talk</a><a class='add_talkie' href='/books/create'>Book</a>";
    var _manage = "<a class='add_talkie_manage' href='/life-lessons/manage'>Lessons</a><a class='add_talkie' href='/life-talks/manage'>Talks</a><a class='add_talkie' href='/books/manage'>Books</a>";
    var _profileEducopark = "<a class='edit' href='/users/edit'>Edit Profile</a><a class='change_pass' href='/users/changepassword'>New Password</a>";
    var _profileFacebook = "<a class='edit' href='/users/edit'>Edit Profile</a>";

    this.getCreate = getCreate;
    this.getManage = getManage;
    this.getProfile = getProfile;

    function getCreate() {
        return _create;
    }

    function getManage() {
        return _manage;
    }

    function getProfile(authenticationType) {
        if (authenticationType == UserAuthenticationType.Educopark) {
            return _profileEducopark;
        }
        else {
            return _profileFacebook;
        }
    }
}

var _ActiveUser_AvailableSubmenus = new ActiveUser_Submenus();

function activeUser_showSubmenu(submenu) {
    activeUser_hideAllSubmenus();
    $("#reg_user .menu_child_profile").html(submenu);
}

function activeUser_hideAllSubmenus() {
    $('#reg_user .menu_child_profile').html("");

}

//----------------------------------Rater-----------------------------------

function rater_initDynamicBehaviour(parentId) {
    $("#" + parentId + " .rating li").each(
        function(i) {            
            $(this).click(function() {
                rater_fixRate($(this).parent(), (i + 1)); 
                return false;
            });            
        });
}

function rater_flush(rater) {    
    $(rater).removeClass("onestar twostar threestar fourstar fivestar");
}

function rater_fixRate(rater, rate) {
    rater_flush(rater);
    var rateClass = rater_rateToClass(rate);
    $(rater).addClass(rateClass);
    $(rater).next().val(rate);
}

function rater_classToRate(cssClass) {
    if (cssClass.indexOf("onestar") != -1) {
        return 1;
    } else if (cssClass.indexOf("twostar") != -1) {
        return 2;
    } else if (cssClass.indexOf("threestar") != -1) {
        return 3;
    } else if (cssClass.indexOf("fourstar") != -1) {
        return 4;
    } else if (cssClass.indexOf("fivestar") != -1) {
        return 5;
    } else {
        return 0;
    }
}

function rater_rateToClass(rate) {    
    switch (rate) {
        case 1:
            return "onestar";            
        case 2:
            return "twostar";            
        case 3:
            return "threestar";            
        case 4:
            return "fourstar";            
        case 5:
            return "fivestar";
        default: 
            return "";    
    }
}

//-------------------------CuteEditor ImageSelector-------------------------

function ceImageSelector_callInsertImage(ceBrowseImageId) {
    var imageBrowser = $('#' + ceBrowseImageId).get(0);
    //Do this check because Cute Image Selector may not load yet when user wants to load it
    //if so, just wait for one second
    if (typeof (imageBrowser["FocusDocument"]) == 'undefined') {
        window.setTimeout("ceImageSelector_callInsertImage('" + ceBrowseImageId + "');", 1000);
        return;
    }
    imageBrowser.FocusDocument();
    var browserDoc = imageBrowser.GetDocument();
    $("#pnlThumbSelectorContainer").removeAttr("style");    
    imageBrowser.ExecCommand('new');    
    imageBrowser.ExecCommand('ImageGalleryByBrowsing');
    ceImageSelector_inputUrl(ceBrowseImageId);    
}

function ceImageSelector_inputUrl(ceBrowseImageId) {
    var imageBrowser = $('#' + ceBrowseImageId).get(0);
    var editdoc = imageBrowser.GetDocument();
    var imgs = editdoc.images;
    if (imgs.length > 0) {
        ceImageSelector_onImageSelected(imgs[imgs.length - 1].src);
        imageBrowser.ExecCommand('new');
        $("#pnlThumbSelectorContainer").attr("style", "visibility:hidden");        
    }
    else {        
        window.setTimeout("ceImageSelector_inputUrl('" + ceBrowseImageId + "');", 1000);        
    }
}    

//-------------------------Entity{Lesson,Talkie}/Manage.aspx-------------------------

function entityManage_showPnlConfirmDelete(callback) {    
    $("#pnlConfirmDelete").dialog({
        autoOpen: false,
        bgiframe: true,
        resizable: false,
        height: 140,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            "Delete": function() {         
                if (jQuery.isFunction(callback)) {
                    callback.apply();
                }                
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });

    $("#pnlConfirmDelete").dialog('open');
}

//-------------------------Talkies-------------------------

function fillScrollsWithJoinTalkieUserThumbs() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/WebServices/EducoparkService.asmx/GetJoinTalkieUserThumb",
        data: "{}",
        dataType: "json",
        success: function(result, textStatus) {
            if (result.d.IsSuccess == 1) {
                onJoinTalkieUserThumbReceived(result.d.Result, textStatus)
            }
            else {
                handleFault(result.d.FaultType, result.d.FaultMessage);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            handleError(JSON.parse(XMLHttpRequest.responseText));
        }
    });      
    }

function onJoinTalkieUserThumbReceived(userThumb, textStatus) {
    var titleAnchors = $("a.heading");
    $("div.left_talkie_container").each(
    function(i) {            
        var href = titleAnchors.get(i).href;
        filledUserThumb = userThumb.replace(/href=''/g, "href='" + href + "#Talk'");
        var thumbsCount = $(".user_name_container", this).length;
        $(this).append(filledUserThumb);
        if (thumbsCount == 1) {
            $(this).append(filledUserThumb);
        }
    });

    $('div.talkie_participants').each(
    function(i) {            
        var api = $(this).scrollable(
            {
                items: ".left_talkie_container",
                prevPage: ".left",
                nextPage: ".right",
                clickable: false,
                size: 3,
                api: true
            }
        );
            api.begin();
        
    });
}

//-------------------------StartUp-------------------------

$(function() {       
    $("input.search").val("");
    $("input.search").focus(function() {
        $(this).css({ background: '#FFF' });
    });
    $("input.search").blur(function() {
        if ($(this).val() == "") {
            $(this).css({ background: '#fff url(http://www.google.com/cse/intl/en/images/google_custom_search_watermark.gif) no-repeat 5px 3px' });
        }
    });
});

$(function() {
    var api = $("#pnlProcessing").overlay({ speed: 0, closeOnClick: false, api: true });

    // define function that opens the overlay 
    window.showProcessing = function() {
        api.load();
    }

    // define function that opens the overlay 
    window.closeProcessing = function() {
        api.close();
    }
});


//-------------------------Other Functions-------------------------

function logout() {
    //First LogOut From Facebook (deattach Facebook auth cookies)
    //Then Redirect From EducoPark (deattach EducoPark auth cookies)
    FB.ensureInit(function() {
        FB.Connect.ifUserConnected(
            function() { FB.Connect.logoutAndRedirect("/Users/Logout"); },
            function() { window.location.href = "/Users/Logout"; });
    });    
}

$.fn.maxLength = function(symbolsCount) {    
    return $(this).bind("keypress", symbolsCount, function(event) {        
        var key = event.which;
        //all keys including whitespace and return
        if (key >= 32 || key == 13) {
            var maxLength = event.data;
            var length = this.value.length;
            if (length >= maxLength) {
                event.preventDefault();
            }
        }
    }
    );
}

function preloadImages() {
    for (var i = 0; i < arguments.length; i++) {
        $("<img>").attr("src", arguments[i]);
    }
}

function isThisBrowserIE6() {
    return ((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined));
}

function isThisBrowserIE7() {    
    return (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
}

/*
Inserts GA using DOM insertion of <script> tag and "script onload" method to
initialize the pageTracker object. Prevents GA insertion from blocking I/O!

As suggested in Steve Souder's talk. See:
http://google-code-updates.blogspot.com/2009/03/steve-souders-lifes-too-short-write.html
*/

/* acct is GA account number, i.e. "UA-5555555-1" */
function gaSSDSLoad(acct) {
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."),
      pageTracker,
      s;
    s = document.createElement('script');
    s.src = gaJsHost + 'google-analytics.com/ga.js';
    s.type = 'text/javascript';
    s.onloadDone = false;
    function init() {
        pageTracker = _gat._getTracker(acct);
        pageTracker._trackPageview();
    }
    s.onload = function() {
        s.onloadDone = true;
        init();
    };
    s.onreadystatechange = function() {
        if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) {
            s.onloadDone = true;
            init();
        }
    };
    document.getElementsByTagName('head')[0].appendChild(s);
}





