/* Author : Sourav Biswas */

/* Configuration Global Parameters */
// Mapserver thematic Map Parameters
var MAX_LEGENDS = 5;

// Marker Legend Register. Here all the Marker with their name is registered

var MARKER_LEGEND_MARKERS = new Array(	/* Markers used for Dairy */
									  new Array(["/assets/images/map/marker/sqr_altrd/SQR_ALTRD_AQUA.gif","AQUA"],		
												["/assets/images/map/marker/sqr_altrd/SQR_ALTRD_BLUE.gif","BLUE"],
												["/assets/images/map/marker/sqr_altrd/SQR_ALTRD_GREEN.gif","GREEN"],
												["/assets/images/map/marker/sqr_altrd/SQR_ALTRD_ORRANGE.gif","ORRANGE"],
												["/assets/images/map/marker/sqr_altrd/SQR_ALTRD_VIOLET.gif","VIOLET"],
												["/assets/images/map/marker/sqr_altrd/SQR_ALTRD_YELLOW.gif","YELLOW"]),
										/* Markers used for Tourism */
									  new Array(["/assets/images/map/marker/crc_altrd/CRC_ALTRD_AQUA.gif","AQUA"],											  
											    ["/assets/images/map/marker/crc_altrd/CRC_ALTRD_BLUE.gif","BLUE"],
											    ["/assets/images/map/marker/crc_altrd/CRC_ALTRD_GREEN.gif","GREEN"],
											    ["/assets/images/map/marker/crc_altrd/CRC_ALTRD_ORRANGE.gif","ORRANGE"],
											    ["/assets/images/map/marker/crc_altrd/CRC_ALTRD_RED.gif","RED"],
											    ["/assets/images/map/marker/crc_altrd/CRC_ALTRD_VIOLET.gif","VIOLET"],
											    ["/assets/images/map/marker/crc_altrd/CRC_ALTRD_YELLOW.gif","YELLOW"]),
										/* Markers used for Agriculture */
									  new Array(["/assets/images/map/marker/dgnl_sqr/DGNL_SQR_GREEN.gif","GREEN"],
											    ["/assets/images/map/marker/dgnl_sqr/DGNL_SQR_ORRANGE.gif","ORRANGE"],
											    ["/assets/images/map/marker/dgnl_sqr/DGNL_SQR_VIOLET.gif","VIOLET"]),
										/* Markers used for Font Town */
									  new Array(["/assets/images/map/marker/crclr/CRCLR_YELLOW.gif","GREEN"]));

function CS_Map(targetObj, centerLat, centerLong, zoomLavel) {
	// alert("Called....2");

	/* Class variable to hold the state of the map */
	var map = null;
	
	if (map == null) {
		map = new google.maps.Map2(targetObj);

		map.setCenter(new google.maps.LatLng(centerLat, centerLong), zoomLavel);
		map.addControl(new GScaleControl()); // Adding Scale Control
		map.addControl(new GLargeMapControl3D()); // Adding Navigation Control
		map.addControl(new GMapTypeControl()); // Adding MapType Control Map,Satelite, Hybrid
		
		map.addControl(new GZoomControl(
				/* first set of options is for the visual overlay.*/
				{
					nOpacity:.2,
					sBorder:"2px solid red"
				},
				/* second set of optionis is for everything else */
				{
					sButtonHTML:"<img src='"+baseUrl+"/assets/images/map/zoom/rectangle-zoom-button.gif' />",
					sButtonZoomingHTML:"<img src='"+baseUrl+"/assets/images/map/zoom/rectangle-zoom-button-on.gif' />",
					oButtonStartingStyle:{width:'18px',height:'18px'}
				},
				/* third set of options specifies callbacks */
				{
					//buttonClick:function(){display("Looks like you activated GZoom!")},
					//dragStart:function(){display("Started to Drag . . .")},
					//dragging:function(x1,y1,x2,y2){display("Dragging, currently x="+x2+",y="+y2)},
					//dragEnd:function(nw,ne,se,sw,nwpx,nepx,sepx,swpx){display("Zoom! NE="+ne+";SW="+sw)}
				}
			),new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(215,7)));
		// map.setMapType(G_NORMAL_MAP); // Setting Normal Control
		// map.enableGoogleBar();
		// map.setMapType(G_HYBRID_MAP);  //Setting Hybrid Control
		map.enableScrollWheelZoom(); //Enable mouse wheel zoom
	}

	this.setCenter = function(centerLat, centerLong, zoomLavel) {
		map.setCenter(new google.maps.LatLng(centerLat, centerLong), zoomLavel);
	}
	this.setCenterFromBoundbox = function(boundbox){
		map.setCenter(boundbox.getCenter(),map.getBoundsZoomLevel(boundbox));
	}

	this.addOverlay = function(item) {
		map.addOverlay(item);
	}

	this.removeOverlay = function(item) {
		map.removeOverlay(item);
	}

	this.getContainerDiv = function(){
		return targetObj;
	}
	
	this.getMap = function() {
		return map;
	}
}

