﻿function loadList(listToLoad) {

    $('.listPanel').each(function () {
        if ($(this) != $(listToLoad)) {
            //if ($(this).css('display') != 'none') {
            $(this).hide();
            //}
        }
    });
    //$(this).show('blind', 300);
    if ($(listToLoad).css('display') == 'none') {
        $(listToLoad).show('blind', 300);
        var loaded = $(listToLoad).hasClass('loaded');

        if (listToLoad == '#diaryPanel') {
            if (loaded == true) {
                $(listToLoad).smartdiary('scrollToHour', 10);
            }
            else {
                loadDiary();
                $(listToLoad).addClass('loaded')
            }
        }
        else if (loaded == false) {
            if (listToLoad == '#contactList')
                loadSmartList(1, undefined, undefined);
            else if (listToLoad == '#accountList')
                loadSmartList(2, undefined, undefined);

            else if (listToLoad == '#opportunityList')
                loadSmartList(3, undefined, undefined);

            else if (listToLoad == '#supportList')
                loadSmartList(7, undefined, undefined);

            else if (listToLoad == '#appointmentList')
                loadSmartList(5, undefined, undefined);

            else if (listToLoad == '#taskList')
                loadSmartList(6, undefined, undefined);
        }
    }

}

function loadCalendars(callBack) {

    if ($("#diaryPanel").data('calendars') == null) {

        var service = "/Services/DefaultService.svc/GetCalendar";

        var data = { "smartid": $('#usercred').data('sid'), "userid": $('#usercred').data('uid') };

        $.ajax({
            url: service,
            data: JSON.stringify(data),
            success: function(msg)
            { onLoadCalendars(callBack, msg); }
        });
    }
    }
    
function onLoadCalendars(callBack, msg) {

    var cals = new Array();
    
    var last = false;

    for (var i = 0; i < msg.d.length; i++) 
    {
        var cal = { 'id': msg.d[i].CalendarId, 'title': msg.d[i].CalendarName };

        cals.push(cal);

        if (i+1 == msg.d.length)
        {
            last = true;
            $("#diaryPanel").data('calendars', cals);
        }
        loadResource(msg.d[i].CalendarId, last);
    }
}

    
function loadResource(calendarId, last) {

    if ($("#diaryPanel").data('resource') == null) {
        var service = "/Services/DefaultService.svc/GetCalendarResource";

        var data = { "calendarid": calendarId, "userid": $('#usercred').data('uid') };

        $.ajax({
            url: service,
            data: JSON.stringify(data),
            success: function(msg)
            { onLoadResources(calendarId, msg, last); }
        });
    }
}
function onLoadResources(calendarId, msg, last) {

    var res = $("#diaryPanel").data('calendarResources');

    if (res == null) res = new Array();

    for (var i = 0; i < msg.d.length; i++) {

        var re = { 'calendarId': calendarId, 'id': msg.d[i].ResourceId, 'title': msg.d[i].ResourceName, 'index':msg.d[i].ResourceIndex };

        res.push(re);
    }
    res = res.sort(function (a, b) {
        var ai = a.index;
        var bi = b.index;
        return (ai < bi) ? -1 : (ai > bi) ? 1 : 0;
    });

    $("#diaryPanel").data('calendarResources', res);
    if (last == true) {
        GetResource(null);
       //loadDiary();
    }
    }

function GetCalendars() 
{
    return $("#diaryPanel").data('calendars');
}

function GetResource(calendarId) {

    if (calendarId == null) {
        var cals = $("#diaryPanel").data('calendars');
        calendarId = cals[0].id;
    }

    var res = new Array();

    var resources = $("#diaryPanel").data('calendarResources');

    for (var i = 0; i < resources.length; i++) {
        if (resources[i].calendarId == calendarId) {
            var resource = { 'id': resources[i].id, 'title': resources[i].title };
            res.push(resource);
        }
    }
    $("#diaryPanel").data('resources', res);
}

firstLoadCalendar = function () {
    if ($("#diaryPanel").data('resources') != null)
        loadList('#diaryPanel');
    else
        setTimeout('firstLoadCalendar();', 500);
}

 function loadDiary() {

     //var $smartdiary = $('#diaryPanel');
     $smartdiary.smartdiary("loadCalendarWithData");
 }

