/**
 * 
 * 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 Andreas Mayer <andreas.mayer@open-xchange.com>
 * 
 */
//define dialogue here
function ConfigExternalPortalModules() {
	this.cbok;
	this.cbcancel;
}
ConfigExternalPortalModules.prototype = {
	open : function (){
        ox.api.setModal(true);
		//showNode("modal-dialog");
		//$("modal-dialog").style.display="block";
		showNode("config_popups_win");
		$("config_popups_win").style.display="block";
		try {
			setTimeout(function() { $("external_window_uwa_name").focus() }, 0);
		} catch (e) { }
		showNode("window_external_module");
		centerPopupWindow($("window_external_module"));
		$("window_external_module").style.display="block";		
	},
	close : function (){
		if(this.closecb) { this.closecb(); }
		hideNode("config_popups_win");
		$("config_popups_win").style.display="none";
		hideNode("window_external_module");
		$("window_external_module").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";
		}
	},
	cancel : function (){
		$("external_window_uwa_name").value = "";
		$("external_window_uwa_uri").value = "";	
		$("external_autorefresh").checked = false;
		$("external_standalone").checked = false;		
		$("external_window_uwa_params").value = "";					
		this.close();
	},
	commit : function (){
		add_item();
		$("external_window_uwa_name").value = "";
		$("external_window_uwa_uri").value = "";	
		$("external_autorefresh").checked = false;
		$("external_standalone").checked = false;	
		$("external_window_uwa_params").value = "";			
		this.close();
	}
}
var objExternalPopupWindow = new ConfigExternalPortalModules();

register("Loaded", function () {
		addOnClose($("window_external_module"),function() { objExternalPopupWindow.cancel() }); 
	});
//begin script
var oUWAModulesLG;
var objExternalContRemoved = new Array();
var objExternalContChanged = new Array();
var objExternalContAdded;
var sIdEditExternalUWAPortal = -1;

registerView("configuration/portal/external",
	function () { 
		showNode("config_external"); 
		$("config_external").style.display="block"; 
		$("config.external.description").innerHTML = format(_(uwaLink.text), ["<a href=\"" + uwaLink.link.format() + "\" target=\"_blank\">", "</a>"]);
		
        // toolbar
        if (!configToolbars.UWAModules) {
            configToolbars.UWAModules = temporary.configuration.newToolbar(
                _("UWA Modules"), [
                    temporary.configuration.saveButton,
                    {
                        title: _("UWA Modules"),
                        id: "modules",
                        buttons: [{
                            title: _("Add"),
                            id: "add",
                            icons: ["img/menu/add_extview.gif",
                                    "img/menu/add_extview.gif"],
                            event: "OX_Configuration_External_Portalview_Add"
                        }, {
                            title: _("Edit"),
                            id: "edit",
                            icons: ["img/menu/externalview_edit_n.gif",
                                    "img/menu/externalview_edit_d.gif"],
                            event: "OX_Configuration_Edit_External",
                            selection: "portal-external",
                            requires: ["one"]
                        }, {
                            title: _("Remove"),
                            id: "remove",
                            icons: ["img/menu/remove_extview.gif",
                                    "img/menu/remove_extview_d.gif"],
                            event: "OX_Configuration_External_Portalview_Remove",
                            selection: "portal-external",
                            requires: ["some"]
                        }]
                    }, {
                        title: _("Visibility"),
                        id: "visibility",
                        buttons: [{
                            title: _("Enable"),
                            id: "enable",
                            icons: ["img/menu/externalview_activate_n.gif",
                                    "img/menu/externalview_activate_d.gif"],
                            event: "OX_Configuration_Enable_External",
                            selection: "portal-external",
                            requires: ["some"]
                        }, {
                            title: _("Disable"),
                            id: "disable",
                            icons: ["img/menu/externalview_deactivate_n.gif",
                                    "img/menu/externalview_deactivate_d.gif"],
                            event: "OX_Configuration_Disable_External",
                            selection: "portal-external",
                            requires: ["some"]
                        }]
                    }
                ], "modules");
        }
        temporary.configuration.showToolbar(configToolbars.UWAModules);
	},
	function() { 
		register("OX_SAVE_OBJECT",cpe_saveConfiguration);
		register("OX_Cancel_Object",cpe_cancelConfiguration);
		register("OX_Configuration_External_Portalview_Add",openExternalAddPopup);
		register("OX_Configuration_External_Portalview_Remove",remove_items);		
		register("OX_Configuration_Edit_External",openExternalEditPopup);			
		register("OX_Configuration_Enable_External",enable_items);
		register("OX_Configuration_Disable_External",disable_items);
		cpe_enter();
	},
	function() {
		//configuration_askforSave();
		unregister("OX_SAVE_OBJECT",cpe_saveConfiguration);
		unregister("OX_Cancel_Object",cpe_cancelConfiguration);		
		unregister("OX_Configuration_External_Portalview_Add",openExternalAddPopup);
		unregister("OX_Configuration_External_Portalview_Remove",remove_items);
		unregister("OX_Configuration_Edit_External",openExternalEditPopup);						
		unregister("OX_Configuration_Enable_External",enable_items);
		unregister("OX_Configuration_Disable_External",disable_items);		
		cpe_leave();
	},
	function () { 
		hideNode("config_external"); 
		$("config_external").style.display="none"; 
    },
	function () { cpe_enter();}
);

