var j$ = jQuery.noConflict();

(function($){
	var __ImmersiFind = window.__ImmersiFind = window.i$ = {};

	i$ = function() {
	/*********************
	 * private properties
	 *********************/
	var isDEBUG = false,
		map = null,
		customControls = [],
		isStreetViewOn = false,
		largeMapControl = new GLargeMapControl(),
		smallMapControl = new GSmallMapControl(),
		// street view panorama
		stPanorama,
		// street view client
		stClient,
		// street view overlay
		svOverlay,
		anyMarker,
		pegmanPos,
		pegmanIconBase = "http://maps.gstatic.com/mapfiles/cb/man_arrow-",
		curPegmanLatLng = prevPegmanLatLng = null,
		pegmanMarker,
		pegmanIcon = new GIcon(),
		isFound = false,
		isNoStreetView = false,
		svReturnCode = 200; // by default it is success

	var defs = defaults = {
		mapId: "map",
		mapType: "map",
		mapOptions: "",
		resizeCallback: "",
		loadCallback:"",
		streetId: "mapStreet",
		borderId: "mapBorder",
		streetContainerId: "streetContainer",
		mapMaxWidth: 500,
		mapMinWidth: 500,
		mapMaxHeight: 500,		
		mapMinHeight: 500,
		streetHeight: -1, 
		initZoom: 11,
		minZoom: 5,
		centerPoint: [43.6485, -79.3853], // toronto
		// yaw defines the rotation angle around the camera locus in degrees relative from true north. 
		// Yaw angles are measured clockwise (90 degrees is true east)
		// looking north [90: East, 180: South, 270: West]
		yaw:180, 
		// pitch defines the angle variance "up" or "down" from the camera's initial default pitch, which is often (but not always) flat horizontal. 
		pitch:0, // ground [0 ~ -90: looking up, 0 ~ +90: looking down]
		draggableCursor:"",
		largeMapControl:null,
		webcamControlId:"",
		streetViewControlPos:282,
		spanishFlag:"F",
		impId:-1
	};

	/************************************
	 * private methods
	 ***********************************/
	var log = {
		write: function(message) {
			if(isDEBUG) {
				GLog.write(message);
			}
		}
	};

	var getMapInstance = function() {
		return map;
	};

	var getPegman = function(yawNo, latlng_) {
		var latlng = latlng_||curPegmanLatLng||map.getCenter();

		pegmanIcon.image  = pegmanIconBase + yawNo + ".png";
		pegmanIcon.iconSize = new GSize(49, 52);
		pegmanIcon.iconAnchor = new GPoint(25, 35);  		// near base of guy's feet
		pegmanIcon.infoWindowAnchor = new GPoint(25, 5);	// top of guy's head

		pegmanMarker = new GMarker(latlng, {draggable:true, dragCrossMove:false, icon:pegmanIcon});
		map.addOverlay(pegmanMarker);

		curPegmanLatLng = latlng;

		// show street view overlay
		GEvent.addListener(pegmanMarker, "dragstart", function() {
			prevPegmanLatLng = pegmanMarker.getLatLng(); // don't assign curPegmanLatLng it is wrong.
			if(svOverlay != null) {
				log.write("street view is already there");
			} else {
				svOverlay = new GStreetviewOverlay();
				map.addOverlay(svOverlay);
			}
		});

		GEvent.addListener(pegmanMarker, "dragend", function() {
			curPegmanLatLng = pegmanMarker.getLatLng();
			//stPanorama.setLocationAndPOV(curPegmanLatLng);
			getNearestStreetView(curPegmanLatLng);
			map.removeOverlay(svOverlay);
			svOverlay = null;
		});
	}; 

	var removePegman = function() {
		map.removeOverlay(pegmanMarker);
	};
	
	var changePegman = function(yawNo_) {
		var yawNo = yawNo_||0;
		
		removePegman();
		getPegman(yawNo);
	};
	
	var getMapType = function(mapType) {
		switch(mapType) {
			case 'map':	// Normal Map
				mapType = G_NORMAL_MAP;
			break;
			case 'sat':	// Satallite Imagery
				mapType = G_SATELLITE_MAP;
			break;
			case 'hybrid':	//Hybrid Map
				mapType = G_HYBRID_MAP;
			break;
			default:
				mapType = G_NORMAL_MAP;
		};
		return mapType;
	}

	// get initial street view in streetview div. called by toggle button
	var initStreetView = function() {
		map.checkResize();
		isFound = false;
		stClient = new GStreetviewClient();
		stPanorama = new GStreetviewPanorama($(defs.streetId)[0], {pov:{yaw:defs.yaw,pitch:defs.pitch}});

		//getPegman(0, (anyMarker ? anyMarker.getLatLng():null));
		getPegman(0, (anyMarker ? anyMarker.getLatLng():iMap.markers[0].getLatLng()));

		GEvent.addListener(stPanorama, "error", handleNoFlash);
		GEvent.addListener(stPanorama, "yawchanged", onYawChange);
		// this is fired whenever the street view is moved 
		GEvent.addListener(stPanorama, "initialized", onStreetViewMoved);

		getNearestStreetView(curPegmanLatLng);
	};

	var onStreetViewMoved = function(location) {
		curPegmanLatLng = location.latlng;
		pegmanMarker.setLatLng(curPegmanLatLng);
		map.panTo(curPegmanLatLng);
		getAddress(curPegmanLatLng);
	};

	var onYawChange = function(newYaw) {
		var pegmanIconNum = 16;
		var pegmanAngular = 360/pegmanIconNum;
		if (newYaw < 0) {
		  newYaw += 360;
		}
		var newYaw = Math.round(newYaw/pegmanAngular) % pegmanIconNum;

		changePegman(newYaw);
	}

    var handleNoFlash = function(errorCode) {
      if(errorCode == 603) {
        alert("Flash doesn't appear to be supported by your browser");
      } else if(errorCode == 600) {
        log.write("handleNoFlag : No street view data around here.(code: " + errorCode+")");
      }

      // move back to previous point 
      pegmanMarker.setLatLng(prevPegmanLatLng);
      svReturnCode = errorCode;
    };

	var svIdx = 1,
		tryCount = 1,
		dbase = parseFloat(0.0005), 
		incDelta = parseFloat(0.0005);

	var getNearestStreetViewAgain = function(latlng_) {
		var latlng = latlng_||curPegmanLatLng,
			clat = latlng.lat(),
			clng = latlng.lng(),
			ll;

		log.write("getNearestStreetViewAgain > # : "+tryCount+ " : dbase = " + dbase + " svIdx : " + svIdx);
		if(tryCount <= 3) {
			if(svIdx == 1) {
				ll = new GLatLng(clat+dbase, clng);
				svIdx++;
			} else if(svIdx == 2) {
				ll = new GLatLng(clat, clng+dbase);
				svIdx++;
			} else if(svIdx == 3) {
				ll = new GLatLng(clat-dbase, clng);
				svIdx++;
			} else {
				ll = new GLatLng(clat, clng-dbase);				
				svIdx = 1;
				tryCount++;
				dbase += incDelta;
			}
			log.write("getNearestStreetViewAgain > ll = " + ll);
			stClient.getNearestPanorama(ll, checkStreetViewByClient);
		} else {
			log.write("getNearestStreetViewAgain > getNearestStreetViewAgain : NOT FOUND");

			if(!isFound) {
				svOverlay = new GStreetviewOverlay();
				GEvent.addListener(svOverlay, "changed", checkStreetviewWithChanged);
				map.addOverlay(svOverlay);
			}
			else {
				svIdx = 1;
				tryCount = 1;
				dbase = parseFloat(0);
				pegmanMarker.setLatLng(prevPegmanLatLng);
				map.panTo(prevPegmanLatLng);
			}
		}
	};

	var checkStreetviewWithChanged = function(hasStreetviewData) {
		if(hasStreetviewData) {
			if(!isStreetViewOn) {
				log.write("street view found with map mode");
				map.removeOverlay(svOverlay);
				svOverlay = null;
			}
			else
				alert("There is no Street View data around me but you can see blue lines on the map. Please move me over the lines. ");
		} 
		else {
			if(isStreetViewOn) {
				alert("There is no Street View data within the current map.");
				isNoStreetView = true;
				switchStreetView();
				isNoStreetView = false;
			}
		}
	}

	var checkStreetViewByClient = function(panoData) {
		if(panoData.code == 500) { // SERVER_ERROR
			alert('The server is not responding to queries street view data.');
			return;
		} else if(panoData.code == 600) { // NO_NEARBY_PANO
			log.write('checkStreetViewByClient > No street view data around here. ');
			getNearestStreetViewAgain();
		} else {
			log.write("checkStreetViewByClient > Got it");
			// reset the values of finding nearest panorama
			svIdx = 1;
			tryCount = 1;
			dbase = parseFloat(0.0005);

			showStreetViewByClient(panoData);
		}
	};

	var showStreetViewByClient = function(panoData) {
		var adjustYaw = computeAngle(curPegmanLatLng, panoData.location.latlng);

		stPanorama.setLocationAndPOV(panoData.location.latlng, {yaw:adjustYaw});
		pegmanMarker.setLatLng(panoData.location.latlng);
		map.panTo(panoData.location.latlng);
		curPegmanLatLng = panoData.location.latlng;
		getAddress(panoData.location.latlng);
		isFound = true;
    }

    // to calculate angle in order to make it towards a potential building location
    // it is used internally by google 
    var computeAngle = function(endLatLng, startLatLng) {
      var DEGREE_PER_RADIAN = 57.2957795;
      var RADIAN_PER_DEGREE = 0.017453;

      var dlat = endLatLng.lat() - startLatLng.lat();
      var dlng = endLatLng.lng() - startLatLng.lng();
      // We multiply dlng with cos(endLat), since the two points are very closeby,
      // so we assume their cos values are approximately equal.
      var yaw = Math.atan2(dlng * Math.cos(endLatLng.lat() * RADIAN_PER_DEGREE), dlat) * DEGREE_PER_RADIAN;
      return wrapAngle(yaw);
   	};

    var wrapAngle = function(angle) {
	    if (angle >= 360)
	      angle -= 360;
	    else if (angle < 0)
	     angle += 360;

	    return angle;
  	};

	var removeStreetView = function() {
		stPanorama.remove();
		map.removeOverlay(pegmanMarker);
		pegmanMarker = null;
		
		if(svOverlay != null)
			map.removeOverlay(svOverlay);
		
		curPegmanLatLng = prevPegmanLatLng = null;
		isFound = false;
	};
		
	var geocoder = new GClientGeocoder();
	
	var getAddress = function(latlng) {
		if (defs.spanishFlag == "T")
			geocoder.setBaseCountryCode("es");

		geocoder.getLocations(latlng, cbShowAddress);
	};
		
    var cbShowAddress = function(response) {
      if (!response || response.Status.code != 200) {
        //log.write("Geocode status code:" + response.Status.code);
      } else {
        log.write("Geocode: " + response.Placemark[0].address);
      }
	};		

	var svText = "Street View";			//English
	var svTextFr = "vistas a la calle"; //French
	var svTextEs = "vista de calle"; 	//Spanish
	var ignoreClick = false;

	var switchStreetView = function() {
		var svNode = $("#sv_toogle").get(0); //document.getElementById("sv_toogle");
	
		if(!ignoreClick) {
			if(svNode.checked) {
				svNode.checked = false;
			}	else {
				svNode.checked = true;
			}
			toggleView();
		} else {
			ignoreClick = false;
		}
	}

	var switchStreetView2 = function() {
		ignoreClick = true;
		toggleView();
	}

	var streetViewControl = function() {}

	streetViewControl.prototype = new GControl();

	streetViewControl.prototype.initialize = function() {
		var svContainer = document.createElement("div");
	
		// for checkbox
		var svCheck = document.createElement("input");
		svCheck.setAttribute("id", "sv_toogle");
		svCheck.setAttribute("type", "checkbox");
		svCheck.style.height="19"; // only IE
		svCheck.style.cssFloat="left";
		svCheck.style.styleFloat="left"; // for IE
		svCheck.style.position="relative";
		svCheck.style.top="-2px";
		svCheck.onclick=switchStreetView2;
	
		var svDiv = document.createElement("div");
		if (defs.impId==10 || defs.impId==15 || defs.mapId=="#mapDirection") { //Paginas411 or directions.jsp
			svDiv.style.display = "none";
		}
	
		this.setButtonStyle_(svDiv);
		svContainer.appendChild(svDiv);
		svDiv.appendChild(svCheck);
		
		if (defs.spanishFlag == "T") svText = svTextEs;
		
		svDiv.appendChild(document.createTextNode(svText));
	
		GEvent.addDomListener(svDiv, "click", switchStreetView);
		map.getContainer().appendChild(svContainer);
	
		return svContainer;
	}

	streetViewControl.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(defs.streetViewControlPos, 7));
	}

// Sets the proper CSS for the given button element.
	streetViewControl.prototype.setButtonStyle_ = function(button) {
		button.style.color = "#000000";
		button.style.backgroundColor = "white";
	    button.style.font = "small Arial";
		button.style.border = '1px solid #000000';	    
	    button.style.padding = "1px";
	    button.style.height="15px";
		button.style.width = "97px";
		button.style.cursor = "pointer";
	    button.style.fontSize = "12px";
	}	

	var checkStreetviewWithChanged2 = function(hasStreetviewData) {
		if(hasStreetviewData) {
			//log.write("checkStreetviewWithChanged2 : found street view data");
			map.addControl(streetViewControl.prototype); // street view button
			map.removeOverlay(svOverlay); // blue line which is street view
			svOverlay = null;
		} 
	}

	/*******************************
	 * public methods 
	 ******************************/
	var initialize = function(opts) {
		if(!opts.mapId) {
			alert("map instance should be defined.");
			return false;
		}

		// extens defaults options with parameter options
		defs = $.extend(defaults, opts);
		// add # to use in jQuery selector
		defs.mapId = "#"+defs.mapId;
		defs.streetId = "#"+defs.streetId;
		defs.borderId = "#"+defs.borderId;
		defs.streetContainerId = "#"+defs.streetContainerId;

		// initialize map
		if(GBrowserIsCompatible()) {
			map = new GMap2($(defs.mapId).get(0), defs.mapOptions);

			if(defs.onMapLoad != null)
				GEvent.addListener(map, "load", setTimeout(function() {defs.onMapLoad(map);}, 100));			

			map.setCenter(new GLatLng(defs.centerPoint[0], defs.centerPoint[1]), defs.initZoom, getMapType(defs.mapType));

			if (defs.largeMapControl != null) 
				map.addControl(largeMapControl);

			if (defs.webcamControlId == "" && !defs.isDetailPage) 
				map.addControl(new GMapTypeControl());

			map.addControl(new GScaleControl());

			// For InfoPaginas (IMP:10) has not Google Street View but MapJack Street Scene data
			if(defs.impId != 10) {
				svOverlay = new GStreetviewOverlay();
				GEvent.addListener(svOverlay, "changed", checkStreetviewWithChanged2);
				map.addOverlay(svOverlay);
				//checkStreetviewWithChanged2(true);
			}

			// add other custom controls 
			for(var i = 0; i < customControls.length; i++) {
				map.addControl(customControls[i]);
			}

			GEvent.addListener(map, 'zoomend', function() {
				var zoom = map.getZoom();

			  	if(zoom < 7) {
			  		incDelta = parseFloat(0.01);
			  	} else if(zoom >= 7  && zoom < 9) {
			  		incDelta = parseFloat(0.007);
			  	} else if(zoom >= 9 && zoom < 11) {
			  		incDelta = parseFloat(0.005);
			  	} else if(zoom >= 11 && zoom < 13) {
			  		incDelta = parseFloat(0.003);
			  	} else if(zoom >= 13 && zoom < 15) {
			  		incDelta = parseFloat(0.002);
			  	} else {
			  		incDelta = parseFloat(0.0009);
			  	}
			}); 
		} 
		else {
			alert("Sorry, the Google Maps API is not compatible with this browser");
		}

	    return map;
	};
		
	var isStreetView = function() {
		return isStreetViewOn;
		//return jQuery("#sv_toogle").get(0).checked; //$("#sv_toogle").get(0).checked;
	};

	var toggleView = function() {
		$(defs.streetId).toggleClass("hideDiv");

		if(!isStreetViewOn) {
			isStreetViewOn = true;
			
			$(defs.mapId).height(defs.mapMinHeight/2);
			log.write("defs.mapId : " + defs.mapId + ", defs.mapMinHeight/2 : " + defs.mapMinHeight/2);
			$(defs.streetId).height(defs.mapMinHeight/2);
			log.write("defs.streetId : " + defs.streetId + ", defs.mapMinHeight/2 : " + defs.mapMinHeight/2);
			
			map.removeControl(largeMapControl);
			map.addControl(smallMapControl);
			initStreetView();

			if(defs.resizeCallback != "") {
				defs.resizeCallback();
			}

			if (defs.webcamControlId != "") $("#"+defs.webcamControlId).hide();
			
		} 
		else {
			isStreetViewOn = false;
			
			$(defs.mapId).css("height", defs.mapMinHeight+"px");
			//$(defs.mapId).height(defs.mapMinHeight);
			map.removeControl(smallMapControl);
			map.addControl(largeMapControl);
			removeStreetView();

			if (defs.mapId=="#mapDetail") {		
				//map.checkResize();
				map.setCenter(new GLatLng(defs.centerPoint[0], defs.centerPoint[1]), defs.initZoom, getMapType(defs.mapType));
			}
			map.checkResize();
			if (defs.webcamControlId != "") $("#"+defs.webcamControlId).show();
		}
	};
	
	var getStreetViewInstance = function() {
		return stPanorama;
	};
	
	var getNearestStreetView = function(latlng) {
		stClient.getNearestPanorama(latlng, checkStreetViewByClient);
	};
		
	var addCustomControls = function(custControl) {
		customControls.push(custControl);
	};
	
	var setAnyMarker = function(marker) {
		anyMarker = marker;
	};
	
	// return public methods
	return {
		getMapInstance: getMapInstance,
		getStreetViewInstance: getStreetViewInstance,
		isStreetView: isStreetView,
		initializeMap: initialize,
		toggleView: toggleView,
		getStreetView: getNearestStreetView,
		addCustomControls: addCustomControls,
		setAnyMarker: setAnyMarker,
		log: log
		//movePegmanTo: movePegmanTo
	}
  }();

