naviki.main.portlets.AbstractPortlet = function(config) {

	/* set the config */
	this.config = config;
	this.type   = this.config['type'];
	this.lpUID  = this.config['lpUID'];
	this.pageID = this.config['pageID'];
	
	/* the url for the db calls */
	this.dburl = 'index.php?eID=tx_naviki_pi_portlets&actionId=';
	
	/* create the panel config */
	var panelconfig = {
		width:""+this.config['width']+"px",
		visible:true,
		draggable:true,
		close:true,
		constraintoviewport: false,
		underlay: "none"
	};
	
	/* the panelname */
	this.panelname = this.config['containerid']+'.portlet.nr.'+new Date().valueOf();
	
	/* create the real YUI Panel */
	YAHOO.widget.Panel.superclass.constructor.call(this, this.panelname, panelconfig); 

	this.x = -1;
	this.y = -1;
	this.dbid = -1;
	this.minimized = 0;
	this.myDTDrags = new Array();

	/* register events */
	eventMgr.updatePortlet.subscribe(this.updatePortlet, this);
	eventMgr.updateWidth.subscribe(this.updateWidth, this);
	
	/* make some inits */
	this.initialize();
};


/* set the dbid for this portlet */
naviki.main.portlets.AbstractPortlet.prototype.setDBID = function(dbid) {
	this.dbid = dbid;
};

/* get the x position in the matrix layout */
naviki.main.portlets.AbstractPortlet.prototype.getXMatrixPosition = function() {
	return this.x;
};

/* get the y position in the matrix layout */
naviki.main.portlets.AbstractPortlet.prototype.getYMatrixPosition = function() {
	return this.y;
};

/* set the x position in the matrix layout */
naviki.main.portlets.AbstractPortlet.prototype.setXMatrixPosition = function(x) {
	this.x = x;
};

/* set the y position in the matrix layout */
naviki.main.portlets.AbstractPortlet.prototype.setYMatrixPosition = function(y) {
	this.y = y;
};

/* set if the portlet is minimized or not */
naviki.main.portlets.AbstractPortlet.prototype.setMinimized = function(minimized) {
	this.minimized = minimized;
};

/* get the type of the portlet */
naviki.main.portlets.AbstractPortlet.prototype.getType = function() {
	return this.type;
};

/* this method is called to update the position in the layout matrix */
naviki.main.portlets.AbstractPortlet.prototype.updatePositionInLayout = function(x, y) {
	this.x = x;
	this.y = y;
	this.save();
};




naviki.main.portlets.AbstractPortlet.prototype.onSaveSuccess = function(o) {
	var result = YAHOO.lang.JSON.parse(o.responseText);
	var me = o.argument[0];
	if (result['STATE'] == "OK") {
		//alert("Position updated.");
	} else {
		alert("Fehler: "+result['ERROR_TEXT']);
	}	
};

naviki.main.portlets.AbstractPortlet.prototype.onSaveFail = function() {
	alert("Ein Fehler ist aufgetreten.");
};

/* save the current state of thep portlet */
naviki.main.portlets.AbstractPortlet.prototype.save = function() {
	var address = "index.php?eID=tx_naviki_pi_portlets&actionId=updatePortlet"+
		"&x="+this.x+
		"&y="+this.y+
		"&uid="+this.dbid+
		"&minimized="+this.minimized;
	var getXML = YAHOO.util.Connect.asyncRequest("GET",address, {
		success : this.onSaveSuccess,
		failure : this.onSaveFail,
		argument: [this],
		cache: true
	});
};


naviki.main.portlets.AbstractPortlet.prototype.getPageID = function() {
	return this.config['portletcontainer'].config['pageId']; 
};

/* this method is called when hiding the portlet */
naviki.main.portlets.AbstractPortlet.prototype.onHiding = function(type, e, me) {
	this.config['portletcontainer'].deletePortlet(this);
	return;
};


/* this method is called while dragging the portlet */
naviki.main.portlets.AbstractPortlet.prototype.onDragging = function(type, e, me) {
	//this.logger.log("Type: "+type, "debug");
	this.logger.log("E: "+e+" e[0]: "+e[0], "debug");
	//this.logger.log("Me: "+me, "debug");
	
	if (e[0] == "startDrag") {
		this.container.style.position = "absolute";
		this.container.style.zIndex   = naviki.main.Util.bringToTop();
		return;
	}
	if (e[0] == "endDrag") {
		this.config['portletcontainer'].onPortletEndDrag(this);
		this.container.style.zIndex = naviki.main.Util.bringToTop();
		return;
	}
};

