var map;
var bObj;
var cObj;
var currentType;
var currentFixedType;
var currentFixedOrganizations = new Array();
var currentJsonData;
var currentSearch = "";
var initialSearch = false;
var bAutoReload = true;
var MaxZoom = 15;
var MinZoom = 9;
var objSearch;
var fixedOverlay; 
var organizationOverlay;
var searchOverlay;
var HOST_PATH = "http://imap.esolutionsgroup.ca/trra_resources";
var cmsURL = "http://directory.trra.ca/";

var currentOrganizations = new Array();

var initialTRRASearch = true;

var sSearchID = unescape(extractValues(document.location.href, "trra_id=")); 
var sSearchType = unescape(extractValues(document.location.href, "type=")); 
var sSearchURL = unescape(extractValues(document.location.href, "back_url=")); 

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

var gSmallIcon = createGIcon({image: HOST_PATH + "/images/trra_markers/blue-single.gif", width:8, height: 8});
var gClusterIcon = createGIcon({image: HOST_PATH + "/images/trra_markers/blue-multiple.gif", width:11, height: 11});
var gSmallIconOrganizations = createGIcon({image: HOST_PATH + "/images/trra_markers/grey-single.gif", width:8, height: 8});
var gClusterIconOrganizations = createGIcon({image: HOST_PATH + "/images/trra_markers/grey-multiple.gif", width:9, height: 9});
var gSmallIconSearch = createGIcon({image: HOST_PATH + "/images/trra_markers/search-result.gif", width:10, height: 10});
var gSmallIconIntersection = createGIcon({image: HOST_PATH + "/images/trra_markers/red-single.gif", width:8, height: 8});
var gClusterIconSearch = createGIcon({image: HOST_PATH + "/images/trra_markers/search-result.gif", width:10, height: 10});

function createGIcon(obj) {
	var gTempIcon = new GIcon();
	gTempIcon.image = obj.image;
	gTempIcon.iconSize = new GSize(obj.width,obj.height);
	gTempIcon.iconAnchor = new GPoint(Math.round(obj.width/2),obj.height);
	return gTempIcon;
}

function Info() {}

Info.prototype = new GControl();

Info.prototype.initialize = function(map) {
	  var container = document.createElement("div");
	  GEvent.addDomListener(container, "mouseover", function() { this.style.cursor="pointer"; });
	  container.style.width = "45px";
	  
	  var north = document.createElement("img");
	  north.src = HOST_PATH + "/images/tools/northArrow.png";
	  with (north.style) {
		paddingLeft="18px";
		paddingBottom="7px";	  
	  }
	  
	  var pan_up = document.createElement("img");
	  pan_up.src = HOST_PATH + "/images/tools/pan_up.png";
	  GEvent.addDomListener(pan_up, "click", function() {pan(0,1);});
	  with (pan_up.style) {
		paddingLeft="15px";
		paddingBottom="5px";
	  }
	  
	  var pan_left = document.createElement("img");
	  pan_left.src = HOST_PATH + "/images/tools/pan_left.png";
	  GEvent.addDomListener(pan_left, "click", function() {pan(1,0);});
	  with (pan_left.style) {
		padding="2px";
		paddingLeft="5px";
	  }
	  
	  var pan_right = document.createElement("img");
	  pan_right.src = HOST_PATH + "/images/tools/pan_right.png";
	  GEvent.addDomListener(pan_right, "click", function() {pan(-1,0);});
	  with (pan_right.style) {
		padding="2px";
	  }
	  
	  var pan_down = document.createElement("img");
	  pan_down.src = HOST_PATH + "/images/tools/pan_down.png";
	  GEvent.addDomListener(pan_down, "click", function() {pan(0,-1);});
	  with (pan_down.style) {
		paddingLeft="15px";
		paddingTop="5px";
		paddingBottom="10px";
	  }
	  
	  var zoom_in = document.createElement("img");
	  zoom_in.src = HOST_PATH + "/images/tools/zoom_in.png";
	  GEvent.addDomListener(zoom_in, "click", function() {zoom("ZOOM_IN");});
	  with (zoom_in.style) {
		padding="2px";
		paddingLeft="15px";
	  }
	  
	  var zoom_out = document.createElement("img");
	  zoom_out.src = HOST_PATH + "/images/tools/zoom_out.png";
	  GEvent.addDomListener(zoom_out, "click", function() {zoom("ZOOM_OUT");});
	  with (zoom_out.style) {
		padding="2px";
		paddingLeft="15px";
	  }
	  
	  container.appendChild(north);
	  container.appendChild(pan_up);
	  container.appendChild(pan_left);
	  container.appendChild(pan_right);
	  container.appendChild(pan_down);
	  container.appendChild(zoom_in);
	  container.appendChild(zoom_out);
	  
	  map.getContainer().appendChild(container);
      return container; 
    }