i$.iMapControls = function() {
		//function mapControl() {}
		//function moveRefreshControl() {}	
		//function webcamSelectTypeControl() {}
		//function recenterControl() {}
		//function waitControl() {}
			
		/******************************
		 * Private Variables
		 ******************************/
		var ignoreClick = false;		
		var hybridDetailDiv = null;
		var satelliteDetailDiv = null;
		var mapDetailDiv = null;
		
		var mapControlDefs = mapControlDefaults = {
			mapId: "",
			isMoreWebcamsOn: "T",
			typeText: "More Webcams",
			recenterText: "Recenter",
			moveRefreshText: "Move & Refresh",
			strLoading: "Loading",
			strMap: "Map",
			strSate: "Satellite",
			strHybrid: "Hybrid",			
			webcamSelectTypeControlOffsetX: 384, //Street button pos - 187
			moveRefreshControlOffsetX: 152, 
			mapControlOffsetX:7,
			waitControlOffsetX:500,
			recenterControlOffsetX:72,	
			hybridDetailControlOffsetX:7, //Detail page only			
			satelliteDetailControlOffsetX:72, //Detail page only
			mapDetailControlOffsetX:137,
			spanishFlag:"F"
		};
		
		var log = {
			write: function(message) {
				if(isDEBUG) {
					GLog.write(message);
				}
			}
		};	
		
		var changeType = function() {
			var moreWebcamNode = document.getElementById("more_camera");

			if(!ignoreClick) {
				if(moreWebcamNode.checked) { // more camera checkbox
					Webcam.setMoreCameras('F');
					moreWebcamNode.checked = false;
				}
				else {
					Webcam.setMoreCameras('T');
					moreWebcamNode.checked = true;
				}
			} else {
				ignoreClick = false;
			}
		};

		var changeTypeByCheckBox = function() {
			ignoreClick = true;
			var moreWebcamNode = document.getElementById("more_camera");

			if(moreWebcamNode.checked)  { // more camera checkbox
				Webcam.setMoreCameras('T');
			}
			else { 
				Webcam.setMoreCameras('F');
			}
		};

		var switchRefresh = function() {
			var mrCheck = document.getElementById("move_refresh");

			if(!ignoreClick) {
				if(iMap.isRefreshMapOn) {
					Webcam.setControlButtonNormal(mrCheck);
					iMap.isRefreshMapOn = false;
				}
				else {
					Webcam.setControlButtonBold(mrCheck);
					iMap.isRefreshMapOn = true;
				}
			} else {
				ignoreClick = false;
			}
		};

		var switchRefreshByCheckBox = function() {
			ignoreClick = true;
			var mrCheck = document.getElementById("move_refresh");

			if(iMap.isRefreshMapOn) {
				Webcam.setControlButtonNormal(mrCheck);
				iMap.isRefreshMapOn = false;
			}
			else {
				Webcam.setControlButtonBold(mrCheck);
				iMap.isRefreshMapOn = true;
			}
		};
		
		var initializeControls = function(opts) {
			// extens defaults options with parameter options
			mapControlDefs = $.extend(mapControlDefaults, opts);
			
			if (mapControlDefs.spanishFlag=="T") {
				mapControlDefs.strLoading = "Carga";
				mapControlDefs.typeText = "Más Webcams";
				mapControlDefs.recenterText = "Más reciente";
				mapControlDefs.moveRefreshText = "Mueva y Refresque";				
				mapControlDefs.strMap = "Mapa";
				mapControlDefs.strSate = "Satellite";
				mapControlDefs.strHybrid = "Hybrido"
			}
		};
		
		webcamSelectTypeControl = function(){};
		webcamSelectTypeControl.prototype = new GControl();	
		/*
		webcamSelectTypeControl.prototype.initialize = function(map) {
			var container = document.createElement("div");
			container.setAttribute("id", "webcamContainer");		

			// for checkbox
			var selectCheck = document.createElement("input");
			selectCheck.setAttribute("id", "more_camera");
			selectCheck.setAttribute("type", "checkbox");
			selectCheck.style.height="19";  // only IE
			selectCheck.style.cssFloat="left";
			selectCheck.style.styleFloat="left"; // for IE
			selectCheck.style.position="relative";
			selectCheck.style.top="-2px";
			selectCheck.onclick=changeTypeByCheckBox;

			// for label of More Webcams
			var selectTypeDiv = document.createElement("div");
					
			this.setButtonStyle_(selectTypeDiv);
			container.appendChild(selectTypeDiv);
			selectTypeDiv.appendChild(selectCheck);
			selectTypeDiv.appendChild(document.createTextNode(mapControlDefs.typeText));
			
			if (mapControlDefs.isMoreWebcamsOn == 'T') Webcam.setControlButtonBold(selectCheck);

			GEvent.addDomListener(selectTypeDiv, "click", changeType);
			map.getContainer().appendChild(container);

			return container;
		};

	  	webcamSelectTypeControl.prototype.getDefaultPosition = function() {
	  		var offsetX = mapControlDefs.webcamSelectTypeControlOffsetX;
	  		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(offsetX, 7));
	  	};

	  	// Sets the proper CSS for the given button element.
	  	webcamSelectTypeControl.prototype.setButtonStyle_ = function(button) {
		    button.style.color = "#000000";
		    button.style.backgroundColor = "white";
		    button.style.font = "small Arial";
		    button.style.border = "1px solid black";
		    button.style.padding = "1px";
		    button.style.cursor = "pointer";
		    button.style.fontSize = "12px";
		    button.style.height="15px";
		    button.style.width = "110px"; //130px
	  	};
		*/
	  	moveRefreshControl = function() {};
		moveRefreshControl.prototype = new GControl();
		moveRefreshControl.prototype.initialize = function(map) {
			var moveRefreshContainer = document.createElement("div");

			// for checkbox
			var mrCheck = document.createElement("input");
			mrCheck.setAttribute("id", "move_refresh");
			mrCheck.setAttribute("type", "checkbox");
			mrCheck.style.height="19"; // only IE
			mrCheck.style.cssFloat="left";
			mrCheck.style.styleFloat="left"; // for IE
			mrCheck.style.position="relative";
			mrCheck.style.top="-2px";
			mrCheck.onclick=switchRefreshByCheckBox;

			var moveRefreshDiv = document.createElement("div");

			this.setButtonStyle_(moveRefreshDiv);
			moveRefreshContainer.appendChild(moveRefreshDiv);
			moveRefreshDiv.appendChild(mrCheck);
			moveRefreshDiv.appendChild(document.createTextNode(mapControlDefs.moveRefreshText));
			mrCheck.checked = iMap.isRefreshMapOn;

			GEvent.addDomListener(moveRefreshDiv, "click", switchRefresh);
			map.getContainer().appendChild(moveRefreshContainer);

			return moveRefreshContainer;
		};

		moveRefreshControl.prototype.getDefaultPosition = function() {
			var offsetX = mapControlDefs.moveRefreshControlOffsetX;	   	
			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(offsetX, 7));
		};

		// Sets the proper CSS for the given button element.
		moveRefreshControl.prototype.setButtonStyle_ = function(button) {
		    button.style.color = "#000000";
			button.style.backgroundColor = "white";
			button.style.font = "small Arial";
			button.style.border = '1px solid #000000';	    
			button.style.padding = "1px";
			button.style.height= "15px";
			button.style.width= "125px"; //150px    
			button.style.cursor = "pointer";
			button.style.fontSize = "12px";
		};

		mapControl = function() {};
		mapControl.prototype = new GControl();
		mapControl.prototype.initialize = function(map) {
		  	var mapContainer = document.createElement("div");

			var mapButtonDiv = document.createElement("div");
			mapButtonDiv.setAttribute("mapType", "M");
			mapButtonDiv.setAttribute("mText", mapControlDefs.strMap);
			mapButtonDiv.setAttribute("sText", mapControlDefs.strSate);
			
			this.setButtonStyle_(mapButtonDiv);
			mapContainer.appendChild(mapButtonDiv);
			mapButtonDiv.appendChild(document.createTextNode(mapControlDefs.strSate));
			GEvent.addDomListener(mapButtonDiv, "click", function() { Webcam.changeMapType2(mapButtonDiv); });
			
			map.getContainer().appendChild(mapContainer);
			return mapContainer;
		};

		mapControl.prototype.getDefaultPosition = function() {
			var offsetX = mapControlDefs.mapControlOffsetX;
			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(offsetX, 7));
		};

		  // Sets the proper CSS for the given button element.
		mapControl.prototype.setButtonStyle_ = function(button) {
			button.style.color = "#000000";
			button.style.backgroundColor = "white";
		    button.style.font = "small Arial";
		    button.style.border = "1px solid black";
		    button.style.padding = "1px";
		    button.style.marginBottom = "2px";
		    button.style.textAlign = "center";
		    button.style.width = "60px";
		    button.style.cursor = "pointer";
		    button.style.fontSize = "12px";
			button.style.fontWeight = "normal";	    
		}; 
				
	  	waitControl = function() {};
		waitControl.prototype = new GControl();
		waitControl.prototype.initialize = function(map) {
			var waitContainer = document.createElement("div");
			var waitDiv = document.createElement("div");
			this.setButtonStyle_(waitDiv);
			waitContainer.appendChild(waitDiv);
			waitDiv.appendChild(document.createTextNode(mapControlDefs.strLoading));

			map.getContainer().appendChild(waitContainer);
			return waitContainer;
		};

		waitControl.prototype.getDefaultPosition = function() {
	   		var offsetX = mapControlDefs.waitControlOffsetX;
	   		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(offsetX, 7));
	  	};

		// Sets the proper CSS for the given button element.
	 	waitControl.prototype.setButtonStyle_ = function(button) {
			button.style.color = "#0000FF";
			button.style.fontWeight = "bold";
			button.style.backgroundColor = "white";
	    	button.style.font = "small Arial";
	    	button.style.border = "1px solid black";
	    	button.style.padding = "1px";
	    	button.style.marginBottom = "2px";
	    	button.style.textAlign = "center";
	    	button.style.width = "70px"; //130px
	    	button.style.fontSize = "13px";
	  	};
	  	
		recenterControl = function(){};
		recenterControl.prototype = new GControl();
		recenterControl.prototype.initialize = function(map) {
			var recenterContainer = document.createElement("div");
			var recenterDiv = document.createElement("div");
			this.setButtonStyle_(recenterDiv);
			recenterContainer.appendChild(recenterDiv);
			recenterDiv.appendChild(document.createTextNode(mapControlDefs.recenterText));
			GEvent.addDomListener(recenterDiv, "click", GoCenterMap);

			map.getContainer().appendChild(recenterContainer);
			return recenterContainer;
		};

		recenterControl.prototype.getDefaultPosition = function() {
			var offsetX = mapControlDefs.recenterControlOffsetX;

			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(offsetX, 7));
		};

		// Sets the proper CSS for the given button element.
		recenterControl.prototype.setButtonStyle_ = function(button) {
	 		button.style.color = "#000000";
			button.style.backgroundColor = "white";
		    button.style.font = "small Arial";
		    button.style.border = "1px solid black";
		    button.style.padding = "1px";
		    button.style.textAlign = "center";
		    button.style.width = "75px";
		    button.style.cursor = "pointer";
		    button.style.fontSize = "12px";
		};
		
		/*  Detail Page only */		
		hybridDetailControl = function() {};
		hybridDetailControl.prototype = new GControl();
		hybridDetailControl.prototype.initialize = function(map) {
		  	var mapContainer = document.createElement("div");
			hybridDetailDiv = document.createElement("div");
			hybridDetailDiv.setAttribute("mapType", 'hybrid');
			this.setButtonStyle_(hybridDetailDiv);
			mapContainer.appendChild(hybridDetailDiv);
			hybridDetailDiv.appendChild(document.createTextNode(mapControlDefs.strHybrid));
			GEvent.addDomListener(hybridDetailDiv, "click", function() { 
				map.setMapType(getMapType(hybridDetailDiv, satelliteDetailDiv, mapDetailDiv)); 
			});
			
			map.getContainer().appendChild(mapContainer);
			return mapContainer;
		};

		hybridDetailControl.prototype.getDefaultPosition = function() {
			var offsetX = mapControlDefs.hybridDetailControlOffsetX;
			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(offsetX, 7));
		};

		  // Sets the proper CSS for the given button element.
		hybridDetailControl.prototype.setButtonStyle_ = function(button) {
			button.style.color = "#000000";
			button.style.backgroundColor = "white";
		    button.style.font = "small Arial";
		    button.style.border = "1px solid black";
		    button.style.padding = "1px";
		    button.style.marginBottom = "2px";
		    button.style.textAlign = "center";
		    button.style.width = "60px";
		    button.style.cursor = "pointer";
		    button.style.fontSize = "12px";
			button.style.fontWeight = "normal";	    
		}; 
		
		satelliteDetailControl = function() {};
		satelliteDetailControl.prototype = new GControl();
		satelliteDetailControl.prototype.initialize = function(map) {
		  	var mapContainer = document.createElement("div");
			satelliteDetailDiv = document.createElement("div");
			satelliteDetailDiv.setAttribute("mapType", 'sat');
			this.setButtonStyle_(satelliteDetailDiv);
			mapContainer.appendChild(satelliteDetailDiv);
			satelliteDetailDiv.appendChild(document.createTextNode(mapControlDefs.strSate));
			GEvent.addDomListener(satelliteDetailDiv, "click", function() { 
				map.setMapType(getMapType(satelliteDetailDiv, hybridDetailDiv, mapDetailDiv));
			});
			
			map.getContainer().appendChild(mapContainer);
			return mapContainer;
		};

		satelliteDetailControl.prototype.getDefaultPosition = function() {
			var offsetX = mapControlDefs.satelliteDetailControlOffsetX;
			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(offsetX, 7));
		};

		  // Sets the proper CSS for the given button element.
		satelliteDetailControl.prototype.setButtonStyle_ = function(button) {
			button.style.color = "#000000";
			button.style.backgroundColor = "white";
		    button.style.font = "small Arial";
		    button.style.border = "1px solid black";
		    button.style.padding = "1px";
		    button.style.marginBottom = "2px";
		    button.style.textAlign = "center";
		    button.style.width = "60px";
		    button.style.cursor = "pointer";
		    button.style.fontSize = "12px";
			button.style.fontWeight = "normal";	    
		}; 
		
		mapDetailControl = function() {};
		mapDetailControl.prototype = new GControl();
		mapDetailControl.prototype.initialize = function(map) {
		  	var mapContainer = document.createElement("div");
			mapDetailDiv = document.createElement("div");
			mapDetailDiv.setAttribute("mapType", 'map');
			this.setButtonStyle_(mapDetailDiv);
			mapContainer.appendChild(mapDetailDiv);
			mapDetailDiv.appendChild(document.createTextNode(mapControlDefs.strMap));
			GEvent.addDomListener(mapDetailDiv, "click", function() { 
				map.setMapType(getMapType(mapDetailDiv, hybridDetailDiv, satelliteDetailDiv)); 
			});			
			map.getContainer().appendChild(mapContainer);
			return mapContainer;
		};

		mapDetailControl.prototype.getDefaultPosition = function() {
			var offsetX = mapControlDefs.mapDetailControlOffsetX;
			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(offsetX, 7));
		};

		  // Sets the proper CSS for the given button element.
		mapDetailControl.prototype.setButtonStyle_ = function(button) {
			button.style.color = "#000000";
			button.style.backgroundColor = "white";
		    button.style.font = "small Arial";
		    button.style.border = "1px solid black";
		    button.style.padding = "1px";
		    button.style.marginBottom = "2px";
		    button.style.textAlign = "center";
		    button.style.width = "60px";
		    button.style.cursor = "pointer";
		    button.style.fontSize = "12px";
			button.style.fontWeight = "bold";	    
		}; 

		var getMapType = function(mainDiv, otherDiv, theOtherDiv) {
			var mapType = mainDiv.getAttribute("mapType");
			
			mainDiv.style.fontWeight = 'bold';
			if (otherDiv != null) otherDiv.style.fontWeight = 'normal';			
			if (theOtherDiv != null) theOtherDiv.style.fontWeight = 'normal';
			
			switch(mapType) {
				case 'map':	// Normal Map
					mapType = G_NORMAL_MAP;
				break;
				case 'sat':	// Satallite Imagery
					mapType = G_SATELLITE_MAP;
				break;
				case 'hybrid':	//Hybrid Map
					mapType = G_HYBRID_MAP;
				break;
				default:
					mapType = G_NORMAL_MAP;
			};
			return mapType;
		}		

		// return public methods
		return {
			initializeControls:initializeControls,
			webcamSelectTypeControl:webcamSelectTypeControl,
			mapControl:mapControl,
			waitControl:waitControl,
			moveRefreshControl:moveRefreshControl,
			recenterControl:recenterControl,
			hybridDetailControl:hybridDetailControl,
			satelliteDetailControl:satelliteDetailControl,
			mapDetailControl:mapDetailControl,
			log: log
		}; 	
  }();  
  jQuery(document).unload(function(){ GUnload(); });  
})(jQuery);

