/*<script language="javascript" src="../../../../countryg_test.php" type="text/php"></script>*/
//== Create a Custom GControl == //
var Entering=0;
var pg_lg_area='';
var border_color ;
var polygon_inner_color ;
function GPolygonControl() 
{
	pg_lg_area=radio_input_test;
	var g = GPolygonControl.prototype.G;
	//alert("fun1="+radio_input_test);
    if(pg_lg_area=='lg_area')
    {
	  g.lineColor = "#0000FF";	
      g.fillColor = "#FF00FF";
	  //  g.lineColor = "#FF0000";
    }
    if(pg_lg_area=='pgarea')
    {
	  g.lineColor="#FF0000";	
      g.fillColor="#0000FF";
     }
	//alert("in fun");
}
GPolygonControl.prototype = new GControl();
GPolygonControl.prototype.initialize = function(map) {
       
   // obtain Function Closure on a reference to "this"
   var me=this;

   // store a reference to the map so that we can call setZoom() on it
   me.map = map;
   
   // Is this MSIE, if so we need to use AlphaImageLoader
   var agent = navigator.userAgent.toLowerCase();
   if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){me.ie = true;} else {me.ie = false}

   // create the background graphic as a <div> containing an image
   var containerP = document.createElement("div");
   containerP.style.width="34px";
   containerP.style.height="34px";
   containerP.style.cursor="pointer";
   containerP.id = "polygonControl";
    
	 
   // Handle transparent PNG files in MSIE
   if(me.ie) {
     var loader = '<a id="addPolygon" href="javascript:void(0)"><span id="addPolygonSpan" style="width:33px;height:33px;display:inline-block;' ;
     loader +=  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='gmap/javascript/polygon/images/addashape.png');" ;
     loader +=  '"><img id="addPolygonPic" style="filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="gmap/javascript/polygon/images/addashape.png" width="33" height="33" border="0" alt=""></span></a>'; 
     containerP.innerHTML = '<div id="addPolygonDiv" style="height:33px; width:33px; cursor:pointer;">'+loader+'</div>';
   } else {
	 // Line below modified on 19-02-09
	 //containerP.innerHTML = '<a id="addPolygon" href="javascript:void(0)"><img id="addPolygonPic" src="gmap/javascript/polygon/images/addashape.png"  width=33 height=33 border="0" ></a>';
	 var loader = '<a id="addPolygon" href="javascript:void(0)"><img id="addPolygonPic" src="gmap/javascript/polygon/images/addashape.png"  width=33 height=33 border="0" ></a>';
	 containerP.innerHTML = '<div id="addPolygonDiv" style="height:33px; width:33px; cursor:pointer;">'+loader+'</div>';
	 // End of modifications on 19-02-09
   }

   // attach the control to the map
   me.map.getContainer().appendChild(containerP);
   me.containerP = containerP;


   // add toggle event polygon tool button
   //GEvent.addDomListener(me.containerP, 'click', me.polygButtonClick.on);
   $("#polygonControl").toggle(function(){me.polygButtonClick.on();},function(){me.polygButtonClick.off();});
   
  return containerP;
}
      
// == Set the default position for the control ==//
GPolygonControl.prototype.getDefaultPosition = function(){
     return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100, 0));
}      

// == create default coordinate icon ==//
GPolygonControl.prototype.icon = function(){
	
	var coordIcon = new GIcon();
	coordIcon.iconSize = new GSize(12,12);
	coordIcon.iconAnchor = new GPoint(6,9);
	coordIcon.infoWindowAnchor = new GPoint(8,0);
	coordIcon.image = "gmap/javascript/polygon/images/inflection.png";
	coordIcon.imageP = "gmap/javascript/polygon/images/inflectionP.png";
	return coordIcon;
} 

//== global variables ==//
//alert(pg_lg_area);
//border_color="#FF0000";
  // polygon_inner_color="#0000FF";
GPolygonControl.prototype.G={	ie:(navigator.userAgent.indexOf("MSIE")==-1)?false:true,
								polygon:null,
								tooltip:null,
								tooltip_handler:null,
								polygon_handler:null,
								addnewpolygonline_handler:null,
								polygonMarkers:new Array(),
								polygonPoints:new Array(),
								newline:null,
								prmPolygons:new Array(),//permanent polygons, stored in multi-dimensional array (accessible from polyCtrl global var)	
								newGLinePoints:new Array(),
								newGLinePoints2:new Array(),
								newline:null,
								newline2:null,
								adjustvertex_handler:null,
								//currentcolor:"#0000ff",
								currentcolor:"#FF8000",
								//lineColor:"#0000ff", // blue line
								lineColor:border_color, 
								lineWeight:4,
								lineOpacity:.5,
								//fillColor:"#0000ff", // blue fill
								fillColor:polygon_inner_color, // blue fill
								fillOpacity:.4,
								//primary info window html is broken up into 4 pieces. It is assembled with the commented variables in between
								editInfoWindowHtml1:'<div id="editInfoWindow" style="position: relative; left: 6px; top: 7px; width: 279px;"><div><div class="msedit"><table class="iwspan"><tbody><tr><td><table class="inputField"><tbody><tr><td class="label">Title</td><td><input id="titlePoly" class="title" type="text" maxlength="250" value="',
	 /*+g.prmPolygons[k][2]+*/  editInfoWindowHtml2:'"/></td><td><div id="colorIcon" class="icon" onmouseover="javascript:this.style.borderColor = \'#0000FF\'" onmouseout="javascript:this.style.borderColor = \'#DDDDDD\'"><div id="currentColor" class="poly" style="border-color: rgb(191, 191, 191); background-color:',
	 /*+g.prmPolygons[k][4]+*/  editInfoWindowHtml3:'"/></a></div></td></tr></tbody></table><table class="inputField"><tbody><tr><td class="label">Description</td><td class="tabs"><table><tbody><tr><td><span class="stab">Plain text</span></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table><div><div id="rtfield" class="textField description"/><textarea id="descPoly" name="textarea" class="textField description">',
	 /*+g.prmPolygons[k][3]+*/  editInfoWindowHtml4:'</textarea></div><table style="margin-top:20px"><tbody><tr><td class="navLeft"><span class="lk"></span><a id="polyDelete" style="cursor: pointer;" href="javascript:void(0)">Delete </a>&nbsp;&nbsp;<span class="lk"></span><a id="polyEdit" style="cursor: pointer;" href="javascript:void(0)"> Edit</a></td><td class="navRight"><button id="cancelPoly">Cancel</button></td><td class="navRight"><button id="okPoly">OK</button></td></tr></tbody></table></div><div class="msstyle" style="display:none; position: absolute; left: 0px; top: 0px;"/></div></div>'																		
} 

GPolygonControl.prototype.me = function(){return this;} 							
        
//== main entry point to polygon functions. Called by the click event of the polygon button ==//
GPolygonControl.prototype.polygButtonClick={  
		
	on:function(){
		//alert("on");
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G;
		//***** call to turn off any other digitizer tools. needs to be added depending on what other tools are being used *******//
	 	//togToolsOff(); //togDistOff();
	 	
	 	//change the button pic
	 	if(g.ie) {
		 	var loader = '<a id="addPolygon" href="javascript:void(0)"><span id="addPolygonSpan" style="width:33px;height:33px;display:inline-block;' ;
	       	loader +=  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='gmap/javascript/polygon/images/addashapeP.png');" ;
	      	loader +=  '"><img id="addPolygonPic" style="filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="gmap/javascript/polygon/images/addashapeP.png" width="33" height="33" border="0" alt=""></span></a>'; 
	      	$('#addPolygonDiv').html(loader);	
	 	} else {
	 		$('#addPolygonPic').attr("src","gmap/javascript/polygon/images/addashapeP.png");
	 	}
	 	
				me.polygpointClick.add();
				  //add a custom tooltip
				me.cursorTooltip.show("Click  on any point to complete the polygon");
	},
	
	off:function(){
		//alert("off");
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G;
   		if(g.ie){
   			var loader = '<a id="addPolygon" href="javascript:void(0)"><span id="addPolygonSpan" style="width:33px;height:33px;display:inline-block;' ;
       		loader +=  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='gmap/javascript/polygon/images/addashape.png');" ;
      		loader +=  '"><img id="addPolygonPic" style="filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="gmap/javascript/polygon/images/addashape.png" width="33" height="33" border="0" alt=""></span></a>';
      		$('#addPolygonDiv').html(loader);
   		} else {
    	 	$('#addPolygonPic').attr("src","gmap/javascript/polygon/images/addashape.png");			 	
    	}
 		
 		document.getElementById("googlemap").firstChild.firstChild.style.cursor = "default";
 		if(g.polygon || g.polygonMarkers.length > 0){
 			me.removePolygon();
 		}
		g.polygon = null;
		if(g.polygon_handler) {
			me.polygpointClick.remove();
       	}
       	if(g.addnewpolygonline_handler) {
      		me.newLine.remove();
      	}
		if(me.tooltip_handler) {
			me.cursorTooltip.hide();
		}
 		//need to add additional object removal if the button is clicked before the line is finished
 		return false;
	}        		
} 