Info.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10));
}

function go() {
    var mapOpts = { draggableCursor:"default", draggingCursor:"default" }                  
    map = new GMap2(document.getElementById("TRRA_DIV"), mapOpts);    
  
    var trraCC = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0,  ' - Map Data © 2008 Statistics Canada, Ontario MNR');
    var eSolCC = new GCopyrightCollection('© 2008 <a style="font-family:Arial;font-size:10px;font-weight:bold;" href="http://www.esolutionsgroup.ca/" target="_blank">eSolutionsGroup</a>');
    eSolCC.addCopyright(trraCC);

    var mapLayer = new GTileLayer(eSolCC, 9, 15);
    mapLayer.getTileUrl = function(tile, zoom) {
		//base tile URL
        return "http://imap.esolutionsgroup.ca/Map/Map.ashx?z="+zoom+"&x="+tile.x+"&y="+tile.y+"&v="+"street"+"&o=trra&s=stage";
    };

    mapLayer.isPng = function() { return true; };
    mapLayer.getOpacity = function() { return 1.0; }

    var trraMap = new GMapType([mapLayer], new GMercatorProjection(20), "TRRA");
    map.addMapType(trraMap);
    map.setMapType(trraMap);
    map.removeMapType(G_NORMAL_MAP);
    map.removeMapType(G_HYBRID_MAP);
    map.removeMapType(G_SATELLITE_MAP);
    
	 map.disableDoubleClickZoom();
    GEvent.addListener(map, "dblclick", function (overlay, latlng) {
        zoom("ZOOM_IN", latlng);
    });
    	   
    map.setCenter(new GLatLng(43.554519, -79.719543), MinZoom);  
    map.getPane(G_MAP_FLOAT_SHADOW_PANE).style.visibility = "hidden"; //remove();
    objSearch = actb(document.getElementById('tb'),new Array('a'));
    addLabels();
	clearCheckboxes();	
	map.addControl(new GScaleControl());
	map.addControl(new Info());
	
	checkSearch();
		
}

function checkSearch() {

	if ((sSearchType) && (sSearchURL) && (sSearchID)){
		
        $('urlplaceholder').href = sSearchURL + "?type=" + sSearchID;
		//$('urlplaceholder').style.display = "block";
				
        if (sSearchURL != 'undefined') {
            $('urlplaceholderWrap').style.display = "block";
        }        		
		
		switch (sSearchType) {
			case "BD": 
				$('urlplaceholder').innerHTML = "Back to directory";
				break;
			case "S":
				$('urlplaceholder').innerHTML = "Back to search";
				break;
			default: break;
		}	
		
	}	
	
}

function clearCheckboxes() {
	bAutoReload = false;
	var tmp = document.getElementsByTagName("input");	
	for (var i=0; i < tmp.length; i++) {   
	   if (tmp[i].type == "checkbox") {
			if (tmp[i].value == 31 || tmp[i].value == 34 || tmp[i].value == 35) {
				tmp[i].checked = true;
				tmp[i].onclick();
			}
			else
				tmp[i].checked = false;
	   }
	}
	reloadFixedOrganizations();
}

