﻿var hideLogin = false;
var currentCubeID=0;
var currentTab = 1;
var carouselStatus = new Array(STATUS_UNINITIALIZED, STATUS_UNINITIALIZED, STATUS_UNINITIALIZED, STATUS_UNINITIALIZED, STATUS_UNINITIALIZED);
var carouselNames=new Array('myHistoryCarousel','myElementsCarousel','myCubesCarousel','myFavoritesCarousel','myPeopleCarousel');
var carouselControlTypes=new Array(2,3,4,1,0);
var carouselInstances=new Array('','','','','');
var commentCarousel;
var commentCarouselStatus = STATUS_UNINITIALIZED;
var newsBitsCarouselsStatus = STATUS_UNINITIALIZED;
var resetComments=false;
var CANVAS_TAB = 4;
var loggedIn = false;
var cubeInfoLoaded = true;
var fb_title;
var fb_description;
var fb_logo;
var CurrentBrandColor;
var CurrentBrandImage;
var CurrentBrandLogo;
var CurrentBrandLink;
var CurrentBrandRepeatStyle;
var CurrentBrandBGPosition;
var defaultBackgroundColor;
var defaultBackgroundImage;
var defaultLogoImage;
var defaultLogoLink;
var defaultBrandRepeatStyle;
var defaultBrandBGPosition;
var firstLoad = true;

function SetContentAreaLocation(url) {
    if (url.toLowerCase().indexOf("viewcube")>-1 && !cubeInfoLoaded) {
        ShowCubeInfo();
    } else if (url.toLowerCase().indexOf("viewcube")==-1) {
        HideCubeInfo();
    } else {
//        alert(3);
    }
    $('#ifrm').attr("src", url);    
}

function IsFirstLoad() {
    if (firstLoad) {
        firstLoad = false;
        return true;
    } else {
        return false;
    }
}

function ShowCubeInfo() {
    $("#FactoidsDiv").hide();
    $("#CubeInfoControlDiv").show();
}

function HideCubeInfo() {
    $("#CubeInfoControlDiv").hide();
    $("#FactoidsDiv").show();
    if (newsBitsCarouselsStatus == STATUS_UNINITIALIZED) {
        $('#newsbitsCarousel').jcarousel({
            scroll: 1
        });
        $('#factoidsCarousel').jcarousel({
            scroll: 1
        });
    }
    //set fields for facebook
    $("#fb_title").attr("content", fb_title);
    $("#fb_description").attr("content", fb_description);
    $("#fb_logo").attr("href", fb_logo);
    
    SetDefaultBrandingInfo();
}

function SetDefaultBrandingInfo() {
    $('body').css("backgroundColor", defaultBackgroundColor);
    $('body').css("backgroundImage", defaultBackgroundImage);
    $('body').css("backgroundRepeat", defaultBrandRepeatStyle);
    $('body').css("backgroundPosition", defaultBrandBGPosition);
    $("#LogoImage").attr("src", defaultLogoImage);
    $("#LogoLink").attr("href", defaultLogoLink);
//    $("#LogoLink").attr("target", "ifrm");
}

function DownloadFileByID(id) {
    $('#hiddengetfileiframe').attr("src","GetFile.aspx?eid="+id);
}
var FBConnectLogout = false;
 
