var _downX, _downY;

var Handlers = {
	zoomEndHandler: function() {
		MapLIB.removeInfoBox();

		for(var i = 19; i >= 1; i--) {
			if(i == MapLIB.getMapInstance().GetZoomLevel())
				jQuery('#zoomScale' + i).get(0).src = "/images/zoomstep_on.gif";
			else
				jQuery('#zoomScale' + i).get(0).src = "/images/zoomstep_off.gif";
		}	
		
		Webcam.getWebcamMarkers();
	},

	mouseDownHandler: function(e) {
		// if infobox is open, close it
		MapLIB.removeInfoBox();

		_downX = e.mapX;
		_downY = e.mapY;

		MapLIB.vars.isMouseDown = true;
	    MapLIB.vars.isCustomStartPan = false;
	},

	mouseUpHandler: function(e) {
		if(MapLIB.vars.isMouseDown && MapLIB.vars.isCustomStartPan) {
			Webcam.getWebcamMarkers();

			MapLIB.vars.isMouseDown = false;
		    MapLIB.vars.isClickedAvatarBeam = false;
		}
	},	
	
	mouseMoveHandler: function(e) {
		// it plays role as a startpan event
	    if(MapLIB.vars.isMouseDown && !MapLIB.vars.isCustomStartPan)
	        MapLIB.vars.isCustomStartPan = true; // only once per pan.
	},
	
	mouseClickHandler: function(e) {
		var map = CPTraffic.map;

		// as map is moved by dragging map, click event is fired.
		// So in order to identify click and dragging, keep point as of mousedown event.
		if(e.elementID != null && _downX == e.mapX && _downY == e.mapY) {
			var shape = map.GetShapeByID(e.elementID);

			if(!CPTraffic.isGetDirectionMode) {
				Webcam.addRoute(shape._can_id, shape._can_params.wcName, shape._can_params.html, shape);
			} else if(typeof shape._can_params !== 'undefined') {
				var idHtml = jQuery(shape._can_params.html).find("#maincam_container").css("background-color","#FFFFFF").css("border", "none").end()
										.find("#maincam_name").css("background-color", "#FFCC00").css("margin-top","10px").css("margin-bottom", "5px").end() 
										.find("#camera_thumb_view").css("border", "none").css("height", "").end()
										.find("#maincam_sub_name").attr("id", "maincam_sub_name_pop").end()
										.find("#maincam").css("margin-bottom", "0").attr("id", "maincam_pop").end()
										.find("#camera_thumb_view").css("background-color", "#FFFFFF").end()
										.find("#other_views").css("display", "none").end()
										.find("#thumb1_img").attr("id","thumb1_img_pop").end()
										.find("#thumb2_img").attr("id","thumb2_img_pop").end()
										.find("#thumb3_img").attr("id","thumb3_img_pop").end()
										.find("a[href^=javascript:]").attr("href", function(idx) {
											return "javascript:CPTraffic.switchCam("+(idx+1)+",true)";
										}).end().html();
				shape.SetDescription(idHtml);
				MapLIB.showInfoBox(shape, e);
			}
			
		}
	},

	mouseOverHandler: function(e) {
		var map = CPTraffic.map;
		
		if (document.getElementById("maincam")!=null) {
			jQuery('#roundBC').css('display','none'); //Don't show the round bottom part.
		}
		
		if(e.elementID != null) {
			var shape = map.GetShapeByID(e.elementID);
			
			// mouse might keep hovering until users move out mouse 
			if(Webcam.hoveredMarker != "" && Webcam.hoveredMarker.GetID() == shape.GetID()) {
				return true;
			}
			else if(shape.GetTitle() != "") {
				// hover over direction icon such as start and end icon
				return true;
			}
			else {
				// show camera on left side view
				document.getElementById("camera_view").innerHTML = shape._can_params.html;

				shape.switchImage('H');

				// make previous highlighted marker normal
				if(Webcam.hoveredMarker != "" && Webcam.hoveredMarker != shape) {
					Webcam.hoveredMarker.switchImage('N');
				}
				// save new highlighted marker to buffer
				Webcam.hoveredMarker = shape;
			}
		
			return true;
		}
	}	
}