//== toggle map click listener ==//
GPolygonControl.prototype.polygpointClick = {
     
	add:function(){	
		//add the marker listener
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G;
	    g.polygon_handler = GEvent.addListener(map,"click", me.polygonHandlerM);	
	},
	
	remove:function(){
		//remove the cursor tooltip, listeners, etc.
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G; 
		me.cursorTooltip.hide();
		GEvent.removeListener(g.polygon_handler);
		g.polygon_handler = null;
	}
}

// == access the polygonHandler function depending on whether the click was on the map or on the line tracking mouse movement === //
GPolygonControl.prototype.polygonHandlerM = function(overlay,point){
	if(point){
		var me = GPolygonControl.prototype.me();
		me.polygonHandler(point);	
	}
}

// == as above ==//
GPolygonControl.prototype.polygonHandlerL = function(para){
	
	if(para){
		var me = GPolygonControl.prototype.me();
		me.polygonHandler(para);	
	}
}

GPolygonControl.prototype.polygonHandler = function(click) {
	var me = this.me(); 
	var g = this.G;
	var icon = this.icon();
	if(click){
		var point = click;
		//change cursor type
		document.getElementById("googlemap").firstChild.firstChild.style.cursor = "crosshair";
		var marker = me.addMarkerListeners(point);
		g.polygonMarkers.push(marker);        			 
		g.polygonPoints.push(point);
		 
		map.addOverlay(marker);
		
		if(g.addnewpolygonline_handler==null) {me.newLine.add(g.lineColor);}
	
		if(g.polygonMarkers.length > 1) {
			if(g.polygon){map.removeOverlay(g.polygon);}
		 	g.polygon = new BDCCPolygon(g.polygonPoints, g.lineColor,g.lineWeight,g.lineOpacity,g.fillColor,g.fillOpacity); 
		 	map.addOverlay(g.polygon);
		}
	 }
}

GPolygonControl.prototype.cursorTooltip={
	
	show:function(message){
		var g = GPolygonControl.prototype.G;
		if(!g.tooltip_handler) {	 	
	 		g.tooltip = document.createElement("div");
			
	 		document.getElementById("googlemap").appendChild(g.tooltip);
	 		g.tooltip.innerHTML = '<div  id="polyCursorTooltip" style="border: 1px solid #666666; background-color: #ffffff; color: #666666;">'+ message +'</div>';
	      			
			function showMarkerTooltip(point) {
				var point1=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
				var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(point,map.getZoom());
				var anchor= new GPoint(-20,15);
				var width = -12;
				var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point1.x - anchor.x + width,- offset.y + point1.y +anchor.y)); 
				pos.apply(g.tooltip);
		 	}	
				     
	    	g.tooltip_handler = GEvent.addListener(map, "mousemove", function(point) {
	      			showMarkerTooltip(point);
	     	});
	     }    			
	},
	
	hide:function(){
		var g = GPolygonControl.prototype.G;
      	GEvent.removeListener(g.tooltip_handler);
      	g.tooltip_handler = null;
      	document.getElementById("googlemap").removeChild(g.tooltip);
    }
}

GPolygonControl.prototype.addMarkerListeners = function(point) {
	var me = this.me(); 
	var g = this.G;
	var icon = this.icon();

	var marker = new GMarker(point, {icon:icon, title:"Click a marker to end."});
	GEvent.addListener(marker,"mouseover",function(){marker.setImage(icon.imageP);});
	GEvent.addListener(marker,"mouseout",function(){marker.setImage(icon.image);});
	//		GEvent.addListener(map, 'click', function(overlay, latlng)  { alert(latlng); var a=latlng.lat(); } );
	GEvent.addListener(marker,"click",function(para) {
		//									   alert(para);
			if(g.polygonPoints.length > 2){  Entering=0;
					me.polygonEnd();
				//	alert(radio_input_test);
				var check_polygon=confirm(" Is this the polygon you wish to draw ? \n Click Ok to continue, Cancel to exit");
				if(check_polygon==false)
				{
				   var polygon_draw=confirm(" Do you want to draw again the polygon?");
				   if(polygon_draw==true)
				   {
					   clearmap();
					   GPolygonControl.prototype.polygButtonClick.on(); 
					   if(radio_input_test=='pgarea') 
					   {
						    document.getElementById('pgarea').checked= true;
			                document.getElementById('pgarea').disabled= false; 
							showStepsInfo(1); 
					    } 
					   if(radio_input_test=='lg_area')
					   {
						    document.getElementById('lg_area').checked= true;
							document.getElementById('lg_area').disabled= false;
							showStepsInfo(3);
					    }
				    }
				   if(polygon_draw==false)
				   {
					   clearmap(); 
					 }
				   } 
				   else {
					 GPolygonControl.prototype.polygButtonClick.off();    
					 showLoading(true);
					 document.getElementById("statusDIV").innerHTML = 'Please wait process is going on...';
					 OnConfirmation(para);
				 }
				// document.getElementById("addPolygonDiv").style.visibility = 'hidden';
			}
	});
			
 return marker;
}

//== add tracking line listener Note: ie bdccpoly vml bug adds a dashed line to first polygon object!!???!!! ==//
GPolygonControl.prototype.newLine = {
	
	add:function(lineColor){
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G; 
		g.addnewpolygonline_handler = GEvent.addListener(map, "mousemove", function(point) {
	    		if(g.polygonMarkers.length > 0) { 
					if(point){
						var newGLinePoints = new Array();
						newGLinePoints[0] = g.polygonPoints[g.polygonMarkers.length-1];
						if(g.newline){map.removeOverlay(g.newline);} 
						newGLinePoints[1] = point;
						//Hack: there is a bdcc vml bug here, that recreates the polyline after it has been removed, and it loses the mousemove events.
						var linestyle = (g.ie)?null:"dash";
						g.newline = new BDCCPolyline(newGLinePoints,lineColor,3,0.5,"Line",linestyle);
						GEvent.addListener(g.newline, "click", me.polygonHandlerL);
						map.addOverlay(g.newline); 
					}
				}
		});
	},
	
	remove:function() {
		var g = GPolygonControl.prototype.G; 
	    GEvent.removeListener(g.addnewpolygonline_handler);
	    if (g.newline) {map.removeOverlay(g.newline);g.newline=null;}
	    g.addnewpolygonline_handler = null;
	}
}

GPolygonControl.prototype.polygonEnd = function(){ 		
	var g = this.G;
	if(g.addnewpolygonline_handler && g.polygonMarkers.length > 2) {
		if(g.polygon){map.removeOverlay(g.polygon);g.polygon=null;}//should this call the full removePolygon function???
		g.polygonPoints[g.polygonMarkers.length] = g.polygonPoints[0];
		var prmPolygon = this.createPolygon(g.polygonPoints, g.lineColor,g.lineWeight,g.lineOpacity,g.fillColor,g.fillOpacity);
		var length = g.prmPolygons.length;
		g.prmPolygons[length] = new Array();
		g.prmPolygons[length][1] = prmPolygon;
		g.prmPolygons[length][2] = "";             //reserved for title
		g.prmPolygons[length][3] = "";             //reserved for description
	    g.prmPolygons[length][4] = ""+g.lineColor+"";
	    g.prmPolygons[length][5] = ""+g.lineWeight+"";
	    g.prmPolygons[length][6] = ""+g.fillOpacity+"";
	    g.prmPolygons[length][7] = ""+g.fillColor+"";
	    
		map.addOverlay(prmPolygon);
		              							
		this.newLine.remove();
		this.polygpointClick.remove();
		document.getElementById("googlemap").firstChild.firstChild.style.cursor = "default";
		//alert("len"+g.polygonMarkers.length);
		for (i=0;i<g.polygonMarkers.length;i++) {map.removeOverlay(g.polygonMarkers[i]);}
		//alert("in for"+g.polygonMarkers);
		g.polygonMarkers = new Array();
		g.polygonPoints = new Array();
		
		// note: the following calls this.polygButtonClick.off() by triggering the button toggle with a click to maintain correct button state
		$("#polygonControl").trigger("click");
	}		 								
}

