naviki.main.portlets.Container = function(config) {
	this.config = config;
	this.divid = config['divid'];
	this.containerid  = config['containerid'];
	this.containerObj = config['containerObj'];
	
	this.initialize();
};


/* Deleting the portlet */
naviki.main.portlets.Container.prototype.deletePortlet = function (portlet) {
	/* first delete it */
	var i=0;
	for (i=0;i<this.portlets.length;i++) {
		if (portlet.dbid == this.portlets[i].dbid) {
			/* found portlet to delete */
			/* and from the portlets-array */
			this.portlets.splice(i,1);

			/* and also from the db */
			var address = "index.php?eID=tx_naviki_pi_portlets&actionId=deletePortlet"+
			"&uid="+portlet.dbid;
			var getXML = YAHOO.util.Connect.asyncRequest("GET",address, {
				success : this.onDeletePortletSuccess,
				failure : this.onDeletePortletFail,
				argument: [this, portlet],
				cache: false
			});
			/* update the position of all other portlets */
			this.layout.updatePortletPositions();
		}
	}
};

/* portlet was deleted from the db */
naviki.main.portlets.Container.prototype.onDeletePortletSuccess = function(o) {
	var result = YAHOO.lang.JSON.parse(o.responseText);
	var container = o.argument[0];
	var portlet = o.argument[1];
	if (result['STATE'] == "OK") {
		//alert("Und wech");
		/* this will delete the portlet also from the layout */
		portlet.destroy();
	} else {
		alert("Fehler: "+result['ERROR_TEXT']);
	}	
};

/* error while deleting a portlet from db */
naviki.main.portlets.Container.prototype.onDeletePortletFail = function() {
	alert("Ein Fehler ist aufgetreten.");
};


/* Dragging ended */
naviki.main.portlets.Container.prototype.onPortletEndDrag = function (portlet) {
	/* place the portlet in the layout */
	this.layout.placePortlet(portlet);	
};

/* portlet was added to the database */
naviki.main.portlets.Container.prototype.onAddingPortletSuccess = function(o) {
	var result = YAHOO.lang.JSON.parse(o.responseText);
	var container = o.argument[0];
	if (result['STATE'] == "OK") {
		//alert("p: "+p);
		container.portlets[result['INDEX']].setDBID(result['UID']);		
	} else {
		alert("Fehler: "+result['ERROR_TEXT']);
	}	
};

/* error while adding portlet to db */
naviki.main.portlets.Container.prototype.onAddingPortletFail = function() {
	alert("Ein Fehler ist aufgetreten.");
};

naviki.main.portlets.Container.prototype.addPortlet = function(typeid) {
	var index = this.portlets.length;

	/* create portlet */
	this.createPortlet(index, ''+typeid);	
	/* add the portlet to the layout */
	this.layout.addNewPortlet(this.portlets[index]);
		
	/* save it also to the db */
	var address = "index.php?eID=tx_naviki_pi_portlets&actionId=addNewPortlet"+
		"&x="+this.portlets[index].getXMatrixPosition()+
		"&y="+this.portlets[index].getYMatrixPosition()+
		"&index="+index+
		"&type="+this.portlets[index].getType();
	var getXML = YAHOO.util.Connect.asyncRequest("GET",address, {
		success : this.onAddingPortletSuccess,
		failure : this.onAddingPortletFail,
		argument: [this],
		cache: false
	});
	
	/* add it to the overlay manager */
	this.overlaymanager.register([this.portlets[index]]);
	
	/* update region */
	this.containerregion = YAHOO.util.Dom.getRegion(this.containerid);
};

naviki.main.portlets.Container.prototype.prepareAddDialog = function() {
	if (this.addDialog) {
		return;
	}
	
	var dialog_container = document.getElementById("naviki-dialogs");
	var dialog = document.createElement("div");
	dialog.id = ""+dialog_container.id+"_"+this.containerid;
	var content = '';
	content += '<div class="portletDialog">'+
		'<form>'+
  		'<p>'+naviki.Lang.getLL('portletsAddPortletMessage')+'<br/><br/></p>'+
  		'<table>';
  	for (var i=0;i<this.PORTLET_TYPES.length;i++) {
  		content += '<tr><td valign="top"><input style="width:auto" type="checkbox" name="'+
  			'checkbox'+i+'" id="'+this.containerid+'_checkbox_addDialog_'+i+'"></td><td>'+this.PORTLET_TYPES[i]['name']+'</td></tr>';
	} 
  	content += '</table>'+
		'</form>'+
		'</div>';
	 
	dialog.innerHTML = content;
	
	dialog_container.appendChild(dialog);
	this.addDialog = new naviki.main.ModalDialog(
		""+dialog.id,{ 	
			width: "300px",  
			visible: false,
			modal: true,
			draggable: true,
			fixedcenter: true,  
       		zindex: 50,  
			close: true,  
			constraintoviewport: true,	        
	        
	        buttons: [ 
	        	{ text:"Ok", handler: this.handleAddDialogOk }  
	        ] 
	    }
	 );
	
	 this.addDialog.portletcontainer = this;
	 this.addDialog.setHeader(naviki.Lang.getLL("portletsAddPortlet"));
	 
	 this.addDialog.render();
};