jQuery(document).ready(function() {

    //set default bg color and bg image
     defaultBackgroundColor =  $('body').css("backgroundColor");
     defaultBackgroundImage = $('body').css("backgroundImage");
     defaultBrandRepeatStyle = $('body').css("backgroundRepeat");
     defaultBrandBGPosition = $('body').css("backgroundPosition");
     defaultLogoImage = $("#LogoImage").attr("src");
     defaultLogoLink = $("#LogoLink").attr("href");
     //alert(defaultLogoImage);

    //fix bottom links
     jQuery.each(jQuery.browser, function(i) {
         if ($.browser.msie) {
             $("#BottomLinks").css("marginTop", "0");
         }
     });     

    //get the default facebook field info
    fb_title = $("#fb_title").attr("content");
    fb_description = $("#fb_description").attr("content");
    fb_logo = $("#fb_logo").attr("href");

    SetUpCarousel('myHistoryCarousel');
    SetUpCarouselVert('CommentsCarousel');
    commentCarouselStatus=STATUS_INITIALIZED;
    $("#ddlSearchTypes").selectbox();
    LoadCanvas();
    
//    ChangeTab(4,true)
    
    //create event handlers for forms
    $('#LoginBox').keydown(function(e){
        if (e.keyCode == 13) {
            DoLogin();
            return false;
        }
    });
    $('#PasswordBox').keydown(function(e){
        if (e.keyCode == 13) {
            DoLogin();
            return false;
        }
    });
    $('#SearchBox').keydown(function(e){
        if (e.keyCode == 13) {
            DoSearch();
            return false;
        }
    });
    if (hideLogin) {
        loggedIn=true;
        HideLoginControl();
    }

    FB_RequireFeatures(["XFBML"], function() {
                                                FB.Facebook.init($("#fbAppKey").val(), "xd_receiver.htm", {'reloadIfSessionStateChanged': false} );
                                                FB.ensureInit(function(){/*empty callback*/});
                                                FB.Facebook.get_sessionState().waitUntilReady(function() {
                                                 
                                                var api = FB.Facebook.apiClient;
                                                
                                                //alert(api.get_session().uid);
                                                CheckIfFBUserIDExists(api.get_session().uid); //check if the Facebook User is registered in Ucubd
                                                
                                                });
                                   }
    );
    if ($("#RewrittenUserID").val() != "0") {
        SetContentAreaLocation("memberprofile.aspx?id=" + $("#RewrittenUserID").val());
    }
   
});

function SetUpCarousel(name) {
//    alert('in setupmode:' + name);
   jQuery('#' + name).jcarousel( {
        itemVisibleOutCallback: 
        {
            onAfterAnimation:   
                function(carousel, item, i, state, evt) { 
                    onAfterAnimationHandler(carousel, item, i, state, evt); 
                }
        },
        itemLoadCallback: horizontalCarousel_itemLoadCallback,
        initCallback: onInitCarousel, 
        scroll: 5
    });
//    alert('done with setup:' + name);
}

//function SetUpNewsBitsCarousel(name) {
//   jQuery('#' + name).jcarousel( {
//        itemLoadCallback: Carousel_itemLoadCallback,
//        scroll: 1
//    });
//}

function SetUpCarouselVert(name) {
   jQuery('#' + name).jcarousel( {
        itemVisibleOutCallback: 
        {
            onAfterAnimation:   
                function(carousel, item, i, state, evt) { 
                    onAfterAnimationHandler(carousel, item, i, state, evt); 
                }
        },
        itemLoadCallback: commentsCarousel_itemLoadCallback,
        initCallback: onInitCommentCarousel, 
        scroll:3, 
        vertical: true
    });
}

function LoadChannels(cubeID) {

    currentCubeID=cubeID;
    var dataForWebService = "{_cubeID:" + cubeID + "}";
            
    $.ajax({
        type: "POST",
        url: "ScrollableListWebService.asmx/GetChannels",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
          LoadChannelsCallback(msg.d);
        },
        error: AjaxCallErrorHandler
    });
    
}

function HideLoginControl() {
    //hide the login control
    $('#LoginDiv').hide();
    $('.CanvasButtons').show();
    ShowLoggedInDiv();
    
}

function ShowLoginControl() {
    $('#LoginDiv').show();
    $('#LoggedInDiv').hide();
    $('#LoginLink').show();
    $('#LoginLink2').show();
    $('#LogOutLink').hide();
    $('#MyAccountLink').hide();
    $('#TemplatesLink').hide();
}

function HideLoginControlSlow() {
    //hide the login control
    $('#LoginDiv').hide();
    ShowLoggedInDiv();
}

function ShowLoggedInDiv() {
    $('#LoginLink').hide();
    $('#LoginLink2').hide();
    $('#LogOutLink').show();
    $('#MyAccountLink').show();
    $('#TemplatesLink').show();
    FillInLoggedInDivInfo();
}

function LoadChannelsCallback(channelItems) {
    for (var x=0;x<channelItems.length;x++) {
        var item = channelItems[x];
        GenerateChannel(item, x+1);
    }
}