jQuery(document).ready(function($) {
	$.fn.sort = function() {
        return this.pushStack( jQuery.makeArray( [].sort.apply( this, arguments ) ) );
	};

	function checkSpecialCh(str) {
		var spReg = new RegExp(/\@|\||\%|\^|\&|\$|\'|\"/);
		var spCh = str.match(spReg);
		
		if(spCh && spCh.length > 0) {
			var msgText;
			if(CPTraffic.frenchFlag == 'F')
				msgText = 'Special character ' + spCh[0] + ' is not allowed for the name.';
			else
				msgText = 'Le caractère spécial ' + spCh[0] +' ne peut pas s’utiliser dans le nom.';
			alert(msgText);
			return true;
		}
		else
			return false;
	};

	function checkPromptText(promptText) {
    	if($('#'+promptText).val().length == 0) {
    		var msgText;
    		if(CPTraffic.frenchFlag == 'F')
    			msgText = 'Please enter a route name.';
    		else
    			msgText = 'Entrer le nom de l’itinéraire';
    		alert(msgText);
    		return false;
    	
    	} else if ($('#'+promptText).val().length > 25) {
    		var msgText;
    		if(CPTraffic.frenchFlag == 'F')
    			msgText = 'You entered '+$('#'+promptText).val().length+' characters.\nPlease enter a route name in maxium of 25 characters.';
    		else
    			msgText = 'Vous êtes entré '+$('#'+promptText).val().length+' caractères.\nEntrer le nom de l’itinéraire dans le maxium de 25 caractères.';
    		alert(msgText);
    		return false;
    		
    	} else if(checkSpecialCh($('#'+promptText).val())) {
    		return false;
    	}

    	if(CPCookie.checkSameRoute($('#'+promptText).val()))
    		return false;

    	return true;
	};

    // save cookie
    $('#cookie_prompt_OK').click(function() {
    	if(!checkPromptText('cookie_prompt_name'))
    		return false;
    	
    	CPTraffic.saveRoute(true);
	}); 
    $('#cookie_prompt_name').keydown(function(e) {
    	if(e.keyCode == 13) {
        	if(!checkPromptText('cookie_prompt_name'))
        		return false;
        	
    		CPTraffic.saveRoute(true);
    		$(this).val('');
    		return false;
  		}
  		else if(e.keyCode == 27) {
  			$.unblockUI({fadeOut:10});
  			return false;
  		}
    });
    // don't use keyup
    $('#new_prompt_name').keydown(function(e) {
    	if(e.keyCode == 13) {
        	if($('#new_prompt_list_saveas').is(':checked')) {
            	if(!checkPromptText('new_prompt_name'))
            		return false;
            	
	        	CPTraffic.saveRoute(true);
	    		$(this).val('');
	    		return false;
        	}
  		}
  		else if(e.keyCode == 27) {
  			$.unblockUI({fadeOut:10});
  			return false;
  		}
    });
    
    $('#textMe').click(function(){
    	Webcam.getListOfRoutes();
    });
    
    $('#newTraffic').click(function () {
    	if(CPTraffic.isFromSavedList && CPTraffic.isChanged) {
    		jQuery('#new_prompt_msg').css('display','block');
			CPTraffic.promptNew();
			//CPTraffic.promptNewList(110);
		}
		else if(!CPTraffic.isChanged) {
			CPTraffic.promptConfirm();
		}
		else {
			jQuery('#new_prompt_msg').css('display','none');
			CPTraffic.promptNew();
			//CPTraffic.promptRouteName();
		}

    	return false;
    });
    
    $('#saveTraffic')
    .click(function() {
    	if(CPTraffic.isFromSavedList && !CPTraffic.isChanged) {
    		return false; // nothing changes
    	}
    	else if(CPTraffic.isFromSavedList) {
    		//$('#new_prompt_new').css('display','none');
    		CPTraffic.promptNewList(110);
    	} else {
    		//CPTraffic.promptNew();
    		CPTraffic.promptRouteName();
    	}
    });

    $('.tr_unlink')
    .mouseover(function() {
    	if($(this).is(':disabled')) {
    		$(this).css({'cursor':'default'});
    	} else {
    		$(this).css({'cursor':'pointer', 'textDecoration':'underline'});
    	}
    })
    .mouseout(function(){
    	$(this).css({'textDecoration':'none'});
    });

    $('#new_confirm_prompt_yes').click(function() {
    	Webcam.deleteAllRoute();
    	$.unblockUI({fadeOut:10});    	
    });
    $('#new_prompt_yes').click(function() {
    	if(CPTraffic.isFromSavedList && CPTraffic.isChanged)
    		CPTraffic.promptNewList(110);
    	else
    		CPTraffic.promptRouteName();
    	//CPTraffic.promptNewList(110);
    });
    $('#delete_prompt_yes').click(function() {
    	CPCookie.deleteRouteOK();
    	$.unblockUI({fadeOut:10});
    	return false;
    });
    $('.new_prompt_no').click(function() {
    	Webcam.deleteAllRoute();
    	$.unblockUI({fadeOut:10});
    });
    $('.new_prompt_cancel').click(function() {
    	$('.prompt_name_txt').val('');
    	$('.over_route_msg').css('visibility','hidden');
    	$.unblockUI({fadeOut:10}); 
    	return false; 
    });

    $('#new_prompt_list_ok').click(function() {
    	if($('#new_prompt_list_save').is(':checked')) {	// overwrite
    		CPTraffic.saveRoute(false);
    	}
    	else if($('#new_prompt_list_saveas').is(':checked')) {	// create a new route 
        	if(!checkPromptText('new_prompt_name'))
        		return false;
        	
    		CPTraffic.saveRoute(true);
    		$('#new_prompt_name').val('');
    	}
    	else if($('#new_prompt_list_disregard').is(':checked')) {
        	Webcam.deleteAllRoute();
    		$.unblockUI({fadeOut:10}); 
    		return false;
    	}
    });

	$('#new_prompt_list_save').click(function() {
		$('#new_prompt_name').get(0).disabled = true;
		$('.over_route_msg').css('visibility','hidden');
	});
    $('#new_prompt_list_saveas').click(function() {
    	$('#new_prompt_name').get(0).disabled = false;
		if(CPCookie.curMyRoute.length >= CPCookie.maxRoutes) {
			$('.over_route_msg').css('visibility','visible');
			$('.first_route').html(CPCookie.curMyRoute[CPCookie.maxRoutes-1].split("|")[0])
		}
		else {
			$('.over_route_msg').css('visibility','hidden');
		}
    });
/*
    $('#myrouteTitle')
     .mouseover(function() { $(this).css('cursor','pointer')})
     .click(function(e) {
    	var cookieHtml = CPCookie.loadCookies();
    	var html = '<table border="0"><tr><td align="right" height="5px"><img id="detailViewExit" src="/images/exit.gif" border="0" /></td></tr><tr><td>'+cookieHtml+'</td></tr></table>';

 		$('<div id="myroutePopup"></div>')
		.css({position:'absolute', 
			  display:'block',
			  'font-size':'11px',
		      top:$('#cookieHistory').offset().top,
		      left:$('#cookieHistory').offset().left,
		      padding:'2px',
		      border:'1px solid #CACACA',
		      backgroundColor:'#FFFFFF'
		      })
		.html(html)
		.appendTo('body');
		//.end()
		//.dropShadow({ color: "#555", left: 5, top: 5, opacity: 0.3 });

		$('#detailViewExit')
		 .mouseover(function(){
			$(this).css('cursor','pointer');
		 })
		 .click(function(){
			$('#myroutePopup').remove();
		}); 		
     });
*/    
	// -----------------------------------------------------
	// tab menus
	// click traffic link
    $("#trafficTabs a:first").click(function(){
    	// for the first time, jQuery returns 'undefined' I don't know why
		document.getElementById("trafficTabs").getElementsByTagName("li")[0].setAttribute("id", "current");
		document.getElementById("trafficTabs").getElementsByTagName("li")[1].setAttribute("id", "");    

    	$("#trafficContainer").css("display", "block");
    	$("#directionContainer").css("display", "none");
    	jQuery('#roundBC').css('display','none');
    	//CPTraffic.map.closeInfoWindow();
    	MapLIB.removeInfoBox();
    	CPTraffic.isGetDirectionMode = false;
    });

	// click get directions link
    $("#trafficTabs a:last").click(function(){
		document.getElementById("trafficTabs").getElementsByTagName("li")[0].setAttribute("id", "");
		document.getElementById("trafficTabs").getElementsByTagName("li")[1].setAttribute("id", "current");

    	$("#trafficContainer").css("display", "none");
    	$("#directionContainer").css("display", "block");
    	jQuery('#roundBC').css('display','block');
    	CPTraffic.isGetDirectionMode = true;
    });
    // -----------------------------------------------------

	$("#getDir").click(function(){
		return CPGetDirection.getDirections(false);
	});

	$("#reverseGetDir").click(function(){
		return	CPGetDirection.getDirections(true);
	});

    $('#dir_from').keydown(function(e) {
  		if(e.keyCode == 13) {
  			return CPGetDirection.getDirections(false);
  		} else if(e.keyCode == 9) { // tab key
  			$('#dir_to').focus();
  			return false; // must be used
  		}
    });

    $('#dir_to').keydown(function(e) {
  		if(e.keyCode == 13) {
  			e.preventDefault();
  			//e.stopPropagation doesn't work
  			return CPGetDirection.getDirections(false);
  		}
    });

	// from homepage of traffic
	$("#goHP").click(function(e){
		goToTheCity();
	});
	
	$("#goTopTR").click(function(e){
		var sLoc = jQuery('#cityTR').val();
		if(sLoc == "" || sLoc.split(',').length != 2) {
			var msgText;
			if(CPTraffic.frenchFlag == 'F')
				msgText = 'Please type city and province. (e.g: Toronto, ON) ';
			else
				msgText = 'Entrer la ville et la province. (e.g: Montréal, QC)';
			alert(msgText);
			return;
		}
		var city = sLoc.split(',')[0];
		var prov = sLoc.split(',')[1];
		var lang = CPTraffic.frenchFlag == 'F' ? '0' : '1';

		window.location = "/tr/trafficList.jsp?lang="+lang+"&trProv="+$.trim(prov)+"&loc="+$.trim(city);		
	});

	// called from MapListing page. In other words, first search for something in business search and then changed the tab to traffic
	// lang value comes from Webcam not CPTraffic
	$("#goTopTRListing").click(function(e){
		var sLoc = jQuery('#cityTR').val();
		if(sLoc == "" || sLoc.split(',').length != 2) {
			var msgText;
			if(CPTraffic.frenchFlag == 'F')
				msgText = 'Please type city and province. (e.g: Toronto, ON) ';
			else
				msgText = 'Entrer la ville et la province. (e.g: Montréal, QC)';
			alert(msgText);
			return;
		}
		var city = sLoc.split(',')[0];
		var prov = sLoc.split(',')[1];
		var lang = CPTraffic.frenchFlag == 'F' ? '0' : '1';

		window.location = "/tr/trafficList.jsp?lang="+lang+"&trProv="+$.trim(prov)+"&loc="+$.trim(city);		
	});

    $('#cityTR').keydown(function(e) {
  		if(e.keyCode == 13) {
  			var sLoc = jQuery('#cityTR').val();
  			if(sLoc == "" || sLoc.split(',').length != 2) {
  				// because of auto complete function, enter key event can be occurred.
  				return;
  			}
  			var city = sLoc.split(',')[0];
  			var prov = sLoc.split(',')[1];
  			var lang = Webcam.frenchFlag == 'F' ? '0' : '1'; //////

  			window.location = "/tr/trafficList.jsp?lang="+lang+"&trProv="+$.trim(prov)+"&loc="+$.trim(city);	
  		}
    });	
	
	$("#getDirHP").click(function(e){
		doGetDirections();
	});

	$("#reverseGetDirHP").click(function(e){
		var isReverse = true;
		doGetDirections(isReverse);
	});

    $('#dir_from_hp').keydown(function(e) {
  		if(e.keyCode == 13) {
  			return false;
  		} else if(e.keyCode == 9) {
  			$('#dir_to_hp').focus();
  			return false; // must be used
  		}
    });
    $('#clear_directions a:first-child').click(function(){
    	//CPGetDirection.gDir.clear();
    	CPTraffic.map.DeleteRoute();
    	$('#clear_directions').css("display", "none");
    	$("#directionRoute").html("");
    });
});

var CPCookie = { 
	cookieRouteName : "route",
	curMyRoute:[],
	maxRoutes: 3,
	selectedRoute: "",

	setCookie: function(curValue) {
		var expires;
		var expDays = 120;
		var date = new Date();

		date.setTime(date.getTime()+(expDays*24*60*60*1000)); // 3 months
		expires = "; expires="+date.toGMTString();

		var newValue = curValue;
		var oldValue = this.getCookie(this.cookieRouteName);

		if(oldValue != "") {
			newValue = curValue + "@" + oldValue;
		}
		
		// up to 3 values
		var vArr = newValue.split("@");
		if(vArr.length > this.maxRoutes) {
			newValue = newValue.substring(0, newValue.lastIndexOf("@"));
		}
		
		document.cookie = this.cookieRouteName + "=" + escape(newValue) + expires + "; path=/" ;
	},

	// overwrite the route which was selected before
	save: function(routeVal) {
		var name = (routeVal.split('|'))[0];

		// find the route in the cookie with name
		for(var i = 0; i < this.curMyRoute.length; i++) {
			var aRoute = this.curMyRoute[i].split('|');
			if(name == aRoute[0]) {
				// replace old one with new value
				this.curMyRoute[i] = routeVal;
				this.refreshMyRoute();
				break;
			}
		}
	},

	deleteRoute: function(name) {
		CPCookie.selectedRoute = name;
		jQuery('#delete_route_name').html(name);
		 
		jQuery.blockUI( { message: jQuery('#confirm_delete'), css:{padding:'10px 0',width:'300px','font-size':'12px'}, overlayCSS:{backgroundColor:'#FFFFFF', opacity:'0.4'} } );
	},
	// called from confirm message box
	deleteRouteOK: function() {	
		var t = [];
		var name = CPCookie.selectedRoute; 
		
		for(var i = 0; i < this.curMyRoute.length; i++) {
			var aRoute = this.curMyRoute[i].split('|');
			if(name != aRoute[0]) 
				t.push(this.curMyRoute[i]);
			else
				;//alert('found');
		}
		// copy new route to the array
		this.curMyRoute = [];
		jQuery.extend(this.curMyRoute, t);
		
		// if this route is selected before, it should be removed from left pan
		if(name == jQuery('#myroute_name').html())
			Webcam.deleteAllRoute();
		
		this.refreshMyRoute();		
	},
	
	// check if there is the same name as users type
	checkSameRoute: function(routeVal) {
		var name = (routeVal.split('|'))[0];
		
		for(var i = 0; i < this.curMyRoute.length; i++) {
			var aRoute = this.curMyRoute[i].split('|');
			if(name == aRoute[0]) {
				var msgText;
				if(CPTraffic.frenchFlag == 'F')
					msgText = 'There is the same name as route ' + name +'.';
				else
					msgText = 'Le nom d’itinéraire ' + name + ' existe déjà';
				
	    		alert(msgText);
				return true;
			}
		}
		return false;
	},

	refreshMyRoute: function() {
		var expires;
		var expDays = 120;
		var date = new Date();

		date.setTime(date.getTime()+(expDays*24*60*60*1000)); // 3 months
		expires = "; expires="+date.toGMTString();				

		//alert(this.curMyRoute.join("@"));
		// reset the cookie
		document.cookie = this.cookieRouteName + "=" + escape(this.curMyRoute.join("@")) + expires + "; path=/" ;
		this.curMyRoute = this.getCookie(this.cookieRouteName).split('@');
		jQuery('#cookieHistory').html(" ");
		this.loadCookies();
	},

	getCookie: function(name) {
		var cname = name + "=";

		var ca = document.cookie.split(';');
		for(var i = 0;i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1,c.length);
			}
			
			if (c.indexOf(cname) == 0) {
				return unescape(c.substring(cname.length, c.length));
			}
		}
		return "";
	},

	loadCookies: function() {
		this.curMyRoute = [];
		this.curMyRoute = this.getCookie(this.cookieRouteName).split('@');

		if(this.curMyRoute[0] == "") { // no history
			jQuery('#cookieHistoryContainer').css('display','none');
			return;
		}
		
		var html = "";

		for(var i = this.curMyRoute.length, cnt = 1; cnt <= this.maxRoutes && i > 0; i--, cnt++) {
			var cValue = this.curMyRoute[i-1].split('|');
			var chName, provName, cityName, wcIds, lang;

			chName = cValue[0]; // cookie history name
			provName = cValue[1];
			cityName = cValue[2];
			wcIds = cValue[3];

			if(cValue.length == 5) {
				lang = cValue[4];
			}
			// because the structure of history is changed, it should deal with previous history.
			else {
				//lat = cValue[4];
				//lng = cValue[5];				
				lang = cValue[6]; 
			}

			html += "<div style='font-size:11px'><span style='font-size:12px;'>"+((this.curMyRoute.length-i)+1)+"/"+this.maxRoutes+":</span>  <a href='javascript:CPTraffic.getRouteMap(\""+chName+"\", \""+provName+"\",\""+cityName+"\",\""+wcIds+"\",\""+lang+"\")' style='color:#ffffff'>"+chName+"</a> " +
				   "<a href='javascript:CPCookie.deleteRoute(\""+chName+"\")' ><img src='http://cpgimg.com/images/box_sel.gif' border='0'  style='position:relative;top:3px;'/></a></div>";

			//jQuery("#cookieHistory").html(jQuery("#cookieHistory").html() + html);
		}
		jQuery("#cookieHistory").html(html);
		//return html;
	},

	// save as
	addRoute: function(cValue) {
		this.setCookie(cValue);

		jQuery("#cookieHistory").html(" ");
		if(jQuery('#cookieHistoryContainer').css('display') == 'none') {
			jQuery('#cookieHistoryContainer').css('display', 'block');
		}

		this.loadCookies();
	},

	deleteCookie: function() {
		document.getElementById("cookieHistoryContainer").style.display = 'none';
		document.getElementById("cookieHistory").innerHTML = "";
		document.cookie = this.cookieRouteName + "=; expires=-1; path=/";
		document.getElementById("clearButton").style.display='none';
	}
};

