var map;
var mapElement;
var controleElement;
var mapOpac = 0;
var dclick = false;
var fading = false;
var displayed = false;
var poly = false;

var defLat = 47.27922900;
var defLng = -105.46875;
var defZoom = 2;

var reqZoomLevel = 15;
var reqFlagLevel = 16;
var maxZoomLevel = 18;
var currMsg = "";
var oldMsg = "";
var oldPoly = false;
var point = false;
var flagmarker = false;
var icon = false;
var geocoder = false;
var geocodeTimer = false;

var clickedPoint = false;
var savedPoint = false;
var savedZoom = false;

var localSearch;
var linkId = 0;
var currLinkId = 0;

    function defaultInit( ) {
	if(!map) displayMap(null, null, true);
    }

	function usePointFromPostcode(postcode, callbackFunction) {
	  linkId++;

	if(!localSearch) localSearch = new GlocalSearch();

	  localSearch.setSearchCompleteCallback(null,
	    function() {

	      if (localSearch.results[0]) {    
	        var resultLat = localSearch.results[0].lat;
	        var resultLng = localSearch.results[0].lng;
	        var point = new GLatLng(resultLat,resultLng);
	        callbackFunction(point);
	      }else{
	        alert("Cannot find location, please try again.");
	      }
	    });  
	    
	  localSearch.execute(postcode + ", UK");
	}