//== creates markers used when editing polygon ==//
GPolygonControl.prototype.createMarkerG = function(point,icon,number,color,k,last){ 
	var g = this.G;
	var icon = this.icon();
	var marker = new GMarker(point,{icon: icon, draggable: true, bouncy: false, title:"Drag to move vertex. Click to end editing."});
	marker.number = parseInt(number); //retain state information for use in the listener
	GEvent.addListener(marker,"mouseover",function(){marker.setImage(icon.imageP);});
	GEvent.addListener(marker,"mouseout",function(){marker.setImage(icon.image);});
	
	GEvent.addListener(marker, "dragstart", function() {
			//start/end points need to get their respective before/after points
			g.newGLinePoints[0] = (marker.number != 0)? g.polygonPoints[parseInt(marker.number)-1]:g.polygonPoints[parseInt(last)]; 
			g.newGLinePoints2[0] = (marker.number != last)?g.polygonPoints[parseInt(marker.number+1)]:g.polygonPoints[0]; 
			
			g.adjustvertex_handler = GEvent.addListener(map, "mousemove", function(point) {
					g.newGLinePoints[1] = point;
					g.newGLinePoints2[1] = point;					
					if (g.newline1) {map.removeOverlay(g.newline1);}
					if (g.newline2) {map.removeOverlay(g.newline2);}
					
					if(marker.number != 0 && marker.number != last){
						g.newline1 = new BDCCPolyline(g.newGLinePoints.slice(0,2),color,4,0.5,"New Line","dot");
						map.addOverlay(g.newline1);					
						g.newline2 = new BDCCPolyline(g.newGLinePoints2.slice(0,2),color,4,0.5,"New Line","dot");
						map.addOverlay(g.newline2);
					} else if(marker.number == 0 || marker.number == last){
						g.newline1 = new BDCCPolyline(g.newGLinePoints.slice(0,2),color,4,0.5,"New Line","dot");
						map.addOverlay(g.newline1);
						g.newline2 = new BDCCPolyline(g.newGLinePoints2.slice(0,2),color,4,0.5,"New Line","dot");
						map.addOverlay(g.newline2);
					}
			});
	});
	
	GEvent.addListener(marker, "dragend", function() {
			var point = g.newline1.getVertex(1);
			if (g.newline1) {map.removeOverlay(g.newline1);}
			if (g.newline2) {map.removeOverlay(g.newline2);}
			g.polygonPoints.splice(parseInt(marker.number),1,point)
			g.polygonPoints.splice(0,0,g.polygonPoints[parseInt(last)]);  //overlap start and end points to close polygon
			g.polygon = GPolygonControl.prototype.createPolygon(g.polygonPoints, color,g.lineWeight,g.lineOpacity,color,g.fillOpacity,k); 
			g.polygonPoints.shift(); //delete overlapping point
			map.addOverlay(g.polygon);
			map.removeOverlay(g.prmPolygons[k][1]);
			g.prmPolygons[k][1] = g.polygon;
			GEvent.removeListener(g.adjustvertex_handler);
	});
	
	GEvent.addListener(marker, "click", function() {
		if(g.polygonMarkers.length > 0){
			for(var i=0; i<g.polygonMarkers.length; i++) {
				map.removeOverlay(g.polygonMarkers[i]);
			}
			g.polygonMarkers = new Array();
			g.polygonPoints = new Array();
			g.polygon = null;
		}
	});
	
  return marker;
}

GPolygonControl.prototype.returnVertices = function(polygon) {
	var vertices = new Array();
	  for (var i=0; i < polygon.getVertexCount(); i++) {
	  	vertices[i] = polygon.getVertex(i);
	  }
  return vertices;
}
var prmPolygon = "";
var paraDup;
var pts;
var pts_array = new Array();
//== external polygon creation function ==/	      
GPolygonControl.prototype.createPolygon = function(polygonPoints,lineColor,lineWeight,lineOpacity,fillColor,fillOpacity,k){ 
	//alert("before polygonPoints"+polygonPoints);
	var me = this.me();
	var g = this.G;
	if(typeof(k)=="undefined"){var k = g.prmPolygons.length;} //new polygons need to find k, existing polygons use preexisting k
	prmPolygon = new BDCCPolygon(polygonPoints,lineColor,lineWeight,lineOpacity,fillColor,fillOpacity);
    GEvent.addListener(prmPolygon,"mouseover",function(){
    		prmPolygon.setFillOpacity(parseFloat(fillOpacity)+.3);
    });
    GEvent.addListener(prmPolygon,"mouseout",function(){prmPolygon.setFillOpacity(fillOpacity);});
    
    GEvent.addListener(prmPolygon,"click",function(para){
	  if(Entering==0)  
	  {   
	      showLoading(true);
		  document.getElementById("statusDIV").innerHTML = 'Please wait process is going on...';
	  	  OnConfirmation(para);
	   }
	});
	var pt_value;
	OnConfirmation = function(para) {	
			if(para){
				paraDup = para
				pts = polygonPoints;
				pts_array = pts;
				pt_value=pts_array[0];
				var address;
				var geocoder;
				geocoder = new GClientGeocoder();
				geocoder.getLocations(pt_value, showAddress);
				me.addInfoWindowListeners(para, k);
			} else {//mac firefox hack -- bug in normal poly click event, use getCenter instead
			//alert("in else");
				var hackClick_handler = GEvent.addListener(map,"click",function(overlay,point){
					if(overlay){
						var center = overlay.getBounds().getCenter();
						map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.prmPolygons[k][2]+g.editInfoWindowHtml2+g.prmPolygons[k][4]+g.editInfoWindowHtml3+g.prmPolygons[k][3]+g.editInfoWindowHtml4));
						me.addInfoWindowListeners(center, k);
						GEvent.removeListener(hackClick_handler);
					}
				});
			}
//This is for Pg area and Language area
			function showAddress(response) {
							  //map.clearOverlays();
				                               //response=[ object object ]
				  if (!response || response.Status.code != 200) {
					alert("Status Code:" + response.Status.code);
					showLoading(false);
					document.getElementById("statusDIV").innerHTML = "";
				  } else {
					place = response.Placemark[0];
					//alert("gpolygon");
					//alert(document.getElementById(radio_id).value);
					//alert(radio_input_test);
					 flag=radio_input_test;
					//alert(response.Placemark[1]);
					point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
				  //	marker = new GMarker(point);
				  //	map.addOverlay(marker);

					var cntry_code = place.AddressDetails.Country.CountryNameCode;
					//var cntry_code = document.getElementById("countryrog").value; 
					//alert(cntry_code);
					// map.getBaseCountryCode(); 
					var cntry_name = place.AddressDetails.Country.CountryName; 
					var address = place.address;
					var area_latlang = place.Point.coordinates[0] + "," + place.Point.coordinates[1];

					var temp_array = new Array();
					temp_array = address.split(',');
					var i;
					for(i=0;i<temp_array.length;i++) {
						var add_values=temp_array[i];
						//alert("add:"+add_values);   // Complete address
					}

					var area_latlang = response.name;
					var xmlHttp;
					 try
					 {
						 // Firefox, Opera 8.0+, Safari
						 xmlHttp=new XMLHttpRequest();
					 }
					catch (e)
					{
					  // Internet Explorer
					  try
						{
							xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
						}
					  catch (e)
						{
						try
						  {
							xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
						  }
						catch (e)
						  {
							alert("Your browser does not support AJAX!");
							return false;
						  }
						}
					}
					xmlHttp.onreadystatechange = function()
					{
						if(xmlHttp.readyState == 4)
						{
							HandleResponse(xmlHttp.responseText);
						}
					}
					//alert(fttp_pgname_polygon);
					//alert("country code:"+cntry_code+"\n country name:"+cntry_name+'flag='+flag);
					var urlrog = document.getElementById("countryrog").value;
					xmlHttp.open("POST", "gmap/javascript/sqlinsert.php", true);
					xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
					if(fttp_pg_area==0)
					{
					   xmlHttp.send( '&cntry=' + cntry_code + '&cntry_name=' + cntry_name +'&flag='+flag + '&urlrog=' + urlrog);	 
					 }
					if(fttp_pg_area==1)
					{
					  xmlHttp.send( '&cntry=' + cntry_code + '&cntry_name=' + cntry_name +'&flag='+flag + '&urlrog=' + urlrog+'&fttp_pg_area='+fttp_pg_area+'&fttp_pgname='+fttp_pgname+'&fttp_population='+fttp_population+'&fttp_religion='+fttp_religion+'&fttp_language='+fttp_language);
					  fttp_pg_area=0;
					}
					var html;
						function HandleResponse(response) {
							//alert(response);
							if(response != 1) {
								//alert("gpolygon"+temp_array[0]);
															html = response;
                            //alert("gpoly"+response);
							var temp2_array = new Array();
							temp2_array = html.split('|');
							temp=temp2_array[0].split('1@');
							temp2_array[0]=temp[0];
							//alert(temp2_array[1]);
							var temporary =new Array();
							//oku
							compare=temp[1];
							//alert(compare);
							 var tabs = [];  // info Tabs container for InfoWindows
							 var tab_labels = [];			
							 var htmls = [];
	                         for(var i=0;i<temp2_array.length;i++) 
							  {
								 var pop_values=temp2_array[i];
								}
							 if(compare=='pgarea')    // Pg area has value has area
							 {  
							    tab_labels.push('People Info'); htmls.push(temp[0]);
								//tab_labels.push('information');htmls.push(temporary[0]);
							   }
							  if(compare=='lg_area')
							  { 
								 tab_labels.push('Language Info'); htmls.push(temp[0]);
								//tab_labels.push('Linguistic');htmls.push(temporary[0]);
								//tab_labels.push('Cultural');htmls.push(fourthtab[0]);   
							   } 
                              //temp2_array[1] += "<table border='0'><tr><td class='tab_table_value'><b>Address:"+address+"</b></td></tr></table>";
							  if(compare=='pgarea')
							  {
							     temp2_array[1] += "<table border='0'><tr><td><input type='submit' name='savepg_info' value='Save People Group Info' onclick='return save_pg_area();' class='submitbutton'></td>";
								 
							  }
							  if(compare=='lg_area')
							  {
								  temp2_array[1] += "<table border='0'><tr><td><input type='submit' name='savelg_info' value='Save Language Areas Info' onclick='return save_lg_area()' class='submitbutton'></td>";
							   }
							  temp2_array[1] += "<td><input type='button' value='Clear' onclick='save_pg_area_clear();' class='submitbutton' /></td></tr>";
							  temp2_array[1] += "<tr><td><input type='hidden' value='"+cntry_name+"' id='cntry_name' name='cntry_name'/></td></tr><tr><td><input type='hidden' value='"+cntry_code+"' id='cntry_code' name='cntry_code'/></td></tr>";
							  temp2_array[1] += "<tr><td><input type='hidden' value='"+polygonPoints+"' id='poly_latlang' name='poly_latlang'/></td></tr>";
							  temp2_array[1] += "<tr><td><input type='hidden' value='"+area_latlang+"' id='area_latlang' name='area_latlang'/></td></tr></table></form>";

							//html = parseToHTML(temp2_array[1]);
							tab_labels.push('Information'); htmls.push(temp2_array[1]);
								
							for (var j=0; j < htmls.length; j++) {
								//alert("htmls len:"+htmls.length);
								htmls[j] = '<div class="infowindow" style="width:283px;height:270px">' + htmls[j] + '</div>';
								tabs.push(new GInfoWindowTab(tab_labels[j],htmls[j]));
							}
							point=pt_value;
							map.openInfoWindowTabsHtml(point,tabs);  
                            showLoading(false);
							document.getElementById("statusDIV").innerHTML = '';
							} 
							else if(response == 1){
								document.getElementById('statusDIV').innerHTML = "Invalid Query.";
							}
						}

					 }
				}

		//alert("latlatns first value::"+pt_value);	
	}

	//Code ended by Suresh on 9/22/2008
 return prmPolygon;
}

