/**
 * 
 * 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) 2004-2010 Open-Xchange, Inc.
 * Mail: info@open-xchange.com 
 * 
 * @author Stefan Preuss <stefan.preuss@open-xchange.com>
 * 
 */

function ParticipantsExternal(storage, on_ok_cb) {	
	// init livegrid and new storage for exteral e-mail addresses
    this.selection = new Selection();
    this.storage = new Storage(0, [], 0, 0, 0, 0, function(external) { return external.id; });
    this.grid = new LiveGrid([
    { 
        text: "Name",
        i18n: true,
        clear: LiveGrid.makeClear(""),
        set: function(div, external) {
            if (div.firstChild)
                div.firstChild.data = external.displayName;
            else
                div.appendChild(document.createTextNode(external.displayName));
        }
    },
    {
        text: "E-Mail",
        i18n: true,
        clear: LiveGrid.makeClear(""),
        set: function(div, external) {
            if (div.firstChild)
                div.firstChild.data = external.email;
            else
                div.appendChild(document.createTextNode(external.email));
        }
    }
    ], this.selection);
    this.grid.emptylivegridtext = "";
    
    // add livegrid header and content to dom node
    $("part.ext.grid.header").appendChild(this.grid.getHeader());
    this.grid.getTable($("part.ext.grid"));
    
    var Self = this;
    this.on_close_cb = function() {
    	Self.clearList();
    	Self.closeDialog(); 	
    }
    this.on_open_cb = function() {
    	Self.clearList();
        Self.showDialog();     
    }
    this.on_clear_click_cb = function(e) { 
        Self.clearList(); 
    };
    this.on_cancel_click_cb = function(e) {
        Self.on_close_cb();
    };
    this.on_ok_cb = on_ok_cb;
    this.on_ok_click_cb = function(e) {
    	if (Self.on_ok_cb) {
    		Self.on_ok_cb(clone(Self.storage.data.data));
    	}
        Self.on_close_cb(); 
    };
    this.on_add_click_cb = function(e) { 
        Self.validateAddress($("part.ext.displayname").value, $("part.ext.email").value); 
    };
    register("OX_Object_Open_External", function() { 
        Self.on_open_cb(); 
    });   
    addOnClose($("part.ext.container"), function() {
    	Self.on_close_cb();
    });   
}


ParticipantsExternal.prototype = {
	
	/**
     * Displays the external E-Mail Dialog
     */
    showDialog: function() {
    	addDOMEvent($("part.ext.button_ok"), "click", this.on_ok_click_cb);
    	addDOMEvent($("part.ext.button_cancel"), "click", this.on_cancel_click_cb);
    	addDOMEvent($("part.ext.button_clear"), "click", this.on_clear_click_cb);
    	addDOMEvent($("part.ext.button_add"), "click", this.on_add_click_cb);    
        this.grid.enable(this.storage);
        if ($("modal-dialog")) {
            ox.api.setModal(true);
//        	showNode("modal-dialog");
//        	$("modal-dialog").style.display = "block";
        }
        centerPopupWindow($("part.ext.container"));
        $("part.ext.container").style.display = 'block';
    },  
    
    /**
     * Closes the external E-Mail Dialog
     */
    closeDialog: function() {
    	removeDOMEvent($("part.ext.button_ok"), "click", this.on_ok_click_cb);
        removeDOMEvent($("part.ext.button_cancel"), "click", this.on_cancel_click_cb);
        removeDOMEvent($("part.ext.button_clear"), "click", this.on_clear_click_cb);
        removeDOMEvent($("part.ext.button_add"), "click", this.on_add_click_cb);
        if ($("modal-dialog")) {
            ox.api.setModal(false);
//            $("modal-dialog").style.display = "none";
//            hideNode("modal-dialog");
        }
        $("part.ext.container").style.display = "none";
        this.grid.disable();
    },
    
    /**
     * Resets the list of external e-mail addresses
     */
    clearList: function(){
        $('part.ext.displayname').value = "";
        $('part.ext.email').value = "";
        this.storage.remove(0, this.storage.ids.length);
    },
    
    /**
     * Adds a new external e-mail address to the list
     * @param displayName The display name
     * @param email The e-mail address (required)
     */
    addToList: function(displayName, email) {
        displayName = trimStr(displayName || "");
        email = trimStr(email);
        /* checking duplicates */
        for (var i in this.storage.data.data) {
        	if (this.storage.data.data[i].email === email) return;
        }
        this.storage.append([{ id: this.storage.ids.length, displayName: displayName, email: email }]);     
    },
    
    /**
     * Gets the display name and email address from the page, validates and 
     * adds it to the list. Afterwards the fields on the page gets cleared
     * or fucused. 
     */
    validateAddress : function(displayName, email) {
    	var Self = this;
    	function markInput() {
    		if (!$("part.ext.email").className.match(/border-color-error/gi)) {
                $("part.ext.email").className += " border-color-error";
            }
    	}
    	function goahead(displayName, email) {
            $("part.ext.email").className = removeClass($("part.ext.email").className, "border-color-error");
            Self.addToList(displayName, email);
            $("part.ext.displayname").value = "";
            $("part.ext.email").value = "";
        }
        if (email.length == 0) {
            markInput();
            newAlert(_("Error"), _("Please enter a valid E-Mail address!"), 
                function() {
                   setFocus($("part.ext.email"));
                }
            );
        } else if (!corewindow.validateEmail(email)) {
        	markInput();
        	var message = _("The E-Mail address you have entered seems not to be valid. Would you like to add it anyway?");
        	if (corewindow.isIDNEmail(email)) {
        		message = _("You entered an E-Mail address with IDN domain. In some environments IDN domains will not work as expected. Would you like to add it nevertheless?");
        	}
            newConfirm(_("Error"),
                message, 
                AlertPopup.YESNO, null, null,
                function() { 
                	goahead(displayName, email); 
                }, 
                function () { 
                	setFocus($("part.ext.email")); 
                }
            );
        } else {        
            goahead(displayName, email);
            setFocus($("part.ext.displayname"));
        }
    } 
}

fileloaded();