function CS_LayersMapServer(map, mapServerURL, transparency, lgndsString, zPrty) {
	var tileLayerObj = null;
	var layerObj = null;
	var legendString = lgndsString;
	var boundingBox = null;
	var url = mapServerURL;
	var trans = transparency;
	var zPriority = (isNaN(zPrty)?0:zPrty); 

	try{
		tileLayerObj = new GTileLayer(null,0,18,{tileUrlTemplate:url,isPng:true,opacity:trans });
		layerObj = new GTileLayerOverlay(tileLayerObj ,{zPriority:zPriority});
		
		map.addOverlay(layerObj);
	}catch(e){
		layerObj = null;
	}
	
	this.showLayer = function(){
		layerObj.show();
	}

	this.hideLayer = function(){
		layerObj.hide();
	}
	
	this.isHidden = function(){
		return layerObj.isHidden();
	}
	
	this.removeLayer = function(){
		map.removeOverlay(layerObj);
	}

	this.getLegend = function(){
		return legendString; 
	}
	this.setLegend = function(lgndObj){
		legendObj = lgndObj;
	}
	this.setTransparency = function(transLevel){
		this.removeLayer();
		trans = transLevel; 
		layerObj = new GTileLayerOverlay( new GTileLayer(null,0,18,{tileUrlTemplate:url,isPng:true,opacity:trans }),{zPriority:zPriority});
		map.addOverlay(layerObj);
	}
	this.setBoundingBox = function(bounds){
		map.setBounds();
	}
}

