/**
 * 
 * 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>
 * 
 */

var cms_init_bool=false;
var cms_currentsignature=-1;
var cms_signatures=new Array();
var cms_signatureposition;

function ConfigSignatures() {
	this.cbok;
	this.cbcancel;
	this.grid;
	this.storage;
	this.selection = new Selection();
    this.storage = new Storage(0, [], 0, 0, 0, 0, function(data) { return data.id; });    
}
ConfigSignatures.initGrid = function() {
	configsignatures.grid = new LiveGrid([
    { 
        text: "Name",/*i18n*/
        i18n: true,
        clear: LiveGrid.makeClear(""),
        set: function(div, data) {
            if (div.firstChild)
                div.firstChild.data = data.name;
            else
                div.appendChild(document.createTextNode(data.name));
        }
    },
    {
        text: "Place",/*i18n*/
        i18n: true,
        clear: LiveGrid.makeClear(""),
        width: "6em",
        set: function(div, data) {
        	var place = data.place.match(/below/) ? _("below") : _("above");
            if (div.firstChild)
                div.firstChild.data = place;
            else
                div.appendChild(document.createTextNode(place));
        }
    },
    {
        text: "Default",/*i18n*/
        i18n: true,
        clear: LiveGrid.makeClear(""),
        width: "6em",
        set: function(div, data) {
            if (div.firstChild)
                div.firstChild.data = data.isDefault ? _("Yes") : "";
            else
                div.appendChild(document.createTextNode(data.isDefault ? _("Yes") : ""));
        }
    }
    ], configsignatures.selection);
    configsignatures.grid.emptylivegridtext = "";
    configsignatures.grid.events.register("Selected", function() {
    	// get selected signature
    	var ids = configsignatures.grid.selection.getSelected();
    	// clear current preview
    	removeChildNodes($("cms_signatures_preview"));
    	if (ids.length != 0) {
    		// replace newlines by BR tags (IE7 needs the space for subsequent BR tags!)
    		var signature_text = cms_signatures[ids[0]].signature_text.replace(/\n/g, " <br/>");
    		// cleanup spaces
    		signature_text = replaceLeadingSpaces(signature_text);
    		// set content
    		$("cms_signatures_preview").innerHTML = signature_text;
    		// parse links in preview
    	   	parseDirectLinksInMails($("cms_signatures_preview"));
    	}
        ox.ToolBarController.processSelection("signatures", false, ids);
    	
    	function replaceLeadingSpaces(text) {
    		return text.replace(/(^|<br\s*\/?>)([ \t]+)|([ \t]{2,}|\t)/g,
    			function(_, prefix, m1, m2) {
    				var match = (m1 || m2).replace(/\t/g, "        "); // TODO: real tabs
    				var retval = new Array((match.length + 3) >> 1);
    				retval[0] = prefix || "";
    				var max = match.length >> 1;
    				for (var i = 1; i <= max; i++) retval[i] = "&nbsp; ";
    				if (match.length & 1) retval[retval.length - 1] = "&nbsp;";
    				return retval.join("");
    			});
    	}
    });
    configsignatures.grid.events.register("Activated", function(ids) {           
            if (ids && ids.length > 0) {
                triggerEvent("OX_Configuration_Edit_Signature");
            }
        }
    );
    configsignatures.grid.events.register("Delete", 
        function(ids){
            deleteMails(activefolder, ids) 
        }
    );
    
    // add livegrid header and content to dom node
    $("cms_signatures_header").appendChild(configsignatures.grid.getHeader());
    configsignatures.grid.getTable($("cms_signatures_grid"));
}
ConfigSignatures.open = function () {
    ox.api.setModal(true);
	//showNode("modal-dialog");
	//$("modal-dialog").style.display="block";
	showNode("config_popups_win");
	$("config_popups_win").style.display="block";
	showNode("window_signature");
	centerPopupWindow($("window_signature"));
	$("window_signature").style.display="block";
}
ConfigSignatures.close = function () {
	if (this.closecb) { globalalert.cbclose(); }
	hideNode("window_signature");
	$("window_signature").style.display="none";
	hideNode("config_popups_win");
	$("config_popups_win").style.display="none";
	ox.api.setModal(false);
	//hideNode("modal-dialog");
	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);
		//$("modal-dialog").style.display="none";
	}
	if (configsignatures.grid && configsignatures.grid.focus != undefined) {
		setFocus($("cms_signatures_grid"));
		configsignatures.grid.selection.click(configsignatures.grid.focus);
		configsignatures.grid.showFocus();
	}
}
ConfigSignatures.commitcancel = function () {
	if(configsignatures.cbcancel) { 
		if(configsignatures.cbcancel()) {
			ConfigSignatures.close();
		}
	} else { 
		ConfigSignatures.close(); 
	}
}
ConfigSignatures.commitok = function () {
	if(configsignatures.cbok) { 
		if(configsignatures.cbok()) {
			ConfigSignatures.close();
		}
	} else { 
		ConfigSignatures.close(); 
	}
}

