/**
 * 
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 * 
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 * 
 * Copyright (C) Open-Xchange Inc., 2006-2011
 * Mail: info@open-xchange.com 
 * 
 * @author Markus Wagner <markus.wagner@open-xchange.com>
 * 
 */

var calendarGrid = null;
var lastUpdateOfCalendarTimestamp = "";
var idsCalendarForSelected = [];
var lastCalendarSearch = {};
function calendarDeleteSearch()
{    
    calendarGrid.sort = function(id, order) {
        initLiveGridCalendar(currentpath2[2]);
    };    
    triggerEvent("OX_Switch_View", getLastCalendarView());
}
function initCalenderLiveGridOnLoad() {
    
    if (calendarGrid) {
        removeChildNodes($("listeCalendar"));
        calendarGrid = null;
    }
    
    temporary.lists.calendar = temporary.MakeList({
        updated: function() { calendarGrid.recreate(); },
        columns: [
            {   
                text: "&#160;",
                sortable: false,
                width: "16px",
                style: {padding: 0},
                set: function(div, text) {
                    if (div.firstChild) {
                        div.firstChild.src = text > 0 ? getFullImgSrc("img/calendar/calendar_series.gif") : getFullImgSrc("img/calendar/calendar16x16.gif");
                    } else {
                        div.appendChild(newnode("img", 0,
                            {src: text > 0 ? getFullImgSrc("img/calendar/calendar_series.gif") : getFullImgSrc("img/calendar/calendar16x16.gif"), alt: "Serie"}));
                    }
                },
                clear: function(div) {
                    if (div.firstChild) {
                        div.firstChild.src = getFullImgSrc("img/dummy.gif");
                    } else {
                        div.appendChild(newnode("img", 0,
                            {src: getFullImgSrc("img/dummy.gif"), alt: "Serie", width: "16", height: "16"}));
                    }
                },
                index:5
            }, {    
                text: "&#160;",
                sortable: false,
                width: "16px",
                style: {padding: 0},
                set: function(div, text) {
                    var imgSrc;
                    if(text[12] && text[12].length > 1) {
                        imgSrc = getFullImgSrc("img/calendar/group.gif");
                    } else {
                        imgSrc = getFullImgSrc("img/dummy.gif");
                    }
                    if (div.firstChild) {
                        div.firstChild.src = !text[6] ? imgSrc : getFullImgSrc("img/private_flag.gif");
                        div.firstChild.alt = !text[6] ? "G" : "P";
                    } else {
                        div.appendChild(newnode("img", 0,
                            {
                                src: !text[6] ? imgSrc : getFullImgSrc("img/private_flag.gif"),
                                alt: !text[6] ? "G" : "P",
                                width: "16", 
                                height: "16"                            
                            }));
                    }
                },
                clear: function(div) {
                    if (div.firstChild) {
                        div.firstChild.src = getFullImgSrc("img/dummy.gif");
                    } else {
                        div.appendChild(newnode("img", 0,
                            {src: getFullImgSrc("img/dummy.gif"), alt: "G", width: "16", height: "16"}));
                    }
                }
            }, {
                i18n: "description", /*i18n context*/
                text: "Title", /*i18n*/
                sortable: true,
                id: 200,
                set: LiveGrid.defaultSet,
                clear: LiveGrid.makeClear(""),
                index:7
            }, {
                text: "Start", /*i18n*/
                sortable: true,
                i18n: true,
                id: 201,
                width: "14%",
                set: function(div, data) {
                    if (!div.firstChild) {
                        div.appendChild(document.createTextNode(" "));
                    }
                    if (data) {
                        var dateToShow = data[8];
                        if (data[13] === true) {
                            div.firstChild.data=formatDate(dateToShow, "date");
                        } else {
                            div.firstChild.data=formatDate(dateToShow, "datetime");
                        }           
                    } else {
                        div.firstChild.data=""; 
                    }               
                },
                clear: LiveGrid.makeClear("")
            }, {
                text: "End", /*i18n*/
                sortable: true,
                i18n: true,
                id: 202,
                width: "14%",
                set: function(div, data) {
                    if (!div.firstChild) {
                        div.appendChild(document.createTextNode(" "));
                    }
                    if (data) {
                        var dateToShow = data[9];
                        /*
                         * if it's a full day appointment it's minus one day
                         */
                        if (data[13] === true) {
                            dateToShow -= 864e5; /* ms/day */
                            div.firstChild.data=formatDate(dateToShow, "date");
                        } else {
                            div.firstChild.data=formatDate(dateToShow, "datetime");
                        }           
                    } else {
                        div.firstChild.data=""; 
                    }               
                },
                clear: LiveGrid.makeClear("")
            }, {
                text: "Location", /*i18n*/
                sortable: true,
                i18n: true,
                id: 400,
                width: "10%",
                set: LiveGrid.defaultSet,
                clear: LiveGrid.makeClear(""),
                index:10
            }, {
                text: "Folder", /*i18n*/
                sortable: false,
                i18n: true,
                id: 20,
                width: "14%",
                set: function(div,folderId) {
                        if (folderId > 0) {
                            ox.api.folder.get({
                                folder: folderId,
                                success: function (folder) {
                                    function getName(folder) {
                                        return folder.title || "";
                                    }
                                    if (div.firstChild) {
                                        div.firstChild.data = getName(folder);
                                    } else {
                                        div.appendChild(document.createTextNode(getName(folder)));
                                    }
                                }
                            });
                        } else {
                            if (div.firstChild) {
                                div.firstChild.data = " ";
                            } else {
                                div.appendChild(document.createTextNode(" "));
                            }
                        }
                },
                clear: LiveGrid.makeClear(""),
                index:1
            }, {
                text: "Flag", /*i18n*/
                sortable: true,
                i18n: true,
                id: 102,
                width: "4em",
                set: function(div,text) {
                    if (div.firstChild) {
                        div.firstChild.src = getFullImgSrc("img/menu/tag_" + (text||0) + ".gif");
                    } else {
                        div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/menu/tag_" + (text||0) + ".gif"), alt: "tag"}));
                    }
                },
                clear: function(div) {
                    if (div.firstChild) {
                        div.firstChild.src = getFullImgSrc("img/dummy.gif");
                    } else {
                        div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/dummy.gif"), alt: "tag", width: "16", height: "16"}));
                    }
                },
                index:11
            }
        ]
    });
    
    calendarGrid = new LiveGrid(temporary.lists.calendar.columns,
        calendarSelection, "calendar");
    calendarGrid.contextmenu = globalContextMenus.calendar;
    
    calendarGrid.sort = function(id, order) {
        initLiveGridCalendar(currentpath2[2]);
    };
    
    calendarGrid.sort_id = 201;
    calendarGrid.sort_order = "asc";

    $("listeCalendarHeader").appendChild(calendarGrid.getHeader());
    calendarGrid.getTable($("listeCalendar"));
    
    // livegrid double click 
    calendarGrid.events.register("Activated", function(ids){
        if(ids && ids.length > 0) {
            if(menuhasRight(ids,"WRITE") && !isPrivateApp()) {
                selectedAppointment = ids;
                openAppointmentPopup();
            } else {
                triggerEvent("OX_New_Error", 4, _("You do not have write permission for this object."));
            }
        } else {
            triggerEvent("OX_Before_Create_Calendar");
        }
    });
    
    // what to do when select a appointment
    calendarGrid.events.register("Selected", function(ids){
        selectedAppointment = calendarGrid.selection.getSelected();
        triggerEvent("Selected", selectedAppointment);
    });
    
    calendarGrid.events.register("Delete", function(ids){
        if(menucheckRight("DELETE")) {
            deleteAppointment();
        } else {
            triggerEvent("OX_New_Error", 4, _("You do not have write permission for this object."));
        }
    });
    var hover = calendarGrid.addHover(OXAppointmentHover.getContent().node, function(id) {
        OXAppointmentHover.actualHover=hover;
        OXAppointmentHover.refillContent(id.id,id.folder,id.recurrence_position);                    
    });
    hover.setSize(OXAppointmentHover.contentobject.node);
        
    calendarGrid.events.register("Changed", function(data) { calendar_HeaderUpdate(data.ids.length); });
}
var cwwcurrentmonday;
function initLiveGridCalendar(range) {
    showallappointments=calendar_getAllFoldersAttribute();
    $("allAppointmentListView").checked=showallappointments;
    
    var start = null;
    var end = null;
    switch(range){
        case "day":    
                start = Date.UTC(activeYear, activeMonth, activeDay);
                end = Date.UTC(activeYear, activeMonth, (activeDay+1));
                break;
        case "month":
                start = Date.UTC(activeYear, activeMonth, 1);
                end = Date.UTC(activeYear, activeMonth + 1, 1);
                break;
        case "workweek":
                start = getDayInSameWeek(new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0)), startofweek) * 864e5;                
                end = start +(cwwdaysinweek*1000*60*60*24);
                break;
        case "week":
                start = getDayInSameWeek(new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0)), weekStart) * 864e5;
                end = start + 604800000;
                break;
        case "custom":
            start = Date.UTC(activeYear,activeMonth,activeDay);              
            end = start +(cwwdaysinweek*1000*60*60*24);
            break;
        case "search":
                calendarGrid.sort = function (sort, order) {
                    calendarSearch(lastCalendarSearch.module, 
                           lastCalendarSearch.searchstring,
                           { sort: sort, order: order},
                           null, lastCalendarSearch.folder
                        );};
                calendarGrid.disablehover=!configGetKey("gui.effects.hover.calendar");
                calendarGrid.enable(tmpStorage);
                storageCache.setCurrent(tmpStorage);
                break;
    }
    if(end !== null && start !== null){
        if(!calendar_getAllFoldersAttribute()){
                var options = {action: "all", folder: activefolder, start : start, end : end, columns : "1, 20, 207, 206, 2"};
                if (calendarGrid.sort_id) {
                    options.sort = calendarGrid.sort_id;
                    options.order = calendarGrid.sort_order;
                }
                options.showPrivate = true;
                storageCache.get(
                    AjaxRoot + "/calendar",
                    options,
                    function(storage) {
                        calendarGrid.disablehover=!configGetKey("gui.effects.hover.calendar");
                        calendarGrid.enable(storage);
                        storageCache.update();
                    },
                    "209,101,200,201,202,400,102,220,401,221",
                    true,
                    calendar_serializeid,
                    calendar_makeID
                );
        } else {
            var options = {action: "all", start : start, end : end, columns : "1, 20, 207, 206, 2"};
            if (calendarGrid.sort_id) {
                options.sort = calendarGrid.sort_id;
                options.order = calendarGrid.sort_order;
            }
            options.showPrivate = true;
            storageCache.get(
                AjaxRoot + "/calendar",
                options,
                function(storage) {
                    calendarGrid.disablehover=!configGetKey("gui.effects.hover.calendar");
                    calendarGrid.enable(storage);
                    storageCache.update();
                },
                "209,101,200,201,202,400,102,220,401,221",
                true,
                calendar_serializeid,
                calendar_makeID
            );
        }
    }
    updateHeaderListView();
}