function CS_Markers(map,markerDetails,legend) {
	var gLatLng = null;
	var details = null;
	var legendString = legend;
	
	var markerCluster = null;
	var markers = [];
	var cIcon = null;
	var htmlText = null;	
	var tempMarker = null;
	
	var tmpTime = null;
	
	if(map != null && markerDetails != null){
		tmpTime = new Date().getTime();
		len = markerDetails.length;

		markers = new Array();
		try{
			var i,len;
			for(i=0; i<len ;i++){
				tempMarker = null;

				gLatLng = markerDetails[i][0];
				details = markerDetails[i][1];

				cIcon = new GIcon(G_DEFAULT_ICON);
				cIcon.image = baseUrl+MARKER_LEGEND_MARKERS[details[0][0]][details[0][1]][0];
				cIcon.shadow = "";

				cIcon.iconSize = new GSize(13, 18);
				cIcon.iconAnchor = new GPoint(6, 18);

				htmlText = getInfoBoxContent(details);
				tempMarker = createMarker(gLatLng,{icon :cIcon},htmlText);
				map.addOverlay(tempMarker);
				markers.push(tempMarker);
			}
			//alert("Layer Processing Time : ["+tmpTime+"] : "+(new Date().getTime()-tmpTime));
		}catch(e){
			alert("[Map file :: Marker] : "+e);
			alert(details[0][0]+":"+details[0][1]/*+"\n"+baseUrl+MARKER_LEGEND_MARKERS[details[0][0]][details[0][1]][0]*/);
		}
	}else{
		//alert("Map or Marker Layer Null");
	}

	function createMarker(point,markerOptions,html) {		
		var marker = new GMarker(point,markerOptions);
		//GEvent.addListener(marker,"mouseover",function(){
		GEvent.addListener(marker,"click",function(){
			marker.openInfoWindowHtml(html);
		});
		return marker;
	}

	function getInfoBoxContent(details){
		var startText = '<table width="200px" border="0" cellspacing="2" cellpadding="0" class="infoWindow">';
		var endText = '</table>';
		var ibItr,ibLen;
		var html = null;
		if(details != null && (ibLen = details.length) > 1){
			html = startText;
			for(ibItr = 1; ibItr<ibLen ; ibItr++){
				html += '<tr><td width="30%" valign="top" class="label">'+(details[ibItr][0]!=''?details[ibItr][0]+':':'')+'</td><td width="70%">'+details[ibItr][1]+'</td></tr>';
			}
			html += endText;
		}else{
			html = startText+'<tr><td>N/A</td></tr>'+endText;
		}
		//alert(html);
		return html;
	}

	this.showClusterMarkers = function(map){
		markerCluster = new MarkerClusterer(map.getMap(), markers);
	}
	
	this.removeClusterMarkers = function(map){	
		markerCluster.clearMarkers();		
	}
	
	this.showMarker = function(map) {
		//alert("Called 2a");
		var iS,lenS;
		if(markers != null){
			lenS = markers.length;
			for(iS = 0 ; iS<lenS ; iS++){
				//map.addOverlay(markers[iS]);
				markers[iS].show();
			}
		}
		//alert("Showing Executed");
	}
	
	this.hideMarker = function() {		
		//alert("Called 2b");
		var iH,lenH;
		if(markers != null){
			lenH = markers.length;
			for(iH = 0 ; iH<lenH ; iH++){
				//map.removeOverlay(markers[iH]);
				markers[iH].hide();
			}
		}
		//alert("Hiding Executed");
	}
	
	this.removeMarkers = function(){//alert("Called 2b");
		var iH,lenH;
		if(markers != null){
			lenH = markers.length;
			for(iH = 0 ; iH<lenH ; iH++){
				map.removeOverlay(markers[iH]);
				
			}
		}
		//alert("Hiding Executed");
	}
	
	this.getLegendString = function(){
		return legendString;
	}
}

function CS_MarkerLegends(divId, className, label,dataArray){
	var legStrStart = '<div id="'+divId+'"><ul class="'+className+'"><li class="header">'+label+'</li>';
	var legStrEnd = '</ul><div style="height:1px; clear:both"></div></div>';
	
	var legStr = null;
	
	var mlmItr = 0;
	var mlmLen = dataArray.length;
	
	legStr = legStrStart;
	
	for(mlmItr = 0; mlmItr<mlmLen; mlmItr++){
		legStr += "<li style='padding-left:10px'><img src='"+(baseUrl+MARKER_LEGEND_MARKERS[dataArray[mlmItr][0]][dataArray[mlmItr][1]][0])+"' align='absmiddle' />&nbsp;&nbsp;"+dataArray[mlmItr][2]+"</li>";
	}
	
	legStr += legStrEnd;
	
	this.getLegendString = function(){
		return legStr;
	}
}

function CS_LineLegends(colourParams,divId,className,label,type){
	var legStrStart = '<div id="'+divId+'"><ul class="'+className+'"><li class="header">'+label+'</li>';
	var legStrEnd = '</ul><div style="height:1px; clear:both"></div></div>';
	
	this.getLegendString = function(){
		return legStrStart+'<li style="padding-left:10px"><div style="width:11px; height:1px; float:left; background:rgb('+colourParams[0][0]+'); border: 1px solid rgb('+colourParams[0][1]+')" ></div><div style="float:left; border:none; position:static">&nbsp;&nbsp;'+colourParams[0][2]+'</div></li>'+legStrEnd;
	}
}

