$().ready(function(){
	streetViewData = null;
	panorama = [];
	lodgingLocation = null;
	wrapDiv = $('<div class="loaderCon"><img class="preLoader" src="' + image('/img/global/preWhitePage.gif') + '"/></div>'); 
	
	streetView = function(latitude, longitude, _div, _noDataMsg, _callback, _pitch){
		//if (!lodgingLocation || lodgingLocation.lat() != latitude || lodgingLocation.lng() != longitude){
			lodgingLocation = new GLatLng(latitude, longitude);
			div = _div;
			callback = _callback;
			pitch = _pitch == null? -10: _pitch;
			$(div)
				.show()
				.addClass('loaderCon')
				.prepend('<img style="z-index: 4000" class="preLoader SVLoad" src="' + image('/img/global/preWhitePage.gif') + '"/>');
			
			noDataMsg = _noDataMsg;
			
			panoClient = new GStreetviewClient(); 
			panoClient.getNearestPanorama(lodgingLocation, showPanoData);
		//}
	}
	
	showPanoData = function(panoData){
		
		streetViewData = {
			has_street_view: false,
			distance: null,
			latitude: null,
			longitude: null,
			yaw: null,
			pitch: null
		};
		
		if (panoData.code == 200) {
			panoLatLng = panoData.location.latlng;
			POV = __calculatePOV(panoLatLng, lodgingLocation);
			
			if (panorama == undefined || 
				panorama[$(div).attr('id')] == undefined || 
				panorama[$(div).attr('id')] == null){
				panorama[$(div).attr('id')] = new GStreetviewPanorama(div);
				GEvent.addListener(panorama[$(div).attr('id')], "error", handleErrors);
			}
			panorama[$(div).attr('id')].setLocationAndPOV(panoLatLng, POV);
		}
		else {
			if (panorama != undefined &&
				panorama[$(div).attr('id')] != undefined &&
				panorama[$(div).attr('id')] != null)
				panorama[$(div).attr('id')].remove();
				
			if (noDataMsg)
				$(div).html(noDataMsg);
			else $(div).hide(); 
		}
		$('.SVLoad').remove();
		if (callback) callback(panoData.code == 200)
	}
	
	__calculatePOV = function(startLatLng, endLatLng) {
		var DEGREE_PER_RADIAN = 57.2957795;
		var RADIAN_PER_DEGREE = 0.017453;
		
		if (endLatLng==null){
			endLatLng=startLatLng;
		}
		
		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;
      	
      	if (yaw >= 360) yaw -= 360;
		else if (yaw < 0) yaw += 360;
			
		return {yaw: yaw, pitch: pitch!=undefined? pitch:-10};
	}   
	
	handleErrors = function(){
		panorama.remove();
	}
});