// THIS CODE IS NOT APPROVED FOR USE IN/ON ANY OTHER UI ELEMENT OR PRODUCT COMPONENT. 
// Copyright (c) 2007 Renderspace. All rights reserved.


function clearNetworkContent(isChangedWarning) {
    if (globalIsContentChanged && isChangedWarning && CONTENT_CHANGED_CONFIRM_MESSAGE) {
        if (!confirm(CONTENT_CHANGED_CONFIRM_MESSAGE)) return false;
    }
        
    var currElem = objectManager.firstChildObject;
    while (currElem) {
        var nextElem = currElem.nextObject;
        if (currElem.type == "Connector") currElem.release();
        currElem = nextElem;
    }
    currElem = objectManager.firstChildObject;
    while (currElem) {
        var nextElem = currElem.nextObject;
        if ((currElem.type == "Person") || (currElem.type == "Initiative")) currElem.release();
        currElem = nextElem;
    }
    globalIsContentChanged = false;
}


function loadNetworkData(fileContent) {
    globalIsContentChanged = false;
    clearNetworkContent(false);
    
    fileContent = fileContent.split("\n");
    for (var i in fileContent) {
        if (fileContent[i]) {
            var data = fileContent[i].split("|");
            var type = data[0];
            if (((type == "P") || (type == "I")) && (data.length >= 5)) {
                var id = data[1];
                var xPos = parseInt(data[2]);
                var yPos = parseInt(data[3]);
                var name = data[4];
                var elem = null;
                if      (type == "P") elem = new PersonObject(objectManager, id, name); 
                else if (type == "I") elem = new InitiativeObject(objectManager, id, name); 
                if (elem) {
                    elem.show(true, true, 1);
                    elem.setPosition(xPos, yPos, 0, 0);
                }
            }
            else if ((type == "C") && (data.length >= 3)) {
                var elem1 = objectManager.findObjectByID(objectManager, data[1], "Person", true);
                var elem2 = objectManager.findObjectByID(objectManager, data[2], "Initiative", true);
                var conn = new ConnectorObject(objectManager, elem1, elem2);
                conn.show(true, true, 1);
            }
        }
    }
    
    globalIsContentChanged = false;
}


function saveNetworkData() {
    var fileContent = "";
    
    var currElem = objectManager.firstChildObject;
    while (currElem) {
        if ((currElem.type == "Person") || (currElem.type == "Initiative")) {
            if (currElem.type == "Person") fileContent += "P";
            if (currElem.type == "Initiative") fileContent += "I";
            fileContent += "|" + currElem.id + "|" + currElem.x + "|" + currElem.y + "|" + currElem.name + "\n";
        }
        currElem = currElem.nextObject;
    }
    
    currElem = objectManager.firstChildObject;
    while (currElem) {
        if (currElem.type == "Connector") {
            var id1 = currElem.element1.id;
            var id2 = currElem.element2.id;
            if (currElem.element1.type == "Initiative") {
                var tmpId = id1;
                id1 = id2;
                id2 = tmpId;
            }
            
            fileContent += "C|" + id1 + "|" + id2 + "\n";
        }
        currElem = currElem.nextObject;
    }
    
    globalIsContentChanged = false;
            
    return fileContent;
}


function findConnectorOfElements(elem1, elem2) {
    if ((elem1 == null) || (elem2 == null)) return null;
    
    var tempElem = elem1.parentObject.firstChildObject;
    while (tempElem) {
        if (tempElem.type == "Connector") {
            if (((tempElem.element1 == elem1) && (tempElem.element2 == elem2))
             || ((tempElem.element2 == elem1) && (tempElem.element1 == elem2))) return tempElem;
        }
        tempElem = tempElem.nextObject;
    }
            
    return null;
}