function loadCalendarListClick() {

    if ($('#homeList').css('display') != 'none') {
        $('#homeList').toggle('blind', 500);
    }
    if ($('#contactList').css('display') != 'none') {
        $('#contactList').toggle('blind', 500);
    }
    if ($('#calendarList').css('display') == 'none') {
        $('#calendarList').toggle('blind', 500);
    }
}
function loadSmartList(toe, gb, ih)
{
    var r, c, uri,pl,lDiv,sList,jsonData,oldH,newH,iS,sList;
    pl = ih == true ? 'home' : 'page';
    r = 5;
    if (ih == true)
        r = 15;
    else if (gb == undefined)
        r = 10;
    c = 0;
    uri = smartListService(toe);
    lDiv = $('.sd-'+pl + 'div-' + toe);
    if (lDiv.hasClass('loaded')) {
        if (ih == true)
            sList = $('.sd-' + pl + 'list-' + toe);
        else
            sList = $('.sd-' + pl + 'list-' + toe + '-' + gb.replace(/ /g, ''));
        c = sList.children().length;
        if (c < 0) c = 0;
        sList.append('<li class=\'loading\'></li>');
    }
    jsonData = { 'smartid': $('#usercred').data('sid'), 'count': r, 'skip': c };
    if (gb != undefined) {
        if (toe == 5) {
            var dt = new Date(gb);
            var st = new Date();
            var fin = new Date();
            if (dt < st)
                lDiv.data('start', dt);
            else if (dt > fin)
                lDiv.data('finish', dt);
            //jsonData['gb'] = gb.toDateString();
        }
        //else {
        jsonData['gb'] = gb;
        //}
    }
    else if (toe == 5 && ih != true) {
        var today = new Date();
        lDiv.data('start', new Date(today.getFullYear(), today.getMonth(), today.getDate() - 3));
        lDiv.data('finish', new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7));
    }
//    else if (toe != 5 && ih != true) {
//    $.ajax({ type: "POST", url: '/Services/DefaultService.svc/EntityListGB', data: JSON.stringify({ 'sid': $('#usercred').data('sid'),'entity':toe }),
//         dataType: "json",
//        success: function(msg) {
//            if (msg.d != null) {
//                for (var gg = 0; gg < msg.d.length; gg++) {
//                    gbList.push(msg.d[gg]);
//                }
//            }
    //        }



//    });
//    }
    var t = toe != 5 || ih == true ? 1 : (gb != undefined ? 7 : 7);
    if (t == 1 && toe == 1 && ih != true && gb == undefined)
        t = 50;

    for (var r = 0; r < t; r++) {
            jsonData['seq'] = r;
            if (toe == 5) {
                if (t > 1 && gb == undefined) {
                    jsonData['gb'] = new Date().toDateString();
                }
            }
            $.ajax({ type: "POST", url: uri, data: JSON.stringify(jsonData),
                 dataType: "json",
                success: function(msg) {
                    oldH = ''; newH = '';
                    if (msg.d.length == 0 && toe != 5)
                        r = 50;
                    for (var i = 0; i < msg.d.length; i++) {
                        iS = msg.d[i];
                        if (iS.gbdate != null) {
                            var gdt = JsonToJavaDate(iS.gbdate)
                            iS.title = gdt.toTimeString().substr(0, 5) + ' - ' + iS.title;
                            iS.groupby = gdt.toDateString();
                        }
                        if (toe != 5)
                            newH = iS.groupby.toUpperCase();
                        else
                            newH = iS.groupby;
                        if (ih != true) {
                            if (oldH != newH) {
                                sList = getHeaderList(toe, gb, newH);
                            }
                        }
                        else if (sList == undefined) {
                            sList = $('.sd-homelist-' + toe);
                        }
                        createListEvent(iS.id, iS.flagstatus, newH, toe, iS.title, ih, false);
                    }
                    if (sList != undefined)
                        sList.find('.loading').remove();

                    lDiv.find('.loading').remove();

                    lDiv.addClass('loaded');
                    lDiv.find('.loading-blk').remove();
                }
            });
    }
}




//function loadSmartList(gb, entity, $list) {
//    var homelist = false;
//    var records = 25;
//    if (gb == undefined || gb == 'null') {
//        gb = 'null'
//        records = 100;
//    }
//    else if (gb == 'home') {
//        gb = undefined;
//        homelist = true;
//        records = 15;
//    }
//    var count = 0;
//    var service = smartListService(entity);
//    if ($('#'+$list).hasClass('loaded')) 
//    {
//        var cList = '#' + $list + '_' + gb;
//        count = $(cList).children().length;