/* add a new portlet */
naviki.main.portlets.Container.prototype.onPortletAddClick = function() {
	this.portletContainer.prepareAddDialog();
	this.portletContainer.updateAddDialog();
	this.portletContainer.addDialog.show();
};

/* create a portlet */
naviki.main.portlets.Container.prototype.createPortlet = function(index, type) {
	var text = "";
	var typeindex = 0;
	for (var i=0;i<this.PORTLET_TYPES.length;i++) {
		if (this.PORTLET_TYPES[i]['typeid'] == type) {
			typeindex = i;
		}
	}
	var classname = ""+this.PORTLET_TYPES[typeindex]['classname'];

	text = "" +
		'this.portlets[index] = new naviki.main.portlets.'+classname+'({'+
		'containerid: this.layout.getContainerID(),'+
		'portletcontainer: this,'+
		'width: this.layout.getPortletWidth(),'+
		'type: '+type+ ','+
		'lpUID: this.config["lpUID"],'+
		'pageID: this.config["pageId"]'+
		'});';
	eval(text);
};

/* create all loaded portlets */
naviki.main.portlets.Container.prototype.createLoadedPortlets = function(rows) {
	var i = 0;
	/* check if the user has any portlets at all */
	if (rows.length > 0) {
		for (i=0;i<rows.length;i++) {
			if(typeof rows[i]['portlettype']!="undefined"){
				this.createPortlet(i,rows[i]['portlettype']);
				this.portlets[i].setDBID(rows[i]['uid']);
				this.portlets[i].setXMatrixPosition(rows[i]['x']);
				this.portlets[i].setYMatrixPosition(rows[i]['y']);
				this.portlets[i].setMinimized(rows[i]['minimized']);
			}
		}
	} else {
		this.createDefaultPortlets();
	}
	
	/* place all portlets to the layout */
	this.layout.placeAllPortlets();	
};

/* updates the checkboxes in the add dialog */
naviki.main.portlets.Container.prototype.updateAddDialog = function() {
	var typeid;
	var wehave = 0;
	for (var i=0;i<this.PORTLET_TYPES.length;i++) {
		typeid = this.PORTLET_TYPES[i].typeid;
		/* now check, if we have such a portlet */
		wehave = 0;
		for (var j=0;j<this.portlets.length;j++) {
			if (typeid == this.portlets[j].getType()) {
				wehave = 1;
			}
		}
		if (wehave == 1) {
			document.getElementById(""+this.containerid+'_checkbox_addDialog_'+i).checked = "true";
		} else {
			document.getElementById(""+this.containerid+'_checkbox_addDialog_'+i).checked = null;
		}
	}
};

/* creates the default portlets for a user */
naviki.main.portlets.Container.prototype.createDefaultPortlets = function() {
	var dpstring = this.config['defaultPortlets'];
	var portletnumbers = dpstring.split(",");
	var i=0;
	for (i=0;i<portletnumbers.length;i++) {
		this.addPortlet(portletnumbers[i]);		
	}
};


/* loading the portlets was ok */
naviki.main.portlets.Container.prototype.onLoadPortletsSuccess = function(o) {
	var result = YAHOO.lang.JSON.parse(o.responseText);
	var container = o.argument[0];
	if (result['STATE'] == "OK") {
		container.createLoadedPortlets(result['RESULTVALUE']);	
	} else {
		alert("Fehler: "+result['ERROR_TEXT']);
	}	
};

/* error while loading the portlets */
naviki.main.portlets.Container.prototype.onLoadPortletsFail = function() {
	alert("Ein Fehler ist aufgetreten.");
};

/* load the portlets from db */
naviki.main.portlets.Container.prototype.loadPortlets = function() {
	var address = "index.php?eID=tx_naviki_pi_portlets&actionId=getPortlets";
	var getXML = YAHOO.util.Connect.asyncRequest("GET",address, {
		success : this.onLoadPortletsSuccess,
		failure : this.onLoadPortletsFail,
		argument: [this],
		cache: false
	});
};