;
    function loadMap(lat, lng, zoom) {
      if (GBrowserIsCompatible()) {
		map = new GMap2(mapElement);
		//map.disableDoubleClickZoom();
		if(lat && lng) {
			map.setCenter(new GLatLng(lat, lng), 13);
			if(zoom) map.setZoom(zoom);
			else map.setZoom(reqFlagLevel);
		} else {
			map.setCenter(new GLatLng(defLat, defLng), 13);
			map.setZoom(defZoom);
		}
		map.setMapType(G_HYBRID_MAP);
		map.enableScrollWheelZoom( );
		map.enableContinuousZoom( );

		GEvent.addListener(map, "zoomend", function( ) {
			setMapMessage( );
		});

		GEvent.addListener(map, "dblclick", function(marker, point) {
			/*map.panTo(point);*/
			clickedPoint = point;
			map.setZoom(map.getZoom( ));
			checkZoom( );
		});    
		

		geocoder = new GClientGeocoder( );
      } else {
		alert("Sorry, your web browser is not compatible with Google(R) Maps.\nThis means you should upgrade your browser\n"+
			"to use GetMyFling.");
	}
    }

	function checkZoom( ) {
		//if(map.getZoom( ) < reqZoomLevel && map.getZoom( ) < maxZoomLevel) {
		//	map.setZoom( map.getZoom( ) + 4 > maxZoomLevel ? maxZoomLevel : map.getZoom( ) + 4);
		//} else {
		//	document.title+=(map.getZoom( ) +", "+reqZoomLevel);
			updateFlagPos( );
		//}
	}

	function geocodeMap( ) {
		if(geocodeTimer) clearTimeout(geocodeTimer);
		geocodeTimer = setTimeout("goGeocode()", 1500);
	}

	function goGeocode( ) {
		clearTimeout(geocodeTimer);
		moveToLocation(document.getElementById("location").value);
	}

	function updateDetailText( ) {
		var el1 = document.getElementById("seeking");
		var el2 = document.getElementById("type");
		var mapL = document.getElementById("actualLocation");

		if(el1 && el2 && mapL) {
			var text = document.getElementById("detailText");
			if(el1.value!="" && el2.value!="") {
				if(mapL.value == "") {

					text.innerHTML = "Pinpoint The Location Details, Using Map &raquo;";
				} else text.innerHTML = "Now set the date and time of your encounter &darr;";
			} else text.innerHTML = "";
		}
	}
	
	function moveToLocation(location) {
		/*if(!geocoder) geocoder = new GClientGeocoder( );

		if(geocoder) {
			geocoder.getLatLng(
				location,
				function(point) {
					if (!point) {
						alert("Could not find this location, please try again.");
					} else {
						panTo(point.lat( ), point.lng( ), reqFlagLevel + 1);
					}
				}
			);
		}*/
		
		currLinkId = linkId + 1;
		usePointFromPostcode(location, function(point) { if(linkId==currLinkId) { panTo(point.lat( ), point.lng( ), reqFlagLevel + 1); }});
	}

	function setMapMessage( ) {
		if(map.getZoom( ) >= reqZoomLevel) {
			updateMessage(poly ? promptAltMessage : promptMessage);
			if(poly) {
				document.getElementById("indgr").style.display = "inline";
				document.getElementById("indrem").style.display = "inline";
				document.getElementById("indred").style.display = "none";
				document.getElementById("indor").style.display = "none";

			} else {
				document.getElementById("indgr").style.display = "none";
				document.getElementById("indrem").style.display = "none";
				document.getElementById("indred").style.display = "none";
				document.getElementById("indor").style.display = "inline";				
			}
		} else {
			updateMessage(poly ? zoomAltMessage : zoomMessage);
			if(poly) {
				document.getElementById("indgr").style.display = "inline";
				document.getElementById("indrem").style.display = "inline";
				document.getElementById("indred").style.display = "none";
				document.getElementById("indor").style.display = "none";			
				/*if(flagmarker && map.getZoom( ) > reqFlagLevel) {
					map.removeOverlay(flagmarker);
					flagmarker = null;
				}*/
			} else {
				document.getElementById("indgr").style.display = "none";
				document.getElementById("indrem").style.display = "none";
				document.getElementById("indred").style.display = "inline";
				document.getElementById("indor").style.display = "none";							
			}
		}
	}
	
	function updateFlagPos( ) {
		if(map.getZoom( ) >= reqZoomLevel) {
			stopDemo( );

			//var center = map.getCenter( );
			var lat = clickedPoint.lat( );
			var lng = clickedPoint.lng( );
			polys = [
				new GLatLng(lat - areaLatSize, lng - areaLngSize),
				new GLatLng(lat + areaLatSize, lng - areaLngSize),
				new GLatLng(lat + areaLatSize, lng + areaLngSize),
				new GLatLng(lat - areaLatSize, lng + areaLngSize),
				new GLatLng(lat - areaLatSize, lng - areaLngSize)
			];
			if(poly) {
				map.removeOverlay(poly);
			}

			document.getElementById("actualLocation").value = clickedPoint;

			poly = new GPolygon(polys,areaLineColour,areaLineSize,1,areaFillColour,areaFillOpac);
			map.addOverlay(poly);
			if(flagmarker) map.removeOverlay(flagmarker);

			var text = document.getElementById("mapText");
			if(text) {
				text.innerHTML = "Now set your encounter details below &darr;";
			}
			updateDetailText( );
			checkDisabled( );

			icon = new GIcon( );
			icon.image = flagImage;
			icon.iconSize = new GSize(flagSize, flagSize);
			icon.iconAnchor = new GPoint(flagAnchorX, flagAnchorY);
			flagmarker = new GMarker(clickedPoint, icon);	
			map.addOverlay(flagmarker);

			point = clickedPoint;	
			savedPoint = clickedPoint;
			savedZoom = map.getZoom( );
			setMapMessage( );
		}
	}
	
	function toggleMarker( ) {
		if(poly) {
			map.removeOverlay(poly);
			oldPoly = poly;
			poly = false;
			setMapMessage( );
			map.removeOverlay(flagmarker);
			var text = document.getElementById("mapText");
			if(text) {
				text.innerHTML = "Pinpoint The Location Details, Using Map &raquo;";
				document.getElementById("actualLocation").value = "";
				checkDisabled( );
			}
			flagmarker = false;
			updateDetailText( );
		} else {
			if(oldPoly) {
				map.addOverlay(oldPoly);
				map.returnToSavedPosition( );
				setMapMessage( );
			}
		}
	}

	function updateMessage(text) {
		oldMsg = currMsg;
		currMsg = text;
		document.getElementById("mapMessageText").innerHTML = currMsg;
	}
	
    function displayMap(lat, lng, zoom, demo) {
	if(!displayed) {
		mapElement = document.getElementById("map");  
		controlElement = document.getElementById("mapControls");
		loadMap(lat, lng, zoom);
		var text = document.getElementById("mapText");
		if(text) {
			text.style.visibility = "";
		}
		fadeInMap( );
		displayed = true;
	}

	if(!demo) stopDemo( );
    }

    function updatePan(panElement) {
	var value = panElement.options[panElement.selectedIndex].value;
	if(value) {
		var parts = value.split("_");
		if(parts.length == 3) {
			panTo(parts[1], parts[2], 4);
		}
	}
    }

    function panTo(lat, lng, zoom, demo) {
	if(!demo) stopDemo( );

	if(!displayed) {
		displayMap(lat, lng, zoom);
	} else {
		map.panTo(new GLatLng(lat, lng));
		if(zoom) map.setZoom(zoom);	
	}
    }
    
    function fadeInMap(slow) {
	if(fading) return;
	else {
		fading = true;
		if(slow) {
			mapOpac+= 0.02; 
			mapDelay = 150;	
		} else {
			mapOpac+= 0.05; 
			mapDelay = 200;	
		}
		mapElement.style.opacity = mapOpac;
		controlElement.style.opacity = mapOpac;
		mapElement.style.filter = "alpha(Opacity="+(mapOpac * 100)+");";
		controlElement.style.filter = "alpha(Opacity="+(mapOpac * 100)+");";		
		if(mapOpac >= 1) {
			mapOpac = 1;
			mapElement.style.opacity = 1;
			controlElement.style.opacity = 1;
			fading = false;
			var text = document.getElementById("mapText");
			if(text) {
				text.innerHTML = "Pinpoint The Location Details, Using Map &raquo;";
			}
			return;
		} else {
			fading = false;
			setTimeout("fadeInMap()", mapDelay);
		}
	}
    }

    /* Form */
    function updateType(selectVar) {
	var noTime = {
		"holiday-romance": 1,
		"relationship": 1
	};

	if(selectVar) {
		var type = selectVar.options[selectVar.selectedIndex].value;
		if(noTime[type]) {
			document.getElementById("startTime").disabled = "disabled";
			document.getElementById("startTime").className = "disabled";	
			document.getElementById("endTime").disabled = "disabled";
			document.getElementById("endTime").className = "disabled";	
		} else {
			document.getElementById("startTime").disabled = "";
			document.getElementById("startTime").className = "";	
			document.getElementById("endTime").disabled = "";
			document.getElementById("endTime").className = "";	
		}
	}
    }

    function checkZeroLength(id) {
	var gadget = document.getElementById(id);
	if(gadget) {
		if(gadget.value!="") {
			return true;
		}
	}

	return false;
    }

    function validDate(id) {
	var gadget = document.getElementById(id);
	if(gadget) {
		var regex = /^\d{1,2}(\/|\-|\s)\d{1,2}(\/|\-|\s)\d{4}$/;
		if(gadget.value.match(regex)) {
			return true;
		}
	}

	return false; 
    }

    function updateCombos( ) {
	var endDate = document.getElementById("endDate");
	if(endDate) {
		if(endDate.value == "End Date") {
			var startDate = document.getElementById("startDate");
			if(startDate) endDate.value = startDate.value;
		}
	}
    }

    function checkTime(id) {
	var time = document.getElementById(id);
	if(time) {
		var text = time.value.replace(/\s/g, "");
		text = text.toLowerCase( );
		var timeRegex = /^\d{1,2}(.?)\d{2}(am|pm)?$/;
		if(text.match(timeRegex)) {		
			return true;
		}
	}

	return false;
    }

    function checkDisabled( ) {
	var val = getValidationStage( );
	var stage = val[0];

	switch(stage) {
		case 3:
			var left = document.getElementById("leftcontent");
			left.className = "leftcontent";
			var right = document.getElementById("rightcontent");
			right.className = "rightcontent";
			var submit = document.getElementById("submit");
			submit.className = "submitbutton";
			break;		
		case 2:
			var left = document.getElementById("leftcontent");
			left.className = "leftcontent fadedOut";
			var right = document.getElementById("rightcontent");
			right.className = "rightcontent";
			var submit = document.getElementById("submit");
			submit.className = "fadedOut submitbutton";
			break;
		case 1:
			var left = document.getElementById("leftcontent");
			left.className = "leftcontent";
			var right = document.getElementById("rightcontent");
			right.className = "rightcontent fadedOut";
			var submit = document.getElementById("submit");
			submit.className = "fadedOut submitbutton";
			break;
	}
    }

    function getValidationStage( ) {
	var valErrors = [];
	var stage = 1;

	if(!checkZeroLength("actualLocation")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"Please choose a location using the Map.";
		document.getElementById("mc").className = "";
		document.getElementById("location").className = "";	
	} else {
		document.getElementById("mc").className = "correct";
		document.getElementById("location").className = "correct";	
	}
	if(!checkZeroLength("seeking")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"Please choose the correct gender information.";
		document.getElementById("seeking").className = "";
	} else {
		document.getElementById("seeking").className = "correct";
	}
	if(!checkZeroLength("type")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"Please choose the correct type of encounter.";
		document.getElementById("type").className = "";
	} else {
		document.getElementById("type").className = "correct";
	}
	if(!validDate("startDate")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"The start date must be in a valid format (dd/mm/yyyy).";
		document.getElementById("startDate").className = "";
	} else {
		document.getElementById("startDate").className = "correct";
	}
	if(!validDate("endDate")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"The end date must be in a valid format (dd/mm/yyyy).";
		document.getElementById("endDate").className = "";
	} else {
		document.getElementById("endDate").className = "correct";
	}
	if(	!checkZeroLength("startTime") || document.getElementById("startTime").value=="Start Time" ||
		!checkTime("startTime")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"Please specify a valid start time.";
		document.getElementById("startTime").className = "";
	} else {
		document.getElementById("startTime").className = "correct";
	}	
	if(!checkZeroLength("endTime") || document.getElementById("endTime").value=="End Time" ||
		!checkTime("endTime")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"Please specify an valid end time.";
		document.getElementById("endTime").className = "";
	} else {
		document.getElementById("endTime").className = "correct";
	}	

	if(valErrors.length==0) stage = 2;

	if(!checkZeroLength("my-clothing-colour") || !checkZeroLength("my-clothing-type")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"Please specify the colour and type of clothing you were wearing.";
		document.getElementById("my-clothing-colour").className = "";
		document.getElementById("my-clothing-type").className = "";
	} else {
		document.getElementById("my-clothing-colour").className = "correct";
		document.getElementById("my-clothing-type").className = "correct";
	}	
	if(!checkZeroLength("my-feature-colour") || !checkZeroLength("my-feature-type")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"Please specify the colour and type of your prominent feature.";
		document.getElementById("my-feature-colour").className = "";
		document.getElementById("my-feature-type").className = "";
	} else {
		document.getElementById("my-feature-colour").className = "correct";
		document.getElementById("my-feature-type").className = "correct";
	}
	if(!checkZeroLength("your-clothing-colour") || !checkZeroLength("your-clothing-type")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"Please specify the colour and type of clothing your fling was wearing.";
		document.getElementById("your-clothing-colour").className = "";
		document.getElementById("your-clothing-type").className = "";
	} else {
		document.getElementById("your-clothing-colour").className = "correct";
		document.getElementById("your-clothing-type").className = "correct";
	}
	if(!checkZeroLength("your-feature-colour") || !checkZeroLength("your-feature-type")) {
		valErrors[valErrors.length >= 1 ? valErrors.length : 0] = 
			"Please specify the colour and type of your fling's prominent feature.";
		document.getElementById("your-feature-colour").className = "";
		document.getElementById("your-feature-type").className = "";
	} else {
		document.getElementById("your-feature-colour").className = "correct";
		document.getElementById("your-feature-type").className = "correct";
	}

	if(valErrors.length==0) stage = 3;

	return [
		stage, valErrors
	];
    }

    function updateGenderText(gadget) {
	if(gadget) {
		var value = gadget.value;
		var m1 = document.getElementById("genderWear");
		var m2 = document.getElementById("genderFeature");
		if(value.substring(1)=="f") {
			if(m1) m1.innerHTML = "She";
			if(m2) m2.innerHTML = "She";
		} else {
			if(m1) m1.innerHTML = "He";
			if(m2) m2.innerHTML = "He";
		}	
	}
    }

    function validateForm( ) {
	var errors = getValidationStage( );
	var valErrors = errors[1];

	if(valErrors.length > 0) {
		var error = valErrors.join("\n\t");
		alert("Sorry, you must correct the following errors before submitting your fling:\n\n\t"+error);
		return false;	
	}

	return true;
    }

    function initCellMap(id, center, boundary) {
	var cellMap = document.getElementById(id);
	 if (GBrowserIsCompatible() && cellMap) {
		var map2 = new GMap2(cellMap);

		//map.disableDoubleClickZoom();
		map2.setCenter(new GLatLng(center[0], center[1]), 13);
		map2.setZoom(reqFlagLevel-3);

		var points = [ ];
		for(id in boundary) {
			points[points.length] = new GLatLng(boundary[id][0], boundary[id][1]);
		}

		poly = new GPolygon(points, areaLineColour,areaLineSize,1,areaFillColour,areaFillOpac);

		map2.addOverlay(poly);

		var icon2 = new GIcon( );
		icon2.image = flagImage;
		icon2.iconSize = new GSize(flagSize, flagSize);
		icon2.iconAnchor = new GPoint(flagAnchorX, flagAnchorY);
		var flagmarker2 = new GMarker(new GLatLng(center[0], center[1]), icon2);	
		map2.addOverlay(flagmarker2);

		map2.enableScrollWheelZoom( );
		map2.enableContinuousZoom( );
		map2.setMapType(G_HYBRID_TYPE);
	}

    }

    var demopoints = [
	{mapLat: 54.319062, mapLng: 24.464407, flagLat: 54.31896, flagLng: 24.464704},
	{mapLat: 0.128145, mapLng: 52.20207, flagLat: 0.128226, flagLng: 52.202187},
	{mapLat: -73.965411, mapLng: 40.782605, flagLat: -73.965527, flagLng: 40.782514},
	{mapLat: -73.965527, mapLng: 40.782514, flagLat: -73.965527, flagLng: 40.782514},
	{mapLat: 2.294576, mapLng: 48.858689, flagLat: 2.294764, flagLng: 48.858207},
	{mapLat: -73.985823, mapLng: 40.748403, flagLat: -73.984951, flagLng: 40.748091},
	{mapLat: -81.549392, mapLng: 28.373197, flagLat: -81.549392, flagLng: 28.373197},
	{mapLat: 2.291422, mapLng: 48.859633, flagLat: 2.291422, flagLng: 48.859633},
	{mapLat: 78.04209, mapLng: 27.174913, flagLat: 78.042203, flagLng: 27.174579},
	{mapLat: 151.215241, mapLng: -33.85674, flagLat: 151.215359, flagLng: -33.856215},
	{mapLat: -74.04444, mapLng: 40.689421, flagLat: -74.044123, flagLng: 40.688619},
	{mapLat: -81.74688, mapLng: 36.28583, flagLat: -81.74688, flagLng: 36.28583},
	{mapLat: 1.409495, mapLng: 38.889346, flagLat: 1.409495, flagLng: 38.889346},
	{mapLat: 12.492399, mapLng: 41.890106, flagLat: 12.492753, flagLng: 41.889966},
	{mapLat: 12.492753, mapLng: 41.889966, flagLat: 12.492753, flagLng: 41.889966},
	{mapLat: 31.133891, mapLng: 29.978961, flagLat: 31.134208, flagLng: 29.980466},
	{mapLat: 1.051319, mapLng: 51.357365, flagLat: 1.051319, flagLng: 51.357365},
	{mapLat: 7.424773, mapLng: 43.735158, flagLat: 7.42752, flagLng: 43.734538},
	{mapLat: -80.12328, mapLng: 25.806044, flagLat: -80.122706, flagLng: 25.806063}
   ];

    var counter = 0;
    var timer = null;
    var demoPoly = null;
    var demoFlag = null;

    function startDemo( ) {
	counter = Math.floor(Math.random( ) * demopoints.length);
	displayMap(demopoints[counter].mapLng, demopoints[counter].mapLat, 18, true);	
	

	timer = setTimeout(scrollNext, 100);
    }

    function scrollNext( ) {
	if(timer) clearTimeout(timer);

	panTo(demopoints[counter].mapLng, demopoints[counter].mapLat, 18, true);
	var lat = demopoints[counter].flagLng;
	var lng = demopoints[counter].flagLat;

	polys = [
		new GLatLng(lat - areaLatSize, lng - areaLngSize),
		new GLatLng(lat + areaLatSize, lng - areaLngSize),
		new GLatLng(lat + areaLatSize, lng + areaLngSize),
		new GLatLng(lat - areaLatSize, lng + areaLngSize),
		new GLatLng(lat - areaLatSize, lng - areaLngSize)
	];

	if(demoPoly) {
		map.removeOverlay(demoPoly);
	}
        if(demoFlag) {
		map.removeOverlay(demoFlag);
        }

	var dicon = new GIcon( );
	dicon.image = flagImage;
	dicon.iconSize = new GSize(flagSize, flagSize);
	dicon.iconAnchor = new GPoint(flagAnchorX, flagAnchorY);
	demoFlag = new GMarker(new GLatLng(lat, lng), dicon);	
	map.addOverlay(demoFlag);

	demoPoly = new GPolygon(polys,areaLineColour,areaLineSize,1,areaFillColour,areaFillOpac);
	map.addOverlay(demoPoly);


	counter++;

	if(counter > demopoints.length - 1) {
		counter = 0;
	}

	timer = setTimeout(scrollNext, 30000);
    }

    function stopDemo( ) {
	if(timer) clearTimeout(timer);
	if(map) map.removeOverlay(demoFlag);
	if(map) map.removeOverlay(demoPoly);
    }