var cpe_init_bool=false;
var cp_externalcontents=new Object();

function cpe_saveConfiguration() {
	bPortalConfigChanged = true;
	triggerEvent("OX_Save_Configuration",false,false); 
	
}

function cpe_cancelConfiguration() {
	configuration_changed_fields["gui"]=false;
	cpe_enter();	
}

function cpe_enter(){
	objExternalContAdded = new Array();
	//add_item();
	if(oUWAModulesLG == undefined)
	{
		oUWAModulesLG= new LiveGrid([ 
				{
					index: 1,
                    i18n: "description", /*i18n context*/
					text: "Title", /*i18n*/
					width: "9em",
					set: function  (div, text){
					removeChildNodes(div);
					var sDisplayString =  _(text);
					div.appendChild(document.createTextNode(sDisplayString));	
					},
					clear: LiveGrid.makeClear("...")				
				},
				{
					index: 2,
					text: "URI", /*i18n*/
					i18n: true,				
					set: function  (div, text){
					removeChildNodes(div);
					var sDisplayString =  _(text);
					div.appendChild(document.createTextNode(sDisplayString));	
					},
					clear: LiveGrid.makeClear("...")				
				},
				{
					index: 5,
					text: "Visibility", /*i18n*/
					i18n: true,				
					width: "9em",
					set: function  (div, text){
					removeChildNodes(div);
					var sDisplayString =  (text)?_("enabled"):_("disabled");
					div.appendChild(document.createTextNode(sDisplayString));	
					},
					clear: LiveGrid.makeClear("...")				
				}
			], new Selection());
		oUWAModulesLG.emptylivegridtext="";		
		$("lg_header_uwa_modules").appendChild(oUWAModulesLG.getHeader());
		oUWAModulesLG.getTable($("lg_uwa_modules"));	
		oUWAModulesLG.events.register("Selected",function (ids) {
            ox.ToolBarController.processSelection("portal-external", false,
                oUWAModulesLG.selection.getSelected());
		});			
		oUWAModulesLG.events.register("Activated",function (ids) {
            if(oUWAModulesLG.selection.count > 0) openExternalEditPopup();		
		});					
	}
    ox.ToolBarController.processSelection("portal-external", false, []);
	setUWALG();
	setConfigPath($("cext_header"));
}
function setUWALG()
{
	var oStorage = new Storage(0, [],null,null,null,null,function (x){
					return x[0];
		});	
	var oAllWidgts = configGetKey("gui.portal.externalcontents");
	var aData = new Array();
	for (var indx=0;indx<oAllWidgts.length;indx++)
	{
		var oAr = oAllWidgts[indx];
		var sParameterStr = "";
		for(var sKey in oAr["parameter"])
		{
			if(sParameterStr != "")
				sParameterStr += ', ';
			sParameterStr += sKey + ':' + oAr["parameter"][sKey];
		}
		var sUWAId = (oAr["id"])?oAr["id"]:oAr["title"];
		aData.push(new Array(sUWAId,oAr["title"],oAr["url"],oAr["autorefresh"],
															sParameterStr,oAr["visible"],oAr["standalone"]));	
	}
	oStorage.append(aData);	
	oUWAModulesLG.enable(oStorage);					
}

function openExternalEditPopup(){
	objExternalPopupWindow.open();
	var oExternalObj = configGetKey("gui.portal.externalcontents");		
	var aSelectedRows = oUWAModulesLG.selection.getSelected();		
	sIdEditExternalUWAPortal = aSelectedRows[0];
	$("external_window_uwa_name").value = oUWAModulesLG.storage.data.data[aSelectedRows[0]][1];
	$("external_window_uwa_uri").value = oUWAModulesLG.storage.data.data[aSelectedRows[0]][2];	
	$("external_autorefresh").checked = oUWAModulesLG.storage.data.data[aSelectedRows[0]][3];		
	$("external_window_uwa_params").value = oUWAModulesLG.storage.data.data[aSelectedRows[0]][4];
	$("external_standalone").checked = oUWAModulesLG.storage.data.data[aSelectedRows[0]][6];		
}

