var courses=[];
var regions=[];
var calInit=false;
var map;
var geocoder=null;
var mapCenter;
var mapBounds;
var mapMarkers = {};
var visibleInfoWindow = null;
var ne;
var sw;
var mapMarkers=[];
var overlay;
var temp={};

//Maps
//COURSE VIEWING
function initBasic(){
	if(mapCenter){
		defineAllMarkers();
		var latlng = mapCenter.split(",");
		var myLatlng = new google.maps.LatLng(latlng[0],latlng[1]);
		var myOptions = {
			zoom: 10,
			center: myLatlng,
			scrollwheel: false,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			mapTypeControl:false
			
		};
		
		map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
		marker = smallMarker(latlng[0],latlng[1],'blue',$('#address').html() );
	}
}

//REGION EDITING
function initKeyDrag(){
	defineAllMarkers();
	var latlng = mapCenter.split(",");
	var myLatlng = new google.maps.LatLng(latlng[0],latlng[1]);
	var myOptions = {
		zoom: 12,
		center: myLatlng,
		scrollwheel: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
	map.enableKeyDragZoom();
	//temp = smallMarker(latlng[0],latlng[1],'blue','Lat = '+latlng[0]+'<br/>Long = '+latlng[1]);
}

function zoomBounds(bounds){
	if(map){
		map.fitBounds(bounds); 
		overlay = new ProjectedOverlay(map,'/img/maps/square1.png', bounds, {percentOpacity:40}) ;
	}
}

function overlayRegions(){
	for (var i in regions){
		bounds = new google.maps.LatLngBounds(
			new google.maps.LatLng(regions[i].south, regions[i].west),
			new google.maps.LatLng(regions[i].north, regions[i].east)
		);
		regions[i].overlay = new ProjectedOverlay(map,'/img/maps/square'+Math.floor(Math.random()*3+1)+'.png', bounds, {percentOpacity:40});
	}
}

function overlayCourses(){
	for (var i in courses){
		courses[i].marker = smallMarker(courses[i].latitude, courses[i].longitude, (courses[i].assigned == true ? 'green' : 'red'), courses[i].name )
	}
}

//COURSE EDITING
function initRefiner(){
	defineAllMarkers();
	var latlng = mapCenter.split(",");
	var myLatlng = new google.maps.LatLng(latlng[0],latlng[1]);
	var myOptions = {
		zoom: 14,
		center: myLatlng,
		scrollwheel: false,
		mapTypeId: google.maps.MapTypeId.HYBRID
	};
	
	map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
	geocoder = new google.maps.Geocoder();
	temp = smallMarker(latlng[0],latlng[1],'blue','Lat = '+latlng[0]+'<br/>Long = '+latlng[1]);
}

function refineAddress(address){
	//var address = document.getElementById("address").value;
	temp.marker.setMap(null);
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
            map.setCenter(results[0].geometry.location);
			var center = map.getCenter();
			var button = '<input type="button" value="Apply" onclick="useTempCord();"/>';
			temp.infoWindow = new google.maps.InfoWindow({content: "Coordinate:<br/>"+center.lat().toString()+", "+center.lng().toString()+"<br/>(draggable)<br/>"+button, size: new google.maps.Size(200, 50)});
            temp.marker = new google.maps.Marker({
                map: map, 
                position: results[0].geometry.location,
				draggable: true,
				clickable: true
            });
			google.maps.event.addListener(temp.marker, 'click', function(){openInfoWindow(temp.infoWindow, temp.marker)});
			google.maps.event.addListener(temp.marker, 'dragend', function(){updateTempMarker()});

			openInfoWindow(temp.infoWindow, temp.marker);
          } else {
            alert("Could not find the specified address");
          }
        } else {
          alert("Geocode was not successful");
        }
      });
    }
}

function searchAddress(address){
	//var address = document.getElementById("address").value;
	if(temp.marker) temp.marker.setMap(null);
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
            map.setCenter(results[0].geometry.location);
            map.setZoom(10);
			var center = map.getCenter();
			temp.infoWindow = new google.maps.InfoWindow({content: address, size: new google.maps.Size(200, 50)});
            temp.marker = new google.maps.Marker({
                map: map, 
                position: results[0].geometry.location,
				draggable: false,
				clickable: true
            });
			google.maps.event.addListener(temp.marker, 'click', function(){openInfoWindow(temp.infoWindow, temp.marker)});
			openInfoWindow(temp.infoWindow, temp.marker);
			if($('#courseList').length>0){
				$('#loader').fadeIn();
				getInBounds();
			}
          } else {
            alert("Could not find the specified address");
          }
        } else {
          alert("Geocode was not successful");
        }
      });
    }
}