function CS_LayerLegends(minm,maxm,colourParams,divId,className,label,type){
	var legStrStart = '<div id="'+divId+'"><ul class="'+className+'"><li class="header">'+label+'</li>';
	var legStrEnd = '</ul><div style="height:1px; clear:both"></div></div>';
	//alert(colourParams[0][0]+""+colourParams[0][1]);
	var v1;
	var v2;
	var v3;
	var v4;
	var v5;
	var v6;
	
	this.isInitialized = function(){
		if(v1 != null && v2 != null && v1 != '' && v2 != ''){
			return true;
		}else{
			return false;
		}
	}
	
	this.defaultInitialize = function(divitions){
		var i;
		if(divitions <= MAX_LEGENDS){
			v1 = minm;
			for(i=2 ; i <= divitions ; i++){
				eval("v"+i+"="+(parseInt(minm)+parseInt((maxm-minm)/(divitions))*(i-1)));
			}
			eval("v"+(divitions+1)+" = maxm");
		}else{
			this.defaultInitialize(MAX_LEGENDS);
		}
	}
	
	this.getLegendString = function(divId,styleClass){
		var legendString = legStrStart;
		
		if((v1 != null && v1 != '') && (v2 != null && v2 != '')){
			legendString += '<li style="padding-left:10px"><div style="width:11px; height:11px; float:left; background:rgb('+colourParams[0][0]+'); border: 1px solid rgb('+colourParams[0][1]+')" ></div><div style="float:left; border:none; position:static">&nbsp;&nbsp;'+((colourParams[0][2]!= null)?colourParams[0][2]:v1+' - '+v2)+'</div></li>';
			//legendString += '<li><div style="border:1px solid rgb('+colourParams[0][1]+'); background:rgb('+colourParams[0][0]+');" class="code" /><div class="text">&nbsp;&nbsp;'+v1+' - '+v2+'</div></li>';
		}
		if((v2 != null && v2 != '') && (v3 != null && v3 != '')){
			legendString += '<li style="padding-left:10px"><div style="width:11px; height:11px; float:left; background:rgb('+colourParams[1][0]+'); border: 1px solid rgb('+colourParams[1][1]+')" ></div><div style="float:left; border:none; position:static">&nbsp;&nbsp;'+((colourParams[1][2]!= null)?colourParams[1][2]:v2+' - '+v3)+'</div></li>';
			//legendString += '<li><div style="border:1px solid rgb('+colourParams[1][1]+'); background:rgb('+colourParams[1][0]+');" class="code" /><div class="text">&nbsp;&nbsp;'+v2+' - '+v3+'</div></li>';
		}
		if((v3 != null && v3 != '') && (v4 != null && v4 != '')){
			legendString += '<li style="padding-left:10px"><div style="width:11px; height:11px; float:left; background:rgb('+colourParams[2][0]+'); border: 1px solid rgb('+colourParams[2][1]+')" ></div><div style="float:left; border:none; position:static">&nbsp;&nbsp;'+((colourParams[2][2]!= null)?colourParams[2][2]:v3+' - '+v4)+'</div></li>';
			//legendString += '<li><div style="border:1px solid rgb('+colourParams[2][1]+'); background:rgb('+colourParams[2][0]+');" class="code" /><div class="text">&nbsp;&nbsp;'+v3+' - '+v4+'</div></li>';
		}
		if((v4 != null && v4 != '') && (v5 != null && v5 != '')){
			legendString += '<li style="padding-left:10px"><div style="width:11px; height:11px; float:left; background:rgb('+colourParams[3][0]+'); border: 1px solid rgb('+colourParams[3][1]+')" ></div><div style="float:left; border:none; position:static">&nbsp;&nbsp;'+((colourParams[3][2]!= null)?colourParams[3][2]:v4+' - '+v5)+'</div></li>';
			//legendString += '<li><div style="border:1px solid rgb('+colourParams[3][1]+'); background:rgb('+colourParams[3][0]+');" class="code" /><div class="text">&nbsp;&nbsp;'+v4+' - '+v5+'</div></li>';
		}
		if((v5 != null && v5 != '') && (v6 != null && v6 != '')){
			legendString += '<li style="padding-left:10px"><div style="width:11px; height:11px; float:left; background:rgb('+colourParams[4][0]+'); border: 1px solid rgb('+colourParams[4][1]+')" ></div><div style="float:left; border:none; position:static">&nbsp;&nbsp;'+((colourParams[4][2]!= null)?colourParams[4][2]:v5+' - '+v6)+'</div></li>';
			//legendString += '<li><div style="border:1px solid rgb('+colourParams[4][1]+'); background:rgb('+colourParams[4][0]+');" class="code" /><div class="text">&nbsp;&nbsp;'+v5+' - '+v6+'</div></li>';
		}
		try{
			if(colourParams[5][0] != "" && colourParams[5][1] != "" && colourParams[5][2] != ""){
				legendString += '<li style="padding-left:10px"><div style="width:11px; height:11px; float:left; background:rgb('+colourParams[5][0]+'); border: 1px solid rgb('+colourParams[5][1]+')" ></div><div style="float:left; border:none; position:static">&nbsp;&nbsp;' + colourParams[5][2] + '</div></li>';
			}
		}catch(e){}
		//legendString += '<li style="text-align:right"><a href="javascript:openDynamicThemeLightBox(\''+minm+'\',\''+maxm+'\',\''+label+'\',\''+type+'\')">Change Legend Intervals</a></li>';
		legendString += legStrEnd;
		
		return legendString;
	}
	
	this.getLegendArray = function(){
		var legendParamsArray = [];
		if(v1 != null && v1 != ''){
			legendParamsArray.push(v1);
		}
		if(v2 != null && v2 != ''){
			legendParamsArray.push(v2);
		}
		if(v3 != null && v3 != ''){
			legendParamsArray.push(v3);
		}
		if(v4 != null && v4 != ''){
			legendParamsArray.push(v4);
		}
		if(v5 != null && v5 != ''){
			legendParamsArray.push(v5);
		}
		if(v6 != null && v6 != ''){
			legendParamsArray.push(v6);
		}
		
		return legendParamsArray;
	}
	
	this.setV1 = function(v1f){
		v1 = v1f;
	}
	this.getV1 = function(){
		return v1;
	}
	
	this.setV2 = function(v2f){
		v2 = v2f;
	}
	this.getV2 = function(){
		return v2;
	}
	
	this.setV3 = function(v3f){
		v3 = v3f;
	}
	this.getV3 = function(){
		return v3;
	}
	
	this.setV4 = function(v4f){
		v4 = v4f;
	}
	this.getV4 = function(){
		return v4;
	}
	
	this.setV5 = function(v5f){
		v5 = v5f;
	}
	this.getV5 = function(){
		return v5;
	}
	
	this.setV6 = function(v6f){
		v6 = v6f;
	}
	this.getV6 = function(){
		return v6;
	}
}

