﻿///<reference path="Utils.js" />
///<reference path="WebUtils.js" />

var friendsList = null;
function InitFriendsList(userId, contentId, uid, sessionId, contentUserId) {
    if (friendsList == null) {
        onSuccess = function(result) {
            friendsList = result.d;
            initFriendsInput(userId, contentId, uid, contentUserId);
        };
        onFailure = function(result) {
            alert("Error")
        };

        callWebService("{uid:'" + uid + "',sessionId:'" + sessionId + "'}", "GetFriendsList", onSuccess, onFailure);
    }
    else {
        initFriendsInput(userId, contentId, uid, contentUserId);
    }
}

function initFriendsInput(userId, contentId, uid, contentUserId) {
    initAutoComplete(userId, contentId, uid, contentUserId);
    ShowPanel("pnlFriendsList");
    HidePanel("pnlLoading");
}

function initAutoComplete(userId, contentId, uid, contentUserId) {
    $("#firendsList").autocomplete(friendsList, {
        dataType: "json",
        parse: function(data) {
            return $.map(data, function(row) {
                return {
                    data: row,
                    value: row.Value,
                    result: row.Caption
                }
            });
        },
        formatItem: function(item) {
            return item.Caption;
        }
    });

    $("#firendsList").result(function(event, data, formatted) {
        addTag(data, userId, contentId, uid, contentUserId);
    });
}

function addTag(item, userId, contentId, uid, contentUserId) {
    onSuccess = function(result) {
        addTagNotification(item.Text, result.d);
    };
    onFailure = function(result) { alert("Error") };

    //int contentId, int taggerUserId, string taggedUserId, string tagText, eServiceTypes serviceType
    var params = "{contentId:'" + contentId + "',contentUserId:'" + contentUserId + "',taggerUserId:'" + userId + "',taggedUserId:'" + item.Value + "',tagText:'" + item.Text + "',serviceType:'3'}"
    callWebService(params, "AddTag", onSuccess, onFailure);
}

function addTagNotification(name, result) {
    var html;
    switch (result) {
        case 1:
            html = "<br/><strong>" + name + "</strong> was tagged";
            break;
        case 2:
            html = "<br/><strong>" + name + "</strong> is already tagged <br/> in this video";
            break;
        default:
            html = "<br/>There has been an error, <br/> please try again later";
    }

    $("#pnlTagNotification").html(html);
    $("#firendsList").val("");
}

function EndTagAction() {
    $("#pnlTagNotification").html("");
    $("#firendsList").val("");
    HidePanel('tagPanel');
    ShowPanel('userLinks'); 
}