//FOR COURSE EDITOR
function testAddress(src){
	switch(src){
		case 'finder':
			address = $('#addressFinder').val();
			break;
		case 'fields':
			address = $('#GolfCourseAddress').val() +', '+ $('#GolfCourseCity').val() +' '+ $('#GolfCourseState').val() +','+ $('#GolfCourseZip').val();
			break;
	}
	if(address !=''){
		refineAddress(address);
	} else {
		alert('Address field is empty or doesn\'t exist');
	}
}

function useTempCord(){
	center = temp.marker.getPosition();
	$('#GolfCourseLatitude').val(center.lat().toString());
	$('#GolfCourseLongitude').val(center.lng().toString());
}

function updateTempMarker(){
	center = temp.marker.getPosition();
	button = '<input type="button" value="Apply" onclick="useTempCord();"/>';
	temp.infoWindow = new google.maps.InfoWindow({content: "Coordinate:<br/>"+center.lat().toString()+", "+center.lng().toString()+"<br/>"+button, size: new google.maps.Size(200, 50)});
	openInfoWindow(temp.infoWindow, temp.marker);
}

//MAIN FINDER
function initFinder(){
	//load marker shapes
	defineAllMarkers();
	
	//MAP PARAMETERS
	var latlng = mapCenter.split(",");
	var myLatlng = new google.maps.LatLng(latlng[0],latlng[1]);
    var myOptions = {
      zoom: 9,
      center: myLatlng,
      scrollwheel: false,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
	
	google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
		getInBounds();
	});
	google.maps.event.addListener(map, 'dragend', function() {
		$('#loader').fadeIn();
		getInBounds();
	});
	google.maps.event.addListener(map, 'zoom_changed', function() {
		$('#loader').fadeIn();
		getInBounds();
	});
	geocoder = new google.maps.Geocoder();
}

function getInBounds(){
	mapBounds = map.getBounds();
	ne = mapBounds.getNorthEast().toUrlValue();
	sw = mapBounds.getSouthWest().toUrlValue();
	zoom = map.getZoom();
	//$('#footer').html(ne+" "+sw);
	$.ajax({
		type: "POST",
		data: {"ne":ne,"sw":sw,"zoom":zoom},
		dataType: "json",
		url: '/golf_courses/coursemap/', 
		success: function(R){
			parseCourses(R);
		},
		error: function(XHR,e){
			$('#loader').html('Err');
		}
	});
}

function parseCourses(arr){
	$('.mapListRow').hide();
	
	var old = courses;
	courses=[];
	
	var tempMarker;
	var orderArray = [];
	var idArray = [];
	for(var i in arr){
		switch(arr[i].type){
			case 'public':
				tempMarker = mapMarkers['publicDot'];
				break;
			case 'private':
				tempMarker = mapMarkers['privateDot'];
				break;
			case 'municipal':
				tempMarker = mapMarkers['municipalDot'];
				break;
			default:
				tempMarker = mapMarkers['unregDot'];
				break;
		}
		if(old[arr[i].id] != undefined){
			courses[arr[i].id] = old[arr[i].id];
		} else {	
			if(arr[i].mark)
				courses[arr[i].id] = dotMarker(arr[i].lat , arr[i].lng, tempMarker, $('#courseInfo_'+arr[i].id).html());
		}
		//$('#course_'+arr[i].id).fadeIn();
		orderArray.push($('#course_'+arr[i].id).parent().clone());
		idArray.push(arr[i].id);
		$('#course_'+arr[i].id).parent().remove();
	}
	for (i=0;i<orderArray.length;i++){
		$('#courseList').append(orderArray[i]);
		$('#course_'+idArray[i]).show();
	}
	$('#loader').fadeOut();
}

function showCourse(id){
	openInfoWindow(courses[id].infoWindow, courses[id].marker);
}