function GenerateChannel(item, index) {
    var html = '<a href="javascript:SetContentAreaLocation(\'' + item.LinkURL + '\');"><img src="' + item.ImageURL + '" border="0" class="ChannelImageItem" /></a>';
    $('#Channel' + index).html(html);
}

function TrimExpiringURL(url) {
    try {
        if (url.indexOf("?") > 1) {
            return url.substring(0, url.indexOf("?"));
        } else {
            return url;
        }
    } catch (ex) {
        return "";
    }        
}


function GetCubeInfo(cubeID, cubeName, cubeDescription, cubeImageURL, BrandingColor, BrandImage, BrandLogo, BrandLink, BrandRepeatStyle, BrandingBGPosition) {

    //set fields for facebook
    $("#fb_title").attr("content", cubeName);
    $("#fb_description").attr("content", cubeDescription);
    $("#fb_logo").attr("href", cubeImageURL);
    
    //set branding elements
    if (CurrentBrandColor != BrandingColor && typeof BrandingColor != 'undefined') {
        CurrentBrandColor = BrandingColor;
        if(BrandingColor == 'default') {
            $('body').css("backgroundColor", defaultBackgroundColor);
        } else {
            $('body').css("backgroundColor", BrandingColor); 
        }
    }

    if (TrimExpiringURL(CurrentBrandImage) != TrimExpiringURL(BrandImage) && typeof BrandImage != 'undefined') {
        CurrentBrandImage = BrandImage;
        if (BrandImage == 'default') {
            $('body').css("backgroundImage", defaultBackgroundImage);
        } else {
            $('body').css("backgroundImage", "url(" + BrandImage + ")");
        }
    }

    if (CurrentBrandRepeatStyle != BrandRepeatStyle && typeof BrandRepeatStyle != 'undefined') {
        CurrentBrandRepeatStyle = BrandRepeatStyle;
        if (BrandRepeatStyle == 'default') {
            $('body').css("backgroundRepeat", defaultBrandRepeatStyle);
        } else {
            $('body').css("backgroundRepeat", CurrentBrandRepeatStyle);
        }
    }

    if (CurrentBrandBGPosition != BrandingBGPosition && typeof BrandingBGPosition != 'undefined') {
        CurrentBrandBGPosition = BrandingBGPosition;
        if (BrandingBGPosition == 'default') {
            $('body').css("backgroundPosition", defaultBrandBGPosition);
        } else {
            $('body').css("backgroundPosition", CurrentBrandBGPosition);
        }
    }

    if (CurrentBrandLogo != BrandLogo && BrandLogo != "" && typeof BrandLogo != 'undefined') {
        CurrentBrandLogo = BrandLogo;
        if(BrandLogo == 'default' || BrandLogo == defaultLogoImage) {
            $("#LogoImage").attr("src", defaultLogoImage);
            $('.LogoBackgroundCell').css("backgroundImage", "url(images/channels_area/logo-glass-bg-cutoff.png)");
            //alert(defaultLogoImage);
        } else {
            $("#LogoImage").attr("src", BrandLogo);
            $('.LogoBackgroundCell').css("backgroundImage", "url(images/channels_area/logo-glass-bg.png)");
        }
    } else if (BrandLogo == "") {
            $('.LogoBackgroundCell').css("backgroundImage", "url(images/channels_area/logo-glass-bg-cutoff.png)");        
    }

    if (CurrentBrandLink != BrandLink && typeof BrandLink != 'undefined') {
        if (BrandLink == '') {
            BrandLink = 'default';
        }
        CurrentBrandLink = BrandLink;
        if(BrandLink == 'default') {
            $("#LogoLink").attr("href", defaultLogoLink);
            $("#LogoLink").removeAttr("target");
            //alert("default " + defaultLogoLink);
        } else {
            $("#LogoLink").attr("href", BrandLink);
            $("#LogoLink").attr("target", "_blank");
           // alert("brand link " + BrandLink);
        }
    }
    
    var dataForWebService = "{_cubeID:" + cubeID + "}";
            
    LoadChannels(cubeID);
     
    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/GetCubeInfo",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
          CubeInfoCallback(msg.d);
        },
        error: AjaxCallErrorHandler
    });
    
}