//var xmlHttp5;
//function for image verification on 12/9/2008 added by Suresh
function img_verification(){
	var img_ver = escape(document.getElementById("code").value);
	//alert(img_ver);
	//The below code is for image verification
	var xmlHttp5;
		 try
		 {
			 // Firefox, Opera 8.0+, Safari
			 xmlHttp5=new XMLHttpRequest();
		 }
		catch (e)
		{
		  // Internet Explorer
		  try
			{
				xmlHttp5=new ActiveXObject("Msxml2.XMLHTTP");
			}
		  catch (e)
			{
			try
			  {
				xmlHttp5=new ActiveXObject("Microsoft.XMLHTTP");
			  }
			catch (e)
			  {
				alert("Your browser does not support AJAX!");
				return false;
			  }
			}
		}
	
		 //xmlHttp5.onreadystatechange = function()
		 //{
		//		if(xmlHttp5.readyState == 4)
		//		{
		//			HandleResponse5(xmlHttp5.responseText);
		//		}
	      //}
		 var flag=5;
		 var urlrog = document.getElementById("countryrog").value;
		 xmlHttp5.open("POST", "gmap/javascript/sqlinsert.php", false);
		 xmlHttp5.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		 xmlHttp5.send("&code="+img_ver+"&flag="+flag + '&urlrog=' + urlrog);
		
		if(xmlHttp5.readyState == 4 || xmlHttp5.status == 200) {
			var a = xmlHttp5.responseText;
			return a;
		}
		 //alert(a);
		 //function HandleResponse5(response5) {
		 //alert(response5);
		 //var res=response5;
		 //alert(res);
		//	if(response5==1) {
		//		alert('Validation string not valid! Please try again once!');
		//		return false;
		//		}
		//	else if(response5==2) {
				//alert('Validation string is valid.');
		//		return true;
		//	}
		// }
		
}

//End function for image verification on 12/9/2008 added by Suresh

//PG area save data added by suresh on 11/21/2008
function save_pg_area_clear()
{
	var pgname = escape(document.getElementById("peopleGroupName").value);
	document.getElementById("peopleGroupName").value='';
	document.getElementById("languageName").value='';
	document.getElementById("PeopleCountryPopulation").value='';
	if (document.getElementById("1galphas")) {
		document.getElementById("1galphas").value='';
	}
	if (document.getElementById("1galphas")) {
		document.getElementById("1galphas").value='';
	}
	if (document.getElementById("lgname_list")) {
		document.getElementById("lgname_list").value='all';
	} 
	if (document.getElementById("lglistdiv")) {
		document.getElementById("lglistdiv").innerHTML = '';
		document.getElementById("lglistdiv").style.display = 'none';
	}

	if (document.getElementById("lgothershdgdiv")) {
		document.getElementById("lgothershdgdiv").innerHTML = '';
		document.getElementById("lgothershdgdiv").style.display = 'none';
	}

	if (document.getElementById("lgalphasdiv")) {
		document.getElementById("lgalphasdiv").innerHTML = '';
		document.getElementById("lgalphasdiv").style.display = 'none';
	}

	if (document.getElementById("pgothershdgdiv")) {
		document.getElementById("pgothershdgdiv").innerHTML = '';
		document.getElementById("pgothershdgdiv").style.display = 'none';
	}

	if (document.getElementById("pgalphasdiv")) {
		document.getElementById("pgalphasdiv").innerHTML = '';
		document.getElementById("pgalphasdiv").style.display = 'none';
	}

	if (document.getElementById("pglistdiv")) {
		document.getElementById("pglistdiv").innerHTML = '';
		document.getElementById("pglistdiv").style.display = 'none';
	}

	if (document.getElementById("pgalphas")) {
		document.getElementById("pgalphas").value='';
	}

	document.getElementById("religion").value='';
	document.getElementById("christianPercentage").value='';
	document.getElementById("resourcesAvailable").value='';
	document.getElementById("churches").value='';
	document.getElementById("sourceInfo").value='';
	document.getElementById("code").value='';
}