/* get the container of the portlet, the real div which includes the yahoo panel */
naviki.main.portlets.AbstractPortlet.prototype.getPanelContainer = function() {
	return this.container;
};

/* get the x position (pixel) of the portlet container */
naviki.main.portlets.AbstractPortlet.prototype.getX = function() {
	return YAHOO.util.Dom.getRegion(this.container.id).left;
};

/* get the y position (pixel) of the portlet container */
naviki.main.portlets.AbstractPortlet.prototype.getY = function() {
	return YAHOO.util.Dom.getRegion(this.container.id).top;
};

/* the render function for the portlet / panel */
naviki.main.portlets.AbstractPortlet.prototype.render = function(con) {
	naviki.main.portlets.AbstractPortlet.superclass.render.call(this, con);
	var id_con = this.id+"_c";
	this.container = document.getElementById(id_con);
	this.container.style.position = "static";
};

/* init */
naviki.main.portlets.AbstractPortlet.prototype.initialize = function() {
	
    this.logger = new YAHOO.widget.LogWriter("AbstractPortlet"); 
	this.logger.log("Init: ", "debug");

	/* register me for dragging events */	
	this.dragEvent.subscribe(this.onDragging, "");
	this.hideEvent.subscribe(this.onHiding, "");
	
	/* the datasource for the YUI table */
	this.oDataSource = new YAHOO.util.DataSource(this.dburl);
	this.oDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; 
	this.oDataSource.connXhrMode = "queueRequests";
	this.oDataSource.responseSchema = {
		resultsList: 'RESULTVALUE.RESULTLIST', 
	    fields: this.fields,
	    metaFields: { 
			totalRecords: "RESULTVALUE.TOTALRECORDS"
		}
	}; 

	/* the columns definition */
	this.aColumnDefs = [
		{key:"uid", label:"", formatter: this.formatTableRow} 
    ];
	
	/* create template */
	if(this.garbage==true){
		var garbage = '<div class="tx-naviki-pi-portlets-garbage paginator_garbage_'+this.type+'"></div>';
	}else{
		garbage = "";
	}

	/* create the config for the YUI table */
	this.oConfigs = { 
		paginator: new YAHOO.widget.Paginator({
			template: '<div style="width: 100%">'+
					'<table style="width: 100%; text-align: center"><tr style="text-align: center">'+
					'<td class="paginator_prevlinks_'+this.type+'">{PreviousPageLink}</td>'+
					'<td class="paginator_pagelinks_'+this.type+'" style="width: 100%; text-align: center">{PageLinks}</td>'+
					'<td class="paginator_nextlinks_'+this.type+'"><table><tr><td>'+garbage+'</td><td>{NextPageLink}</td></tr></table></td>'+
					'</tr></table>'+
					'</div>',
        	rowsPerPage: 5,
            previousPageLinkLabel : "&#9668;",
            nextPageLinkLabel : "&#9658;",
            alwaysVisible: false
        }),
		initialRequest: "sort=id&dir=asc&startIndex=0&results=5",
		dynamicData: true,
		MSG_ERROR : naviki.Lang.getLL('yui_dataTable_msg_error'),
        MSG_EMPTY : naviki.Lang.getLL('yui_dataTable_msg_empty'),
        MSG_LOADING : "<div><img src='"+naviki.Util.FILEADMIN_PATH + "img/ajax-loader-2.gif'/></div>"
    };
	
	//when a page has been turned, only the ways that are on the currrent page shoud be displayed
	this.oConfigs.paginator.subscribe('render',this.updatePagination);
	this.oConfigs.paginator.subscribe('render',this.addDDRow);
	this.oConfigs.paginator.myObj = this;
	
	/* create div */
	this.tablediv = document.createElement("div");

	/* the div for the table */
	this.setBody(this.tablediv);
	
	/* crete the YUI table */
	this.oDataTable = new YAHOO.widget.DataTable(
		this.tablediv,
		this.aColumnDefs,
		this.oDataSource,
		this.oConfigs
	);
	
	/* so i have a reference to the portlet */
	this.oDataTable.getColumn(0).naviki_pi_portlet = this;

	/* the header text */		
	this.setHeader(this.headerName);
	
	this.oDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
		if(typeof oPayload!="undefined"){
			oPayload.totalRecords = oResponse.meta.totalRecords;
			return oPayload;
		}else{
			return oResponse;
		}
    };

	this.oDataTable.subscribe('renderEvent',this.addDDRow);
	this.oDataTable.subscribe('renderEvent',this.updatePagination);
	this.oDataTable.myObj = this;
};