function createNetworkElement(typeName, id, name, xPos, yPos) {
    var elem = objectManager.findObjectByID(objectManager, id, typeName, true);
    if (elem != null) return null; // already existing
    
    switch (typeName) {
        case "Person": {
            elem = new PersonObject(objectManager, id, name); 
            getRemoteFile("GET", "/ajaxfunc.php", "func=getpersoninitiatives&id=" + id, false, false, onRemoteDataReceived, "Person");
        }; break;
        case "Initiative": {
            elem = new InitiativeObject(objectManager, id, name); 
            getRemoteFile("GET", "/ajaxfunc.php", "func=getinitiativepersons&id=" + id, false, false, onRemoteDataReceived, "Initiative");
        }; break;
    }
    
    if (elem) {
        elem.show(true, true, 1);
        if (xPos == null) xPos = Math.floor(Math.random() * (mainHScrollbar.pageSize + mainHScrollbar.maxRange - mainHScrollbar.minRange - 150) + mainHScrollbar.minRange) + 50;
        if (yPos == null) yPos = Math.floor(Math.random() * (mainVScrollbar.pageSize + mainVScrollbar.maxRange - mainVScrollbar.minRange - 150) + mainVScrollbar.minRange) + 50;
        elem.setPosition(xPos, yPos, 0, 0);
    }
    
    return elem;
}


function createNetworkElementFromSelection(typeName, selectionElemName) {
    if (selectionElemName == null) return null;
    var selectionElem = document.getElementById(selectionElemName);
    if (selectionElem == null) return null;
    if (selectionElem.selectedIndex < 0) return null;
    var id = selectionElem.options[selectionElem.selectedIndex].value;
    var name = selectionElem.options[selectionElem.selectedIndex].text;
    
    return createNetworkElement(typeName, id, name, null, null);
}


function showNetworkElementDetails(element) {
    if (element == null) return false;
    if ((element.type != "Person") && (element.type != "Initiative")) return false;
    var prefix = "";
    if (element.type == "Person") prefix = "2";
    if (element.type == "Initiative") prefix = "1";
    navigateToLink("/" + prefix + "?id=" + element.id, true);
    return true;
}


function showNetworkElementRelations(element) {
    if (element == null) return false;
    if ((element.type != "Person") && (element.type != "Initiative")) return false;
    var func = (element.type == "Person") ? "getpersoninitiativenames" : "getinitiativepersonnames";
    getRemoteFile("GET", "/ajaxfunc.php", "func=" + func + "&id=" + element.id, false, false, onRemoteDataReceived, element.type + "Relations");
    return true;
}


function loadNetworkFile(fileName, fileID) {
    if (globalUserID == null) {
        alert(USER_NOT_LOGGED_IN_MESSAGE);
        return false;
    }

    if ((fileName == null) || (fileName == "")) {
        if (globalIsContentChanged && CONTENT_CHANGED_CONFIRM_MESSAGE) {
            if (!confirm(CONTENT_CHANGED_CONFIRM_MESSAGE)) return false;
        }
        return selectFileDialog("load");
    }
    
    globalCurrentFileName = fileName;
    globalCurrentFileID = fileID;
    var fileContent = getRemoteFile("GET", "/ajaxfunc.php", "func=getuserfile&uid=" + globalUserID + "&fid=" + fileID, false, false, null, null);
    return loadNetworkData(fileContent);
}


function saveNetworkFile(fileName) {
    if (globalUserID == null) {
        alert(USER_NOT_LOGGED_IN_MESSAGE);
        return false;
    }
    if ((fileName == null) || (fileName == "")) return selectFileDialog("save");

    globalCurrentFileName = fileName;
    var fileContent = saveNetworkData();
    if (fileContent.length >= 8000) {
        alert(FILE_TOO_LARGE_MESSAGE);
        return false;
    }
    globalCurrentFileID = getRemoteFile("POST", "/ajaxfunc.php", "func=setuserfile&uid=" + globalUserID + 
        "&name=" + fileName + "&content=" + encodeURIComponent(fileContent), false, false, null, null);
    alert(((globalCurrentFileID == "") || (globalCurrentFileID == 0)) ? CANNOT_SAVE_FILE_MESSAGE : FILE_SAVED_MESSAGE);
    return true;
}