function getProfile(sName, trraId) {

	// get the profile HTML from a reponse or set the content of the profile window to an aspx/ashx page

    if (trraId) {
		oProfileWindow = new Window({id:"ProfileWindow", url: cmsURL + "ajax.mvc/MediumProfile?trraId=" + trraId, className: "alphacube",  minimizable: false, maximizable: false, width:400, height:400, zIndex: 2500, resizable: false, title: "Profile", draggable:false, wiredDrag: false, left:0,top:0, destroyOnClose: true, recenterAuto:false})
		//jQuery.nyroModalManual({ modal: false, type: 'iframe', width: 367, id: "ProfileWindow", url: cmsURL + "ajax.mvc/MediumProfile?trraId=" + trraId });
	}
	
	else {
		oProfileWindow = new Window({id:"ProfileWindow", url: cmsURL + "ajax.mvc/MediumProfile?orgName=" + sName, className: "alphacube",  minimizable: false, maximizable: false, width:400, height:400, zIndex: 2500, resizable: false, title: "Profile", draggable:false, wiredDrag: false, left:0,top:0, destroyOnClose: true, recenterAuto:false})
		//jQuery.nyroModalManual({ modal: false, type: 'iframe', width: 367, id: "ProfileWindow", url: cmsURL + "ajax.mvc/MediumProfile?orgName=" + sName });
	}
    
    oProfileWindow.showCenter();             
    
}

function kmlExport() 
{
	var kmlWindow = new Window({id:"kmlExportWindow", url: "/en/includes/kmlexport.asp" , className: "alphacube",  minimizable: false, maximizable: false, width:400, height:460, zIndex: 2500, resizable: false, title: "Export Map Data Request", draggable:false, wiredDrag: false, left:0,top:0, destroyOnClose: true, recenterAuto:false})	
	kmlWindow.showCenter();             
}

function toggleSector(sectorName, sectorID, link) {	

	bAutoReload = false;
	
	if (link.className == "sectorLink") {	    
	    
		for (var i=0; i < link.parentNode.getElementsByTagName("input").length; i++) {
			link.parentNode.getElementsByTagName("input")[i].checked = true;
			link.parentNode.getElementsByTagName("input")[i].onclick();
		}
		
		link.className = "sectorLinkOn";
		
		
	}
	
	else {
	
		for (var l=0; l < link.parentNode.getElementsByTagName("input").length; l++) {
		
			if (link.parentNode.getElementsByTagName("input")[l].checked){
				link.parentNode.getElementsByTagName("input")[l].checked = false;
				link.parentNode.getElementsByTagName("input")[l].onclick();
			}
			
		}
		
		link.className = "sectorLink";
		
	}
	
	reloadOrganizations();
	
}
	
function toggleSubSector(subSectorName, sectorName, subSectorID, sectorID, checkbox) {

	// if true then turn on --- if false check the count of true checkboxes ... if 0 then turn off	
	if (currentOrganizations.length == 0) {
        currentOrganizations[currentOrganizations.length] = subSectorID;
		jQuery.post('/en/services/stats.aspx', { stattype: 'AddMapSectors', values: 'sectors=' + subSectorName });
    }
    else {
        if (currentOrganizations.inArray(subSectorID)) {          
            currentOrganizations.removeElement(subSectorID);              
        }
        else {
            currentOrganizations[currentOrganizations.length] = subSectorID;           
			jQuery.post('/en/services/stats.aspx', { stattype: 'AddMapSectors', values: 'sectors=' + subSectorName });
		}
    }         
    
	if (currentOrganizations.length > 0 && bAutoReload) {
		handleRequest({marker_type:"ORGANIZATION", request_type: "LOAD_MARKERS", param_1:currentOrganizations.toString()}); 		
	}
	
	if (bAutoReload) {
		if (checkbox.checked) {
			$(sectorID.toString()).className = "sectorLinkOn";
		}
		else {
			var bRemove = true;
			// if there are no checks left in that menu then turn it off
			for (var k=0; k < $(sectorID.toString()).parentNode.getElementsByTagName("input").length; k++) {
				if ($(sectorID.toString()).parentNode.getElementsByTagName("input")[k].checked)
					bRemove = false;
			}
			if (bRemove)
				$(sectorID.toString()).className = "sectorLink";
		}	
	}
		
    if (currentOrganizations.length == 0 && organization_marker_manager != null) {
        organization_marker_manager.clearMarkers();    
    }
	
	updateCurrentlyViewing(unescape(subSectorName), unescape(sectorName), checkbox);
    currentType = currentOrganizations.toString();  
	map.closeInfoWindow();
	
}