// MAP MARKERS
function defineAllMarkers(){
	//finder
	mapMarkers['publicDot'] = new google.maps.MarkerImage('/img/css/publicDot.png',
		  new google.maps.Size(20, 20),
		  new google.maps.Point(0,0),
		  new google.maps.Point(10, 10));
	mapMarkers['privateDot']  = new google.maps.MarkerImage('/img/css/privateDot.png',
		  new google.maps.Size(20, 20),
		  new google.maps.Point(0,0),
		  new google.maps.Point(10, 10));
	mapMarkers['municipalDot']  = new google.maps.MarkerImage('/img/css/municipalDot.png',
		  new google.maps.Size(20, 20),
		  new google.maps.Point(0,0),
		  new google.maps.Point(10, 10));
	mapMarkers['unregDot']  = new google.maps.MarkerImage('/img/css/unregDot.png',
		  new google.maps.Size(20, 20),
		  new google.maps.Point(0,0),
		  new google.maps.Point(10, 10));
	//shadow for dots
	mapMarkers['dotshadow']  = new google.maps.MarkerImage('/img/css/dotshadow.png',
		  new google.maps.Size(12, 10),
		  new google.maps.Point(0,0),
		  new google.maps.Point(0, 0));
	//shape for dots
	mapMarkers['dotshape']  = {coord: [0, 0, 20, 0, 20, 20, 0 , 20],type: 'poly'};
		  
	//small markers
	mapMarkers['smallblue']  = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_blue.png',
		  // This marker is 20 pixels wide by 32 pixels tall.
		  new google.maps.Size(12, 20),
		  // The origin for this image is 0,0.
		  new google.maps.Point(0,0),
		  // The anchor for this image is the base of the marker
		  new google.maps.Point(6, 20));
	mapMarkers['smallred']  = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_red.png',
		  new google.maps.Size(12, 20),
		  new google.maps.Point(0,0),
		  new google.maps.Point(6, 20));
	mapMarkers['smallgreen']  = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_green.png',
		  new google.maps.Size(12, 20),
		  new google.maps.Point(0,0),
		  new google.maps.Point(6, 20));
	mapMarkers['smallshadow']  = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_shadow.png',
		  // The shadow image is larger in the horizontal dimension
		  // while the position and offset are the same as for the main image.
		  new google.maps.Size(22, 20),
		  new google.maps.Point(0,0),
		  new google.maps.Point(5, 20));
		  // Shapes define the clickable region of the icon.
		  // The type defines an HTML &lt;area&gt; element 'poly' which
		  // traces out a polygon as a series of X,Y points. The final
		  // coordinate closes the poly by connecting to the first
		  // coordinate.
	mapMarkers['smallshape']  = { coord: [0, 0, 12, 0, 12, 20, 0, 20], type: 'poly'	};
}

function dotMarker(lat,lng,mark,info){
	if(lat && lng){
		var myLatlng = new google.maps.LatLng(lat,lng);
		var infoWindow = new google.maps.InfoWindow({content: info, size: new google.maps.Size(200, 150)});
		var marker = new google.maps.Marker({
	        position: myLatlng,
	        map: map,
	        icon: mark,
	        shadow: mapMarkers['dotshadow'],
	        shape: mapMarkers['dotshape']
	    });
		google.maps.event.addListener(marker, 'click', function(){openInfoWindow(infoWindow, marker)});
		return { marker:marker, infoWindow:infoWindow };
	} 
	return false;
}

function smallMarker(lat,lng,color,info,options){
	if(lat && lng){
		var myLatlng = new google.maps.LatLng(lat,lng);
		var infoWindow = new google.maps.InfoWindow({content: info, size: new google.maps.Size(200, 25)});
		var marker = new google.maps.Marker({
	        position: myLatlng,
	        map: map,
	        icon: mapMarkers['small'+color],
	        shadow: mapMarkers['smallshadow'],
	        shape: mapMarkers['smallshape']
	    });
		google.maps.event.addListener(marker, 'click', function(){openInfoWindow(infoWindow, marker)});
		return { marker:marker, infoWindow:infoWindow };
	} 
	return false;
}

//INFOWINDOWS V3
function openInfoWindow(infoWindow, marker){
	if (visibleInfoWindow) {
		visibleInfoWindow.close();
	}
	if(visibleInfoWindow != infoWindow){
		infoWindow.open(map, marker);
		visibleInfoWindow = infoWindow;
	} else {
		visibleInfoWindow = null;
	}
}