function goToNextListView(direction){
    var tmp = new Date(Date.UTC(activeYear, activeMonth, activeDay));
    var start = null;
    var end = null;
    if(direction > 0){
        switch(currentpath2[2]){
            case "day":
                tmp.setTime(tmp.getTime() + 86400000*1);
                break;
            case "workweek":
                tmp.setTime(tmp.getTime() + 86400000*7);
                break;
            case "week":
                tmp.setTime(tmp.getTime() + 86400000*7);
                break;
            case "month":
                tmp.setUTCDate(1);
                tmp.setUTCMonth(activeMonth+1);
                tmp.setUTCDate(activeDay);
                break;
        }
    } else {
        switch(currentpath2[2]){
            case "day":
                tmp.setTime(tmp.getTime() - 86400000*1);
                break;
            case "workweek":
                tmp.setTime(tmp.getTime() - 86400000*7);
                break;
            case "week":
                tmp.setTime(tmp.getTime() - 86400000*7);
                break;
            case "month":
                tmp.setUTCDate(1);
                tmp.setUTCMonth(activeMonth-1);
                tmp.setUTCDate(activeDay);
                break;
        }
    }
    
    activeYear = tmp.getUTCFullYear();
    activeMonth = tmp.getUTCMonth();
    activeDay = tmp.getUTCDate();
    
    if (oMiniCalendar) {
        oMiniCalendar.setSelectedByDate(activeYear, activeMonth, activeDay);
    }
        
    switch(currentpath2[2]){
        case "day":    
                start = Date.UTC(activeYear, activeMonth, activeDay);
                end = Date.UTC(activeYear, activeMonth, (activeDay+1));
                break;
        case "month":
                start = Date.UTC(activeYear, activeMonth, 1);
                end = Date.UTC(activeYear, activeMonth+1, 1);
                break;
        case "workweek":
                start = getDayInSameWeek(new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0)), startofweek) * 864e5;
                end = start + 435600000;
                break;
        case "week":
                start = getDayInSameWeek(new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0)), weekStart) * 864e5;
                end = start + 604800000;
                break;
        case "search":
                calendarGrid.disablehover=!configGetKey("gui.effects.hover.calendar");
                calendarGrid.enable(tmpStorage);
                storageCache.setCurrent(tmpStorage);
                break;
    }
    if(end !== null && start !== null){
        if(!$("allAppointmentListView").checked){
                var options = {action: "all", folder: activefolder, start : start, end : end, columns : "1, 20, 207, 206, 2"};
                if (calendarGrid.sort_id) {
                    options.sort = calendarGrid.sort_id;
                    options.order = calendarGrid.sort_order;
                }
                storageCache.get(
                    AjaxRoot + "/calendar",
                    options,
                    function(storage) {
                        calendarGrid.disablehover=!configGetKey("gui.effects.hover.calendar");
                        calendarGrid.enable(storage);
                        storageCache.update();
                    },
                    "209,101,200,201,202,400,102,220,401,221",
                    true,
                    calendar_serializeid,
                    calendar_makeID
                );
        } else {
            var options = {action: "all", start : start, end : end, columns : "1, 20, 207, 206, 2"};
            if (calendarGrid.sort_id) {
                options.sort = calendarGrid.sort_id;
                options.order = calendarGrid.sort_order;
            }
            storageCache.get(
                AjaxRoot + "/calendar",
                options,
                function(storage) {
                    calendarGrid.disablehover=!configGetKey("gui.effects.hover.calendar");
                    calendarGrid.enable(storage);
                    storageCache.update();
                },
                "209,101,200,201,202,400,102,220,401,221",
                true,
                calendar_serializeid,
                calendar_makeID
            );
        }
    }
    updateHeaderListView();
}