function exportNetworkFile() {
    var fileContent = saveNetworkData();
    if (fileContent.length >= 8000) {
        alert(FILE_TOO_LARGE_MESSAGE);
        return false;
    }
    var fileID = getRemoteFile("POST", "/ajaxfunc.php", "func=setuserfile&uid=" + globalUserID + 
        "&name=&content=" + encodeURIComponent(fileContent), false, false, null, null);
    var connColor = (CONNECTOR_COLOR.substring(0, 1) == "#") ? CONNECTOR_COLOR.substring(1) : "000000";
    var textColor = (FONT_COLOR.substring(0, 1) == "#") ? FONT_COLOR.substring(1) : "000000";
    navigateToLink("/ajaxfunc.php?func=exportnetwork&uid=" + globalUserID + "&fid=" + fileID + 
        "&ts=" + FONT_SIZE + "&es=" + ELEMENT_SIZE + "&cs=" + CONNECTOR_SIZE + 
        "&cc=" + connColor + "&tc=" + textColor +
        "&att=" + (IS_EXPORT_AS_ATTACHMENT ? "1" : "0"), !IS_EXPORT_AS_ATTACHMENT);
    return false;
}


function confirmFileSaveDialog() {
    var fileNameElem = document.getElementById("network_file_dialog_name");
    var listElem = document.getElementById("network_file_list");
    if ((fileNameElem == null) || (listElem == null)) return false;
    var fileName = fileNameElem.value;
    if (fileName == "") fileName = null;
    if (fileName == null) {
        alert(FILENAME_MUST_BE_SELECTED_MESSAGE);
        return false;
    }
    for (var i = listElem.options.length-1; i >= 0; i--) {
        if (fileName == listElem.options[i].text) {
            if (!confirm(FILE_EXISTS_CONFIRM_MESSAGE)) return false;
        }
    }

    closeFileDialog();
    return saveNetworkFile(fileName);
}


function confirmFileLoadDialog() {
    var listElem = document.getElementById("network_file_list");
    if (listElem == null) return false;
    if (listElem.selectedIndex < 0) return false;
    var fileID = listElem.options[listElem.selectedIndex].value;
    var fileName = listElem.options[listElem.selectedIndex].text;
    if (fileID == null) return false;
    closeFileDialog();
    return loadNetworkFile(fileName, fileID);
}


function onFileSelectedInDialog() {
    var fileNameElem = document.getElementById("network_file_dialog_name");
    var listElem = document.getElementById("network_file_list");
    if (fileNameElem && listElem) {
        fileNameElem.value = (listElem.selectedIndex >= 0) ? listElem.options[listElem.selectedIndex].text : "";
    }
}


function closeFileDialog() {
    var shadowElem = document.getElementById("network_shadow");
    var contentElem = document.getElementById("network_file_dialog");
    if (shadowElem != null) shadowElem.style.display = "none";
    if (contentElem != null) contentElem.style.display = "none";
    document.getElementById("initiative2add").style.display = "inline";
    document.getElementById("person2add").style.display = "inline";
}


function deleteSelectedFile() {
    var listElem = document.getElementById("network_file_list");
    if (listElem == null) return false;
    if (listElem.selectedIndex < 0) return false;
    if (!confirm(FILE_DELETE_CONFIRM_MESSAGE)) return false;
    var fileID = listElem.options[listElem.selectedIndex].value;
    getRemoteFile("GET", "/ajaxfunc.php", "func=deleteuserfile&uid=" + globalUserID + "&fid=" + fileID, false, false, null, null);
    listElem.options[listElem.selectedIndex] = null;
    return true;
}


