/**
 * 
 * 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 Jan Finsel <jan.finsel@open-xchange.com>
 * 
 */

register("OX_Refresh", acceptdeny_start);

function AcceptDenyObject(module,object) {
    this.title=object.title;
    this.location=object.location;
    this.startdate;
    this.enddate;
    this.folder_id=object.folder_id;
    this.created_by=object.created_by;
    this.objectid=object.id;
    this.module=module;
    this.confirmation=-1;
    this.com="";

    if(object.start_date) {
        this.startdate=new Date(object.start_date);
    }
    if(object.end_date) {
        this.enddate=new Date(object.end_date);
    }
    for(var i=0;i<object.users.length;i++) {
        if(object.users[i].id == configGetKey("identifier")) {
            this.confirmation=object.users[i].confirmation;
            this.com=object.users[i].confirmmessage;
        }
    }
}
function AcceptDeny(showdetail) {
    this.showdetail=showdetail;
    var Self=this;

    function mkHandler(type) {
        return function () {
            if (Self.showdetail) {
                var objects = [];
                AcceptDeny.storage.newIterate(AcceptDeny.grid.getSelectedIDs(),
                    emptyFunction, function(i, o) { objects.push(o); },
                function() {
                    acceptdeny_updateConfirm(objects, type,
                        $("acceptdeny_comment3").value, function() {
                            var grid = AcceptDeny.grid;
                            grid.deleteIDs(grid.getSelectedIDs());
                            $("acceptdeny_comment3").value=""; // bug #15388
                            if (!grid.storage.ids.length) {
                                Self.removeDomEvents();
                                AcceptDeny.hide();
                            }
                        });
                });
            } else {
                Self.removeDomEvents();
                acceptdeny_updateConfirm(Self.objects, type,
                    $("acceptdeny_comment2").value, AcceptDeny.hide);
            }
        };
    }
    this.acceptdeny_accept = mkHandler(1);
    this.acceptdeny_decline = mkHandler(2);
    this.acceptdeny_tentative = mkHandler(3);

    this.acceptdeny_later = function () {
        Self.acceptdeny_close();
        if (contimestamp && contimestamp > 0) {
            configSetKey("gui.global.confirmtimestamp",contimestamp);
        }
    };
    
    this.acceptdeny_close = function () {
        Self.removeDomEvents();
        AcceptDeny.hide();
    };
    this.addDomEvents = function () {
        this.removeDomEvents();
        addOnClose($("acceptdeny_object"),Self.acceptdeny_close);
        addDOMEvent($("acceptdeny_accept"), "click", Self.acceptdeny_accept);
        addDOMEvent($("acceptdeny_decline"), "click", Self.acceptdeny_decline);
        addDOMEvent($("acceptdeny_tentative"), "click", Self.acceptdeny_tentative);
        addDOMEvent($("acceptdeny_later"), "click", Self.acceptdeny_later);
    };
    this.removeDomEvents = function () {    
        removeOnClose($("acceptdeny_object"),Self.acceptdeny_close);
        removeDOMEvent($("acceptdeny_accept"), "click", Self.acceptdeny_accept);
        removeDOMEvent($("acceptdeny_decline"), "click", Self.acceptdeny_decline);
        removeDOMEvent($("acceptdeny_tentative"), "click", Self.acceptdeny_tentative);
        removeDOMEvent($("acceptdeny_later"), "click", Self.acceptdeny_later);    
    };
}
AcceptDeny.visible = false;
AcceptDeny.hide = function() {
    hideNode("acceptdeny_object");
    $("acceptdeny_object").style.display="none";
    //ox.api.setModal(false);
//    hideNode("modal-dialog");
//    $("modal-dialog").style.display="none";
//    $("modal-dialog").style.width = "100%";
//    $("modal-dialog").style.height = "100%";
    AcceptDeny.visible = false;
};
AcceptDeny.prototype = {
    changeConfirm : function(acceptdenyobjectarray) {
        AcceptDeny.visible = true;
        this.objects = acceptdenyobjectarray;
        $("acceptdeny_nodetail").style.display="";
        $("acceptdeny_list").style.display = "none";
        var comment = this.showdetail ? $("acceptdeny_comment2")
                                      : $("acceptdeny_comment3");
        comment.value="";
        if(acceptdenyobjectarray && acceptdenyobjectarray.length == 1 && acceptdenyobjectarray[0].com) {
            comment.value=acceptdenyobjectarray[0].com;
        }
        //ox.api.setModal(true);
//        showNode("modal-dialog");
//        $("modal-dialog").style.display="block";
        showNode("acceptdeny_object");
        centerPopupWindow($("acceptdeny_object"));
        $("acceptdeny_object").style.display="block";
        this.addDomEvents();
        
    },
    showConfirmation : function (objects) {
        if (!objects.length) return;
        AcceptDeny.visible = true;
        this.objects = objects;
        if (this.showdetail) {
            $("acceptdeny_nodetail").style.display="none";
            $("acceptdeny_list").style.display = "";
            $("acceptdeny_list_message").style.display =
                objects[0].confirmation ? "none" : "";
            var messages = $("acceptdeny_list_message").
                getElementsByTagName("span");
            switch (objects[0].module) {
                case "tasks":
                    messages[0].style.display = "none";
                    messages[1].style.display = "";
                    $("acceptdeny_show").style.display = "none";
                    break;
                case "calendar":
                    messages[0].style.display = "";
                    messages[1].style.display = "none";
                    $("acceptdeny_show").style.display = "";
                    break;
                default:
                    messages[0].style.display = "none";
                    messages[1].style.display = "none";
                    $("acceptdeny_show").style.display = "none";
            }
            var grid = AcceptDeny.grid;
            if (!grid) {
                var defaultClear = LiveGrid.makeClear("");
                grid = AcceptDeny.grid = new LiveGrid([
                {
                    width: "30px",
                    style: { padding: 0, margin: 0 },
                    text: "&#x00a0;",
                    set: function(div, data) {
                        var src = getFullImgSrc("img/calendar/mod_calendar.gif");
                        if (data.module && data.module == "tasks") {
                            src = getFullImgSrc("img/tasks/mod_tasks.gif");
                        }
                        if (!div.firstChild) {
                            div.appendChild(newnode("img", {height : "24px", width : "24px"}, { src: getFullImgSrc("img/dummy.gif"), align: "absmiddle"}));
                        }
                        div.firstChild.src = src;
                    },
                    clear: function(div) {
                        if (!div.firstChild) {
                            div.appendChild(newnode("img", {height : "24px", width : "24px"}, { src: getFullImgSrc("img/dummy.gif"), align: "absmiddle"}));
                        } else {
                            div.firstChild.src = getFullImgSrc("img/dummy.gif");
                        }
                    }
                },{
                    i18n: "description"/*i18n context*/, text: "Title"/*i18n*/,
                    clear: function(div) {
                        if (!div.firstChild) {
                            div.appendChild(newnode("div", 0, 0,
                                [newtext("")]));
                            div.appendChild(newnode("div", 0, 0,
                                [newtext("")]));
                        } else {
                            div.firstChild.firstChild.data = "";
                            div.firstChild.nextSibling.firstChild.data = "";
                        }
                    },
                    set: function(div, data) {
                        var text = data.location
                            //#. Appointment description in the confirmation dialog.
                            //#. %1$s is the title.
                            //#. %2$s is the location.
                            //#, c-format
                            ? format("%1$s - %2$s", (data.title || ""),
                                                    data.location)
                            : (data.title || "");
                        if (!div.firstChild) {
                            div.appendChild(newnode("div", 0, 0,
                                [newtext(text)]));
                            div.appendChild(newnode("div", 0, 0,
                                [newtext("")]));
                        } else {
                            div.firstChild.firstChild.data = text;
                            div.firstChild.nextSibling.firstChild.data = "";
                        }
                        internalCache.getUsers([data.created_by], function(u) {
                            div.firstChild.nextSibling.firstChild.data =
                                //#. Second line in the grid of the notification dialog
                                //#. %s is the name of the appointment creator
                                //#, c-format
                                format(_("created by %s"), u[data.created_by].display_name);
                        });
                    }
                }, {
                    text: "Start"/*i18n*/, i18n: true, index: "startdate",
                    width: "11em", clear: defaultClear,
                    set: LiveGrid.dateSetTime
                }, {
                    text: "End"/*i18n*/, i18n: true, index: "enddate",
                    width: "11em", clear: defaultClear,
                    set: LiveGrid.dateSetTime
                }], new Selection());
                $("acceptdeny_list_header").appendChild(grid.getHeader());
                grid.columns[1].style = { height: "3.2em" };
                grid.getTable($("acceptdeny_list_body"));
                var setDisabled = classNameSetter("font-color-disabled");
                grid.events.register("Selected", function(count) {
                    $("acceptdeny_all").checked =
                        count == grid.storage.ids.length;
                    setDisabled($("acceptdeny_show"), count != 1);
                    setDisabled($("acceptdeny_accept"), count == 0);
                    setDisabled($("acceptdeny_decline"), count == 0);
                    setDisabled($("acceptdeny_tentative"), count == 0);
                    
                    // change button text - either it's an appointment or a task 
                    var ids = grid.getSelectedIDs();
                    if (ids.length != 1) return;
                    grid.storage.newIterate(ids, emptyFunction,
                        function(i, object) {
                            if (!object.module) return;
                            var butText = _("Show in calendar");
                            if (object.module == "tasks") {
                                butText = _("Show in task");
                            }
                            $("acceptdeny_show-button").firstChild.data = butText;
                        });
                });
                AcceptDeny.storage = new Storage(0, [], 0, 0, 0, 0,
                    function(x) { return x.objectid; });
                addDOMEvent($("acceptdeny_all"), "click", function() {
                    if ($("acceptdeny_all").checked) {
                        grid.selection.select(0, grid.storage.ids.length);
                    } else {
                        grid.selection.reset();
                    }
                });
                addDOMEvent($("acceptdeny_show"), "click", function() {
                    var ids = grid.getSelectedIDs();
                    if (ids.length != 1) return;
                    grid.storage.newIterate(ids, emptyFunction,
                        function(i, object) {
                            activemodule = object.module || "calendar";
                            if (activemodule == "calendar") {
                                activeDay = object.startdate.getUTCDate();
                                activeMonth = object.startdate.getUTCMonth();
                                activeYear = object.startdate.getUTCFullYear();
                            }
                            // change folder
                            ox.UIController.setFolder({
                                folder: object.folder_id,
                                module: "default"
                            });
                            //ox.api.setModal(false);
//                            $("modal-dialog").style.width = 0;
//                            $("modal-dialog").style.height = 0;
                        });
                });
            }
            var storage = AcceptDeny.storage;
            storage.remove(0, storage.ids.length);
            storage.append(objects)
            grid.enable(AcceptDeny.storage);
            grid.selection.click(0);
        } else {
            var acceptdenyobject = objects[0];
            $("acceptdeny_nodetail").style.display="";
            $("acceptdeny_list").style.display = "none";
            $("acceptdeny_notnew").style.display =
                acceptdenyobject.confirmation ? "none" : "";
        }
        //ox.api.setModal(true);
//        showNode("modal-dialog");
//        $("modal-dialog").style.display="block";
        showNode("acceptdeny_object");
        centerPopupWindow($("acceptdeny_object"));
        $("acceptdeny_object").style.display="block";
        this.addDomEvents();
    }
}