function reloadOrganizations() {

	bAutoReload = true;
	sendRequest = false;

	request_queue = new Array(); 

	
	if (currentOrganizations.length > 0) {
	    request_queue[request_queue.length] = {marker_type:"ORGANIZATION", request_type: "LOAD_MARKERS", param_1:currentOrganizations.toString()};
		sendRequest = true;
    }    

    reloadFixedOrganizations(request_queue, sendRequest);		
}

function toggleSubSectorFixed(subSectorName, sectorName, subSectorID, sectorID, checkbox) {

	// if true then turn on --- if false check the count of true checkboxes ... if 0 then turn off	
	if (currentFixedOrganizations.length == 0) {
        currentFixedOrganizations[currentFixedOrganizations.length] = subSectorID;  
		jQuery.post('/en/services/stats.aspx', { stattype: 'AddMapSectors', values: 'sectors=' + subSectorName });
    }
    else {
        if (currentFixedOrganizations.inArray(subSectorID)) {          
            currentFixedOrganizations.removeElement(subSectorID);              
        }
        else {
            currentFixedOrganizations[currentFixedOrganizations.length] = subSectorID;           
			jQuery.post('/en/services/stats.aspx', { stattype: 'AddMapSectors', values: 'sectors=' + subSectorName });
        }
    }         
    
	if (currentFixedOrganizations.length > 0 && bAutoReload) {
		handleRequest({marker_type:"FIXED", request_type: "LOAD_MARKERS", param_1:currentFixedOrganizations.toString()}); 		
	}
	
	if (bAutoReload) {
		if (checkbox.checked) {
			$(sectorID.toString()).className = "sectorLinkOn";
		}
		else {
			var bRemove = true;
			// if there are no checks left in that menu then turn it off
			for (var k=0; k < $(sectorID.toString()).parentNode.getElementsByTagName("input").length; k++) {
				if ($(sectorID.toString()).parentNode.getElementsByTagName("input")[k].checked)
					bRemove = false;
			}
			if (bRemove)
				$(sectorID.toString()).className = "sectorLink";
		}	
	}
		
    if (currentFixedOrganizations.length == 0 && fixed_marker_manager != null) {
        fixed_marker_manager.clearMarkers();    
    }
	
	updateCurrentlyViewing(unescape(subSectorName), unescape(sectorName), checkbox);
    currentFixedType = currentFixedOrganizations.toString();  
	map.closeInfoWindow();
	
}

function reloadFixedOrganizations(request_queue, sendRequest) {

	if (sendRequest == null || sendRequest == 'undefined')
		sendRequest = false;
		
	if (request_queue == null || request_queue == 'undefined')
		request_queue = new Array(); 

	bAutoReload = true;
	
	if (currentFixedOrganizations.length > 0) {	
        request_queue[request_queue.length] = {marker_type:"FIXED", request_type: "LOAD_MARKERS", param_1:currentFixedOrganizations.toString()};
		sendRequest = true;
    }
    	
	if (sSearchID != null && sSearchID != 'undefined' && sSearchID != '') {
		request_queue[request_queue.length] = {marker_type:"SEARCH", request_type: "LOAD_MARKERS_BY_ID", param_1:sSearchID.toString()};
		sendRequest = true;
	}	
		
	if (sendRequest) {
		handleRequestQueue();
	}
		
}