var CPTraffic = {
	map : null,
	initLevel: 12,
	container: null,
	city:null,
	frenchFlag : 'F',	// English
	isFromSavedList: false,
	isChanged: false,
	isGetDirectionMode: false,

	loadTrafficMap : function(lat, lng, prov, city, wcIds, frenchFlag_) {
		this.frenchFlag = frenchFlag_||this.frenchFlag;
		this.city = city;
		
		jQuery(document).ready(function($) {
			var curtab = $("#curtab").html();			
			
			// loading map and set initial options
			CPTraffic.map = MapLIB.init({
				mapId:"map", 
				centerLat:lat, 	// defined in MapListingData.java
				centerLng:lng,	// defined in MapListingData.java
				zoom:CPTraffic.initLevel,
				mapLeftOffset:360,
				lang:CPTraffic.frenchFlag == 'T' ? '1' : '0',	// '1' : French, '0' : English
				resizeCallback:CPTraffic.resizeMap,
				streetScene:false
			});
			// initializing street scene object
			//mjStreetView.init({
			//	 frenchFlag:CPTraffic.frenchFlag, 
			//	 mapInstance:CPTraffic.map});

			CPTraffic.map.AttachEvent("onendzoom", Handlers.zoomEndHandler);
			CPTraffic.map.AttachEvent("onclick", Handlers.mouseClickHandler);
			CPTraffic.map.AttachEvent("onmouseover", Handlers.mouseOverHandler);
			CPTraffic.map.AttachEvent("onmousedown", Handlers.mouseDownHandler);		
			CPTraffic.map.AttachEvent("onmouseup", Handlers.mouseUpHandler);
		    CPTraffic.map.AttachEvent('onmousemove', Handlers.mouseMoveHandler);

			Webcam.map = CPTraffic.map;
			Webcam.frenchFlag = CPTraffic.frenchFlag;

			// if it is executed from traffic home page, skip this because it is run in getDirections function
			if(curtab != 'd') {
				if(wcIds == "-1")
					Webcam.get(CPTraffic.frenchFlag, wcIds);	// without cookie
				else
					// to adjust map with proper zoom which contains all webcams and city as well
					CPTraffic.getInitMap(prov, city, wcIds);	// it comes from one of histories
			}
			
		    var lang = CPTraffic.frenchFlag == 'T' ? '1' : '0';

		    CPTraffic.doWeatherQuery(lat, lng, lang);
		    // news only for English
		    if(lang == 0)
		    	CPTraffic.doNewsQuery(lat, lng, lang);			
			
		    //this.map.onLoadMap = onMapLoaded();
			CPTraffic.initMapSize();
			setTimeout(function(){	window.onresize = CPTraffic.resizeMap; }, 300);
			
		    // if get directions is executed from the home page.
			if(curtab == 'd') {
				CPTraffic.isGetDirectionMode = true;
				CPGetDirection.getDirections(false);
				document.getElementById("trafficTabs").getElementsByTagName("li")[0].setAttribute("id", "");
				document.getElementById("trafficTabs").getElementsByTagName("li")[1].setAttribute("id", "current");
				$("#trafficContainer").css("display", "none");
				$("#directionContainer").css("display", "block");			
			}
		});		
	},

	promptRouteName: function() {
		var height = 60;
		if(CPCookie.curMyRoute.length >= CPCookie.maxRoutes) {
			height = 110;
			jQuery('#cookie_prompt_msg').css('display','block');
			jQuery('.first_route').html(CPCookie.curMyRoute[CPCookie.maxRoutes-1].split("|")[0])
		} else {
			jQuery('#cookie_prompt_msg').css('display','none');
		}
		
		jQuery.blockUI( { message: jQuery('#cookie_prompt'), css:{padding:'5px 0',width:'400px',height:height+'px','font-size':'12px'}, overlayCSS:{backgroundColor:'#FFFFFF', opacity:'0.4'} } );
	},

	promptNew: function() {
		jQuery.blockUI( { message: jQuery('#new_prompt'), css:{padding:'10px 0',width:'320px','font-size':'12px'}, overlayCSS:{backgroundColor:'#FFFFFF', opacity:'0.4'} } );	
	},

	promptConfirm: function() {
		jQuery.blockUI( { message: jQuery('#confirm_prompt'), css:{padding:'10px 0',width:'275px','font-size':'12px'}, overlayCSS:{backgroundColor:'#FFFFFF', opacity:'0.4'} } );	
	},

	promptNewList: function(_height) {
		var height = _height;
		jQuery('#overwrite_route_name').html(": " + jQuery('#myroute_name').html());
		jQuery.blockUI( { message: jQuery('#new_prompt_list'), css:{'padding-top':'10px',width:'450px',height:height+'px','font-size':'12px',cursor:'pointer'}, overlayCSS:{backgroundColor:'#FFFFFF', opacity:'0.4'} } );	
	},

	saveRoute: function(isSaveas) {
		(function($){	
			var cityName = $.trim($("#cityTR").val().split(',')[0]);
			var provName = $.trim($("#cityTR").val().split(',')[1]);
			var wcIds = Webcam.getListOfWebcamIds();

			var routeName;
			if(isSaveas) {
				var tn1 = $("#new_prompt_name").val();
				var tn2 = $("#cookie_prompt_name").val();
				routeName = tn1 == "" ? tn2 : tn1; 
				//alert('save as : ' + routeName);
			} 
			else {
				var tn1 = $("#cookie_prompt_name").val();
				var tn2 = $('#myroute_name').html();
				routeName = tn1 == "" ? tn2 : tn1;
				//alert('save ' + routeName);
			}
			//if($("#myRouteTitleTR").is(':hidden'))
				$('#myRouteTitleTR').find("#myroute_name").html(routeName);//.end().toggleClass("showRouteTitle");
			
			if(routeName != null) {
				var cvalue = routeName+"|"+provName+"|"+cityName+"|"+wcIds+"|"+Webcam.frenchFlag;

				if(isSaveas)
					CPCookie.addRoute(cvalue);
				else
					CPCookie.save(cvalue);

				$.unblockUI({fadeOut:10});
				$('#cookie_prompt_name').val("");				
			}

	    	CPTraffic.isFromSavedList = true;
	    	CPTraffic.isChanged = false;
	    	$('#saveTrafficTR').css('display','none');
	    	//$('#saveTraffic').get(0).disabled = true;
		
		})(jQuery);
	},
	
	// infowindowMode : if user click getdirection tab, the traffic is displayed in infowindows
	switchCam: function(thumbNo, infowindowMode) {
		var suffix = infowindowMode ? "_pop" : "";
		var newImgSrc = document.getElementById("thumb"+thumbNo+"_img"+suffix).getAttribute("src");
		
		document.getElementById("maincam"+suffix).firstChild.setAttribute("src", newImgSrc);
		document.getElementById("maincam_sub_name"+suffix).innerHTML = " &nbsp;<b>:</b> " + document.getElementById("thumb"+thumbNo+"_img"+suffix).getAttribute("alt");
	},

	getInitMap: function(prov, city, wcIds) {
		var $ = jQuery;
		var swLat = 0.;
		var neLat = 0.;
		var swLng = 0.;
		var neLng = 0.;
		var urlData = "";
		 
		if(wcIds == '-1')
			urlData = 'op=bounds&prov='+prov+'&city='+city;
		else 
			urlData = 'op=bounds2&prov='+prov+'&city='+city+'&webcamId='+wcIds;
		
		$.ajax({
			   type: "GET",
			   url: '/traffic.do',
			   data: urlData + '&t='+(new Date()).getTime(),
			   dataType: "xml",
			   success: function(xml) {
				// parse header
				$(xml).find('bound').each(function() {
					swLat = parseFloat($(this).attr("swlat"));
					neLat = parseFloat($(this).attr("nelat"));
					swLng = parseFloat($(this).attr("swlng"));
					neLng = parseFloat($(this).attr("nelng"));
					
					// TopLeftLatLong, BottomRightLatLong
					CPTraffic.map.SetMapView(new VELatLongRectangle(new VELatLong(neLat, swLng), new VELatLong(swLat, neLng)));
					CPTraffic.map.Resize();

					Webcam.get(CPTraffic.frenchFlag, wcIds);
				});
			   },
			   error: function(xhr, textStatus, errorThrown) {
			   	
			   }
		});		
	},

	getRouteMap: function(myroute, prov, city, wcIds,lang_) {
		var lang = lang_ == 'F' ? "0" : "1";

		window.location = "/tr/trafficList.jsp?lang="+lang+"&myrt="+myroute+"&trProv="+prov+"&loc="+city+"&wcIds="+wcIds;
	},	

	doWeatherQuery: function(lat, lng, lang) {
		var $ = jQuery;

		$.ajax({
			   type: "GET",
			   url: '/weather/search2.jsp',
			   data: 'lang=' + lang	+ '&lat=' + lat	+ '&lng=' + lng + '&t='+(new Date()).getTime(),
			   dataType: "xml",
			   success: function(xml) {
				// parse header
				$(xml).find('header').each(function() {
					var resText = $(this).attr("resText");
					var cityName = $(this).attr("cityName");
					var prov = $(this).attr("prov");

					$("#tr_weather").html(resText);
					//$("#iMap_cityNav").html(cityName);
					//$("#iMap_provNav").html(prov);
					
				});
			   },
			   error: function(xhr, textStatus, errorThrown) {
			   	
			   }
		});		
	},

	doNewsQuery: function(lat, lng, lang) {
		var $ = jQuery;
		
		$.ajax({
			   type: "GET",
			   url: '/getNews.jsp',
			   data: 'lang=' + lang	+ '&lat=' + lat	+ '&lng=' + lng + '&t='+(new Date()).getTime(),
			   dataType: "xml",
			   success: function(xml) {
				// parse header
				$(xml).find('header').each(function() {
					var resText = $(this).attr("resText");

					$("#tr_news").html(resText);
				});
			   },
			   error: function(xhr, textStatus, errorThrown) {
			   	
			   }
		});	
	},
	
	setSize: function() {
		var $ = jQuery;

		var minHeight = 500;
		//var minStreetSceneHeight = 200;
		var minWidth = 500;
		var mapLeftOffset = 360; // this offset is fixed otherwise it is very hard to adjust the left offset of the map div.
		var clHeight = $(window).height();

		var topOffset;
		var mapTop = $('#'+MapLIB.defaults.mapId).offset().top;
		//var streetTop = $("#mapStreet").offset().top;	

		//if(streetTop <= 0) {
			topOffset = mapTop;
		//} else {
		//	topOffset = Math.min(mapTop, streetTop);
		//}

		var newHeight = Math.max(minHeight, clHeight - topOffset - 100);
		// make it half, so that it expands along map div as window is resized
		//var streetSceneHeight = parseInt(Math.max(minStreetSceneHeight, newHeight / 2));

		// check if there is box ad
		if($("#_boxad_").length != 0) {
			newWidth = Math.max(minWidth, $(window).width() - mapLeftOffset - 135); // 135 is size of box ad
		} else {
			newWidth = Math.max(minWidth, $(window).width() - mapLeftOffset - 3);
		}

		//if(mjStreetView.isStreetView) {
		//	$("#mapStreet").width(newWidth).height(streetSceneHeight);
		//	$("#map").width(newWidth).height(newHeight - streetSceneHeight - 3); // -3 is adjustment for listing height;
		//	map.Resize(newWidth, newHeight - streetSceneHeight - 3);		
		//} else {
			$('#'+MapLIB.defaults.mapId).width(newWidth).height(newHeight);
			this.map.Resize(newWidth, newHeight);
		//}

		$("#directionRoute").height(newHeight-105);

		MapLIB.vars.prevSize = MapLIB.getWindowSize();
	},

	initMapSize: function() {
		CPTraffic.setSize();
	},

	resizeMap: function() {
		var currWindowSize = MapLIB.getWindowSize(); 

		if((currWindowSize.width != MapLIB.vars.prevSize.width) || (currWindowSize.height != MapLIB.vars.prevSize.height)) {
			MapLIB.removeInfoBox();
			MapLIB.vars.prevSize = currWindowSize; 
			CPTraffic.setSize();
		}
	}
};

