/* Declaring valid date character, minimum year and maximum year */
var dtCh= "-";
var minYear=2006;
var maxYear=2006;

$.googleMap = {
	maps: {},
	passJson: function(m) {		
		$.googleMap.maps["the_map"].clearOverlays();
		$('#loading_text').empty().html('Loading......');
		if (!m) {
				$('#loading_text').empty().html('No data was passed?');
		}
		else {
			$.getJSON(m, loadJson);//end get json			
		}//end if
	},
	mapNum: 1
};
$.fn.googleMap = function(lat, lng, zoom, options) {

	// If we aren't supported, we're done
	if (!window.GBrowserIsCompatible || !GBrowserIsCompatible()) return this;

	// Default values make for easy debugging
	if (lat == null) lat = 27.946609;
	if (lng == null) lng = -82.458366;
	if (!zoom) zoom = 6;

	// Sanitize options
	if (!options || typeof options != 'object')	options = {};
	options.mapOptions = options.mapOptions || {};
	options.setup = options.setup || [];
	options.controls = options.controls || {};

	// Map all our elements
	return this.each(function() {
		// Make sure we have a valid id
		if (!this.id) this.id = "gMap" + $.googleMap.mapNum++;
		// Create a map and a shortcut to it at the same time
		var map = $.googleMap.maps[this.id] = new GMap2(this, options.mapOptions);
		// Center and zoom the map
       	map.setCenter(new GLatLng(lat, lng), zoom);
       	// Add controls to our map
       	for (var i = 0; i < options.controls.length; i++) {
	       	var c = options.controls[i];
	       	eval("map.addControl(new " + c + "());");
       	}
       	// If we have markers, put them on the map
       	if (options.passJson[0]){
       		$.googleMap.passJson(options.passJson[0])
       	}
       	$.googleMap.zoomMax = options.setup[1];
       	$.googleMap.zoomMin = options.setup[0];

				GEvent.addListener(map,"movestart",function() {});
				GEvent.addListener(map, "moveend", function() {
					$.googleMap.Bounds = $.googleMap.maps["the_map"].getBounds();
					$.googleMap.SouthWest = $.googleMap.maps["the_map"].getBounds().getSouthWest();
					$.googleMap.NorthEast = $.googleMap.maps["the_map"].getBounds().getNorthEast();
					$.googleMap.newZoom = $.googleMap.maps["the_map"].getZoom();

					if ($.googleMap.encodedPolyline){
						if ($.googleMap.newZoom > 10){
							 $.googleMap.maps["the_map"].removeOverlay($.googleMap.encodedPolyline);     
						}else{
							 $.googleMap.maps["the_map"].addOverlay($.googleMap.encodedPolyline);     
						}
					}
					if ($.googleMap.newZoom < $.googleMap.zoomMin){
						$.googleMap.maps["the_map"].setZoom($.googleMap.zoomMin);
					}
					if ($.googleMap.newZoom > $.googleMap.zoomMax){
						$.googleMap.maps["the_map"].setZoom($.googleMap.zoomMax);
					}
				});
    });
};

//regular JavaScript function
function showmapnav(){
	$('#jqmLegend').jqm().jqmShow();
}
function hidemapnav(){
	$('#jqmLegend').jqm().jqmHide();
}


function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        /* Check that current character is number. */
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    /* All characters are numbers. */
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    /* Search through string's characters one by one. */
    /* If character is not in bag, append to returnString. */
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	/* February has 29 days in any year evenly divisible by four, */
    /* EXCEPT for centurial years which are not also divisible by 400. */
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12);	
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strYear=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strDay=dtStr.substring(pos2+1);	
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (!pos1==4 || pos2==-1){
		$('#loading_text').empty().html('The date format should be : yyyy-mm-dd');
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		$('#loading_text').empty().html('Please enter a valid date.');
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		$('#loading_text').empty().html('Please enter a valid date.');
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		$('#loading_text').empty().html('Please enter a valid 4 digit year between '+minYear+' and '+maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		$('#loading_text').empty().html('Please enter a valid date.');
		return false;
	}
return true;
}

function ServiceRequest(formId) {
    var form_ref = document.getElementById(formId); 
		var primary_crime_type_id = form_ref.primary_crime_type_id.value;
		var county_id = form_ref.county_id.value;
		var county_zip = form_ref.county_zip.value;
		var crime_date_min = form_ref.crime_date_min.value;
		var crime_date_max = form_ref.crime_date_max.value;
    if (county_zip != '') {
        zip_or_county = county_zip;
    }
    else if (county_zip == '' && county_id != 0) {
        zip_or_county = county_id;
    }
    else {
        $('#loading_text').empty().html('Please select a county or enter a zip.');
        return false;
    }
	if (isDate(crime_date_min)== false){
        return false;
	}	
	if (isDate( crime_date_max)==false){
        return false;
	}
		addItem(primary_crime_type_id,zip_or_county ,crime_date_min,crime_date_max);
    $('#jqmHelp').jqm().jqmHide();    
    var url = "/crime/data/" + primary_crime_type_id + "/" + zip_or_county + "/" + crime_date_min + "/" + crime_date_max + "/";
    $.googleMap.passJson(url);
}


