/**
 * 
 * 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>
 * @author Stefan Preuss <stefan.preuss@open-xchange.org>
 * 
 */

var globalconflicts = new ConflictsPopup();

function ConflictsPopup() {    
    this.object;
    this.conflicts;
    this.closecb;
    this.cbcancel;
    this.cbignore;
}

ConflictsPopup.tableTemplate;

ConflictsPopup.open = function (object,conflicts,closecb,cbcancel,cbignore) {
    globalconflicts.object = object;
    globalconflicts.conflicts = conflicts;
    globalconflicts.closecb = closecb;
    globalconflicts.cbcancel = cbcancel;
    globalconflicts.cbignore = cbignore;
    
    removeChildNodes($("conflict_window_appointments"));
    $("conflict_window_ignore").style.display = "block";
    $("conflict_recurrence_msg").style.display =
        object.recurrence_type ? "" : "none";
    
    // iterate trough each conflict and draw rows
    for (i in conflicts) {
        var table = newnode("tbody");
        var tmp = conflicts[i];
        var tr = document.createElement("tr");
        
        var img = newnode("img", { cursor:"pointer"}, { src: getFullImgSrc("img/minus.gif"), align:"absmiddle", width:16, height:16 });
        
        // draw each conflict in a seperate tr 
        tr.appendChild(newnode("td", 0, { className:"cell" },
                [ img ]));
        tr.appendChild(newnode("td", 0, { className:"cell" }, 
                [ document.createTextNode(tmp.title || _("Private")) ] ));
        var node_C = newnode("td", 0, { className:"cell" });      
        tr.appendChild(node_C);
        tr.appendChild(newnode("td", 0, { className:"cell" }, 
                [ tmp.start_date ? document.createTextNode(formatDate(tmp.start_date, isToday(tmp.start_date) ? "time" : "datetime")) : _("Private") ]));
                
        tr.appendChild(newnode("td", 0, { className:"cell" }, 
                [ tmp.end_date ? document.createTextNode(formatDate(tmp.end_date, isToday(tmp.end_date) ? "time" : "datetime")) : _("Private") ]));
        table.appendChild(tr);
        
        // resolving creator of appointment
        internalCache.getObjects([{ type:1, id:tmp.created_by }], (function(creator, node) {
            return function(user) {
                node.appendChild(document.createTextNode(user[creator.id].display_name || ""));
            };
        })({ type:1, id:tmp.created_by }, node_C));
            
        // creating participant rows
        var table_P = newnode("tbody");
        var tmp_T = ConflictsPopup.tableTemplate.cloneNode(true);
        tmp_T.style.padding="0px";
        tmp_T.appendChild(table_P);
        
        var tmp_TR = newnode("tr");
        img.onclick = (function(img, tr) {
            return function(e) {
                var isOpen = img.src.match(/minus.gif/gi);
                img.src = isOpen ? getFullImgSrc("img/plus.gif") : getFullImgSrc("img/minus.gif");
                tr.style.display = isOpen ? "none" : "";
            };
        })(img, tmp_TR);
        
        tmp_TR.appendChild(newnode("td",{padding:"0px"},{colSpan:5},[tmp_T])); 
        table.appendChild(tmp_TR);
        
        // using internal cache to resolve display names and append results to the given td node
        if (tmp.participants && tmp.participants.length) {
            internalCache.getObjects(tmp.participants, (function(cbObj, cb_node) {
                    return function(cb_participants) {
                        for (var ia=0; ia < cbObj.participants.length; ia++) {
                            var tmp_dn = cb_participants[cbObj.participants[ia].id].display_name || "";
                            var tr = newnode("tr");
                            
                            // draw each conflict in a seperate tr      
                            tr.appendChild(newnode("td", 0, { className:"cell" },
                                    [ newnode("img", null, { src:getFullImgSrc("img/dummy.gif"), align:"absmiddle", width:"16", height:"16" }) ]));

                            tr.appendChild(newnode("td", 0, { className:"cell" },
                                    [ 
                                        newnode("img", 0, 
                                            { src: getFullImgSrc("img/calendar/" + 
                                                (cb_participants[cbObj.participants[ia].id].type == 1 ? "user" : "ressourcen") + ".gif"), 
                                              align: "absmiddle", width: "16", height: "16" }),
                                        document.createTextNode(" " + tmp_dn) 
                                    ]));
                            
                            var confirmClass = "";
                            var confirmText = _("waiting");                        
                            switch(cbObj.participants[ia].confirmation) {
                                case 1:
                                   confirmClass = "appointmentACCEPTED";
                                   confirmText = _("accepted");
                                   break;
                                case 2:
                                   confirmClass = "appointmentDECLINED";
                                   confirmText = _("declined");
                                   break;
                                case 3:
                                   confirmClass = "appointmentTENTATIVE";
                                   confirmText = _("tentative");
                                   break;
                            }
                            confirmClass += " cell";
                            tr.appendChild(newnode("td", { colSpan:3 }, { className:confirmClass },
                                    [ document.createTextNode(confirmText) ]));
                            
                            cb_node.appendChild(tr);
                        }
                    };
                })(tmp, table_P));
        }
        
        // disable 'ignore conflict button' if any appointment hard conflicts 
        if (tmp.hard_conflict) {
            $("conflict_window_ignore").style.display = "none";
        }
        
        // finally append everything to container
        var finalNode = ConflictsPopup.tableTemplate.cloneNode(true);
        finalNode.style.borderBottom="1px dotted silver";
        finalNode.appendChild(table);
        $("conflict_window_appointments").appendChild(finalNode);
    }

    ox.api.setModal(true);
    //showNode("modal-dialog");
    //$("modal-dialog").style.display="block";
    
    
    showNode("disable_confirm_window");
    $("disable_confirm_window").style.display="block";

    showNode("conflict_window");
    centerPopupWindow($("conflict_window"));
    $("conflict_window").style.display="block";
    
};