//FOR KEYDRAGZOOM
function captureBox(bnds){
	var sw = bnds.getSouthWest();
	var ne = bnds.getNorthEast();
	
	if($("#RegionEditForm").length > 0){ // REGION EDITOR PAGE
		$('#RegionNorth').val(ne.lat());
		$('#RegionEast').val(ne.lng());
		$('#RegionSouth').val(sw.lat());
		$('#RegionWest').val(sw.lng());
		if(temp){
			if(temp.overlay) temp.overlay.remove();
			if(temp.marker)  temp.marker.setMap(null);
		}
		temp = smallMarker((sw.lat()+ne.lat())/2,(sw.lng()+ne.lng())/2,'blue','<b>New Center</b>');
		temp.overlay = new ProjectedOverlay(map,'/img/maps/square'+Math.floor(Math.random()*3+1)+'.png', bnds, {percentOpacity:40});
		zoomBounds(bnds);
	} else { // GENERAL REGIONS PAGE
		if(temp){
			if(temp.overlay) temp.overlay.remove();
			if(temp.marker) temp.marker.setMap(null);
		}
		temp={};
		//temp = smallMarker((sw.lat()+ne.lat())/2, (sw.lng()+ne.lng())/2, 'blue', 'New Region: ,true);
		temp.overlay = new ProjectedOverlay(map,'/img/maps/square'+Math.floor(Math.random()*3+1)+'.png', bnds, {percentOpacity:40});
		$('#RegionNorth').val(ne.lat());
		$('#RegionEast').val(ne.lng());
		$('#RegionSouth').val(sw.lat());
		$('#RegionWest').val(sw.lng());
	}
}


//FORMATTING
//equalize div heights
function equalCols(animate){
	var maxheight=0;
	$('.height').each(function(){
		if($(this).height() > maxheight) maxheight = $(this).height();
	});
	if(animate){
		$('.height').animate({height: maxheight},1000);
	} else {
		$('.height').css({height: maxheight});
	}
}
function enableExpanders(){
	$('.expand').click(function(){
		$(this).hide();
		$(this).next('.collapse').show();
		$(this).parent().next('.detail').slideDown('fast');
	});
	$('.collapse').click(function(){
		$(this).hide();
		$(this).prev('.expand').show();
		$(this).parent().next('.detail').slideUp('fast');
	});
}
$(document).ready(function(){
	setTimeout('equalCols(true)',500);
});
//group collapsing
$(document).ready(function(){
	$('.groupHead')
		.hover(function(){
			$(this).css({cursor:"pointer"});
		})
		.click(function(){
			$('.height').css({height:""});
			$(this).next('tr,div').find('.groupContents').slideToggle('fast');
		});
		
	enableExpanders();
});
//datepickers
$(document).ready(function(){
	$('.datepicker').datepicker({ dateFormat: 'mm/dd/yy',showOn:'both',buttonImage:'/img/datepicker.png', buttonImageOnly: true});
});
//dialogs
$(document).ready(function(){
	$('.dialog').dialog({
		title: false,
		autoOpen: false,
		width: 800,
		modal: true,
		buttons: {
			Close: function(){$(this).dialog('close');}
		},
		close: function(){}
	});
});


function focusTextInput(item,value) {
	if ($(item).val() == value) {
		$(item).val("");
	}
	$(item).removeClass("greyed");
}

function blurTextInput(item,value) {
	if($(item).val() == "" || $(item).val() == value) {
		$(item).val(value);
		$(item).addClass("greyed");
	}
}

//FORMS
function updateUnForecasted(){
	date = $('#ForecastFdate').val();
	$('#selectionsHolder').fadeOut();
	$.ajax({
		type: "POST",
		data: {"date":date},
		url: '/forecasts/forecast_selections', 
		success: function(R){
			$('#selectionsHolder').html(R).fadeIn();
		},
		error: function(XHR,e){
			$('#selectionsHolder').html(e).fadeIn();
		}
	});
}

function duplicateFields(src,target,nolabel){
	
	if($(src).hasClass('inputGroup')){
		block = $(src).clone(true);
	} else {
		block = $(src).find('.inputGroup:first').clone(true);
	}
	
	block.children(':input').each(function(){
		$(this).attr("id","");
		newname = $(this).attr("name");
		newname = newname.replace(/\[([0-9])*\]/g,"[]");
		$(this).attr("name", newname);
	});
	
	block.css({display:'none'});
	block.find('.multiRemove:first').css({display:"inline"});
	block.find('.multiAdd:first').css({display:"none"});
	$(target).append(block);
	if(nolabel){
		$(target).find('.inputGroup:last').find('label').hide();
	}
	$(target).find('.inputGroup:last').slideDown(200);
	//block.slideDown();
}

function removeElem(item){
	$(item).fadeOut(300,function(){$(item).remove()});
}

function getIconPreviews(){
	//$('.iconPreview img').fadeOut();
	$('.iconSelect').each(function(){
		icon = '<img src="/img/forecast/'+$(this).val()+'.jpg" alt="IconNotFound" style="height:60px;"/>';
		$(this).parent().parent().find('.iconPreview').html(icon);
	});
	//$('.iconPreview img').fadeIn();
}