function CubeInfoCallback(cubeInfo) {
    ShowCubeInfo();
    $('#ViewCreator').attr("href","javascript:SetContentAreaLocation('MemberProfile.aspx?id="+cubeInfo.CreatorID+"');");
    var cubeCreatorString = "<a href='javascript:SetContentAreaLocation(\"MemberProfile.aspx?id=" + cubeInfo.CreatorID + "\");'>" + cubeInfo.CreatorName + '</a>';
    $('.CubeCreator').html(cubeCreatorString);
    $('.CubeDescription').html(cubeInfo.Description);
    $('#UserAvatar').attr('src',cubeInfo.CreatorAvatarUrl);
    
    //update comments label
    $('#CommentsLabel').html('Comments (0)');
    //update comments carousel
    if (commentCarouselStatus == STATUS_UNINITIALIZED) {
        SetUpCarouselVert('CommentsCarousel');
    } else {
        commentCarousel.reset();
    }
}

function horizontalCarousel_itemLoadCallback(carousel, state) {
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }
    
    var carouselID=carousel.container[0].id;
    
    var dataForWebService = "{_listType:" + carouselControlTypes[GetIndexByName(carouselID)] + ",_startIndex:" + carousel.first + ",_endIndex:" + carousel.last + "}";
 
    $.ajax({
        type: "POST",
        url: "ScrollableListWebService.asmx/GetSideScrollingControlItems",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
        horizontalCarousel_itemAddCallback(carousel, carousel.first, carousel.last, msg.d);
        },
        error: AjaxCallErrorHandler
    });
}
 
function horizontalCarousel_itemAddCallback(carousel, first, last, valuesContainer) {
    var values=valuesContainer.ListItems;
    carousel.size(valuesContainer.TotalLength);
    
    for (var x=0;x<values.length;x++) {
        var item = values[x];
        if (item.ImageURL!=null) {
            var itemName = carousel.container[0].id + "Item" + x;
            carousel.add(first + x, controlPanelCarousel_getItemHTML(item, itemName, carousel.container[0].id));
            CreateToolTip(itemName);
        }
    }
}

function CreateToolTip(itemName) {
    //alert(': ' + itemName);
    $("#" + itemName).cluetip({
          hoverClass: 'highlight',
          cluetipClass: 'jtip', 
          sticky: false,
          closePosition: 'title',
          waitImage: true,
          arrows: true,
          closeText: '<img src="js/cluetip/images/cross.png" border="0">',
          //truncate: 60,
          showTitle: false,
          hoverIntent: {
                            sensitivity:  3,
                            interval:     50,
                            timeout:      0
          }
    });
}

function controlPanelCarousel_getItemHTML(item, itemName, carouselName) {
    var linkSuffix='';
    //adjust link
    if (item.ItemType == ITEM_TYPE_ELEMENTS) {
        switch (carouselName) {
            case "myHistoryCarousel":
                linkSuffix = "&listType=2";
                break;
            case "myElementsCarousel":
                linkSuffix = "&listType=3";
                break;
        }
    }
    var imagestring = '<a href="javascript:SetContentAreaLocation(\'' + item.LinkURL + linkSuffix + '\');" id="' + itemName + '" tsitle="' + item.Title + '" rel="' + item.ToolTipURL + '"><img src="' + item.ImageURL + '" width="30" height="36" alt="" border="0" /></a>';
//    alert(imagestring);
    return imagestring;
}

function onAfterAnimationHandler(carousel, item, i, state, evt) {
    carousel.remove(i);
}

function commentsCarousel_getItemHTML(item) {
    return '<table border="0" cellspacing="0" cellpadding="0" class="SingleCommentTable"><tr><td class="CommentImageCell"><div><img src="' + item.ImageURL + '" class="CommentImage" alt="" border="0" /></div><div class="CommentUserName">' + item.UserName + '</div></td><td style="background-image: url(images/CubeInfoArea/comment-bg2.gif);width:160px;height:35px;" class="CommentCell">' + item.Comment + '</td></tr></table>';
}