function save_pg_area() {
	//alert("in save pg area");
	
	var img_ver = escape(document.getElementById("code").value);
	var cntry_name = escape(document.getElementById("cntry_name").value); //alert(cntry_name);
	var ROG3= escape(document.getElementById("cntry_code").value);
	// Peoplegroup name means here popentid in a number
	var peopleGroupName = escape(document.getElementById('peopleGroupName').value);
	var PeopleCountryPopulation = escape(document.getElementById("PeopleCountryPopulation").value);
	// Here peoplegroupname is popentid
	if(peopleGroupName!= 'others')
	{
		var peopleGroupName = escape(document.getElementById("peopleGroupName").value); 
		var pgnameSelectedIndex = escape(document.getElementById("peopleGroupName").selectedIndex);
		var pgresponsename = document.update_pg.peopleGroupName.options[pgnameSelectedIndex].text;
	}
	if(document.getElementById("pgalphas"))
    {
      var pgalphas = escape(document.getElementById("pgalphas").value);
	  if(peopleGroupName=='others' && pgalphas!='')
	  {
			var peopleGroupName = escape(document.getElementById("pgname_list").value);
			var pgnameSelectedIndex = escape(document.getElementById("pgname_list").selectedIndex);
			var pgresponsename = document.update_pg.pgname_list.options[pgnameSelectedIndex].text; 
		}
     }
	// Here languagenameval is language id
	var languageNameVal = escape(document.getElementById("languageName").value);
	if(languageNameVal!='others')
	{
		var languageNameVal = escape(document.getElementById("languageName").value);
		var languageName = languageNameVal;
	} 
	if(document.getElementById("lgalphas"))
    {
      var lgalphas = escape(document.getElementById("lgalphas").value);
	  if(languageNameVal=='others' && lgalphas!='')
	  {
		  var languageNameVal = escape(document.getElementById("lgname_list").value);
		  var languageName = languageNameVal;
	   }
	}
	var ZonePopulation =0  // escape(document.getElementById("ZonePopulation").value);
	var population =  escape(document.getElementById("PeopleCountryPopulation").value);
	var GSECStatus = 0 // escape(document.getElementById("GSECStatus").value);
	var religion = escape(document.getElementById("religion").value);
	var secondReligionFollowers =0  // escape(document.getElementById("secondReligionFollowers").value);
	var christianPercentage = escape(document.getElementById("christianPercentage").value);
	var resourcesAvailable = escape(document.getElementById("resourcesAvailable").value);
	var churches = escape(document.getElementById("churches").value);
	var sourceInfo = escape(document.getElementById("sourceInfo").value);
	var bibleYear = 0
	var ntYear = 0
	var portionsYear = 0
	//alert(portionsYear);
	var jesusFilm = 0
	//alert(jesusFilm);
	var gospelRecording = 0
	var radioBroadcast = '0';
	var likelihood = '100';
	var isPolygon = 'true';
	var geographicdataInLatLng = escape(document.getElementById('poly_latlang').value);
	var errormsg='';
	var errorfld='';
    //alert(peopleGroupName);
	if(peopleGroupName=='') { 
		errormsg += "Please select the People Group Name\n";
		errorfld = 'A';
	}
	
	if(document.getElementById("peopleGroupName").value=='others')  
	{
	  if(document.getElementById("pgalphas").value =='')
      {
         errormsg += "Please select the alphabet dropdown\n";
       }
	  // alert(document.getElementById("pgalphas").value); alert(document.getElementById("pgname_list").value);
	  if(document.getElementById("pgalphas").value !='' &&document.getElementById("pgname_list").value=='all')
	  {
		errormsg += "Please select the People Group Name generated alphabetical list\n";  
	   }
	 }
	 if(document.getElementById("languageName").value=='others')  
	{
	  if(document.getElementById("lgalphas").value =='')
      {
         errormsg += "Please select the alphabet dropdown\n";
       }
	  if(document.getElementById("lgalphas").value !='' &&document.getElementById("lgname_list").value=='all')
	  {
		errormsg += "Please select the Language Group Name generated alphabetical list\n";  
	   }
	}
	/*if(PeopleCountryPopulation!='')
	{
	   if(isNaN(PeopleCountryPopulation))
	   {
		 errormsg += "Please enter People Country Population in numerics\n"; 
		 errorfld += 'A';
	   }
	}*/
	if(ZonePopulation!='')
	{
	   if(isNaN(ZonePopulation))
	   {
		 errormsg += "Please enter Zone Population in numerics\n"; 
		 errorfld += 'A';
	   }
	}
	if(likelihood!='')
	{
	   if(isNaN(likelihood))
	   {
		 errormsg += "Please enter Likelihood in numerics\n"; 
		 errorfld += 'A';
	   }
	}
	if(population!='')
	{
	   populationsplit=population.split('.');
	   if(isNaN(population) ||populationsplit[1]!=undefined)
	   {
		 errormsg += "Please enter population in numerics without decimals\n"; 
		 errorfld += 'B';
		 check_population=1;
	   } 
	 if(population<0)
	  { 
	     errormsg +="Please enter postive numbers for population\n";
	   }
	  if(population.length>15)
	 {  
	    errormsg +="Please enter population below 16 digits\n";
	   }  
	}
	if(population=='') {
		errormsg += "Please enter population\n";
		errorfld += 'B';
	}
	if(secondReligionFollowers!='')
	{
	  if(isNaN(secondReligionFollowers))
	   {
		 errormsg += "Please enter numerics for second religion people\n"; 
		 errorfld += 'C';
	   }	 
	}
	
   if(christianPercentage!='')
   {
	  if( isNaN(christianPercentage) )
	  { 
	   errormsg +="Please enter percentage as numbers or decimals\n";
	  }
	 if(christianPercentage<0)
	  { 
	    errormsg +="Please enter postive numbers for percentage of christians\n";
	   } 
	}	 
	if(img_ver=='') {
		errormsg += "Please enter verification code\n";
		errorfld += 'E';
	} else {
		//alert('img_ver='+img_ver);
		var pass = img_verification();
		//alert('pass='+pass);
		if( pass == 1 ){
			errormsg += "Incorrect image verification given\n";
			errorfld += 'E';
		}
	}
	if(errormsg !='') {
		alert(errormsg);
		//alert(errorfld);
		if (errorfld!='')
		{
			if (errorfld.match('A')) {
			//	document.getElementById("peopleGroupName").focus();
			} 
			else 
			if (errorfld.match('B')) {
			
				
			//	document.getElementById("PeopleCountryPopulation").focus();
			} 
			else if (errorfld.match('D')) {
				document.getElementById("christianPercentage").focus();
			} else if (errorfld.match('E')) {
				document.getElementById("code").focus();
			}
		}
		document.getElementById('siimage').src = 'captcha-secureimage/securimage_show.php?sid=' + Math.random(); 
		document.getElementById("code").value = '';
		return false;
	}
	else {
		//call the webservice
		
		 var xmlHttp;
		 try
		 {
			 // Firefox, Opera 8.0+, Safari
			 xmlHttp=new XMLHttpRequest();
		 }
		catch (e)
		{
		  // Internet Explorer
		  try
			{
				xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			}
		  catch (e)
			{
			try
			  {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			  }
			catch (e)
			  {
				alert("Your browser does not support AJAX!");
				return false;
			  }
			}
		}

		 xmlHttp.onreadystatechange = function()
		 {
				document.getElementById("statusDIV").innerHTML = 'Please wait process is going on...';
				showLoading(true);	
				if(xmlHttp.readyState == 4)
				{
					HandleResponse(xmlHttp.responseText);
				 }
	      } 
		 var flag=1;
		 christianPercentage = Math.round(christianPercentage*Math.pow(10,4))/Math.pow(10,4);
		 //alert("flag"+flag);
		 xmlHttp.open("POST", "webservice_string_new.php", true);
		 xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		 xmlHttp.send( '&countryName='+cntry_name+'&PeopleCountryPopulation='+PeopleCountryPopulation+'&ZonePopulation='+ZonePopulation+'&population='+population+'&religion='+religion+'&secondReligionFollowers='+secondReligionFollowers+'&christianPercentage='+christianPercentage+'&languageName='+languageName+'&resourcesAvailable='+resourcesAvailable+'&churches='+churches+'&sourceInfo='+sourceInfo+'&peopleGroupName='+peopleGroupName+'&GSECStatus='+GSECStatus+'&bibleYear='+bibleYear+'&ntYear='+ntYear +'&portionsYear='+portionsYear +'&jesusFilm='+jesusFilm +'&gospelRecording='+gospelRecording+'&radioBroadcast='+radioBroadcast +'&likelihood='+likelihood +'&geographicdataInLatLng='+geographicdataInLatLng +'&isPolygon='+isPolygon +'&flag='+flag+'&ROG3='+ROG3); 
		
		 function HandleResponse(response) {
			if(response) {
				//CityPeopleGroup Saved Successfully 
				//citypeoplegroupadded successfully
				//CityPeopleGroup Saved Successfully 
				var peoplegroupid_resp=response.split("||");
				var peoplegroupid=peoplegroupid_resp[0];
				var response=peoplegroupid_resp[1];
				document.getElementById("statusDIV").innerHTML = pgresponsename+' '+response;
				Entering=1;
				recentpolygon=1;
				singlepgpoly(peoplegroupid);
				clear_StepsInfo();
				GEvent.addListener(prmPolygon,"click",function(para){
	            if(Entering==1)  
	            {
	  	            singlepgpoly(peoplegroupid);
					clear_StepsInfo();
	               }
	             });
				document.getElementById('pgarea').checked=false; 
				//pagerefresh();
		    }
		 }
		map.closeInfoWindow();
	}	
}