function updateHeaderListView() {
    switch(currentpath2[2]){
        case "day":
            $("calendarlistheaderdiv").style.visibility = "visible";
            $("calendarlistheader").firstChild.data=formatDate(new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0)), "dateday");
            break;
        case "week": //No break
        case "workweek":
            $("calendarlistheaderdiv").style.visibility = "visible";        
            var oCalendarTool = new calendarTool(activeMonth,activeYear);
            $("calendarlistheader").firstChild.data = _("CW") + " " + 
                    formatDateTime("w yyyy", new Date(getKeyDayOfWeek(new Date(Date.UTC(activeYear,activeMonth,activeDay))) * 864e5));
            break;
        case "month":
            $("calendarlistheaderdiv").style.visibility = "visible";        
            $("calendarlistheader").firstChild.data = formatDateTime("MMMM yyyy", new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0)));
            break;
        case "custom":
            $("calendarlistheaderdiv").style.visibility = "visible";        
            var start = Date.UTC(activeYear, activeMonth, activeDay);
            $("calendarlistheader").firstChild.data = cwwdaysinweek == 1
                ? formatDate(start, "dateday")
                : formatDate(start, "date") + " - " +
                  formatDate(start + (cwwdaysinweek - 1) * 864e5, "date"); // ms/day
            break;
        case "search":
            $("calendarlistheaderdiv").style.visibility = "hidden";
            $("calendarlistheader").firstChild.data = ' ';
            break;
    }
}