function commentsCarousel_itemLoadCallback(carousel, state) {

    // Check if the requested items already exist
//    if (carousel.has(carousel.first, carousel.last)) {
//        return;
//    }
        
//    var carouselID=carousel.container[0].id;
    var dataForWebService = "{_mashupID:" + currentCubeID + ",_startIndex:" + carousel.first + ",_endIndex:" + carousel.last + "}";
 
    $.ajax({
        type: "POST",
        url: "ScrollableListWebService.asmx/GetComments",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
        commentsCarousel_itemAddCallback(carousel, carousel.first, carousel.last, msg.d);
        },
        error: AjaxCallErrorHandler
    });
    //alert('c');
}
 
function commentsCarousel_itemAddCallback(carousel, first, last, valuesContainer) {
    var values=valuesContainer.ListItems;
    carousel.size(valuesContainer.TotalLength);
    
    //update comments label
    $('#CommentsLabel').html('Comments (' + valuesContainer.TotalLength + ')');
    
    //if there are no comments, hide the carousel
    if (valuesContainer.TotalLength == 0) {
        //alert('hiding');
        $('#cubeCommentsCarousel').hide();
    } else {
        //alert('showing');
        $('#cubeCommentsCarousel').show('slow');
    }
    
    for (var x=0;x<values.length;x++) {
        var item = values[x];
        carousel.add(first + x, commentsCarousel_getItemHTML(item));
    }
}

function DoLogin() {

//    var dataForWebService = "{_userName:'" + $("#LoginBox").val() + "',_passWord:'" + $("#PasswordBox").val() + "'}";
////    alert(dataForWebService);
//    $.ajax({
//        type: "POST",
//        url: "UtilityWebService.asmx/LoginUser",
//        data: dataForWebService,
//        contentType: "application/json; charset=utf-8",
//        dataType: "json",
//        success: function(msg) {
//            LoginCallBack(msg.d);
//        },
//        error: AjaxCallErrorHandler

//    });

    DoUserLogin($("#LoginBox").val(), $("#PasswordBox").val());

}

function DoUserLogin(username, password) {

    var dataForWebService = "{_userName:'" + username + "',_passWord:'" + password + "'}";
//    alert(dataForWebService);
    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/LoginUser",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            LoginCallBack(msg.d);
        },
        error: AjaxCallErrorHandler

    });

}

function onInitCarousel(carousel, state) { 
    if (state == 'init') { 
        var carouselID=carousel.container[0].id;
        carouselInstances[GetIndexByName(carouselID)] = carousel;
    } 
} 

function onInitCommentCarousel(carousel, state) { 
    if (state == 'init') {
        commentCarousel = carousel;
    } 
} 

function LoginCallBack(msg) {
    if (msg == true) {
        JustLoggedIn();
        loggedIn=true;
        ChangeTab(4);
    } else {
        //show the wide login page in the content area with error message
        SetContentAreaLocation('LoginForm.aspx?invalid=true');
    }
}

function DoSearch() {

    var targetSearchUrl;
    switch ($("#ddlSearchTypes").val()) {
        case 'SearchAll':
            //targetSearchUrl = 'ListPage.aspx?listType=5&searchByUser=false&searchTerm=' + $('#SearchBox').val();
            SearchAllContent($('#SearchBox').val());
            break;
        case 'SearchPeople':
            //targetSearchUrl = 'ListPage.aspx?listType=8&searchByUser=false&searchTerm=' + $('#SearchBox').val();
            SearchPeople($('#SearchBox').val());
            break;
        case 'SearchCubes':
            //targetSearchUrl = 'ListPage.aspx?listType=7&searchByUser=false&searchTerm=' + $('#SearchBox').val();
            SearchCubes($('#SearchBox').val());
            break;
        case 'SearchElements':
            //targetSearchUrl = 'ListPage.aspx?listType=6&searchByUser=false&searchTerm=' + $('#SearchBox').val();
            SearchElements($('#SearchBox').val());
            break;
    }
    //SetContentAreaLocation(targetSearchUrl);

}

function SearchPeople(searchTerm) {
    SetContentAreaLocation('ListPage.aspx?listType=8&searchByUser=false&searchTerm=' + searchTerm);
}

function SearchCubes(searchTerm) {
    SetContentAreaLocation('ListPage.aspx?listType=7&searchByUser=false&searchTerm=' + searchTerm);
}