// Debug Needed
function CS_Tool(map,targetObj){
	/* Function perform Distance measuremtnt */
	var measureState = { shortSegments:[], shortestLength:0 };
	var eventListenerObj;

	this.startMesure = function(){
		eventListenerObj = GEvent.addListener(map, "click", function(marker, point) {
			doMeasure(marker, point);
		});
	}

	this.stopMesure = function(){
		try{
			GEvent.removeListener(eventListenerObj);
			clearMeasure();
		}catch(e){
			alert(e);
		}
	}

	function doMeasure(marker, point){
		var polyline;
		if (measureState.lastPoint) {		
		    measureState.shortestLength += measureState.lastPoint.distanceFrom(point);
		    map.addOverlay(polyline = new GPolyline([measureState.lastPoint, point], "#D5F4FF",2));
		    measureState.shortSegments.push(polyline);

		    //targetObj.innerHTML = "Last Distance in (m): "+measureState.lastPoint.distanceFrom(point).toFixed(3)+"\nTotal Distance in (m): "+measureState.shortestLength.toFixed(3);
		    targetObj.innerHTML = "Total Distance in (m): "+measureState.shortestLength.toFixed(3);
		    //alert("Last Distance in (m): "+measureState.lastPoint.distanceFrom(point).toFixed(3)+"\nTotal Distance in (m): "+measureState.shortestLength.toFixed(3));
		}
		measureState.lastPoint = point;
	}

	function clearMeasure(){
		if (!measureState.lastPoint){
			return;
		}else{
			for (i = 0; i < measureState.shortSegments.length; i++){ 
				map.removeOverlay(measureState.shortSegments[i]);
			}
			measureState = { shortSegments:[],  shortestLength:0 };
		}
	}
}