register("Loaded", function () {
	addOnClose($("window_signature"), 
	   function() {
	   	   ConfigSignatures.close() 
	   }
	); 
});

var configsignatures=new ConfigSignatures();

function openSignatureWindow(sig_name,sig_place,sig_signature,sig_default,cbok,cbcancel) {
	$("signature_window_signature_name").value=sig_name;
	setFocus($("signature_window_signature_name"));	
	cms_signatureposition.setKey(sig_place);
	$("cms_signaturetext").value=sig_signature;
	$("signature_default").checked=sig_default;
	configsignatures.cbok=cbok;
	configsignatures.cbcancel=cbcancel;
	ConfigSignatures.open();
} 

registerView("configuration/mail/signatures",
	function () { 
		showNode("config_mail_signatures"); 
		$("config_mail_signatures").style.display="block";
        
        // toolbar
        if (!configToolbars.signatures) {
            configToolbars.signatures = temporary.configuration.newToolbar(
                _("Signatures"), [
                    temporary.configuration.saveButton,
                    {
                        title: _("Signatures"),
                        id: "signatures",
                        buttons: [{
                            title: _("Add"),
                            id: "add",
                            icons: ["img/menu/add_signature.gif",
                                    "img/menu/add_signature_d.gif"],
                            event: "OX_Configuration_Add_Signature"
                        }, {
                            title: _("Edit"),
                            id: "edit",
                            icons: ["img/menu/edit.gif", "img/menu/edit_d.gif"],
                            event: "OX_Configuration_Edit_Signature",
                            selection: "signatures",
                            requires: ["one"]
                        }, {
                            title: _("Remove"),
                            id: "remove",
                            icons: ["img/menu/remove_signature.gif",
                                    "img/menu/remove_signature_d.gif"],
                            event: "OX_Configuration_Remove_Signature",
                            selection: "signatures",
                            requires: ["some"]
                        }]
                    }
                ], "signatures");
        }
        temporary.configuration.showToolbar(configToolbars.signatures);
    },
	function() { 
		register("OX_Configuration_Add_Signature",cms_addSignature);
		register("OX_Configuration_Edit_Signature",cms_editSignature);
		register("OX_Configuration_Remove_Signature",cms_removeSignature);
 		register("OX_SAVE_OBJECT",cms_saveConfiguration);
		register("OX_Cancel_Object",cms_cancelConfiguration);
		cms_enter();
		if (!configsignatures.grid) {
			ConfigSignatures.initGrid();
		}
		configsignatures.grid.enable(configsignatures.storage);
	},
	function() {
		//configuration_askforSave();
		unregister("OX_Configuration_Add_Signature",cms_addSignature);
		unregister("OX_Configuration_Edit_Signature",cms_editSignature);
		unregister("OX_Configuration_Remove_Signature",cms_removeSignature);
 		unregister("OX_SAVE_OBJECT",cms_saveConfiguration);
		unregister("OX_Cancel_Object",cms_cancelConfiguration);
		configsignatures.grid.disable();
		cms_leave();
	},
	function () { 
		hideNode("config_mail_signatures"); 
		$("config_mail_signatures").style.display="none"; 
	},
	null
);