function SearchElements(searchTerm) {
    SetContentAreaLocation('ListPage.aspx?listType=6&searchByUser=false&searchTerm=' + searchTerm);
}

function SearchAllContent(searchTerm) {
    SetContentAreaLocation('ListPage.aspx?listType=5&searchByUser=false&searchTerm=' + searchTerm);
}

function CheckLoginState(targetFunctionOnSuccess, targetFunctionOnFail) {

    var dataForWebService = "{}";

    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/IsUserLoggedIn",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            if (msg.d == true) {
                targetFunctionOnSuccess();
            } else {
                targetFunctionOnFail();
            }
        },
        error: AjaxCallErrorHandler
    });
    
}

function ShowWriteCommentDiv() {
    $("#CommentsCarousel").hide();
    $("#WriteCommentDiv").show();
    $("#WriteCommentButton").hide();
    $("#InputComment").focus();        
}

function CannotWriteComment() {
    SetContentAreaLocation("LoginForm.aspx");
}

function WriteComment() {
    CheckLoginState(ShowWriteCommentDiv, CannotWriteComment);
}

function HideComment() {
    $("#WriteCommentDiv").hide();
    $("#CommentsCarousel").show();
    $("#WriteCommentButton").show();
}

function WriteCubeComment(cubeID, comment) {

//    var comment = $("#InputComment").val();
    var dataForWebService = "{_commentText:'" + comment.replace(/'/g, "\\'") + "', _mashupID:" + cubeID + "}";

    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/SaveComment",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
          SubmitCommentCallback(msg.d);
        },
        error: AjaxCallErrorHandler
    });
    
}

function SubmitComment() {

//    var comment = $("#InputComment").val();
//    var dataForWebService = "{_commentText:'" + comment.replace(/'/g, "\\'") + "', _mashupID:" + currentCubeID + "}";
////        alert(dataForWebService);

//    $.ajax({
//        type: "POST",
//        url: "UtilityWebService.asmx/SaveComment",
//        data: dataForWebService,
//        contentType: "application/json; charset=utf-8",
//        dataType: "json",
//        success: function(msg) {
//          SubmitCommentCallback(msg.d);
//        },
//        error: AjaxCallErrorHandler
//    });

    WriteCubeComment(currentCubeID, $("#InputComment").val());

}

function SubmitCommentCallback(msg) {
    
    //resetComments=true;
    //commentCarousel.reset();
    //SetUpCarouselVert('CommentsCarousel');
    HideComment();
    commentCarousel.reset();
    $("#InputComment").val("");
    //alert('saved');
}

function JustLoggedIn() {
    if (currentTab != CANVAS_TAB) {
        carouselInstances[GetIndexByName(GetCarouselNameByTabNumber(currentTab))].reset();
        carouselStatus[GetIndexByName(GetCarouselNameByTabNumber(currentTab))] = STATUS_INITIALIZED;
    }
    loggedIn=true;
    HideLoginControlSlow();
    ShowLoggedInDiv();
    LoadCanvas();
    $(".CanvasButtons").show();
}

function FillInLoggedInDivInfo() {

    var dataForWebService = "{}";

    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/GetLoggedInUser",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
          FillInLoggedInDivInfoCallback(msg.d);
        },
        error: AjaxCallErrorHandler
    });
}

function FillInLoggedInDivInfoCallback(user) {
    $(".WelcomeCell").html("Welcome " + user.FirstName + "!");
//    $("#MyAccountLink").html('<a href="javascript:SetContentAreaLocation(\'registerbody.aspx\');">[My Account]</a>');
    $("#LogOutDiv").html('<a href="javascript:DoLogOut();">[Log Out]</a>');
    $('#LoggedInDiv').show();
}

function DoLogOut() {

    var dataForWebService = "{}";

    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/LogOutUser",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            loggedIn = false;
            FB.Connect.logout(function() { });
            FBConnectLogout = true;
            SetContentAreaLocation("ViewCube.aspx");
//            $(".CanvasButtons").hide();
            LoadCanvas();
            ShowLoginControl();
            ChangeTab(1);
        },
        error: AjaxCallErrorHandler
    });
    
    //alert('logging out');
}