function save_lg_area() {
	//alert("in save lg area");
	var img_ver = escape(document.getElementById("code").value);
	var cntry_name = escape(document.getElementById("cntry_name").value); //alert(cntry_name);
	// Peoplegroup name means here popentid in a number
	var ROG3= escape(document.getElementById("cntry_code").value);
	var peopleGroupName = escape(document.getElementById('peopleGroupName').value);
	var PeopleCountryPopulation = escape(document.getElementById("PeopleCountryPopulation").value);
	//alert(pgalphas); alert(peopleGroupName);
	var languageNameVal = escape(document.getElementById("languageName").value);
	if(languageNameVal !='others' ) 
	{
		var languageNameVal = escape(document.getElementById("languageName").value);
			var languageName = languageNameVal;  
			var lgnameSelectedIndex = escape(document.getElementById("languageName").selectedIndex);
			var languageresponse = document.update_pg.languageName.options[lgnameSelectedIndex].text;
		
	}
	if(document.getElementById("lgalphas"))
	{
		var lgalphas= document.getElementById("languageName").value;  
		if(languageNameVal =='others'  &&lgalphas!='')
		{
		  var languageNameVal = escape(document.getElementById("lgname_list").value);
		  var languageName = languageNameVal;
		  var lgnameSelectedIndex = escape(document.getElementById("lgname_list").selectedIndex);
		  var languageresponse = document.update_pg.lgname_list.options[lgnameSelectedIndex].text;
		}
	 }
	if(peopleGroupName!= 'others')
	{
		var peopleGroupName = escape(document.getElementById("peopleGroupName").value); 
		var pgnameSelectedIndex = escape(document.getElementById("peopleGroupName").selectedIndex);
		var pgresponsename = document.update_pg.peopleGroupName.options[pgnameSelectedIndex].text;
	}
	if(document.getElementById("pgalphas"))
    {
      var pgalphas = escape(document.getElementById("pgalphas").value);
	  if(peopleGroupName=='others' && pgalphas!='')
	  {
			var peopleGroupName = escape(document.getElementById("pgname_list").value);
			var pgnameSelectedIndex = escape(document.getElementById("pgname_list").selectedIndex);
			var pgresponsename = document.update_pg.pgname_list.options[pgnameSelectedIndex].text; 
		}
     }
	
	var ZonePopulation =0  // escape(document.getElementById("ZonePopulation").value);
	var population =  escape(document.getElementById("PeopleCountryPopulation").value);
	var GSECStatus = 0 // escape(document.getElementById("GSECStatus").value);
	var religion = escape(document.getElementById("religion").value);
	var secondReligionFollowers =0  // escape(document.getElementById("secondReligionFollowers").value);
	var christianPercentage = escape(document.getElementById("christianPercentage").value);
	var resourcesAvailable = escape(document.getElementById("resourcesAvailable").value);
	var churches = escape(document.getElementById("churches").value);
	var sourceInfo = escape(document.getElementById("sourceInfo").value);
	/*var bibleYear = escape(document.getElementById('bibleYear').value);
	var ntYear = escape(document.getElementById('ntYear').value);
	var portionsYear = escape(document.getElementById('portionsYear').value);
	//alert(portionsYear);
	var jesusFilm = escape(document.getElementById('jesusFilm').value);
	//alert(jesusFilm);
	var gospelRecording = escape(document.getElementById("gospelRecording").value);
	var radioBroadcast = escape(document.getElementById("radioBroadcast").value);
	var likelihood = escape(document.getElementById("likelihood").value);*/
	
	var bibleYear = 0
	var ntYear = 0
	var portionsYear = 0
	//alert(portionsYear);
	var jesusFilm = 0
	//alert(jesusFilm);
	var gospelRecording = 0
	var radioBroadcast = '0';
	var likelihood = '100';
	var isPolygon = 'true';
	var geographicdataInLatLng = escape(document.getElementById('poly_latlang').value);
	var errormsg='';
	var errorfld='';
	if(languageNameVal=='') {
		errormsg += "Please select the Language Area name\n";
		errorfld = 'A';
	}
	/*if(peopleGroupName=='') {
		errormsg += "Please select the people group name\n";
		errorfld = 'B';
	}*/
	//if(document.getElementById("peopleGroupName").value!='' &&document.getElementById("pgalphas").value!='')
	//{
		 //errormsg +="Please select one people group name only\n";
		 //errorfld = 'A';
	//}	 
	if(document.getElementById("languageName").value=='others')  
	{  
	     if(document.getElementById("lgalphas").value =='')
		 {
		    errormsg += "Please select the language alphabet\n";	  
		  }
		 if(document.getElementById("lgalphas").value !='' &&document.getElementById('lgname_list').value =='all') 
		 {
		    errormsg += "Please select the Languagename generated from alphabets\n";	 
		  }
	 }
	if(document.getElementById("peopleGroupName").value=='others')      
	{  
	     if(document.getElementById("pgalphas").value =='')
		 {
		    errormsg += "Please select the people alphabet\n";	  
		  }
		 if(document.getElementById("pgalphas").value !='' &&document.getElementById('pgname_list').value =='all') 
		 {
		    errormsg += "Please select the Peoplegroup generated from alphabets\n";	 
		  }
	 }
	if(ZonePopulation!='')
	{
	   if(isNaN(ZonePopulation))
	   {
		 errormsg += "Please enter Zone Population in numerics\n"; 
		 errorfld += 'A';
	   }
	}
	if(likelihood!='')
	{
	   if(isNaN(likelihood))
	   {
		 errormsg += "Please enter Likelihood in numerics\n"; 
		 errorfld += 'A';
	   }
	}
	if(population=='') {
		errormsg += "Please enter population\n";
		errorfld += 'C';
	}
	if(population!='')
	{
	   populationsplit=population.split('.');
	   if(isNaN(population) ||populationsplit[1]!=undefined)
	   {
		 errormsg += "Please enter population in numerics without decimals\n"; 
		 errorfld += 'B';
		 check_population=1;
	   } 
	   if(population.length>15)
	 {  
	    errormsg +="Please enter population below 16 digits\n";
	   }
	if(population<0)
	  { 
	     errormsg +="Please enter postive numbers for population\n";
	   }	
	}
	if(secondReligionFollowers!='')
	{
	  if(isNaN(secondReligionFollowers))
	   {
		 errormsg += "Please enter numerics for Percentage of second religion followers\n"; 
		 errorfld += 'D';
	   }	 
	 }
    if(christianPercentage!='')
   {
	  if( isNaN(christianPercentage) )
	  { 
	   errormsg +="Please enter percentage as numbers or decimals\n";
	  }    
	if(christianPercentage<0)
	  { 
	    errormsg +="Please enter postive numbers for percentage of christians\n";
	   }  
	} 
	 if(bibleYear!='')
	{
	  var compare=0;	
	  var iChars = "!@#$%^&*()+=[]\\\';,./{}|\":<>?~_ABCDEFGHIJKLMNOPQRSTUVWXYXabcdefghijklmnopqrsuvwxyz";  
      for (var i = 0; i < bibleYear.length; i++) 
	  {
  	    if (iChars.indexOf(bibleYear.charAt(i)) != -1) 
	    {  compare=1;  }
	   }          
	  if(compare==1) {  errormsg+= "Please enter numerics and hypen only for bible year\n" ; } 
	} 
	if(ntYear!='')
	{
	  var compare=0;	 
	  var iChars = "!@#$%^&*()+=[]\\\';,./{}|\":<>?~_ABCDEFGHIJKLMNOPQRSTUVWXYXabcdefghijklmnopqrsuvwxyz";  
      for (var i = 0; i < ntYear.length; i++) 
	  {
  	    if (iChars.indexOf(ntYear.charAt(i)) != -1) 
	    {  compare=1;  }
	   }
	  if(compare==1) {  errormsg+= "Please enter numerics and hypen only for ntyear\n" ; } 
	}
	if(portionsYear!='')
	{
	  var compare=0;	
	  var iChars = "!@#$%^&*()+=[]\\\';,./{}|\":<>?~_ABCDEFGHIJKLMNOPQRSTUVWXYXabcdefghijklmnopqrsuvwxyz";  
      for (var i = 0; i < portionsYear.length; i++) 
	  {
  	    if (iChars.indexOf(portionsYear.charAt(i)) != -1) 
	    {  compare=1;  }
	   }
	  if(compare==1) {  errormsg+= "Please enter numerics and hypen only for portionsyear\n" ; } 
	}
	if(img_ver=='') {
		errormsg += "Please enter verification code.\n";
		errorfld += 'F';
	} else {
		var pass = img_verification();
		if( pass == 1 ){
			errormsg += "Incorrect image verification given\n";
			errorfld += 'F';
		}
	}
	if(errormsg !='') {
		alert(errormsg);
		//alert(errorfld);
		if (errorfld!='')
		{
			if (errorfld.match('A')) {
			//	document.getElementById("languageName").focus();
			} 
			else if (errorfld.match('B')) {
			//	document.getElementById("peopleGroupName").focus();
			} else if (errorfld.match('C')) {
			  //	document.getElementById("PeopleCountryPopulation").focus();
			}  else if (errorfld.match('E')) {
				document.getElementById("christianPercentage").focus();
			} else if (errorfld.match('F')) {
				document.getElementById("code").focus();
			}
		}
		document.getElementById('siimage').src = 'captcha-secureimage/securimage_show.php?sid=' + Math.random(); 
		document.getElementById("code").value = '';
		return false;
	}
	else {
		//call the webservice
		
		 var xmlHttp;
		 try
		 {
			 // Firefox, Opera 8.0+, Safari
			 xmlHttp=new XMLHttpRequest();
		 }
		catch (e)
		{
		  // Internet Explorer
		  try
			{
				xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			}
		  catch (e)
			{
			try
			  {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			  }
			catch (e)
			  {
				alert("Your browser does not support AJAX!");
				return false;
			  }
			}
		}

		 xmlHttp.onreadystatechange = function()
		 {
				document.getElementById("statusDIV").innerHTML = 'Please wait process is going on...';
				showLoading(true);	
				if(xmlHttp.readyState == 4)
				{
					HandleResponse(xmlHttp.responseText);
				}
	      }      
		 var flag=10; isNationalLanguage='false';
		 christianPercentage = Math.round(christianPercentage*Math.pow(10,4))/Math.pow(10,4);
		 //alert(flag);
		xmlHttp.open("POST", "webservice_string_new.php", true);
		 xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		 xmlHttp.send( '&countryName='+cntry_name+'&PeopleCountryPopulation='+PeopleCountryPopulation+'&ZonePopulation='+ZonePopulation+'&population='+population+'&isNationalLanguage='+isNationalLanguage+'&religion='+religion+'&secondReligionFollowers='+secondReligionFollowers+'&christianPercentage='+christianPercentage+'&languageName='+languageName+'&resourcesAvailable='+resourcesAvailable+'&churches='+churches+'&sourceInfo='+sourceInfo+'&peopleGroupName='+peopleGroupName+'&GSECStatus='+GSECStatus+'&bibleYear='+bibleYear+'&ntYear='+ntYear +'&portionsYear='+portionsYear +'&jesusFilm='+jesusFilm +'&gospelRecording='+gospelRecording+'&radioBroadcast='+radioBroadcast +'&likelihood='+likelihood +'&geographicdataInLatLng='+geographicdataInLatLng +'&isPolygon='+isPolygon +'&flag='+flag+'&ROG3='+ROG3); 
		
		 function HandleResponse(response) {
			if(response) 
			{
				var languagegroupid_resp=response.split("||");
				var languagegroupid=languagegroupid_resp[0];
				var response=languagegroupid_resp[1];
				document.getElementById("statusDIV").innerHTML = languageresponse+' '+response;
				Entering=1;
				recentpolygon=1;
				singlelgpoly(languagegroupid);
				clear_StepsInfo();
				GEvent.addListener(prmPolygon,"click",function(para){
	            if(Entering==1)  
	            {
	  	            singlelgpoly(languagegroupid);
					clear_StepsInfo();
	               }
	             });
				 document.getElementById('lg_area').checked=false;
			   }
		 }
		map.closeInfoWindow();
	}	
}
function closeData() {
	map.closeInfoWindow();
}
function deleteData() {
	//map.clearOverlays();
	map.clearOverlays();
}
//Code ended by Suresh
//== edit mode for polygons ==//
GPolygonControl.prototype.adjustline = function(currentPolygon, lineColor, k){ 
	var g = GPolygonControl.prototype.G;	
	var icon = GPolygonControl.prototype.icon();
	var vertices = this.returnVertices(currentPolygon);
	g.polygonPoints = new Array();
	g.polygonMarkers = new Array();
	
	//Note: Don't return start vertex, since start/end vertices overlap
	for (var m=1; m<vertices.length; m++) {
		var marker = GPolygonControl.prototype.createMarkerG(vertices[m],icon,m-1,lineColor,k,vertices.length-2); 				
		g.polygonPoints.push(vertices[m]);
		g.polygonMarkers.push(marker);
		map.addOverlay(marker);
	}					
}