//        if (count < 0) 
//        {
//            count = 0;
//        }
//        else if (count > 1) 
//        {
//            $(cList).find('li:last').after("<li class='loading'>");
//        }
//    }
//    var data = { "smartid": $('#usercred').data('sid'), "count": records, "skip": count };

//    $.ajax({
//        type: "POST",
//        url: service,
//        data: JSON.stringify(data),
//        
//        dataType: "json",
//        success: function(msg) {

//            var hPre = '#' + $list + '_';
//            var header = '';

//            var cList;

//            for (var i = 0; i < msg.d.length; i++) {

//                var iSmart = msg.d[i];

//                var h = iSmart.groupby.toUpperCase();
//                var cid = msg.d[i].id;
//                var txt = msg.d[i].title;
//                var flagStatus = msg.d[i].flagstatus == null ? "" : "<img class='flagImage' src='/images/flags/flag" + msg.d[i].flagstatus + ".png' />";

//                if (h != header && homelist == false) {
//                    header = h;
//                    cList = getHeaderList(entity, header, header);
////                    if ($(hPre + header).length < 1) {
////                        var hId = $list + '_' + header;
////                        var elem = '<h2 class="ui-widget-header ui-corner-all pagemast"><a class="head_expand">' +
////                header + '</a><a id="more' + hId + '" class="moreContact">More...</a><a id="less' + hId +
////                '" class="lessContact">Less...</a></h2><div class="pageList"><ul id="' + $list + '_' + header + '"></ul></div>';
////                        $('#' + $list).append(elem);

////                        cList = hPre + header;

////                        $('#more' + hId).bind('click', function() {
////                            var id = $(this).attr('id');
////                            var hh = id.substr(id.length - 1);
////                            loadSmartList(hh, entity, $list);
////                            return false;
////                        });
////                        $('#more' + hId).parent().corner('top round 8px');
////                    }
////                    else {
////                        cList = $(hPre + header);
////                    }
//                }
//                if (homelist == true) {
//                    //createListEvent(cid, msg.d[i].flagstatus, h, entity, txt);
//                    cList = '#' + $list;
//                }
//                var cli = $('#sdl' + cid);
//                if ($('#sdl' + cid).length > 0) {
//                    $('#sdl' + cid).html(flagStatus + txt);
//                }
//                else {
//                    var appendStr = "<li class=''><a id='sdl" + cid + "' href='#'>" + flagStatus + txt + "</a></li>";

//                    if ($(cList).children().length > 1) {
//                        $(cList).find('li:last').after(appendStr);
//                    }
//                    else {
//                        $(cList).append(appendStr);
//                    }


//                    $("#sdl" + cid).data('cid', cid);
//                    $("#sdl" + cid).data('toe', entity);
//                    $("#sdl" + cid).data('txt', txt);
//                    $("#sdl" + cid).bind('click', function() {
//                        //                var id = $(this).data('cid');
//                        //                var txt = $(this).data('txt');
//                        //                var
//                        //                id = id.substring(3);
//                        openListItem($(this).data('toe'), $(this).data('cid'), $(this).data('txt'));
//                        return false;
//                    });
//                }
//                $(cList).find('li').removeClass('last-child');
//                $(cList).find('li').remove('[class=loading]');
//                $(cList).find('li:last').addClass('last-child');

//                if (homelist == true) {
//                    createListEvent(cid, msg.d[i].flagstatus, h, entity, txt);
//                }
//            }
//            $(".lessContact").bind('click', function() {
//                var id = $(this).attr('id');
//                var map = parseInt(id.substring(5));
//                removeListContent(map);
//                return false;
//            });

//            $('#' + $list).addClass('loaded');




















//            onloadSmartList(msg, entity, gb, $list);
//        },
//        error: AjaxFailed
//    });
//}
function onloadSmartList(msg, entity, gb,$list) {



}





//function appendListEvent($list, $event, toe, txt) {
//    if ($list != undefined) {
//        var ins = false;
//        $list.find('span').each(function() {
//            if (ins == false) {
//                if (toe != 5) {
//                    var st = $(this).html();
//                    if (st.toLowerCase() > txt.toLowerCase()) {
//                        $(this).parents('li').before($event);
//                        ins = true;
//                    }
//                }
//                else {
//                    var st = new Date($(this).html().substr(0, 21));
//                    var nd = new Date(txt.substr(0, 21));
//                    if (st > nd) {
//                        $(this).parents('li').before($event);
//                        ins = true;
//                    }
//                }
//            }
//        });
//        if (ins == false) {
//            $list.append($event);
//        }
//    }
//}