var CPGetDirection = {
	locs: [],

	routeHandler: function(route) {
		var $ = jQuery;
	    var allRoutes = [];
		var directions = $("#RouteTemplate").clone();

		// in the case of wrong addresses
		if(route != null)
			MapLIB.blockMap();		
		
		directions.find("#RouteStartPoint").html(CPGetDirection.locs[0]).end()
				  .find("#RouteEndPoint").html(CPGetDirection.locs[1]).end()
				  .find("#RouteDistance").html(route.Distance.toFixed(1)).end()
				  .find("#RouteTime").html(MapLIB.getTime(route.Time));

   		// Unroll route and populate DIV
   		var legs          = route.RouteLegs;
   		var leg           = null;
   		var turnNum       = 0;  // The turn #

      // Get intermediate legs
   	  // for now, it has only one leg. if users add one more stop, leg will be added.
      for(var i = 0; i < legs.length; i++) {
         // Get this leg so we don't have to derefernce multiple times
         leg = legs[i];  // Leg is a VERouteLeg object

         // Unroll each intermediate leg
         var turn        = null;  // The itinerary leg
         var steps		 = "";
         var legDistance = null;  // The distance for this leg

         for(var j = 0; j < leg.Itinerary.Items.length; j ++) {
            turnNum++;
            turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
            legDistance    = turn.Distance;

            // So we don't show 0.0 for the arrival
            if(legDistance > 0) {
               steps += '<tr><td width="30px" style="border-top:1px solid #999999;padding:5px 0;">' +
              	 	 turnNum + '.</td><td width="259px" style="border-top:1px solid #999999;padding:5px 0;">' + 
              	 	 turn.Text +
              	 	 '</td><td width="60px" align="right" style="border-top:1px solid #999999;padding:5px 0;">' +
              	 	 legDistance.toFixed(1) + 
              	 	 'km</td></tr>';
            }

            if(turn.Shape.GetTitle().indexOf('Step') >= 0  || turn.Shape.GetTitle().indexOf('tape') >= 0)
            	turn.Shape.Hide();

            allRoutes.push(turn.LatLong);
         }
      }

      directions.find("#RouteItineries").append(steps);

      MapLIB.unblockMap();

      // Populate DIV with directions
      CPGetDirection.SetDirections(directions.html());

      // adjust the zoom level to show route line
      CPTraffic.map.SetMapView(allRoutes);
    },

    SetDirections: function (s) {
    	jQuery("#directionRoute").html(s);

       //var d = document.getElementById("directionRoute");
       //d.innerHTML = '<div >' + s + '</div>';
    },

    // time is an integer representing seconds
    // returns a formatted string
    GetTime: function(time) {
       if(time == null)
          return("");

       if(time > 60) {                                 
    	   								// if time == 100
          var seconds = time % 60;       // seconds == 40
          var minutes = time - seconds;  // minutes == 60
          minutes     = minutes / 60;    // minutes == 1

          if(minutes > 60) {                                     
        	  									// if minutes == 100
             var minLeft = minutes % 60;        // minLeft    == 40
             var hours   = minutes - minLeft;   // hours      == 60
             hours       = hours / 60;          // hours      == 1

             return(hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
          }
          else {
             return(minutes + " minutes, " + seconds + " seconds");
          }
       }
       else {
          return(time + " seconds");
       }
    },

	getDirections: function(isReverse) {
		var ret = true;
		(function($, that) {

			//$("#directionRoute").css('display','');
			$("#directionRoute").html(' ');

			if(that.checkDirectionFormValues()) {
				//MapLIB.blockMap();

				var dirFrom, dirTo;
				var locale = "en_CA";

				if(!isReverse) {
					dirFrom = $("#dir_from").val();
					dirTo = $("#dir_to").val();
				}
				else {
					dirFrom = $("#dir_to").val();
					dirTo = $("#dir_from").val();
					
					$("#dir_from").val(dirFrom);
					$("#dir_to").val(dirTo);
				}

				if(CPTraffic.frenchFlag == 'T') { 
					locale = "fr_CA";
				}

				Webcam.getWebcamMarkers();

				var options = new VERouteOptions();
				options.SetBestMapView = false; // Don't change map view
				options.DrawRoute = true;
				options.RouteColor = new VEColor(200,50,255,0.7);
				options.DistanceUnit = VERouteDistanceUnit.Kilometer;
				options.RouteCallback = CPGetDirection.routeHandler;  // Gets VERoute
				options.ShowDisambiguation = false;

				CPGetDirection.locs = [dirFrom, dirTo];

				try {
					$('#clear_directions').css("display", "block");
					CPTraffic.map.GetDirections(CPGetDirection.locs, options);
				} 
				catch(e) {alert(e.message);}
			}
			else {
				ret = false;
			}

		})(jQuery, CPGetDirection);

		return ret;
	},

	checkDirectionFormValues: function(isFromHomepage) {
		var retVal = true;
		var suffix = isFromHomepage ? "_hp" : "";

	 	(function($) {
		 	var errMsg;
		 	var dirFrom = $("#dir_from"+suffix).val();
		 	var dirTo = $("#dir_to"+suffix).val();

		  if(dirFrom == "" && dirTo == "") {
			  if(CPTraffic.frenchFlag == 'F')
				  errMsg = "Please type your start and destination address.";
			  else
				  errMsg = "Entrer l’adresse de départ et de destination";
		  	alert(errMsg);
		  	retVal = false;
		  }
		  else if(dirFrom == "") {
			  if(CPTraffic.frenchFlag == 'F')
				  errMsg = "Please type your start address in From.";
			  else
				  errMsg = "Entrer l’adresse de départ dans De";
		  	alert(errMsg);
		  	retVal = false;
		  }
		  else if(dirTo == "") {
			  if(CPTraffic.frenchFlag == 'F')
				  errMsg = "Please type your end address in To.";
			  else
				  errMsg = "Entrer l’adresse d’arrivée dans Vers";
		  	alert(errMsg);
		  	retVal = false;
		  }
	 	})(jQuery);

	 	return retVal;
	}
};