GPolygonControl.prototype.recreatePolygon = function(polygon,lineColor,lineWeight,lineOpacity,fillColor,fillOpacity,k){ 
	var me = this.me();
	var g = this.G;
	var vertices = this.returnVertices(polygon);
	map.removeOverlay(polygon);
	var newPolygon = new BDCCPolygon(vertices,lineColor,lineWeight,lineOpacity,fillColor,fillOpacity);
	GEvent.addListener(newPolygon,"mouseover",function(){
    		newPolygon.setFillOpacity(parseFloat(fillOpacity)+.3);
    });
    GEvent.addListener(newPolygon,"mouseout",function(){
    		newPolygon.setFillOpacity(fillOpacity);
    });
    GEvent.addListener(newPolygon,"click",function(para){
			if(para){
				map.openInfoWindowHtml(para,g.editInfoWindowHtml1+g.prmPolygons[k][2]+g.editInfoWindowHtml2+g.prmPolygons[k][4]+g.editInfoWindowHtml3+g.prmPolygons[k][3]+g.editInfoWindowHtml4);
				me.addInfoWindowListeners(para, k);
			} else {//mac firefox hack -- bug in normal poly click event
				var hackClick_handler = GEvent.addListener(map,"click",function(overlay,point){
					if(overlay){
						var center = overlay.getBounds().getCenter();
						map.openInfoWindowHtml(center,g.editInfoWindowHtml1+g.prmPolygons[k][2]+g.editInfoWindowHtml2+g.prmPolygons[k][4]+g.editInfoWindowHtml3+g.prmPolygons[k][3]+g.editInfoWindowHtml4);
						me.addInfoWindowListeners(center, k);
						GEvent.removeListener(hackClick_handler);
					}
				});
			}
	});
 return newPolygon;
}

GPolygonControl.prototype.addInfoWindowListeners = function(point, k) {
	var me = this.me();
	var g = this.G;
	var currentPolygon = g.prmPolygons[k][1]
	g.currentcolor = g.prmPolygons[k][7];

	//onchange listeners for title and description values
	$('#titlePoly').change(function() {
		g.prmPolygons[k][2] = $('#titlePoly').val();
	});
	
	$('#descPoly').change(function() {
		g.prmPolygons[k][3] = $('#descPoly').val();
	});
	
	var colorHtml = '<div id="colorPickerDiv" style="position: relative; z-index:100; top:0px; left:0px; width:284px; height:344px; background-image:url(gmap/javascript/polygon/images/transparent.gif)"><form action="javascript:void(0);" style="width: 274px;">  <div class="form-item"><label for="color"></label><input type="text" style="display:none" id="color" name="color" value="#123456" /></div><div id="picker2"></div></form><table class="msstyle" style="height: 118px;"><tbody><tr><td style="vertical-align: top;"><table class="msline"><tbody><tr><td colspan="2"><b class="title">Edit line style</b></td></tr><tr><td class="label">Line width (pixels, 1-20)</td><td><input id="polygonWeight" class="numberfield" type="text" size="3" value="'+g.prmPolygons[k][5]+'"/></td></tr><tr><td class="label">Fill opacity (10-100)</td><td><input class="numberfield" id="polygonOpacity" type="text" size="3" value="'+g.prmPolygons[k][6]*100+'"/></td></tr></tbody></table></td></tr><tr><td><table><tbody><tr><td class="navLeft"/><td class="navRight"><button id="cancelPoly2">Cancel</button></td><td class="navRight"><button id="okPoly2">OK</button></td></tr></tbody></table></td></tr></tbody></table></div>';
				
	//bind color link
	$('#colorIcon').click(function(){
    		map.openInfoWindowHtml(point,colorHtml);
    		var farb = $.farbtastic('#picker2','#color');
    		farb.setColor(g.prmPolygons[k][7]);
			$("#okPoly2").click(function(){
				
				g.lineWeight = g.prmPolygons[k][5] = (parseInt($("#polygonWeight").val()) > 20 || parseInt($("#polylgonWeight").val()) < 1 || isNaN($("#polygonWeight").val()) )?g.prmPolygons[k][5]:$("#polygonWeight").val();
				g.fillOpacity = g.prmPolygons[k][6] = (parseInt($("#polygonOpacity").val()) > 100 || parseInt($("#polygonOpacity").val()) < 10 || isNaN($("#polygonOpacity").val()) )?g.prmPolygons[k][6]:($("#polygonOpacity").val()/100);
				g.fillColor = g.prmPolygons[k][7] = g.currentcolor = g.lineColor = $('#color').val();
				//restart original process
				map.openInfoWindowHtml(point,g.editInfoWindowHtml1+g.prmPolygons[k][2]+g.editInfoWindowHtml2+g.prmPolygons[k][4]+g.editInfoWindowHtml3+g.prmPolygons[k][3]+g.editInfoWindowHtml4);
				me.addInfoWindowListeners(point,k);
				$('#currentColor').css("background-color", g.currentcolor);
			});
			$("#cancelPoly2").click(function(){
				map.openInfoWindowHtml(point,g.editInfoWindowHtml1+g.prmPolygons[k][2]+g.editInfoWindowHtml2+g.prmPolygons[k][4]+g.editInfoWindowHtml3+g.prmPolygons[k][3]+g.editInfoWindowHtml4);
				me.addInfoWindowListeners(point,k);
			});
			$("#polygonWeight").change(function(){
				if(parseInt($("#polygonWeight").val()) > 20 || parseInt($("#polygonWeight").val()) < 1 || isNaN($("#polygonWeight").val()) ) {
					alert("Out of Range. Please select a number between 1 & 20");
					$("#polygonWeight").val(""+g.prmPolygons[k][5]+"");
				}
			});
			$("#polygonOpacity").change(function(){
				if(parseInt($("#polygonOpacity").val()) > 100 || parseInt($("#polygonOpacity").val()) < 10 || isNaN($("#polygonOpacity").val()) ) {
					alert("Out of Range. Please select a number between 10 & 100");
					$("#polygonOpacity").val(""+g.prmPolygons[k][6]+"");
				}
			});
      	return false;
	}); 
	
	//bind delete link
	$("#polyDelete").click(function(){alert("delete link:");
		 map.removeOverlay(currentPolygon);
		 g.prmPolygons.splice(k,1);
		 
		 //remove edit markers if present
		 for (i=0;i<g.polygonMarkers.length;i++) {
		 	map.removeOverlay(g.polygonMarkers[i]);
		  }
		   
		 map.closeInfoWindow();
		 $('#colorPickerDiv').css("display", "none");
		 g.polygonMarkers = new Array();
		 g.polygonPoints = new Array();
	});  
 			 
 	//bind edit link
 	$("#polyEdit").click(function(){		
	   	me.adjustline(currentPolygon,g.prmPolygons[k][7],k);
	   	map.closeInfoWindow();
		$('#colorPickerDiv').css("display", "none");
	}); 
 		   
	//cancel button
	$("#cancelPoly").click(function() {alert("cancelPoly");
	   		map.closeInfoWindow();
	   		$('#colorPickerDiv').css("display", "none");
	});
	   	
	// ok button
	$("#okPoly").click(function() {
	   	var newPolygon = me.recreatePolygon(currentPolygon,g.lineColor,g.lineWeight,g.lineOpacity,g.currentcolor,g.fillOpacity,k); 
		alert("val:"+newPolygon);
	   	map.addOverlay(newPolygon);
	   	g.prmPolygons[k][1] = newPolygon;
	   	g.prmPolygons[k][2] = $("#titlePoly").val();
	   	g.prmPolygons[k][3] = $("#descPoly").val();
	   	g.prmPolygons[k][4] = g.currentcolor;
		alert("val1:"+g.prmPolygons[k][2]);
		alert("val2:"+g.prmPolygons[k][3]);
	   	//g.prmPolygons[k][5] = g.lineWeight; //set above in color ok button
	   	//g.prmPolygons[k][6] = g.fillOpacity;
	   	//g.prmPolygons[k][7] = g.currentcolor;
	   	map.closeInfoWindow();
	   	$('#colorPickerDiv').css("display", "none");
	 });  								
}