function disableCalendarGrid(){
    if(calendarGrid) {
        calendarGrid.disable();
    }
    unregister("OX_Add_Flag", calendarAddTag);
}
var currentCalendarTagProgress = false;
function calendarAddTag(tag, editSingleSeriesOnly) {
    if(currentCalendarTagProgress) {
        return;
    }
    currentCalendarTagProgress = true;
    var tmpselected;
    if(currentpath2[0] == "calendar" && currentpath2[1] == "list" && storageCache.current){
        lastUpdateOfCalendarTimestamp = storageCache.current.timestamp;
    }
    function edit_whole_series() {
        // process appointments in order to remove the recurrence position
        for(var i=0;i<tmpselected.length;i++) {
            tmpselected[i] = { id: tmpselected[i].id, folder: tmpselected[i].folder };
        }
        setTag(tag, tmpselected, lastUpdateOfCalendarTimestamp, finalSetTag);
    }
    function edit_single_series() {
        setTag(tag, tmpselected, lastUpdateOfCalendarTimestamp, finalSetTag);            
    }
    if(selectedAppointment.length){
        tmpselected=selectedAppointment;
    } else { 
        tmpselected=[selectedAppointment];
    }
    var editSingleSeriesOnly = !!editSingleSeriesOnly;
    var isseries=false;
    for(var x=0;x<tmpselected.length;x++) {
        if(tmpselected[x].recurrence_position>0 && tmpselected[x].recurrence_id &&
           tmpselected[x].recurrence_id == tmpselected[x].id) {
            isseries=true;
            break;
        }
    }
    if(isseries && !editSingleSeriesOnly) {
        if(tmpselected.length>1) {
            newConfirm(_("Edit Appointment"),_("Do you want to edit the whole series or single series appointments? Please note when changing a serial appointment, exceptions to the series are reset."),AlertPopup.SERIESBUTTON,null,null,null,null,edit_whole_series,edit_single_series);            
        } else {
            newConfirm(_("Edit Appointment"),_("Do you want to edit the whole series or a single series appointment? Please note when changing a serial appointment, exceptions to the series are reset."),AlertPopup.SERIESBUTTON,null,null,null,null,edit_whole_series,edit_single_series);                        
        }        
    } else {
        setTag(tag, tmpselected, lastUpdateOfCalendarTimestamp, finalSetTag);
    }
    
    function finalSetTag(timestamp) {    
        lastUpdateOfCalendarTimestamp = timestamp;
        if(currentpath2[0] == "calendar" && currentpath2[1] == "detail") {
            reloadAppDetailView();
        } else {
            updateCalendarViewCbSetTag(timestamp);
        }
        // notify
        triggerEvent("OX_After_Update_Appointment");
    }
}
var tmpStorage;
function endProgressCalendarTagging() {
    window.setTimeout(function(){currentCalendarTagProgress = false;},0);    
}

