naviki.main.WaysNextToPoint = function(tablediv, bbox, zoom, lat, lng, pageId, detailMapView) {

	var myObj          = this;
	this.loadedKml     = new Array();
	this.tablediv      = tablediv;
	this.update        = false;
	
	this.detailMapView = detailMapView;
	this.dburl         = 'index.php?eID=tx_naviki_pi_portlets&actionId=waysNextToPointSearch';

	this.oDataSource = new YAHOO.util.DataSource(this.dburl+"&pageid="+pageId+"&bbox="+bbox+"&");
	this.oDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; 
	this.oDataSource.responseSchema = {
		resultsList: 'RESULTVALUE.RESULTLIST', 
		fields: ["number","uid", "title", "tstamp","mediafileurl", "mapurl", "km","kmlfile_rel_path","highlighted_kmlfile_rel_path"],
        metaFields: { 
						totalRecords: "RESULTVALUE.TOTALRECORDS" // Access to value in the server response
					} 
	}; 

	/* the columns definition */
	this.aColumnDefs = [
	    {key:"uid", formatter: this.formatTableRow}
	];

	/* create the config for the YUI table */
	this.oConfigs = { 
		initialRequest: "sort=id&dir=asc&startIndex=0&results=5", // Initial request for first page of data 
		dynamicData: true, 
		paginator: new YAHOO.widget.Paginator({
			alwaysVisible: false,
			rowsPerPage: 5,
            previousPageLinkLabel : "&#9668;",
            nextPageLinkLabel : "&#9658;",  
	        pageReportTemplate: "{currentPage} "+naviki.Lang.getLL('searchPaginatorSeperator')+" {totalPages}", 
	        containers : ["paginator_"+tablediv],
			template: '<div style="width: 100%">'+
			'<table style="width: 100%; text-align: center"><tr style="text-align: center">'+
			'<td class="paginator_prevlinks_'+tablediv+'">{PreviousPageLink}</td>'+
			'<td class="paginator_pagelinks_'+tablediv+'" tyle="width: 100%; text-align: center;">{PageLinks}</td>'+
			'<td class="paginator_nextlinks_'+tablediv+'">{NextPageLink}</td>'+
			'</tr></table>'+
			'</div>'+
			''
        }),
        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('changeRequest',this.handlePagination);
	this.oConfigs.paginator.subscribe('render',this.updatePagination);
	this.oConfigs.paginator.myObj = this;	
	
	// create the YUI table 
	this.oDataTable = new YAHOO.widget.DataTable(
		tablediv,
		this.aColumnDefs,
		this.oDataSource,
		this.oConfigs
	);
	
	this.oDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { 
		oPayload.totalRecords = oResponse.meta.totalRecords;
		return oPayload;
    };
	
	//  a reference to this object WaysNextToPoint, to be accessed by the formatting function
	this.oDataTable.getColumn(0).naviki_ways_nextto_point = this;
	this.oDataTable.naviki_ways_nextto_point              = this;
	this.oConfigs.paginator.naviki_ways_nextto_point      = this;

	this.oDataTable.subscribe('renderEvent',this.updatePagination);
	this.oDataTable.myObj = this;
	
	// center the map
	eventMgr.mapPositioning.fire(lat,lng,zoom);
};

naviki.main.WaysNextToPoint.prototype.formatTableRow = function(elCell, oRecord, oColumn, sData) {
	
	var wayKMLFile = oRecord.getData("kmlfile_rel_path");
	oColumn.naviki_ways_nextto_point.handleResults(wayKMLFile);

	elCell.innerHTML = naviki.main.portlets.Util.formatWayRow({
		record: oRecord,
 		detailWayViewURL: oColumn.naviki_ways_nextto_point.detailMapView
	});	
};

//add way overlay in the map
naviki.main.WaysNextToPoint.prototype.handleResults = function(file){
	eventMgr.addWayOverlay.fire(file,null,null,1);
	this.loadedKml.push(file);

};

//remove way overlay in the map
naviki.main.WaysNextToPoint.prototype.handlePagination = function(){
	for(var i=0;i<this.naviki_ways_nextto_point.loadedKml.length;i++){
		eventMgr.removeWayOverlay.fire(this.naviki_ways_nextto_point.loadedKml[i]);
	}
	this.naviki_ways_nextto_point.loadedKml = new Array();
	this.naviki_ways_nextto_point.update = true;
};

naviki.main.WaysNextToPoint.prototype.updatePagination = function(){
	
	var container = document.getElementById("paginator_"+this.myObj.tablediv);
	var links     = YAHOO.util.Dom.getElementsByClassName("paginator_pagelinks_"+this.myObj.tablediv);
	var prev      = YAHOO.util.Dom.getElementsByClassName("paginator_prevlinks_"+this.myObj.tablediv);
	var next      = YAHOO.util.Dom.getElementsByClassName("paginator_nextlinks_"+this.myObj.tablediv);
	
	if(container!=null && links!=null){
		var regionContainer = YAHOO.util.Dom.getRegion("paginator_"+this.myObj.tablediv);
		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(next);
			var regionprev = YAHOO.util.Dom.getRegion(prev);
			offset         = regionnext.width + regionprev.width + 5;
		}
		
		while((regionLinks.width + offset)>regionContainer.width){
			YAHOO.util.Dom.setStyle(ankers[ankers.length-count], "display", "none");
			regionContainer = YAHOO.util.Dom.getRegion("paginator_"+this.myObj.tablediv);
			regionLinks     = YAHOO.util.Dom.getRegion(links);
			if((regionLinks.width + 40)>regionContainer.width){
				YAHOO.util.Dom.setStyle(ankers[count-1], "display", "none");
				regionContainer = YAHOO.util.Dom.getRegion("paginator_"+this.myObj.tablediv);
				regionLinks     = YAHOO.util.Dom.getRegion(links);
			}
			count++;
		}
	}
};