GPolygonControl.prototype.removePolygon = function(){
	 var g = this.G;
	 if(g.polygon){map.removeOverlay(g.polygon);}
	 for (i=0;i<g.polygonMarkers.length;i++) {
		map.removeOverlay(g.polygonMarkers[i]);
	}
	 map.closeInfoWindow();
	 if(g.newline){map.removeOverlay(g.newline);g.newline=null;}
	 g.polygonMarkers = new Array();
	 g.polygonPoints = new Array();
	 map.closeInfoWindow();
	 GEvent.removeListener(g.addnewpolygonline_handler);
	 GEvent.removeListener(g.polygon_handler);
}
 



//Thiis function is added by Suresh on 9/22/2008

function polyClick1(pt_latlng, oid, q_type) {//alert("pt_latlng"+pt_latlng);
	showLoading(true);
	//alert("after click http://202.63.103.233/worldmap/gmap/sample_suresh.php?oid="+oid+"&q="+q_type);
var oid_url = "gmap/get_xml.php?qURL="+ escape("http://202.63.103.233/worldmap/gmap/sample_suresh.php?oid="+oid+"&q="+q_type);
		document.getElementById('statusDIV').innerHTML = "LOADING polygon tab...";
	
		GDownloadUrl(oid_url, function(data) {
					
		  var oid_xml = GXml.parse(data);
		  var Poly_data = oid_xml.documentElement.getElementsByTagName("point");
		//	alert("Poly_data"+Poly_data);  
		  if (Poly_data.length > 0) {
			document.getElementById("statusDIV").innerHTML = "TAB Records found: "+Poly_data.length;
		  } 
		  else {
			document.getElementById('statusDIV').innerHTML = "TAB Records found: 0";
			return null;
		  }
			
			// SETUP ALL TABS
			var tabs = [];  // info Tabs container for InfoWindows
			var tab_labels = [];			
			var htmls = [];
					
			  for (var i = 0; i < Poly_data.length; i++) {  // LOOP THROUGH TABS XML ELEMENTS
				var oid = Poly_data[i].getAttribute("oid");  // needed to manage these marker points
				
				// Location Tab		
				tab_labels.push('Location');    
				var html = Poly_data[i].getAttribute("loc_html"); 
				//alert("loc_html:\n"+html);
				html = parseToHTML(html);
				//alert("loc_html:\n"+html);
				htmls.push(html);
				
				// Linguistic Tab		
				tab_labels.push('Linguistic');
				var html = Poly_data[i].getAttribute("mis_html"); 
				//alert("mis_html:\n"+html);
			    html = parseToHTML(html);
				//alert("mis_html:\n"+html);
				htmls.push(html);
						
				// Cultural Tab		
				tab_labels.push('Cultural');
				var html = Poly_data[i].getAttribute("cul_html"); 
				//alert("cul_html:\n"+html);
				
			    html = parseToHTML(html);
				//alert("cul_html:\n"+html);
				htmls.push(html);
				
			  }
					  
				// Create Tabbed Info Window
			  for (var j=0; j < htmls.length; j++) {
				  //alert("in for loop:length"+htmls.length);
				//htmls[j] = '<div class=infowindow style="text-align:left; height: 285px; width:'+htmls.length*88+'px">' + htmls[j] + '</div>';
				//position: absolute; left: -15px; top: 10px; width: 200px; height: 160px;
				//htmls[j] = '<div class=infowindow style="position: absolute; left: -5px; top: 2px; right: 10px; text-align:left; height: 180px; width: 140px">' + htmls[j] + '</div>';
				htmls[j] = '<div class="infowindow" style="width:283px; height:270px">' + htmls[j] + '</div>';
				//alert("in for loop:length"+htmls[j]);
				tabs.push(new GInfoWindowTab(tab_labels[j],htmls[j]));
				
			  }
			//alert("after for loop pt_latlng:"+pt_latlng);
			//alert("after for loop tabs:"+tabs);
			map.openInfoWindowTabsHtml(pt_latlng, tabs);
		showLoading(false);	
		 });  // END GDownloadUrl(oid_url)
		  
} // END function createPolyMarker
var alertdisp = false;
function blockchars(e) {
 var key = window.event ? e.keyCode : e.which;
 var keychar = String.fromCharCode(key);
 reg = /\d/;

 if (key==null || key==0 || key==8 || key==9 || key==13 || key==27) {
  return true;
 }

 if (!reg.test(keychar))
 {
 	if (alertdisp == false ) {
		alert('Please enter only numeric values in this field!');
		alertdisp = true;
	}
  return false;
 }
 return;
}
function pagerefresh()
{
 //alert("testing refresh");
 location.reload(true);
 }
/* function clearmap() {
	 map.clearOverlays() ; // document.getElementById("googlemap").innerHTML =''; 
	 document.getElementById("googlemap")
	 GEvent.clearListeners(map,'');
	 document.getElementById("statusDIV").innerHTML = "";
	 document.getElementById("fttpts").checked=false;
	 //The below 3 lines added by Suresh on 9/4/2008  
	 //document.getElementById("churchpts").checked=false;
	// document.getElementById("activitypts").checked=false;
	 //document.getElementById("locationpts").checked=false;
	// document.getElementById("contactpts").checked=false;
	 //The below 3 lines added by Suresh for unselect dropdown after click clearmap and form tag moved to up on 9/26/2008 
	 document.test.sel_peoplegroup.options[0].selected = true;         
	 document.test.sel_lang.options[0].selected = true;
	 document.test.kml.options[0].selected = true;

	 document.test.kml.options[0].selected = true;
	 document.getElementById('pgarea').checked= false; 
	 document.getElementById('pgpoint').checked= false;
	 document.getElementById('lg_area').checked= false; 
	 document.getElementById('lg_point').checked= false;
	 document.getElementById('christ').checked= false;
	 document.getElementById('bible').checked= false;
	 document.getElementById('jfilm').checked= false;
	 document.getElementById('churchpts').checked= false;
	 document.getElementById('activitypts').checked= false;
	 document.getElementById('locationpts').checked= false;
	 document.getElementById('contactpts').checked= false;
	 pgareacheckboxes="";
     checkareacheckboxes='';
	 clear_polycontrol();	 
	 clear_StepsInfo();
	  
     if(moveendlistner!=undefined)
     {
	// alert(moveendlistner);
       GEvent.removeListener(moveendlistner);
      }
	 //document.getElementsByName("gsec_Radios");

	//  DISABLE ALL GSEC RADIO BUTTONS
	var theRadios = document.getElementsByName("gsec_Radios");
	
	for (r=0; r < theRadios.length; r++) {
		theRadios[r].disabled=true;
		theRadios[r].checked=false;//This is added by Suresh on 9/4/2008 for uncheck the radiobutton in city status after press clearbutton
	}

	//This below code is added by Suresh on 9/4/2008 for uncheck the radiobutton in populated places after press clearbutton

	var theRadios = document.getElementsByName("RPP_Radios");
	for (r=0; r < theRadios.length; r++) {
		theRadios[r].disabled=true;
		theRadios[r].checked=false;//This is added by Suresh on 9/4/2008 for uncheck the radiobutton after press clearbutton
	}

	//var theRadios = document.getElementsByName("area");
	var theRadios = document.getElementsByName("pgarea");
	for (r=0; r < theRadios.length; r++) {
		theRadios[r].disabled=true;
		theRadios[r].checked=false;//This is added by Suresh on 11/12/2008 for uncheck the radiobutton after press clearbutton
	}

	//code ended by Suresh on 9/4/2008
	 for (var d=0; d< div_ids.length; d++) {
		 var div_id = "qry_div"+d.toString();
	  //alert('div_id: '+div_id);

		 var qdiv = document.getElementById(div_id);
		 if (qdiv == null) {break;}
		 //qdiv.innerHTML = "";
		 qdiv.style.display="none";
	 }
  // CLEAR LANG/PG POINTS
  for (var id in myRPPMarkers) {
  	//map.removeOverlay(myGSECMarkers[i])
	if (myRPPMarkers[id] instanceof GMarker) {
	  //alert("key: "+id+" value:"+myGSECMarkers[id]);
		var marker = myRPPMarkers[id];
		//marker.hide();
		map.removeOverlay(marker);
		myRPPMarkers[id] = null;
	}
  }
} */