function openExternalAddPopup(){
	sIdEditExternalUWAPortal = -1;
	objExternalPopupWindow.open();
}
function add_item(){	
	var oData = {	name:$("external_window_uwa_name").value,
					autorefresh:($("external_autorefresh").checked)?true:false,
					url:$("external_window_uwa_uri").value,
					parameter:$("external_window_uwa_params").value,
					standalone:($("external_standalone").checked)?true:false
				};
	if(oData.name.length == 0 || oData.url.length == 0)
	{
		return;
	}
	var sParams = oData.parameter;
	var oParams = new Object();	
	if(sParams != "")
	{
		var aPairs = sParams.split(',');
		var aPairsSplited = new Array();
		for(var nP=0;nP<aPairs.length;nP++)
		{
			 var oCurrPair = aPairs[nP].split(':');
			 oParams[trimStr(oCurrPair[0])] = trimStr(oCurrPair[1]);
			 for(var nIndx=2; nIndx < oCurrPair.length; nIndx++)			 
				 oParams[trimStr(oCurrPair[0])] += (':' + trimStr(oCurrPair[nIndx]));
		}
	}
	var nY = 0; //(oPortalObject.matrix.nodes.length-1);
	var nX = 0; //(oPortalObject.matrix.nodes[nY].length) + objExternalContAdded.length;	
	var oExternalObj = configGetKey("gui.portal.externalcontents");	

	if(sIdEditExternalUWAPortal == -1)
	{
		var obj = {id: (oData.name+Math.ceil(Math.random() * 1000)), title:oData.name,
									url:oData.url,autorefresh:oData.autorefresh,visible:true,
									standalone:oData.standalone,parameter:oParams,adj:{x:nX,y:nY,ww:1,hw:1}};									
		objExternalContAdded.push(obj);									
		oExternalObj.push(obj);
	}
	else
	{
		for(var nindx=0;nindx<oExternalObj.length;nindx++)
		{
			var sId = (oExternalObj[nindx]["id"])?oExternalObj[nindx]["id"]:oExternalObj[nindx]["title"];
			if(sId == sIdEditExternalUWAPortal)
			{
				if(oExternalObj[nindx]["id"] == undefined)
					oExternalObj[nindx]["id"] =  (oData.name+Math.ceil(Math.random() * 1000));
				oExternalObj[nindx].title = oData.name;
				oExternalObj[nindx].parameter = oParams;				
				oExternalObj[nindx].url = oData.url;			
				oExternalObj[nindx].autorefresh = oData.autorefresh;
				oExternalObj[nindx].standalone = oData.standalone || false;
				objExternalContChanged.push(sId);
				break;
			}
		}
	}
	configSetKey("gui.portal.externalcontents",oExternalObj);
	configuration_changed_fields["gui"]=true;
	setUWALG();										
}

function change_visibility(bEnable)
{
	var oExternalObj = configGetKey("gui.portal.externalcontents");		
	var aSelectedRows = oUWAModulesLG.selection.getSelected();
	for(var nItem in oExternalObj)
	{
		for(var nSel=0;nSel<aSelectedRows.length;nSel++)
		{
			var sId = (oExternalObj[nItem]["id"])?oExternalObj[nItem]["id"]:oExternalObj[nItem]["title"];
			if(sId == aSelectedRows[nSel])
			{
				oExternalObj[nItem]["visible"] = bEnable;
			}
		}
	}
	configSetKey("gui.portal.externalcontents",oExternalObj);
	configuration_changed_fields["gui"]=true;
	setUWALG();
}
function enable_items(){
	change_visibility(true);	
}
function disable_items(){
	change_visibility(false);
}
function remove_items(){
	var sCommText="Are you sure you want to permanently delete the selected UWA modules?"; /*i18n*/
	
	function cbok() {
		var oExternalObj = configGetKey("gui.portal.externalcontents");		
		var aSelectedRows = oUWAModulesLG.selection.getSelected();
		oUWAModulesLG.deleteIDs(aSelectedRows);			
		objExternalContRemoved =  objExternalContRemoved.concat(aSelectedRows);
		for(var nItem in oExternalObj)
		{
			for(var nSel=0;nSel<aSelectedRows.length;nSel++)
			{
				if(oExternalObj[nItem].id == aSelectedRows[nSel])
				{
					oExternalObj.splice(nItem,1);
				}
			}
		}
		configSetKey("gui.portal.externalcontents",oExternalObj);
		configuration_changed_fields["gui"]=true;
	}
	newConfirm(_("Delete UWA Modules"),_(sCommText),AlertPopup.YESNO,null,null,cbok,null,null);	
}
function cpe_leave(){
	oUWAModulesLG.disable();
}