var WebcamObj = 
{
	hIDs: [],	 // hotspot webcam
	nhIDs: [], 	// non hotspot webcam
	hMarkers:[],	// hostpot markers
	nhMarkers:[],	// non hotspot markers
	
	contains: function(wcId) {
		if(this.hIDs.indexOf(wcId) >= 0)
			return true;
		else if(this.nhIDs.indexOf(wcId) >= 0)
			return true;

		return false;
	},

	clearNonHotspot: function()
	{
		for(var i = 0; i < WebcamObj.nhMarkers.length; i++)
			Webcam.map.DeleteShape(WebcamObj.nhMarkers[i]);
	
		this.nhIDs = [];
		this.nhMarkers = [];
		this.nhIDs.length = 0;
		this.nhMarkers.length = 0;
	},
	
	clearAll: function() {
		for(var i = 0; i < WebcamObj.hMarkers.length; i++)
			Webcam.map.DeleteShape(WebcamObj.hMarkers[i]);
	
		this.hIDs = [];
		this.hMarkers = [];
		this.hIDs.length = 0;
		this.hMarkers.length = 0;
		
		this.clearNonHotspot();
	}
};

var Webcam = 
{
	map : null,
	maxWidth: 400,
	maxHeight: 250,
	dtMaxWidth: 210,
	dtMaxHeight: 130,
	spanishFlag: "F",
	detailFlag: "F",
	isThereWebcams: false,
	isMoreWebcamsOn: true,
	isTypeControlRemoved: false, // to prevent more webcam button from being redrawn
	zoomThread: 10,

	get : function(map, spanishFlag, detailFlag, getWebcamFlag_)
	{
		this.map = map;
		this.spanishFlag = (spanishFlag != null && '1') ? 'T' : 'F';
		this.detailFlag = detailFlag||this.detailFlag;
		var getWebcamFlag = getWebcamFlag_||true;

		if(getWebcamFlag)
			this.getWebcamMarkers();
	},

	setMoreCameras: function(onOff) {
		var dummyDate = new Date();
		var url = '/webcam.do?op=setMoreCameras&userAction='+onOff+'&t='+dummyDate.getTime();

		jQuery.ajax({
			   type: "GET",
			   url: '/webcam.do',
			   data: 'op=setMoreCameras&userAction='+onOff+'&t='+dummyDate.getTime(),
			   //dataType: "html",
			   success: function() {
					if(onOff == 'T') {
						Webcam.isMoreWebcamsOn = true;
					 	Webcam.getWebcamMarkers();
					}
					else {
					 	Webcam.isMoreWebcamsOn = false;
					 	WebcamObj.clearNonHotspot();
					}		
			   },
			   error: function(xhr, textStatus, errorThrown) {
			   	
			   }
			 });
		
		
	},

	setControlButtonBold: function(button) {
		//document.getElementById("more_camera").checked = true;
		button.checked = true;
	},

	setControlButtonNormal: function(button) {
		//document.getElementById("more_camera").checked = false;
		button.checked = false;
	},	

	setCameraType: function(type, action) {
		var dummyDate = new Date();
		var url = '/webcam.do?op=setCamType&sourceType='+type+'&userAction='+action+'&t='+dummyDate.getTime();

		var request = GXmlHttp.create();

		request.open("GET", url, true);

		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				 // do nothing
			}
		}

		request.send(null);
	},

	changeMapType : function(mapType, myDiv, otherDiv1, otherDiv2)
	{
		// change the style for buttons of map type
		myDiv.style.fontWeight = 'bold';
		otherDiv1.style.fontWeight = 'normal';
		
		if(otherDiv2 != null)  // because of Earth control
			otherDiv2.style.fontWeight = 'normal';

		if(mapType == 'M')
			this.map.setMapType(G_NORMAL_MAP);
		else if(mapType == 'E')
			this.map.setMapType(G_SATELLITE_3D_MAP);
		else
			this.map.setMapType(G_HYBRID_MAP);
	},

	changeMapType2 : function(divNode)
	{
		var mapType;

		if(divNode.getAttribute("mapType") == 'M') {
			divNode.setAttribute("mapType", "S"); // Satellite
			divNode.firstChild.nodeValue = divNode.getAttribute("mText");
			this.map.setMapType(G_HYBRID_MAP);
		} else {
			divNode.setAttribute("mapType", "M"); // Map
			this.map.setMapType(G_NORMAL_MAP);
			divNode.firstChild.nodeValue = divNode.getAttribute("sText");
		}
	},

	getWebcamMarkers : function(beView) {
		//alert('webcams...');
		var zoom = this.map.GetZoomLevel();

		// beView : Birds eye view map style 
		var view = beView||map.GetMapView();		
		
		var neLat = view.TopLeftLatLong.Latitude;
		var neLng = view.BottomRightLatLong.Longitude;
		var swLat = view.BottomRightLatLong.Latitude;
		var swLng = view.TopLeftLatLong.Longitude;

		var latDelta = (neLat - swLat) * 0.02;
		var lngDelta = (neLng - swLng) * 0.02;

		neLat = neLat - latDelta;
		neLng = neLng - lngDelta;
		swLat = swLat + latDelta;
		swLng = swLng + lngDelta;

		/*** if this zoom level is changed you should change it from server as well. ***/		
		if(zoom < this.zoomThread)
			WebcamObj.clearNonHotspot();

		//if(Webcam.detailFlag != 'T')
			//Webcam.map.addControl(waitControl.prototype); 
		
		jQuery.ajax({
			   type: "GET",
			   url: "/webcam.do",
			   data: 'op=get&northEastLat=' + neLat + '&southWestLat=' + swLat +'&northEastLng=' + neLng + '&southWestLng=' + swLng +
					'&zoom='+zoom+'&t='+(new Date()).getTime(),
			   dataType: "xml",
			   success: function(xml) {
					Webcam.isThereWebcams = false;
					Webcam.processMarkers(xml);

					if(Webcam.detailFlag != 'T') {
						/*
						// handle the camera types control button to hide or show
						if(!Webcam.isThereWebcams) {
							if(!Webcam.isTypeControlRemoved) {
								Webcam.map.removeControl(webcamSelectTypeControl.prototype);
								Webcam.isTypeControlRemoved = true;
							}
						}
						else if(Webcam.isTypeControlRemoved && !mjStreetView.isStreetView) {
							Webcam.map.addControl(webcamSelectTypeControl.prototype);

							if(Webcam.isMoreWebcamsOn) {
								Webcam.setControlButtonBold(document.getElementById("more_camera"));
							}
							else {
								Webcam.setControlButtonNormal(document.getElementById("more_camera"));
							}
							Webcam.isTypeControlRemoved = false;
						}
					*/
					}					
			   },
			   error: function(xhr, textStatus, errorThrown) {
			   	
			   }
			 });
	},


	callLink: function(url) {
		window.location.href = url;
	},
	
	processMarkers: function(xmlDoc) {	
		var $ = window.jQuery;
		var html = "";
		var marker = "";
		var latLng = "";
		var contentStr = "";
		var thumbSizeW = "100";
		var thumbSizeH = "70";
		var dispHomeUrl = "";
		var wcImgHtml  = "";
		var wc1ImgHtml = "";
		var wc2ImgHtml = "";
		
		var zoom = this.map.GetZoomLevel();

		//var mks = xmlDoc.documentElement.getElementsByTagName("marker");

		$(xmlDoc).find('marker').each(function(idx) {
			var wcId = $(this).attr("wcId");
			var lat = parseFloat($(this).attr("lat"));
			var lng = parseFloat($(this).attr("lng"));
			var cityName = $(this).attr("ctNm");
			var provState = $(this).attr("pvSt");
			var srcUrl = $(this).attr("srcURL");
			var src1Url = $(this).attr("src1URL");
			var src2Url = $(this).attr("src2URL");
			var srcType = $(this).attr("srcType");
			var sizeW = parseInt($(this).attr("szW"));
			var sizeH = parseInt($(this).attr("szH"));
			var homeUrl = $(this).attr("hmURL");
			var liveFeedFlag = $(this).attr("liveFF");
			var liveFeedTag = $(this).attr("liveFT");
			var hotspot = $(this).attr("hot");
			var wcName = (Webcam.spanishFlag == "T" && $(this).attr("wcNmFR") != "") ? $(this).attr("wcNmFR") : $(this).attr("wcNm");
			var wc1Name = (Webcam.spanishFlag == "T" && $(this).attr("wc1NmFR") != "") ? $(this).attr("wc1NmFR") : $(this).attr("wc1Nm");
			var wc2Name = (Webcam.spanishFlag == "T" && $(this).attr("wc2NmFR") != "") ? $(this).attr("wc2NmFR") : $(this).attr("wc2Nm");
			var srcDesc = (Webcam.spanishFlag == "F") ? $(this).attr("srcDes") : $(this).attr("srcDesFR");
			var srcName = (Webcam.spanishFlag == "F") ? $(this).attr("srcNm") : $(this).attr("srcNmFR");
			var wcLabel = (Webcam.spanishFlag == "F") ? $(this).attr("wcLabel") : $(this).attr("wcLabelFR");
			wcLabel = wcLabel == "" ? wcName : wcLabel;

			var isSingleTrafficImage;// = ((srcType == 1 || srcType == 10 || srcType == 11) && src1Url == "") ? true : false;
			var isSingleImage = true;
			
			// check if it is single image or not
			if((srcType == 1 || srcType == 10 || srcType == 11) && src1Url == "") {
				isSingleTrafficImage = true;
				isSingleImage = true;
			} else if((srcType == 1 || srcType == 10 || srcType == 11) && src1Url != "") {
				isSingleTrafficImage = false;
				isSingleImage = false;
			} else {
				isSingleImage = true;
			}

			// if users want to see bigger image, it can use original size
			sizeW = sizeW > Webcam.maxWidth ? Webcam.maxWidth : sizeW;
			sizeH = sizeH > Webcam.maxHeight ? Webcam.maxHeight : sizeH;

			if(Webcam.detailFlag == 'T') {
				sizeW = sizeW > Webcam.dtMaxWidth ? Webcam.dtMaxWidth : sizeW;
				sizeH = sizeH > Webcam.dtMaxHeight ? Webcam.dtMaxHeight : sizeH;
				thumbSizeW = "60";
				thumbSizeH = "33";
			}

			if(liveFeedFlag == 'N')
				contentStr = '<img src="' + srcUrl + '" width="' + sizeW + '" height="' + sizeH + '" title="' + srcDesc + '" border="0" />';
			else
				contentStr = liveFeedTag; // flash data such as 360, live streaming object and so on

			dispHomeUrl = homeUrl;

			if(Webcam.detailFlag != 'T' && homeUrl.length > 50) // if the length of url, cut it up to 70 and then append '...'
				dispHomeUrl = homeUrl.substring(0, 40) + "...";
			else if(Webcam.detailFlag == 'T' && homeUrl.length > 30) // the detail page's map is smaller
				dispHomeUrl = homeUrl.substring(0, 30) + "...";			
			
			if(!(srcType == 1 || srcType == 10 || srcType == 11) || isSingleTrafficImage) {
				html = '<div style="margin-right:11px;margin-left:5px;font-size:10px;">	<table border="0" cellpadding="0" cellspacing="0">' +
					   '		<tr style="background-color:#FFCC00;"> 	<td align="left" style="font-weight:bold;color:#000000;" ><div>' +wcId + ": "+ wcName + '</div>' +
					   '				<div style="font-weight:bold;color:#000000;">' + cityName + ', &nbsp;' + provState + '</div>' + 
					   '			</td>	</tr>	<tr>	<td align="center"><div style="border:1px solid #FFCC00;">' + contentStr + '</div></td> </tr> </table>' +
					   '	<div align="right" >'+'<a href="javascript:void(0)" onClick="window.open(\'' + homeUrl +'\');"  title="' + srcName + '" >' + dispHomeUrl + '</a></div></p> </div>';
			}
			else {
				wcImgHtml  = '<img class="clickImg" id="webcam0" alt="'+wcLabel+'" src="' + srcUrl + '" width="' +thumbSizeW+'" height="'+thumbSizeH+'" style="display:block;border:1px solid #999999;"/>';
				wc1ImgHtml = '<img class="clickImg" id="webcam1" alt="'+wc1Name+'" src="' + src1Url + '" width="'+thumbSizeW+'" height="'+thumbSizeH+'" style="display:block;border:1px solid #999999;"/>';
				wc2ImgHtml = '<img class="clickImg" id="webcam2" alt="'+wc2Name+'" src="' + src2Url + '" width="'+thumbSizeW+'" height="'+thumbSizeH+'" style="display:block;border:1px solid #999999;"/>';
/*
				if(srcType == 10 || srcType == 1) {  // clickable
					wcImgHtml  = "<a href='javascript:switchMainCam(\""+srcUrl+"\", "+wcId+",\"0\")'>" + wcImgHtml + "</a>";
					wc1ImgHtml = "<a href='javascript:switchMainCam(\""+src1Url+"\","+wcId+",\"1\")'>" + wc1ImgHtml + "</a>";
					wc2ImgHtml = "<a href='javascript:switchMainCam(\""+src2Url+"\","+wcId+",\"2\")'>" + wc2ImgHtml + "</a>";							
				}
*/
				
				if(src2Url == "")
					wc2ImgHtml = '<div style="width:100;height:70;"> &nbsp; </div>'; // empty image

				html = '<div style="margin-right:11px;margin-left:5px;font-size:10px;">	<table border="0" cellpadding="0" >' +
							 '		<tr style="background-color:#FFCC00;"> <td colspan="2" align="left" style="font-weight:bold;color:#000000;" ><div>'+wcId + ": " + wcName + '</div>' +
							 '				<div style="font-weight:bold;color:#000000;" >' + cityName + ', ' + provState + '</div>	</td>	</tr>	<tr> <td valign="top">'+
							 '				<div id="mainCamTitle" style="color:#000000;text-align:center;">'+wcLabel+'</div>'+
							 '				<div id="mainCam" style="border:1px solid #999999;">'+contentStr+'</div> </td>' +
							 '			<td width="100px" valign="top">' +
							 '        <div style="text-align:left;"><span id="'+wcId+'-0" style="color:#000000;">'+wcLabel+'</span><br/>' + wcImgHtml + '</div>' +
							 '				<div style="text-align:left;"><span id="'+wcId+'-1" style="color:#000000;">'+wc1Name+'</span><br/>' + wc1ImgHtml + '</div>' +
							 '				<div style="text-align:left;"><span id="'+wcId+'-2" style="color:#000000;">'+wc2Name+'</span><br/>' + wc2ImgHtml + '</div>' +
							 '		</td></tr></table><div align="right" ><a href="javascript:void(0)" onClick="window.open(\'' + homeUrl +'\');" title="' + srcName + '" >' + dispHomeUrl + '</a></div></p></div>';				
			}
			// wcId == 0 means there is more than one non-hotspot within current viewport. 
			if(zoom >= Webcam.zoomThread && wcId == 0) {
				Webcam.isThereWebcams = true;
			}
			// in Birdseye view, zoom level is very high so even if wcId is 0, this block could be executed
			else if(wcId != 0 && !WebcamObj.contains(wcId)) {
				marker = Webcam.createMarker(lat,lng, html, wcId, srcDesc, srcType, isSingleImage);
				
				if(hotspot == 1) {
					WebcamObj.hIDs[WebcamObj.hIDs.length++] = wcId;
					WebcamObj.hMarkers[WebcamObj.hMarkers.length++] = marker;
				}
				else if(hotspot == 0) {
					WebcamObj.nhIDs[WebcamObj.nhIDs.length++] = wcId;
					WebcamObj.nhMarkers[WebcamObj.nhMarkers.length++] = marker;
				}
			}			
		});
	},

	createMarker: function(lat,lng, html, wcId, desc, srcType, isSingleImage) {
	 	var marker;
	 	var camsHTML;
	 	var camsIMG;
	 	var ext = jQuery.browser.version=='6.0' && jQuery.browser.msie ? ".gif" : ".png";
	 	
		if(srcType == 1 || srcType == 10 || srcType == 11) {
		 	camsHTML = "<div style='position:relative;top:0px;left:0px;'><img src='/images/mapicon/traffic_camera_off"+ext+"' /></div>";
		 	camsIMG = "/images/mapicon/traffic_camera_off"+ext; 
		 	camType = 'TRF';
		}
		else if(srcType == 6) {// for now it is not used
		 	camsHTML = "<div style='position:relative;top:0px;left:0px;'><img src='http://cpgimg.com/images/mapicon/web_cam_yellow_outline.png' /></div>";
		 	camsIMG = "/images/mapicon/web_cam_yellow_outline.png";
		 	camType = '360';
		}
		else {
			camsHTML = "<div style='position:relative;top:0px;left:0px;'><img src='/images/mapicon/web_camera_off"+ext+"' /></div>";
			camsIMG =  "/images/mapicon/web_camera_off"+ext;
			camType = 'WEB';
		}

		marker = MapLIB.addPushpin({
					lat: lat,
					lng: lng,
					beakOffsetX:0,
					beakOffsetY:10,					
					pinHTML: camsHTML,
			 		pinIMG: camsIMG,
			 		viewPoint: '',
			 		offsetX:0,
			 		offsetY:0,
			 		id: wcId,
			 		type:(isSingleImage ? "WEBCAMS-S" : "WEBCAMS-M"),
			 		zIndex: 999, // to be behind of pins which has 1000 of z-index
			 		title: '',
			 		desc: html});
/*
		GEvent.addListener(marker, "click", function() {
			if(!mjStreetView.isStreetView) {
				var from;
	
				marker.openInfoWindowHtml(html);
	
				if(Webcam.detailFlag == 'T') from = 'DET';   // from detail pages 
				else if(Webcam.detailFlag == 'M') from = 'MAP';  // from map search
				else from = 'LST';  // from map listing
				
				Webcam.log(wcId, from);
			}
		});
*/
		return marker;
	},

	log: function(wcId, from) {
		var saveURL = '/webcam.do?op=log&webcamId='+wcId+'&from='+from;
		var request = GXmlHttp.create();

		request.open("GET", saveURL, true);

		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				 // do nothing
			}
		}

		request.send(null);
	},

	// show cameras on the map with saved ones before
	show: function(spanishFlag) {
		this.get(this.map, spanishFlag);
	},

	destroy: function() {
		//GUnload();

		delete WebcamObj;
		delete iMap;
	}
};

function switchMainCam(srcUrl, wcId, idx)
{
	document.getElementById("mainCam").firstChild.setAttribute("src", srcUrl);
	document.getElementById("mainCamTitle").innerHTML = document.getElementById(wcId+"-"+idx).innerHTML;
}

// it doesn't seemd to work with IE
window.onUnload = Webcam.destroy();