function updateCalendarViewCbSetTag(currentTagTimestamp) {
    
    if(currentpath2[0] == "calendar" && currentpath2[1] != "detail" && currentpath2[2] != "search"){
    window.setTimeout('endProgressCalendarTagging()',0);
        if(storageCache) {
            storageCache.update(endProgressCalendarTagging);
        }
    } else if(currentpath2[2] == "search"){
        if(currentTagTimestamp) {
            if(storageCache && storageCache.current) {
                storageCache.current.timestamp = currentTagTimestamp;
            }
        }
        calendarSearch(lastCalendarSearch.module, lastCalendarSearch.searchstring, null, endProgressCalendarTagging, lastCalendarSearch.folder);
    }
}

//var sPatternCalendarsearch;
function calendarSearch(module, searchstring, order, callback, folder) {
    //var sPatternCalendarsearch = searchstring;
    tmpStorage = new Storage(lastUpdateOfCalendarTimestamp, [], "", 0, 0, calendar_serializeid, calendar_makeID);
    lastCalendarSearch.module = module;
    lastCalendarSearch.searchstring = searchstring;
    lastCalendarSearch.folder = folder || (calendar_getAllFoldersAttribute() ? null : activefolder);    
    var sOrderString="";
    if (order) {
        sOrderString = "&sort=" + order.sort + "&order=" + order.order;
    }
    var sObject = { };
    sObject.pattern = searchstring;
    if (lastCalendarSearch.folder) {
        sObject.folder = lastCalendarSearch.folder;
    }
    json.put(AjaxRoot + "/calendar?action=search&session=" + session 
           + "&columns=1,20,207,206,2,209,101,200,201,202,400,102,220,401,221" 
           + sOrderString, sObject, null, 
                function(cb){
                    if(callback) {
                        callback();
                    }
                    tmpArray = [];
                    for(var i=0; i < cb.data.length; i++){
                        tmpArray[i] = [    cb.data[i][0],
                                        cb.data[i][1],
                                        cb.data[i][2],
                                        cb.data[i][3],
                                        cb.data[i][4],
                                        cb.data[i][5],
                                        cb.data[i][6],
                                        cb.data[i][7],
                                        cb.data[i][8],
                                        cb.data[i][9],
                                        cb.data[i][10],
                                        cb.data[i][11],
                                        cb.data[i][12],
                                        cb.data[i][13],
                                        cb.data[i][14]
                                    ]; 
                    }
                    tmpStorage.append(tmpArray);
                    lastUpdateOfCalendarTimestamp = cb.timestamp;
                    storageCache.current.timestamp = cb.timestamp;
                    if(!calendarGrid){
                        triggerEvent("OX_Switch_View", "calendar/list/search");
                    } else if(currentpath2[2] != "search"){
                        triggerEvent("OX_Switch_View", "calendar/list/search");
                    } else {
                        calendarGrid.disablehover=!configGetKey("gui.effects.hover.calendar");
                        calendarGrid.enable(tmpStorage);
                        storageCache.setCurrent(tmpStorage);
                    }                    
    });    
}

function isPrivateApp() {
    var owner = (activeFolderOwner != configGetKey('identifier')), privateObj = false;
    if (currentpath[1] == "list" && storageCache && storageCache.current) {
        storageCache.current.newIterate(menuselectedobjects, emptyFunction, function(id, obj) {
            if (owner == true && obj[6] === true) {
                privateObj = true;
            }
        });
    }
    return privateObj;
}

fileloaded();