//TAB VIEWING
function changeTab(tab) {
	if( !$(tab).hasClass('current') ){
		$('#loader').fadeIn('fast');
		$('#mainContentTabs a.current').removeClass('current');
		$(tab).addClass('current');
		
		if($('#mainContent div.content:visible').length>0){
			$('#mainContent div.content:visible').fadeOut(500,function(){
				$('#'+$(tab).attr("id")+"Content").fadeIn(500,function(){
					
					
					$('#loader').fadeOut('fast');
					
					if($(tab).attr("id")=='information' && !map){
						//course viewer only
						initBasic();
					} else if($(tab).attr("id")=='events' && !calInit){
						var events = [];
						$.jMonthCalendar.Initialize(calendarOptions, events);
						refreshEventsCalendar();
						calInit = true;
					}
					$('#centerColumn').css({height:""});
					equalCols();
				});
			});
		} else {
			$('#'+$(tab).attr("id")+"Content").fadeIn(500,function(){
				$('#loader').fadeOut('fast');
				
				if($(tab).attr("id")=='information' && !map){
					//course viewer only
					initBasic();
				} else if($(tab).attr("id")=='events' && !calInit){
					var events = [];
					$.jMonthCalendar.Initialize(calendarOptions, events);
					refreshEventsCalendar();
					calInit = true;
				}
				$('#centerColumn').css({height:""});
				equalCols();
			});
		}
		
	}
}

//EVENTS 
function checkStartAndEndDates() {
	var start = $('#GolfEventSDate');
	var end = $('#GolfEventEDate')
	if(start.val() == "" && end.val() == "") {
		
	} else {
		if (start.val() == "") {
			start.val(end.val());
		} else if(end.val() == "") {
			end.val(start.val());
		} else if(end.val() < start.val()) {
			start.val(end.val());
		}
	}
}

function setStartAndEndDates(date){
	var d = new Date(date);
	//d = date;
	format = (d.getMonth()+1) + '/' + d.getDate() +'/'+ d.getFullYear();
	$('#addEvent').slideDown();
	$('#GolfEventSDate').val(format);
	$('#GolfEventEDate').val(format);
	return false; 
}

function submitEvent(){
	checkStartAndEndDates();
	if($('#GolfEventTitle').val() != ''){
		$('#loader').fadeIn();
		var serial = $('#GolfEventAddForm').serialize().replace(/%5B/g, '[').replace(/%5D/g, ']');
		$.ajax({
			type: "POST",
			data: serial,
			url: '/golf_events/add', 
			success: function(R){
				$('#GolfEventAddForm').clearForm();
				$('#addEvent').slideUp();
				refreshEventsCalendar($('#GolfEventSDate').val());
			},
			error: function(XHR,e){
				$('#addEvent').append('<div class="soft">Error Saving Event:</div>');
				$('#loader').fadeOut();
			}
		});
	} else {
		alert('Event needs a title.');
	}
}

function refreshEventsCalendar(date){
	$('#loader').fadeIn();
	$.ajax({
		type: "POST",
		data: {date: date},
		url: '/golf_events/refresh/'+course_id, 
		success: function(R){
			$('#eventList').html(R);
			$('#loader').fadeOut();			
			$('#centerColumn').css({height:""});
		},
		error: function(XHR,e){
			$('#eventList').html(e);
			$('#loader').fadeOut();
		}
	});
}

function ajaxLoad(item, target){
	$('#loader').fadeIn();
	$.ajax({
		type: "POST",
		beforeSend: function(xhr){
			xhr.setRequestHeader( 'Content-type', 'text/plain');
		}, 
		url: $(item).attr("href"), 
		success: function(R){
			$(target).html(R);
			$('#loader').fadeOut();			
			$('#centerColumn').css({height:""});
		},
		error: function(XHR,e){
			$(target).html(e);
			$('#loader').fadeOut();
		}
	});
}

function removeEvent(item){
	if(confirm('Do you really want to delete this event?')){
		$('#loader').fadeIn();
		$.ajax({
			type: "POST",
			url: $(item).attr("href")+'/'+$(item).attr("id"), 
			beforeSend: function(xhr){
				xhr.setRequestHeader( 'Content-type', 'text/plain');
			},
			success: function(R){
				refreshEventsCalendar();
			},
			error: function(XHR,e){
				$('#loader').fadeOut();
			}
		});
	}
}

//JQUERY Additional functions
$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase(), name=this.name;
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox')
      this.checked = false;
    else if (tag == 'select' && name != 'customer_country')
      this.selectedIndex = '';
  });
};