function updateCurrentlyViewing(subSectorName, sectorName, checkbox)  {
	
	if ($(sectorName)) {	
	
		var tempText = unescapeFromHTML($(sectorName).innerHTML);
		if (tempText.indexOf(subSectorName) > -1) {  // the subsector is already there  
			if (!checkbox.checked){ 
				if (tempText.indexOf(",&nbsp;" + subSectorName) > -1) {  
					tempText = tempText.replace(",&nbsp;" + subSectorName, "");  // if the checkbox is false remove the sub sector
				}
				else if (tempText.indexOf("&nbsp;" + subSectorName) > -1) {  
					tempText = tempText.replace("&nbsp;" + subSectorName, "");  // if the checkbox is false remove the sub sector
				}
				else {
					tempText = tempText.replace(" " + subSectorName, ""); 
				}
			}			
			
			if (tempText.indexOf("</b>,") > -1)
				tempText = tempText.replace("</b>,","</b>");	
			
			$(sectorName).innerHTML = tempText;
			if ($(sectorName).innerHTML.lastIndexOf(">") == $(sectorName).innerHTML.length-1)
				$('currently_viewing').removeChild($(sectorName));
		}
		else {
			if (checkbox.checked) {
			if ($(sectorName).innerHTML.lastIndexOf(">") == $(sectorName).innerHTML.length-1) {
					tempText += "&nbsp;" + subSectorName; 
				}
				else {
					tempText += ",&nbsp;" + subSectorName;
				}
			}			
			$(sectorName).innerHTML = tempText;			
		}
	}
	else {
		var a = document.createElement('span');
		a.id = sectorName;
		a.style.color = "gray";
		a.innerHTML = "<b style='color:black' >&nbsp;" + sectorName + "</b>";
		$('currently_viewing').appendChild(a);
		updateCurrentlyViewing(subSectorName, sectorName, checkbox); 	
	}
}

function unescapeFromHTML(str) {

	if (str) {
		str = str.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'");
		str = str.replace(/&amp;/g, "&");
		return str;
	}
	else 
		return false;
	
}

function pan(x,y) { 
	map.panDirection(x,y); 
}

function zoom(mode, pt) {
    var tmpZoom;
    var bDoZoom = false;
        
    if (mode == "ZOOM_IN") {
        tmpZoom = map.getZoom() + 1;        
        if(tmpZoom <= MaxZoom) {       
            if (pt) {
                if(tmpZoom == 11) 
                    map.setCenter(pt,12);
                else if (tmpZoom == 13)
                    map.setCenter(pt,14);
                else
                    map.setCenter(pt,tmpZoom);
            }
            else {
                if(tmpZoom == 11) 
                    map.setZoom(12);
                else if (tmpZoom == 13)
                    map.setZoom(14);
                else
                    map.setZoom(tmpZoom);
            }
			// manual tweak to Toronto label
			if (map.getZoom() == 10) {
				toronto_fixed.setLatLng(new GLatLng(map_labels_level1.labels[34].alt_latitude, map_labels_level1.labels[34].alt_longitude));
			}			
            request_queue = new Array();                  
            if (map.getZoom() == MaxZoom || map.getZoom() == MaxZoom-1) {
				request_queue[request_queue.length] = {marker_type:"INTERSECTIONS", request_type: "LOAD_MARKERS"};
			}
             
			if (currentFixedType != null && currentFixedType != 'undefined' && currentFixedType != '') {
				request_queue[request_queue.length] = {marker_type:"FIXED", request_type: "LOAD_MARKERS", param_1:currentFixedType};
			}
            
			if (currentType != null && currentType != 'undefined' && currentType != '') {
				request_queue[request_queue.length] = {marker_type:"ORGANIZATION", request_type: "LOAD_MARKERS", param_1:currentType};
			}

            if (currentSearch != null && currentSearch != 'undefined' && currentSearch != '' && currentSearch != 'Keyword') {
				request_queue[request_queue.length] = {marker_type:"SEARCH", request_type: "LOAD_MARKERS", param_1:currentSearch};
			}
                
			if (sSearchID != null && sSearchID != 'undefined' && sSearchID != '') {
				request_queue[request_queue.length] = {marker_type:"SEARCH", request_type: "LOAD_MARKERS_BY_ID", param_1:sSearchID.toString()};
			}
				
            //request_queue[request_queue.length] = {marker_type:"FIXED",request_type:"LOAD_MARKERS"};                
          
            handleRequestQueue();
			map.closeInfoWindow();
        }
    }
    else if (mode == "ZOOM_OUT") {
        tmpZoom = map.getZoom() - 1;        
        if(tmpZoom >= MinZoom) {
            if(tmpZoom == 11)
                map.setZoom(10);
            else if(tmpZoom == 13) 
                map.setZoom(12);
            else
                map.setZoom(tmpZoom); 
            
            if (map.getZoom() < MaxZoom-1) {
                if (intersection_marker_manager) {
                    if (intersection_marker_manager.getMarkerCount(map.getZoom()) > 0)
                        intersection_marker_manager.clearMarkers();
                }                
            }
			// manual tweak to Toronto label
			if (map.getZoom() == 9) {
				toronto_fixed.setLatLng(new GLatLng(map_labels_level1.labels[34].latitude, map_labels_level1.labels[34].longitude));
			}
            
            request_queue = new Array(); 
			
			if (currentFixedType && currentFixedType != 'undefined' && currentFixedType != '')
			    request_queue[request_queue.length] = {marker_type:"FIXED", request_type: "LOAD_MARKERS", param_1:currentFixedType};
			
            if (currentType != null && currentType != 'undefined' && currentType != '')
                request_queue[request_queue.length] = {marker_type:"ORGANIZATION", request_type: "LOAD_MARKERS", param_1:currentType};
            
            if (currentSearch != null && currentSearch != 'undefined' && currentSearch != '' && currentSearch != 'Keyword') {
				request_queue[request_queue.length] = {marker_type:"SEARCH", request_type: "LOAD_MARKERS", param_1:currentSearch};
			}
            
			if (sSearchID != null && sSearchID != 'undefined' && sSearchID != '')
				request_queue[request_queue.length] = {marker_type:"SEARCH", request_type: "LOAD_MARKERS_BY_ID", param_1:sSearchID.toString()};
			
            //request_queue[request_queue.length] = {marker_type:"FIXED",request_type:"LOAD_MARKERS"};                
            handleRequestQueue();
			map.closeInfoWindow();
        }
    }
}