function selectFileDialog(type) {
    var shadowElem = document.getElementById("network_shadow");
    var contentElem = document.getElementById("network_file_dialog");
    var confirmButton = document.getElementById("network_file_dialog_confirm");
    var dialogTitleElem = document.getElementById("network_file_dialog_title");
    var fileNameElem = document.getElementById("network_file_dialog_name");
    var listElem = document.getElementById("network_file_list");
    if ((shadowElem == null) || (contentElem == null) || (listElem == null) || (fileNameElem == null) || (confirmButton == null)) return false;
    var windowWidth = getWindowWidth() + getWindowXScroll();
    var windowHeight = getWindowHeight() + getWindowYScroll();
    shadowElem.style.display = "block";
    shadowElem.style.width = windowWidth + "px";
    shadowElem.style.height = windowHeight + "px";
    contentElem.style.display = "inline";
    contentElem.style.left = ((windowWidth + getWindowXScroll() - 400) >> 1) + "px";
    contentElem.style.top = ((windowHeight + getWindowYScroll() - 400) >> 1) + "px";
    listElem.options.length = 0;
    fileNameElem.value = globalCurrentFileName;
    if (type == "load") {
        dialogTitleElem.innerHTML = LOAD_TEXT;
        fileNameElem.readOnly = true;
        confirmButton.onclick = confirmFileLoadDialog;
        listElem.ondblclick = confirmFileLoadDialog;
    }
    if (type == "save") {
        dialogTitleElem.innerHTML = SAVE_TEXT;
        fileNameElem.readOnly = false;
        confirmButton.onclick = confirmFileSaveDialog;
        listElem.ondblclick = confirmFileSaveDialog;
    }
    document.getElementById("initiative2add").style.display = "none";
    document.getElementById("person2add").style.display = "none";
    
    getRemoteFile("GET", "/ajaxfunc.php", "func=getuserfiles&uid=" + globalUserID, false, false, onRemoteDataReceived, "UserFiles");
    return true;
}


function onRemoteDataReceived(data, userData) {
    if ((userData == "Person") || (userData == "PersonRelations") || (userData == "Initiative") || (userData == "InitiativeRelations")) {
        var isFullRelations = ((userData == "PersonRelations") || (userData == "InitiativeRelations"));
        var type = ((userData == "Person") || (userData == "PersonRelations")) ? "Person" : "Initiative";
        var searchType = ((userData == "Person") || (userData == "PersonRelations")) ? "Initiative" : "Person";
        var data = data.split("\x08");
        if (data.length < 2) return;
        var elementID = data[0];
        var elem1 = objectManager.findObjectByID(objectManager, elementID, type, true);
        if (elem1) {
            var relationList = data[1].split("\n");
            var tempElem = elem1.parentObject.firstChildObject;
            while (tempElem) {
                if ((tempElem != elem1) && (tempElem.type == searchType)) {
                    for (var i in relationList) {
                        if (relationList[i]) {
                            var id = isFullRelations ? relationList[i].split("|")[0] : relationList[i];
                            if (id == tempElem.id) {
                                var conn = findConnectorOfElements(elem1, tempElem);
                                if (conn == null) {
                                    conn = new ConnectorObject(objectManager, elem1, tempElem);
                                    conn.show(true, true, 1);
                                }
                                relationList[i] = null;
                                break;
                            }
                        }
                    }
                }
                tempElem = tempElem.nextObject;
            }
            
            if (isFullRelations) {
                var numElements = 0;
                for (var i in relationList) if (relationList[i]) numElements++;
                
                var radius = numElements * ELEMENT_SIZE * ELEMENT_DAISY_RATIO / (2 * Math.PI);
                if (radius < MIN_RADIUS) radius = MIN_RADIUS;
                
                var elementIndex = 0;
                for (var i in relationList) {
                    if (relationList[i]) {
                        var data = relationList[i].split("|");
                        var pos = elem1.getCenterPos();
                        pos.x += Math.floor(radius * Math.sin(2 * Math.PI * elementIndex / numElements) - ELEMENT_SIZE / 2);
                        pos.y += Math.floor(radius * Math.cos(2 * Math.PI * elementIndex / numElements) - ELEMENT_SIZE / 2);
                        if (pos.x < 0) pos.x = 0;
                        if (pos.y < 0) pos.y = 0;
                        var elem2 = createNetworkElement(searchType, data[0], data[1], pos.x, pos.y);
                        var conn = new ConnectorObject(objectManager, elem1, elem2);
                        conn.show(true, true, 1);
                        elementIndex++;
                    }
                }
            }
        }
    }
    
    if (userData == "UserFiles") {
        var listElem = document.getElementById("network_file_list");
        if (listElem) {
            data = data.split("\n");
            listElem.options.length = 0;
            for (var i in data) {
                if (data[i]) {
                    var name = data[i].split("\x08");
                    var opt = document.createElement("option");
                    opt.value = name[0];
                    opt.text = name[1];
                    if (name.length >= 3) opt.text += " [" + name[2] + "]"; 
                    try {listElem.add(opt, null);}
                    catch (ex) {listElem.add(opt);}
                }
            }
        }
    }
}