function checkDuplicateSignatures(myname) {
	for(var i=0;i<cms_signatures.length;i++) {
		if(cms_signatures[i].signature_name==myname) return true;
	}
	return false;
}
function cms_enter() {
	if(!cms_init_bool) {
		cms_init();
		cms_init_bool=true;
	}
	cms_signatures=new Array();
	if (configContainsKey("gui.mail.signatures")) {
		cms_signatures=configGetKey("gui.mail.signatures");
		configuration_changed_fields["gui"]=false;
	}
	
	cms_fillSignature();	
	setConfigPath($("cms_header"));
}
function cms_init() {
	cms_signatureposition= new ComboBox3(window, "cms_signatureposition", "95%", 1, true,"OX_Configuration_Mail_Signatures_Position_Changed", null);
	var key="below";
	var key2="above"
    cms_signatureposition.addElement(_("Above the text"), key2);
    cms_signatureposition.addElement(_("Below the text"), key);
	cms_signatureposition.getDomNode();
}
function cms_fillSignature() {
	configsignatures.storage.remove(0, configsignatures.storage.ids.length);
	for (var i=0; i<cms_signatures.length; i++) {
        var sig_name = cms_signatures[i].signature_name.length == 0 ? _("Unnamed signature")  : cms_signatures[i].signature_name;       
        configsignatures.storage.append([{ id: i, name: sig_name, place: cms_signatures[i].position, isDefault: cms_signatures[i].signature_default }]);     
    }
    ox.ToolBarController.processSelection("signatures", false, []);
}
function cms_editSignature() {	
	cms_currentsignature = configsignatures.grid.selection.getSelected()[0];	
	openSignatureWindow(cms_signatures[cms_currentsignature].signature_name,cms_signatures[cms_currentsignature].position,cms_signatures[cms_currentsignature].signature_text,cms_signatures[cms_currentsignature].signature_default,cms_changeSignature);
}
function cms_changeSignature() {
	var myobject=new Object();
	if (trimStr($("signature_window_signature_name").value).length == 0) {
        newAlert(_("Invalid Signature"),_("Please enter a name")); /*i18n*/
        $("signature_window_signature_name").focus();
        return false;
    } else if (checkDuplicateSignatures(trimStr($("signature_window_signature_name").value))) {
		if(cms_signatures[cms_currentsignature].signature_name != trimStr($("signature_window_signature_name").value)) {
			newAlert(_("Invalid Signature"),_("This Signature name already exists")); /*i18n*/
			$("signature_window_signature_name").focus();
			return false;		
		}
	}
	myobject.signature_name=trimStr($("signature_window_signature_name").value);
	myobject.position=cms_signatureposition.getKey();
	myobject.signature_text=$("cms_signaturetext").value;
	myobject.signature_default=$("signature_default").checked;
	if(myobject.signature_default) {
		for(var i=0;i<cms_signatures.length;i++) {
			cms_signatures[i].signature_default=false;
		}	
	}
	cms_signatures[cms_currentsignature]=myobject;
	configuration_changed_fields["gui"]=true;
	cms_fillSignature();
	return true;
	
}
function cms_addSignature() {	
	var zaehler=0;
	var sig_name=_("New Signature");
	if (checkDuplicateSignatures(sig_name)) { zaehler=2; }
	while (checkDuplicateSignatures(sig_name+" ("+zaehler+")")) {
		zaehler ++;
	}
	if(zaehler!=0) {
		sig_name=sig_name+" ("+zaehler+")";
	}
	var sig_place="below";
	var sig_signature="";
	var sig_default=false;
	openSignatureWindow(sig_name,sig_place,sig_signature,sig_default,cms_newSignature);
	configuration_changed_fields["gui"]=true;
}
function cms_newSignature() {	
	var myobject=new Object();
	if (trimStr($("signature_window_signature_name").value).length == 0) {
        newAlert(_("Invalid Signature"),_("Please enter a name")); /*i18n*/
        $("signature_window_signature_name").focus();
        return false;
    } else if (!checkDuplicateSignatures(trimStr($("signature_window_signature_name").value))) {
		myobject.signature_name=trimStr($("signature_window_signature_name").value);
		myobject.position=cms_signatureposition.getKey();
		myobject.signature_text=$("cms_signaturetext").value;
		myobject.signature_default=$("signature_default").checked;
		if(myobject.signature_default) {
			for(var i=0;i<cms_signatures.length;i++) {
				cms_signatures[i].signature_default=false;
			}	
		}
	} else {
		newAlert(_("Invalid Signature"),_("This Signature name already exists"));
		$("signature_window_signature_name").focus();
		return false;
	}
	cms_signatures.push(myobject);
	configuration_changed_fields["gui"]=true;
	cms_fillSignature();
	return true;
}
function cms_removeSignature() {
	for (var i=0; i<configsignatures.grid.selection.getSelected().length; i++) {
	   cms_signatures.splice(configsignatures.grid.selection.getSelected()[i], 1);
	}
	cms_fillSignature();
	configuration_changed_fields["gui"]=true;
}
function cms_saveConfiguration() {
	if(configuration_changed_fields["gui"]) {
		configSetKey("gui.mail.signatures",cms_signatures);
	}
	triggerEvent("OX_Save_Configuration",false,false);
}
function cms_cancelConfiguration() {
	configuration_changed_fields["gui"]=false;
	cms_enter();	
}
function cms_leave() { }
fileloaded();