function acceptdeny_updateConfirm(objects, status, message, callback) {    
    var join = new Join(function() {
        json.put(AjaxRoot + "/multiple?session=" + session, requests, null,
                 finalCallback, finalCallback);
    });
    var last = join.add();
    var requests = new Array();
    for (var i = 0; i < objects.length; i++) {
        ox.api.folder.get({
            folder: objects[i].folder_id,
            success: join.add((function(object) {
                return function(folder) {
                    var owner = folder.type == 3 ?
                        folder.created_by :
                        configGetKey("identifier");
                    requests.push({
                        module: object.module, action: "confirm",
                        folder: object.folder_id, id: object.objectid,
                        data: { id: owner, confirmmessage: message,
                                confirmation: status }
                    });
                };
            })(objects[i]))
        });
    }
    last();
    function finalCallback(resp) {
        // TODO CHECK ERRORS
        
        acceptdeny_update_objects_in_cache(requests,
            acceptdeny_get_timestamp(resp));            
        triggerEvent("OX_AcceptDeny_Changed");
        callback();
    }
}

function acceptdeny_get_timestamp(response) {
    return response.timestamp || response[0].timestamp || new Date().getTime();
}

function acceptdeny_update_objects_in_cache(objects, timestamp) {
    
    for (var i in objects) {
        var object = objects[i];
        if (object.module == "calendar") {
            if (storageCache && storageCache.current != null) storageCache.update();
            else lastUpdateOfCalendarTimestamp = timestamp;
            continue; // not implemented right now
            
        }
        
        ox.api.folder.get({
            folder: object.folder,
            success: function (folder) {
                var owner = folder.type == 3 ? folder.created_by : configGetKey("identifier");
                OXCache.moduleMappings[object.module].editObjects(
                      [ { "module": object.module, "folder": object.data.folder_id, "id": object.data.id } ],
                      { "users": 
                        [{ "confirmation": object.data.confirmation,
                           "confirmmessage": object.data.confirmmessage,
                           "id": owner 
                        }],
                        "timestamp": timestamp
                      }
                );
            }
        });
        
    }
}