ConflictsPopup.close = function () {
    if(globalconflicts.closecb) { 
        globalconflicts.closecb(globalconflicts.object); 
    }
    hideNode("conflict_window");
    $("conflict_window").style.display="none";    
    hideNode("disable_confirm_window");
    $("disable_confirm_window").style.display="none";
    var childs=    $("modal-dialog").childNodes;
    var closeall=true;
    for(var i=0; i<childs.length; i++) {
        if(childs[i].tagName && childs[i].tagName == "DIV") {
            if(childs[i].style.display && childs[i].style.display != "none" ) {
                closeall=false;
            }
        }
    }
    
    if(closeall) {
        ox.api.setModal(false);
        //hideNode("modal-dialog");
        //$("modal-dialog").style.display="none";
    }
};

ConflictsPopup.commitignore = function() {
    if (globalconflicts.cbignore) { 
        globalconflicts.cbignore(globalconflicts.object); 
    }
    ConflictsPopup.close();
};

ConflictsPopup.commitcancel = function() {
    if (globalconflicts.cbcancel) { 
        globalconflicts.cbcancel(globalconflicts.object); 
    }
    ConflictsPopup.close();
};

ConflictsPopup.prototype = {
    setIgnore : function (cb) {
        this.cbignore=cb;
    },
    setCancel : function (cb) {
        this.cbcancel=cb;
    },
    setClose: function (cb) {
        this.closecb=cb;
    }
};

register("Loaded",function() {
    addOnClose($("conflict_window"), function () { 
            ConflictsPopup.close(); 
        });
    
    // create table template for later use     
    ConflictsPopup.tableTemplate=newnode("table",{tableLayout:"fixed"},{width:"100%",cellPadding:0,cellSpacing:0},
        [
            newnode("colgroup",0,0,
                [
                    newnode("col",{width:"26px"},0),
                    newnode("col",0,0),
                    newnode("col",{width:"13em"},0),
                    newnode("col",{width:"11em"},0),
                    newnode("col",{width:"11em"},0)
                ])
        ]);
});

fileloaded();