naviki.main.portlets.AbstractPortlet.prototype.updatePagination = function(){
	
	var links   = YAHOO.util.Dom.getElementsByClassName("paginator_pagelinks_"+this.myObj.type)[0];
	var prev    = YAHOO.util.Dom.getElementsByClassName("paginator_prevlinks_"+this.myObj.type)[0];
	var next    = YAHOO.util.Dom.getElementsByClassName("paginator_nextlinks_"+this.myObj.type)[0];
	var garbage = YAHOO.util.Dom.getElementsByClassName("paginator_garbage_"  +this.myObj.type)[0];

	if(garbage!=null){
		 YAHOO.util.Dom.setStyle(garbage,"display","none");
	}

	if(links!=null){
		
		var regionLinks     = YAHOO.util.Dom.getRegion(links);
		var ankers          = links.getElementsByTagName("a");
		var count           = 1;
		var offset          = 0;
		
		if(prev!=null&&next!=null){
			var regionnext = YAHOO.util.Dom.getRegion(prev);
			var regionprev = YAHOO.util.Dom.getRegion(next);
			offset         = regionnext.width + regionprev.width;
		}
		
		while((regionLinks.width + offset)>this.myObj.config['width']){
			YAHOO.util.Dom.setStyle(ankers[count-1], "display", "none");
			regionLinks = YAHOO.util.Dom.getRegion(links);
			if((regionLinks.width + offset)>this.myObj.config['width']){
				YAHOO.util.Dom.setStyle(ankers[ankers.length-count], "display", "none");	
				regionLinks = YAHOO.util.Dom.getRegion(links);
			}
			count++;
		}
	}
};

naviki.main.portlets.AbstractPortlet.prototype.addDDRow = function(){
	
	if(this.myObj.garbage==true){

		var i, id, wayid;
	    var allRows = this.myObj.oDataTable.getTbodyEl().rows; 
	    var records = this.myObj.oDataTable.getRecordSet().getRecords();

	    for(i=0; i<allRows.length; i++) {
	    	wayid = records[records.length-allRows.length+i].getData("uid");
			id    = allRows[i].id;

			// Clean up any existing Drag instances 
			if (this.myObj.myDTDrags[id]) { 
				this.myObj.myDTDrags[id].unreg();
				delete this.myObj.myDTDrags[id]; 
			} 
			
			// Create a Drag instance for each row 
			this.myObj.myDTDrags[id] = new naviki.main.portlets.DDobject(id,null,
					{
						lpUID:this.myObj.lpUID,
						pageID:this.myObj.pageID,
						wayID: wayid,
						type: this.myObj.type
					}
			);
			this.myObj.myDTDrags[id].setHandleElId("portlets_handle_"+wayid);
	    }
	}
};

naviki.main.portlets.AbstractPortlet.prototype.updatePortlet = function(type, e, me){

	var callback = {
			success : function(){
				this.onDataReturnReplaceRows.apply(this,arguments);
			},
			failure : function(){
				this.onDataReturnReplaceRows.apply(this,arguments);
			},
			scope : me.oDataTable,
			cache : true
	};
	
	var startIndex = 0;
	var records    = me.oDataTable.getRecordSet();
	for(var i=0;i<records.getLength();i++){
		if(parseInt(records.getRecord(i).getData('uid'))==parseInt(e[0])){
			startIndex = me.oConfigs.paginator.getStartIndex();
			me.oDataSource.sendRequest("sort=id&dir=asc&startIndex="+startIndex+"&results=5",callback);
			break;
		}
	}
};

naviki.main.portlets.AbstractPortlet.prototype.updateWidth = function(type, e, me){
	me.getPanelContainer().style.width                = e[0] + "px";
	document.getElementById(me.panelname).style.width = e[0] + "px";
};