register("OX_Configuration_Loaded_Complete",acceptdeny_start);

function acceptdeny_start() {    
    function acceptdeny_fill(response) {
        var conarray=new Array();
        var constrings=new Object();
        for (var ia=0; ia<response.length; ia++) {
            if (!response[ia].data || !response[ia].data.length) continue;
            var data = response[ia].data;
            contimestamp = data.timestamp;
            for (var i=0; i<data.length; i++) {
                var newobject=new Object();
                newobject.id=data[i][0];
                newobject.folder_id=data[i][1];    
                newobject.start_date=data[i][2];
                newobject.end_date=data[i][3];
                newobject.users=data[i][5];
                newobject.title=data[i][6];
                newobject.created_by=data[i][7];    
                newobject.location=data[i][8];
                newobject.module = (ia == 0 ? "calendar" : "tasks");
                for(var i2=0; i2<newobject.users.length; i2++) {                    
                    if (newobject.users[i2].id == configGetKey("identifier")) {
                        if (newobject.users[i2].confirmation == 0) {
                            if(!constrings[newobject.folder_id+":"+newobject.id]) {
                                constrings[newobject.folder_id+":"+newobject.id]=true;
                                conarray.push(newobject);        
                            }
                        }
                        break;
                    }
                }
            }    
        }
        showAllConfirmation(conarray);
    }
    var checkconfirmation=true;
    var columns="1,20,201,202,209,221,200,2"
    var confirmtimestamp=0;
    if (configContainsKey("gui.global.confirmtimestamp")) {
        confirmtimestamp = configGetKey("gui.global.confirmtimestamp");
    }
    if (configContainsKey("gui.global.confirmpopup") && 
            configGetKey("gui.global.confirmpopup") == true) {
        var startDate = new Date().getTime();
        var endDate = startDate+360000*24*365*5;
        var requests = [];
        if (configGetKey("modules.calendar.module")) {
            requests.push( { module: "calendar", action: "updates", start: startDate, end: endDate, timestamp: confirmtimestamp, ignore: "deleted", columns: columns + ",400" } )
        }
        if (configGetKey("modules.tasks.module")) {
            requests.push( { module: "tasks", action: "updates", folder: configGetKey("folder.tasks"), start: startDate, end: endDate, timestamp: confirmtimestamp, ignore: "deleted", columns: columns } )
        }
        if (requests.length) {
            (new JSON).put(AjaxRoot + "/multiple?session=" + session, requests, null, acceptdeny_fill);
        }
    }
}
var globalconfirm= new AcceptDeny(true);
var contimestamp;

function showAllConfirmation(acceptdenyarray) {    
    var a = new Array(acceptdenyarray.length);
    for (var i = 0; i < acceptdenyarray.length; i++) {
        a[i] = new AcceptDenyObject(acceptdenyarray[i].module || "calendar", acceptdenyarray[i]);
    }
    globalconfirm.showConfirmation(a);
}
fileloaded();