/* add the portlets specified in the addDialog */
naviki.main.portlets.Container.prototype.addNewPortlets = function(data) {
	var checkbox;
	for (var i=0;i<this.PORTLET_TYPES.length;i++) {
		eval('checkbox = data.'+'checkbox'+i);
		if (!checkbox) {
			/* want to delete the portlet */
			var portlet = this.getPortletFromContainer(this.PORTLET_TYPES[i]['typeid']);
			if (portlet != null) {
				this.deletePortlet(portlet);
			}
		}
	}
	for (var i=0;i<this.PORTLET_TYPES.length;i++) {
		eval('checkbox = data.'+'checkbox'+i);
		if (checkbox) {
			/* want to add this content */
			if (this.isInContainer(this.PORTLET_TYPES[i]['typeid']) == false) {
				this.addPortlet(this.PORTLET_TYPES[i]['typeid']);
			}
		}
	}
};

/* searches a specific portlet type in the container and returns it */
naviki.main.portlets.Container.prototype.getPortletFromContainer = function(typeid) {
	for (var i=0;i<this.portlets.length;i++) {
		if (this.portlets[i].getType() == typeid) {
			return this.portlets[i];
		}
	}
	return null;
};


/* checks if a specific portlet type is in the container */
naviki.main.portlets.Container.prototype.isInContainer = function(typeid) {
	for (var i=0;i<this.portlets.length;i++) {
		if (this.portlets[i].getType() == typeid) {
			return true;
		}
	}
	return false;
};

/* handle the Ok Button from the addDialog */
naviki.main.portlets.Container.prototype.handleAddDialogOk = function(o) {
	this.portletcontainer.addDialog.hide();
	this.portletcontainer.addNewPortlets(this.getData());
};
/* handle the Cancel Button from the addDialog */
naviki.main.portlets.Container.prototype.handleAddDialogCancel = function(o) {
	this.portletcontainer.addDialog.hide();
};


/* init the container */
naviki.main.portlets.Container.prototype.initialize = function() {

	this.containerregion = YAHOO.util.Dom.getRegion(this.containerid);

	/* array which holds all Portlet objects */
	this.portlets = [];
	
	var TEXT_ADD_WIDGET = naviki.Lang.getLL('portletsAddPortlet');
	
	/* the portlet types and names */
	this.PORTLET_TYPES = [];
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsMyWays'),
		classname: "MyWaysPortlet",
		typeid: 1001
	};	
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsMyLongestWays'),
		classname: "MyLongestWaysPortlet",
		typeid: 1002
	};
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsMyPrivateWays'),
		classname: "MyPrivateWaysPortlet",
		typeid: 1007
	};
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsMyBestWays'),
		classname: "MyBestRatedWaysPortlet",
		typeid: 1010
	};
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsMyPublicWays'),
		classname: "MyPublicWaysPortlet",
		typeid: 1011
	};
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsMyRoutingRequest'),
		classname: "MyRoutingRequestPortlet",
		typeid: 1012
	};	
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsLongestWays'),
		classname: "LongestWaysPortlet",
		typeid: 1003
	};
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsHeighestWays'),
		classname: "HeighestWaysPortlet",
		typeid: 1004
	};
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsNewestWays'),
		classname: "NewestWaysPortlet",
		typeid: 1006
	};		
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsMostExportedWays'),
		classname: "MostExportedWaysPortlet",
		typeid: 1008
	};
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsBestRatedWays'),
		classname: "BestRatedWaysPortlet",
		typeid: 1009
	};	
	this.PORTLET_TYPES[this.PORTLET_TYPES.length] = {
		name: naviki.Lang.getLL('portletsUsersWithMostKMUploads'),
		classname: "UsersWithMostKMUploadsPortlet",
		typeid: 1005
	};
	
	/* the overlay manager */
	this.overlaymanager = new YAHOO.widget.OverlayManager();
	
	
	//var dialog = document.getElementById(""+this.config['addDialogDivID']);	   

	/* the add button */
	var addButton = new YAHOO.widget.Button(
	{	label: TEXT_ADD_WIDGET,
		name: this.divid+".addButton",
		container: this.divid 
	});
	addButton.on("click", this.onPortletAddClick);
	addButton.portletContainer = this;
	
	/* add a layout */
	this.layout = new naviki.main.portlets.LayoutColumns({
		containerid: this.containerid,
		container: this,
		columns: 2
	});

	/* load all portlets */
	this.loadPortlets();	
};