naviki.main.RouteSearch = function(tablediv, detailMapView, url) {

	this.detailMapView = detailMapView;
	
	this.oDataSource = new YAHOO.util.DataSource(url);
	this.oDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; 
	this.oDataSource.connXhrMode = "queueRequests"; 
	this.oDataSource.responseSchema = {
		resultsList: 'RESULTVALUE.RESULTLIST', 
	    fields: ["number", "uid" , "title", "tstamp", "mediafileurl", "mapurl", "km"] 
	}; 

	/* the columns definition */
	this.aColumnDefs = [
		{key:"uid", label:"", formatter: this.formatTableRow} 
    ];

	/* create the config for the YUI table */
	this.oConfigs = { 
		paginator: new YAHOO.widget.Paginator({
			alwaysVisible: false,
			rowsPerPage: 5,
            previousPageLinkLabel : "&#9668;",
            nextPageLinkLabel : "&#9658;",  

	        containers : [ 'paginator_'+tablediv ],
			template: '<div style="width: 100%">'+
			'<table style="width: 100%; text-align: center"><tr style="text-align: center">'+
			'<td>{PreviousPageLink}</td>'+
			'<td style="width: 100%; text-align: center">{PageLinks}</td>'+
			'<td>{NextPageLink}</td>'+
			'</tr></table>'+
			'</div>'+
			''
        }),
        initialRequest:"",
        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>"
    };

	/* crete the YUI table */
	this.oDataTable = new YAHOO.widget.DataTable(
		tablediv,
		this.aColumnDefs,
		this.oDataSource,
		this.oConfigs
	);
	/* so i have a reference to the portlet */
	this.oDataTable.getColumn(0).naviki_pi_searchresults = this;
};

naviki.main.RouteSearch.prototype.formatTableRow = function(elCell, oRecord, oColumn, sData) {
	elCell.innerHTML = naviki.main.portlets.Util.formatWayRow({
			record: oRecord,
     		detailWayViewURL: oColumn.naviki_pi_searchresults.detailMapView
	});
};