function clearMap() {

    // Resetting variables
    currentSearch = "";
	sSearchID = "";
    
    // Resetting keyword
    jQuery('#tb').val('Keyword');
    
    // Removing markers
    if (search_marker_manager != null) {
        search_marker_manager.clearMarkers();
        search_marker_manager.refresh();
    }

    if (fixed_marker_manager != null) {
        fixed_marker_manager.clearMarkers();
        fixed_marker_manager.refresh();
    }

    if (organization_marker_manager != null) {
        organization_marker_manager.clearMarkers();
        organization_marker_manager.refresh();
    }
	
	currentFixedOrganizations = new Array();
	currentOrganizations = new Array();
	currentFixedType = null;
	currentType = null; 

	
	map.closeInfoWindow();
    
    // Unchecking checkboxes and changing main sector classes
    jQuery('#menuPlaceholder input:checked').attr('checked', false);
    jQuery('.sectorLinkOn').addClass('sectorLink');
    jQuery('.sectorLinkOn').removeClass('sectorLinkOn');        
	jQuery('#currently_viewing').html('Currently Viewing:');  
    
    // Hiding search result text
    jQuery('#search_text').html('');
    jQuery('#search_text').hide();
        
}

function actb_subset_response(jsonData) {
    bObj.removeScriptTag(); 
    bObj = null;
    var keywordArray = new Array();
    
    for(var i=0;i<jsonData.ResultSet.length;i++) {
        keywordArray[i] = jsonData.ResultSet[i].Name;
    }
    objSearch.actb_keywords = keywordArray;
}

function getMarkerLocationsFromSearch() {  
    if ($('tb').value != null && $('tb').value != '' && $('tb').value != 'Keyword') {  	
        jQuery.post('/en/services/stats.aspx', { stattype: 'AddMapSearch', values: 'search=' + $('tb').value });
		currentSearch = $('tb').value; 
		initialSearch=true;
        handleRequest({marker_type:"SEARCH",request_type:"LOAD_MARKERS", param_1: currentSearch});		
    }
}

function extractValues(sCommandLine, sParameter){
	var iPosition, iStartPosition, iEndPosition;
	iPosition = sCommandLine.indexOf(sParameter);
	if (iPosition != -1){
		iStartPosition = iPosition + sParameter.length;
		iEndPosition = sCommandLine.indexOf("&",iStartPosition);
		if (iEndPosition == -1)
			iEndPosition = sCommandLine.length;
		return sCommandLine.substring(iStartPosition, iEndPosition);
	}	
}	