function TriggerHistoryAreaUpdate() {
    try {
        carouselInstances[GetIndexByName("myHistoryCarousel")].reset();
    } catch (ex) {
        setTimeout('TriggerHistoryAreaUpdate()', 1500);
    }
}

function publishToFacebook(bundle_template_id, cube_id) {
    FB_RequireFeatures(["XFBML"], 
                        function() { 
	                                FB.Facebook.init(   $("#fbAppKey").val(), 
	                                                    "xd_receiver.htm", 
	                                                    {'doNotUseCachedConnectState':true}
	                                );  //close init
	                                FB.ensureInit(function() {
                                                                //make sure that FB libraries are ready to use
                                    });  // close ensureInit
  
                                    var template_data = {
                                                            "images":[  {"src":"http:\/\/www.ucubd.com\/UcubdImageServer\/ShowMashupImage_" + cube_id + ".gif",
                                                                         "href":"http:\/\/www.ucubd.com\/index.aspx?id=" + cube_id}
                                                                     ]
                                                        };  //close templatedata array
  
                                    var FiredOnce = 1;
                                    
                                    function FBConnected() {
                                                                if (FiredOnce == 1) { //there is a facebook bug that fires this function twice
                                                                    //alert("i'm connected");
                                                                    FB.Connect.showFeedDialog(bundle_template_id, template_data, null, null, null, FB.RequireConnect.doNotRequire, callback, null, null );
                                                                }
                                                                FiredOnce ++;
                                    }
  
                                    function FBNotConnected() {
                                        //alert("i'm not connected");
                                        if(!FBConnectLogout)
                                        {
                                            if(confirm("Would you like to publish this cube to your Facebook feed?")) {
                                                FB.Connect.showFeedDialog(bundle_template_id, template_data, null, null, null, FB.RequireConnect.promptConnect, callback, null, null );
                                            } else {
                                            //do nothing
                                            }
                                        }
                                    }
  
                                    function callback() {
                                        //alert("done");
                                    }
   
                                    FB.Connect.ifUserConnected(FBConnected, FBNotConnected);
                        }
    );
}
    
function DoFacebookConnect() {
//alert("i'm in facebookconnect");
    var dataForWebService = "{}";
     
    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/DoFacebookConnect",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
          DoFacebookConnectCallback(msg.d);
        },
        error: AjaxCallErrorHandler
    });

}

function DoFacebookConnectCallback(connectInfo) {
    if (connectInfo.LoginSuccess) {
        JustLoggedIn();
    } else {
        SetContentAreaLocation(connectInfo.RedirectURL);
    }
}

function AddToFavorites(cubeID) {
    AddToFavoritesWrapper(cubeID);
}

function AddToFavoritesWrapper(id) {

    if (!loggedIn) {
        SetContentAreaLocation('LoginForm.aspx?target='+encodeURIComponent('viewcube.aspx?autoadd=true&id='+id));
        return;
    }

    var dataForWebService = "{_cubeID: " + id + "}";
     
    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/AddToFavorites",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function() {
            ChangeTab(5);            
            carouselInstances[GetIndexByName(GetCarouselNameByTabNumber(5))].reset();
        },
        error: AjaxCallErrorHandler
    });

}

function AddToFriends(userID) {
    AddToFavoritesWrapper(userID);
}

function AddToFriendsWrapper(id) {

    if (!loggedIn) {
        SetContentAreaLocation('LoginForm.aspx?target='+encodeURIComponent('memberprofile.aspx?autoadd=true&id='+id));
        return;
    }
    
    var dataForWebService = "{_userID: " + id + "}";
     
    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/AddToFriends",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function() {
            ChangeTab(6);            
            carouselInstances[GetIndexByName(GetCarouselNameByTabNumber(6))].reset();
        },
        error: AjaxCallErrorHandler
    });

}

function ShareWithFriends(cubeID) {
    SetContentAreaLocation('TellFriend.aspx?MashupID=' + cubeID);
}

function CheckIfFBUserIDExists(FBUserID) {

//alert("i'm in CheckIfFBUserIDExists");
    var dataForWebService = "{_FacebookUserID : '" + FBUserID + "'}";
     
    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/IsRegisteredFBUserID",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            if (msg.d == true) {
//            alert("i'm in CheckIfFBUserIDExists");
                DoFacebookConnect(); 
            } else {
//            alert("doesn't exist");   
            }
        },
        error: AjaxCallErrorHandler
    });
}