// main call to geosearch funtion from the typo3-engine
// expected parameters are the div-tag, which should contain the table later on,
// the query to look for in the databases and also the address of the call-back 
// function, because the search should be done asynchronusly, which means AJAX.
// So we provide as like TYPO3 standart another eID file, which isn't rendered by the
// TYPO3 engine and could so be used ideally for AJAX.
// The search should do the following:
//		- query Google Geolocation API for a first (and propably best) result
//		- query our local GeoNames DB (tx_naviki_geonames) for more results
//		- display the results in a YUI DataTable, which provides nice functionallity out
//		  of the box
naviki.main.GeoSearch = function(tbldiv, searchkey, prefixID) {
	
	var myObj   = this;
	this.tbldiv = tbldiv;
	
	// define the eid address
	var url = "index.php?eID="+prefixID+"&actionId=searchAddress&searchKey="+encodeURI(searchkey);
	
	// define table layout
	this.aColumnDefs = [ 			 
        {key:"name", label:"", formatter:this.formatTableRow, sortable:true}
	];
            
    // configure table:
    //		- paginator
    //		- initial request
	this.oConfigs = { 
                paginator: new YAHOO.widget.Paginator({ 
                	alwaysVisible: false,
                    rowsPerPage: 10,
                    previousPageLinkLabel : "&#9668;",
                    nextPageLinkLabel : "&#9658;", 
                    
			        containers : [ 'paginator_'+this.tbldiv ],
					template: '<div style="width: 100%">'+
					'<table style="width: 100%; text-align: center"><tr style="text-align: center">'+
					'<td>{PreviousPageLink}</td>'+
					'<td style="width: 100%; text-align: center">{PageLinks}</td>'+
					'<td>{NextPageLink}</td>'+
					'</tr></table>'+
					'</div>'+
					''
                }),
                initialRequest:"",
                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>"
    };
	
	// configure datasource as input for table
	this.oDataSource = new YAHOO.util.DataSource(url);
	this.oDataSource.connXhrMode = "queueRequests";
	this.oDataSource.connMgr = YAHOO.util.Connect;
	this.oDataSource.connMgr.initHeader('Content-Type', 'application/xml; charset=utf-8', true);
    this.oDataSource.responseType = YAHOO.util.DataSource.TYPE_XML;
	this.oDataSource.responseSchema = {
		resultNode: "Placemark",
		fields: ["name", "coordinates"],
		metaNode: "Document"
	};

	// define and configure the datatable
	this.oDataTable = new YAHOO.widget.DataTable(this.tbldiv, this.aColumnDefs, this.oDataSource, this.oConfigs);	
	this.oDataTable.subscribe("rowMouseoverEvent", this.oDataTable.onEventHighlightRow);
	this.oDataTable.subscribe("rowMouseoutEvent", this.oDataTable.onEventUnhighlightRow);
	this.oDataTable.subscribe("rowClickEvent", function(oArgs){
		eventMgr.displaySearchResult.fire(this.getRecord(oArgs.target));
	});
};

naviki.main.GeoSearch.prototype.formatTableRow = function(elCell, oRecord, oColumn, sData) {
	elCell.innerHTML = "<div style='padding:5px;'>"+oRecord.getData("name")+"</div>";
};

// function to check the input of the searchstring field, which is input of
// geosearch function
function searchstringvalidation(form, skipAlerts) {
	
	// define string-trimmer
	String.prototype.trim = function() {
		// skip leading and trailing whitespace
		// and return everything in between
		var x=this;
		x=x.replace(/^\s*(.*)/, "$1");
		x=x.replace(/(.*?)\s*$/, "$1");
		return x;
	};
	
	// check if search term is too short (too long query...)
	var searchstring = form.txtSearchKey.value;
	if (searchstring.trim == "" || searchstring.length < 3) {
		if(!skipAlerts)
			alert (naviki.Lang.getLL('searchTooShort'));
		return false;
	}
	
	// check if search term contains special chars, which are not permitted
	var special_chars = [/\\/,/\?/,/=/,/:/,/;/,/_/,/#/,/'/,/\+/,/\*/,/~/,/\^/,/°/,/\$/,/&/,/\)/,/\(/,/§/,/!/,/\"/,/\{/,/\}/,/\[/,/\]/,/%/,/</,/>/,/\|/];
	for(var index=0; index<special_chars.length; index++) {
		if (searchstring.match(special_chars[index])) {
			if(!skipAlerts)
				alert (naviki.Lang.getLL('searchInvalid'));
			return false;
		}
	}
	return true;
};

// function to commit the search while pressing the enter-button
function checkEnter(e, formDivId){
	var e = e || window.event;
 	var key = e.keyCode || e.which || e.charCode, Shift = e.shiftKey;
 	
 	if(key == 13){
 		// perform a routing request
 		var f = document.getElementById(formDivId);
 		if(searchstringvalidation(f, true))
 			f.submit();
  		//naviki.main.RoutingRequest();
 	}
};

//function to to change the result target site
function changeTagetSite(formId, targetId){
	document.getElementById(formId).action = targetId;
};