// Create our marker icon	  
function makeIcon (myicon) {
	if (!myicon){		
		myicon ="http://media.tbo.com/assets/_shared/map/point1.png";
	}
	var baseIcon = new GIcon();
	baseIcon.iconSize=new GSize(16,16);
	baseIcon.iconAnchor=new GPoint(16,16);	
	baseIcon.infoWindowAnchor=new GPoint(16,0);          
	var Newicon = new GIcon(baseIcon, myicon, null, "");
	return Newicon;	
}	

function loadJson(json){
	if(json.error){
		$('#loading_text').empty().html('No data avalible for this date range and Zip code');
		return;
	}
	 if ($.googleMap.encodedPolyline){
		$.googleMap.maps["the_map"].removeOverlay($.googleMap.encodedPolyline); 
	}
		
		
		$.googleMap.maps["the_map"].setCenter(new GLatLng(json.Center[0].lat, json.Center[0].lng), parseInt(json.Center[0].zoom));	
		$.each(json.crimes, function(i,item){					
			var _icon = makeIcon (item.icon);
			var point = new GLatLng(item.latitude , item.longitude); 
			var marker = new GMarker(point, {icon:_icon, title:item.address});
			var infoTabs = [];							
				$.each(item.details, function(j,item2){
					// Our info window content
					if (item.details.length < 2){						
						var tempBody ='<div id="info-map"><div class="title">'+item2.crime_type +'</div><div class="street">'+item.address+ '<br> '+ item.city+ ', '+ item.state+ ' '+item.zip +' '+ item.county+'</div><div class="date">Date: '+item2.date+'</div><div class="zoom"><a href="'+ item2.url+'">More Details</a></div></div>';
					}else{
						var tempBody ='<div id="info-map"><div class="street">'+item.address+ '<br> '+ item.city+ ', '+ item.state+ ' '+item.zip +' '+ item.county+'</div><div class="date">Date: '+item2.date+'</div><div class="zoom"><a href="'+ item2.url+'">More Details</a></div></div>';
					}
					infoTabs.push( new GInfoWindowTab(item2.crime_type, tempBody));

				});
			GEvent.addListener(marker, "click", function() {
			  marker.openInfoWindowTabsHtml(infoTabs);
			});//end listener
			$.googleMap.maps["the_map"].addOverlay(marker);
		});//end each
			
		if(json.crimes.length >= 100){
			$('#loading_text').empty().html('More than 100 Service calls were found -- only the latest 100 are displayed.');
		}else{
			$('#loading_text').empty().html(json.crimes.length+' Service calls found.');
		}//end length loding
		
		if(json.Boundry){
			timObject = {
				polylines : [],
				fill: true,
				color: "#0000ff",
				opacity: 0.3,
				outline: true
			};

			var tempBoundry = new Object();
				$.each(json.Boundry, function(j,item){
					console.log(item.bdry);
				 						
						tempBoundry = {points: item.bdry,levels: item.level,color: "#0000ff", opacity: 0.4,weight: 1,numLevels: 4,zoomFactor: 32}
						timObject.polylines.push(tempBoundry);
				});
				console.log(timObject); 	
					
        $.googleMap.encodedPolyline  = new GPolygon.fromEncoded(timObject);
        $.googleMap.maps["the_map"].addOverlay($.googleMap.encodedPolyline );
		}
}

	function addItem(primary_crime_type_id,zip_or_county ,crime_date_min,crime_date_max ) { 		
			 s_pageName='|' + location.pathname + ' - ' + window.document.title + ' - ' + primary_crime_type_id + ' - ' +  zip_or_county +  '|'; 
			 s_prop9='|TBO|-|' + window.document.title  + ' - ' + primary_crime_type_id + ' - ' +  zip_or_county + '|';    

			 setSiteImg();
	}//end Function
	function setSiteImg()
			 {
			 var s_wd=window,s_tm=new Date;if(s_code!=' '){s_code=s_dc('mgtbo');
			 if(s_code)document.write(s_code)}else
			 var sitcatDIV = document.getElementById("sitcat");
			 var sitcatimg =('<im'+'g src="http://mgtbo.112.2O7.net/b/ss/mgtbo/1/F.3-fb/s'+s_tm.getTime()+'?[AQB]'
			 +'&pageName='+escape(s_wd.s_pageName?s_wd.s_pageName:(s_wd.pageName?s_wd.pageName:''))
			 +'&server='+escape(s_wd.s_server?s_wd.s_server:(s_wd.server?s_wd.server:''))
			 +'&ch='+escape(s_wd.s_channel?s_wd.s_channel:(s_wd.channel?s_wd.channel:''))
			 +'&[AQE]" height="1" width="1" border="0" />');              
			 //helpContent.innerHTML = sitcatimg;
			 $('#helpContent').empty().html(sitcatimg);
	}//end Function