function FacebookLoginButton()
{
   DoFacebookConnect();
}


function LoadCanvas() {

    $(".CanvasDiv").html('<img src="images/new_overlay/ajax-loader2.gif" border="0" class="CanvasLoadingImage" />');

//    var dataForWebService = '{_id:' + getQueryVariable("id") + '}';
    
    var dataForWebService = '{}';
    
    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/GetCanvas",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
          RenderCanvas(msg.d);
        },
        error: AjaxCallErrorHandler
    });
}
    
function RenderCanvas(canvas) {
    //alert(canvas);
    $(".CanvasDiv").html(canvas);
}
function GetCurrentTabLabel() {
    return GetTabLabel(currentTab);
}

function GetTabLabel(tabNumber) {
    switch (tabNumber) {
        case 1:
            return "History";
            break;
        case 2:
            return "My Elements";
            break;
        case 3:
            return "My Cubes";
            break;
        case 4:
            return "My Canvas";
            break;
        case 5:
            return "My Favorites";
            break;
        case 6:
            return "My People";
            break;
    }    
}

function SetTabLabel(label)
{
    document.getElementById("TabLabel").innerHTML = label;
}

function ClearTabLabel()
{
    document.getElementById("TabLabel").innerHTML = GetCurrentTabLabel();
}

function GetCarouselNameByTabNumber(tabNumber) {
    var carouselName;
    switch (tabNumber) {
        case 1:
            carouselName = 'myHistoryCarousel';
            break;
        case 2:
            carouselName = 'myElementsCarousel';
            break;
        case 3:
            carouselName = 'myCubesCarousel';
            break;
        case 5:
            carouselName = 'myFavoritesCarousel';
            break;
        case 6:
            carouselName = 'myPeopleCarousel';
            break;
    }
    //alert(carouselName);
    return carouselName;
}

//var debugMode = 'true';

function ChangeTab(tabNumber, ignoreLogin) {

    if (ignoreLogin == undefined) {
        ignoreLogin = false;
    }
    
    
    if ((!loggedIn && tabNumber>1) && !ignoreLogin) {
        SetContentAreaLocation("LoginForm.aspx?tabNumber="+tabNumber);
        ChangeTab(1);
        return;
    }

    currentTab = tabNumber;
    for (i=1;i<=6;i++) {
        if (i == tabNumber) {
            document.getElementById("TabUnderline" + i).style.display="none";
            document.getElementById("TabDiv" + i).style.display="block"; 
            
            //if the carousel on the tab is not set up yet, set it up
            var carouselName=GetCarouselNameByTabNumber(tabNumber);
            if (carouselStatus[GetIndexByName(carouselName)] == STATUS_UNINITIALIZED) {     //if it is the first time opening the tab
                SetUpCarousel(carouselName);
                carouselInstances[GetIndexByName(carouselName)].reset();
                carouselStatus[GetIndexByName(carouselName)] = STATUS_INITIALIZED;
            } else if (carouselStatus[GetIndexByName(carouselName)] == STATUS_NEEDS_RESET) {    //if a reset is needed
            carouselInstances[GetIndexByName(carouselName)].reset();
                carouselStatus[GetIndexByName(carouselName)] = STATUS_INITIALIZED;
            }
        } else {
            //document.getElementById("TabUnderline" + i).src="images/ControlPanel/underline_gray.gif"; 
            document.getElementById("TabUnderline" + i).style.display="block";
            document.getElementById("TabDiv" + i).style.display="none"; 
        }
    }
    document.getElementById("TabLabel").focus();
    return false;
}

function SubmitFeedback() {
    
    var dataForWebService = "{_feedback:'" + $("#feedbackBox").val() + "'}";
            
    $.ajax({
        type: "POST",
        url: "UtilityWebService.asmx/SubmitFeedback",
        data: dataForWebService,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function() {
            $("#FeedbackForm").hide();
            $("#FeedbackThanks").show();
        },
        error: function() {
            $("#FeedbackForm").hide();
            $("#FeedbackThanks").show();
        }
    });
}

function IsUserLoggedIn() {
    return loggedIn;
}