// JavaScript Document

// Debug Logger Variables
// Create the logger
var log = log4javascript.getLogger(); 

// Create a PopUpAppender with default options
var popUpAppender = new log4javascript.PopUpAppender();

// Change the desired configuration options
popUpAppender.setFocusPopUp(true);
popUpAppender.setNewestMessageAtTop(true);

// Add the appender to the logger
//log.addAppender(popUpAppender);

var ajaxAppender = new log4javascript.AjaxAppender('log4js_ajax_mysql.php');
log.addAppender(ajaxAppender);


// Map Variables
var map = null;
var initLong = 0; // These values should be set by the PHP script when loading the map
var initLat = 0; // Also set by the PHP when loading the map
var initZoom = 8;
var layerObj = function() { this.layers = 0; }
var myLayers = new layerObj();
var feature, popup;

var curLatLon;
var searchOn = 0;
var emailOn = 0;
var bioOn = 0;
var jumpLocation;
var jumpIndex;
var linkReports;
var linkArticles;
var linkPhotos;
// This is for the set point function
var markersLayer = new OpenLayers.Layer.Markers("Report Marker");

//------------------------------------------------------
// --- AJAX Request ------------------------------------
//------------------------------------------------------

// Function: ajaxRequest(str, str, str)
// Returns: nothing
// Description: Executes javascript from ./map/map.php

function ajaxRequest(action, value, error){
	new Ajax.Request('./map/map.php?action='+action+'&value='+value,
		{
			method:'get',
			onSuccess: function(transport)
			{
				// If success run javascript from map.php
			},
			onFailure: function(){
				log.debug(error);
			}
		});
}

//------------------------------------------------------
// --- Big Map -----------------------------------------
//------------------------------------------------------

// Function: bigMap(int, int, float, float)
// Returns: nothing
// Description: Displays big map with initial regions or poi

function bigMap(rootPoint, initZoom, initLat, initLong){
	var extent = new OpenLayers.Bounds(-93,28,-85,35);
	var edges = new OpenLayers.Bounds(-91.3,28.4,-88.2,30.5);	

	var options = {
		resolutions: [0.0038, 0.0023, 0.0014, 0.000575, 0.0002875, 0.00014375],
		numZoomLevels:6,
		//minResolution: 0.000075,
		//minExtent: new OpenLayers.Bounds(-0.5, -0.5, 0.5, 0.5), 
		//maxResolution: 0.0046,
		//maxExtent: extent,
		restrictedExtent: edges
	};
	
	map = new OpenLayers.Map( 'map', options );

	// This connects to the map server on NextSailor for the sat view
	//var ol_satview = new OpenLayers.Layer.WMS("Satellite View","http://www.nextsailor.com:8080/satview/wmscache.php",{layers:'global_mosaic'});
	var ol_satview = new OpenLayers.Layer.KaMap("Satellite View", "http://www.nextsailor.com:8080/kamap/tile.php?", {'g':'__base__', 'map': 'satview','i':'png24'});
	// Adds sat overlay
	map.addLayer(ol_satview);

	// This connects to the map server on NextSailor for the NOAA chart
	var ol_mapserv = new OpenLayers.Layer.KaMap("Chart", "http://www.nextsailor.com:8080/kamap/tile.php?", {'g':'__base__', 'map': 'gmap','i':'png24'});
	// Sets initial visibility to 0
	ol_mapserv.setVisibility(0);
	// Adds main layer overlay
	map.addLayers([ol_mapserv]);
	
	// Adds all layers from the database
	ajaxRequest('addMapLayers', '', 'Error returning data from addMapLayers');
	
	// Adds controls to the map
	map.addControl(new OpenLayers.Control.LayerSwitcher());
	map.addControl(new OpenLayers.Control.ZoomBox());
	
	var options = {
      layers: [ol_mapserv.clone()],
      minRatio: 2,
      maxRatio: 28
    };
    var overview = new OpenLayers.Control.OverviewMap(options);
        
    map.addControl(overview);
	
	// Checks for inital lat/long
	if(initLong == 0 && initLat == 0) {
		// center the map to some default
		map.setCenter(new OpenLayers.LonLat(-89.7017, 29.695), 0);
	}
	else {
		map.setCenter(new OpenLayers.LonLat(initLong, initLat), initZoom);
	}
	if(rootPoint != "users" && jumpLocation != 1){
		new Ajax.Updater('mapHeader', './map/switchcontent/map_header_note.php', { method: 'get' });
		new Ajax.Updater('sideBar', './map/switchcontent/map_sidebar.php', { method: 'get' });
		if(showPaging == 1){
			new Ajax.Updater('reportAreaBody', './map/switchcontent/map_reports_paging.php', { method: 'get' });
		}
		else{
			new Ajax.Updater('reportAreaBody', './map/switchcontent/map_reports.php', { method: 'get' });
		}
		getRegions(rootPoint);
	}
}

function noMap(rootPoint, initZoom, initLat, initLong){
		new Ajax.Updater('videoArea', './video_display.php', { method: 'get' });
	if(rootPoint != "users" && jumpLocation != 1){
		new Ajax.Updater('mapHeader', './map/switchcontent/map_header_note.php', { method: 'get' });
		new Ajax.Updater('sideBar', './map/switchcontent/map_sidebar.php', { method: 'get' });
		if(showPaging == 1){
			new Ajax.Updater('reportAreaBody', './map/switchcontent/map_reports_paging.php', { method: 'get' });
		}
		else{
			new Ajax.Updater('reportAreaBody', './map/switchcontent/map_reports.php', { method: 'get' });
		}
		getRegions(rootPoint);
	}
}

//------------------------------------------------------
// --- Small Map ---------------------------------------
//------------------------------------------------------

// Function: bigMap(int, int, float, float)
// Feturns: nothing
// Description: Displays a small less functional map.

function smallMap(point, initZoom){
	var extent = new OpenLayers.Bounds(-93,28,-85,35);
	var edges = new OpenLayers.Bounds(-91.3,28.4,-88.2,30.5);	

	var options = { 
		minResolution: 0.0005,
		minExtent: new OpenLayers.Bounds(-1, -1, 1, 1), 
		maxResolution: 0.0046,
		maxExtent: extent,
		restrictedExtent: edges
	};
	
	map = new OpenLayers.Map( 'mapSmall', options );

	// This connects to the map server on NextSailor for the sat view
	var ol_satview = new OpenLayers.Layer.WMS("Satellite View","http://www.nextsailor.com:8080/satview/wmscache.php",{layers:'global_mosaic'});
	// Adds sat overlay
	map.addLayer(ol_satview);
	
	// Adds all layers from the database
	ajaxRequest('addMapLayers', '', 'Error returning data from addMapLayers');
		
	getPointById(point, initZoom);
}

//------------------------------------------------------
// --- New Point ---------------------------------------
//------------------------------------------------------

// Function: addMultiPoint(int, float, float, str, int, int, obj, int, int)
// Returns: nothing
// Description: Adds a new point to the map, adds point reference to layer, registers mouse events

function newPoint(id,long,lat,icon,width,height,thislayer,isRegion,isAdvertiser,zoom){
	//If no icon set, use default icon
	if(!icon){
		icon = './map/icons/icon_user.png';
	}
	//Setup icon details
	var iconSize =  new OpenLayers.Size(width,height);
	var iconOffset = new OpenLayers.Pixel(-(iconSize.w/2), -(iconSize.h-3));
	var marker = new OpenLayers.Marker(
		new OpenLayers.LonLat(long, lat),
		new OpenLayers.Icon(icon,iconSize,iconOffset)
	);
	
	//Give the marker properties
	marker.id = id;
	marker.long = long;
	marker.lat = lat;
	marker.zoom = zoom;
	marker.layer = thislayer;
	marker.isRegion = isRegion;
	marker.isAdvertiser = isAdvertiser;
	
	//Register marker events
	marker.events.register("mousedown", marker, regionZoom);
	if(isRegion != 1){
		marker.events.register("mousedown", marker, createPopup);
	}
	marker.events.register("mouseover", marker, markerMouseover);
	marker.events.register("mouseout", marker, markerMouseout);
	
	//Create titles for markers
	createTitles(marker);
	
	//Add marker to layer
	thislayer.addMarker(marker); // Add the new marker from the code above at the lat/long
	//marker.setOpacity(0.5);
}

//------------------------------------------------------
// --- Add Multiple Points -----------------------------
//------------------------------------------------------

// Function: addMultiPoint(array([id],[longitute],[latitude],[icon_source],[icon_width],[icon_height]))
// Feturns: nothing
// Description: Passes an array of points to newPoint().

function addMultiPoint(pointArray){
	for(i=0;i<pointArray.length;i++){
		newPoint(pointArray[i][0], pointArray[i][1], pointArray[i][2], pointArray[i][3], pointArray[i][4], pointArray[i][5], pointArray[i][6], pointArray[i][7],  pointArray[i][8], pointArray[i][9]);
	}
}

//------------------------------------------------------
// --- Get Points By ID ----------------------------
//------------------------------------------------------

// Event: getPointsById(int, int);
// Returns: nothing
// Description: Fetches one point where id = pointId and zooms to its location

function getPointById(pointId, zoom){
	ajaxRequest('getPointById', pointId, 'Error returning data from getPointById');
}

function getSinglePointById(pointId, zoom){
	ajaxRequest('clearMapMarkers', '', 'Error returning data from getPointById'); 
	ajaxRequest('getPointById', pointId, 'Error returning data from getPointById');
}

//------------------------------------------------------
// --- Get Points By Parent ----------------------------
//------------------------------------------------------

// Event: getPointsByParent(int);
// Returns: nothing
// Description: Gathers points from the db where parent = pointParent

function getReports(pointParent){
	ajaxRequest('getReports', pointParent, 'Error returning data from getPointsByParent');
}

function getUserReports(user){
	ajaxRequest('getUserReports', user, 'Error returning data from getPointsByParent');
}

function getAdvertisers(pointParent){
	ajaxRequest('getAdvertisers', pointParent, 'Error returning data from getPointsByParent');
}

function getRegions(){
	ajaxRequest('getRegions', 0, 'Error returning data from getPointsByParent');
}


//------------------------------------------------------
// --- Region Zoom -------------------------------------
//------------------------------------------------------

// Event: regionZoom(evt)
// Returns: nothing
// Description: center, zoom, and load regional information for evt.id

function regionZoom(evt){
	if(this.isRegion){
		var zoom;
		if(this.zoom > 0){
			zoom = this.zoom	
		}
		else{
			zoom = 3;
		}
		map.setCenter(new OpenLayers.LonLat(this.long, this.lat),zoom);
		getReports("0,7,"+this.id);
		getAdvertisers(this.id);
		this.layer.setVisibility(false);
		new Ajax.Updater('sideBar', './map/switchcontent/map_sidebar.php?region_id='+this.id, { method: 'get' });
		new Ajax.Updater('mapHeader', './map/switchcontent/map_header_tabs.php?region_id='+this.id, { method: 'get' });
		new Ajax.Updater('mapLocation', './map/switchcontent/map_location.php?region_id='+this.id, { method: 'get' });
		if(showPaging == 1){
			new Ajax.Updater('reportAreaBody', './map/switchcontent/map_reports_paging.php?region_id='+this.id, { method: 'get' });
		}
		else{
			new Ajax.Updater('reportAreaBody', './map/switchcontent/map_reports.php?region_id='+this.id, { method: 'get' });
		}
		if(jumpIndex == 1){
			new Ajax.Updater('indexGallery', '../phpsource/index_gallery.php?page=0&location='+this.id, { method: 'get' });	
			new Ajax.Updater('indexArticles', '../phpsource/index_articles.php?location='+this.id, { method: 'get' });	
		}
		var linkReports = document.getElementById("linkReports");
		linkReports.href = linkReports.href+'?location='+this.id;
		var linkArticles = document.getElementById("linkArticles");
		linkArticles.href = linkArticles.href+'?region='+this.id;
		var linkPhotos = document.getElementById("linkPhotos");
		linkPhotos.href = linkPhotos.href+'?region='+this.id;
	}
}

//------------------------------------------------------
// --- Marker Mouse Over -------------------------------
//------------------------------------------------------

// Event: markerMouseover(evt);
// Returns: nothing
// Description: On marker mouseover change curser to pointer

function markerMouseover(evt){
	document.body.style.cursor='pointer';
}

//------------------------------------------------------
// --- Marker Mouse Out --------------------------------
//------------------------------------------------------

// Event: markerMouseout(evt);
// Returns: nothing
// Description: On marker mouseout change curser to normal

function markerMouseout(evt){
	document.body.style.cursor='auto';
}

//------------------------------------------------------
// --- Create Titles -----------------------------------
//------------------------------------------------------

// Event: createTitles(evt);
// Returns: evt
// Description: Create title tag for Advertisers

function createTitles(evt){
	//Check to see if it's an advertiser
	if(evt.isAdvertiser == 1){
		
		//Setup title variables
		window["feature"+evt.id] = new OpenLayers.Feature(evt, new OpenLayers.LonLat(evt.long,evt.lat));
		window["myMarker2"+evt.id] = window["feature"+evt.id].createMarker();
		window["popup"+evt.id] = window["feature"+evt.id].createPopup(false);
		
		//Add title to map
		ajaxRequest('getTitle', evt.id, 'Error returning data from getTitle');
		
		//Setup title properties
		window["popup"+evt.id].setBackgroundColor("");
		window["popup"+evt.id].setOpacity(1);
		window["popup"+evt.id].setSize(new OpenLayers.Size(130,32));
		evt.layer.map.addPopup(window["popup"+evt.id]); 
	
       /*     window["popup"+evt.id] = new OpenLayers.Popup.Anchored("chicken", 
                                         new OpenLayers.LonLat(evt.long,evt.lat),
                                         new OpenLayers.Size(50,50),
                                         "example popup", true);
        
            evt.layer.map.addPopup(window["popup"+evt.id]); */
	}
}

//------------------------------------------------------
// --- Create Popups -----------------------------------
//------------------------------------------------------

// Event: createPopup(evt);
// Returns: evt
// Description: Create popup information for poi's.

function createPopup(evt){
	//Create Popup
	feature = new OpenLayers.Feature(this, new OpenLayers.LonLat(this.long,this.lat));
	myMarker = feature.createMarker();
	
	//Check to see if the popup is visible, if so remove it
	if (popup != null) {
		this.layer.map.removePopup(popup);
		popup.destroy();
		popup = null;
	}
	
	//If no current popup then create one.
	if (popup == null) {
		popup = feature.createPopup(true);
		//If this is advertiser, get advertiser popup
		if(this.isAdvertiser == 1){
			ajaxRequest('getAdvertiserInfo', this.id, 'Error returning data from getPointDescription');
		}
		else{
			//Else get report popup
			ajaxRequest('getReportInfo', this.id, 'Error returning data from getPointDescription');
		}
		//Setup popup properties
		popup.setBackgroundColor("white");
		popup.setOpacity(1);
		this.layer.map.addPopup(popup);
	} else {
		//Remove popup if available
		this.layer.map.removePopup(popup);
		popup.destroy();
		popup = null;
	}
    Event.stop(evt);
}

//------------------------------------------------------
// --- Show Search Box ---------------------------------
//------------------------------------------------------

// Function: showSearchBox();
// Returns: nothing
// Description: Displays the search box

function showSearchBox(user){
	if(searchOn == 1){
		new Ajax.Updater('searchReports', './map/switchcontent/map_search_reports.php?user='+user+'&search=0', { method: 'get' });
		searchOn = 0;
	}
	else{
		new Ajax.Updater('searchReports', './map/switchcontent/map_search_reports.php?user='+user+'&search=1', { method: 'get' });
		searchOn = 1;
	}
}

//------------------------------------------------------
// --- Search Reports ----------------------------------
//------------------------------------------------------

// Function: searchReports();
// Returns: nothing
// Description: Gathers reports from the databased based on search fields

function searchReports(){
	
	var validError = 0;
	
	//Validate fromMonth
	var fromMonth = document.getElementById('fromMonth').value;
	if(fromMonth == 'MM'){
		fromMonth = "";
	}
	else{
		if(fromMonth > '' && !Number(fromMonth) && fromMonth != 'MM'){
			var validError = 1;
		}
	}
	
	//Validate fromDay
	var fromDay = document.getElementById('fromDay').value;
	if(fromDay == 'DD'){
		fromDay = "";
	}
	else{
		if(fromDay > '' && !Number(fromDay) && fromDay != 'DD'){
			var validError = 1;
		}
	}
	
	//Validate fromYear
	var fromYear = document.getElementById('fromYear').value;
	if(fromYear == 'YYYY'){
		fromYear = "";
	}
	else{
		if(fromYear > '' && !Number(fromYear) && fromYear != 'YYYY'){
			var validError = 1;
		}
	}
	
	//Validate toMonth
	var toMonth = document.getElementById('toMonth').value;
	if(toMonth == 'MM'){
		toMonth = "";
	}
	else{
		if(toMonth > '' && !Number(toMonth) && toMonth != 'MM'){
			var validError = 1;
		}
	}
	
	//Validate toDay
	var toDay = document.getElementById('toDay').value;
	if(toDay == 'DD'){
		toDay = "";
	}
	else{
		var toDay = document.getElementById('toDay').value;
		if(toDay > '' && !Number(toDay) && toDay != 'DD'){
			var validError = 1;
		}
	}

	//Validate toYears
	var toYear = document.getElementById('toYear').value;
	if(toYear == 'YYYY'){
		toYear = "";
	}
	else{
		var toYear = document.getElementById('toYear').value;
		if(toYear > '' && !Number(toYear) && toYear != 'YYYY'){
			var validError = 1;
		}
	}
	
	var region = document.getElementById('region').value;
	
	if(region != ""){
		ajaxRequest('centerToPoint', region, 'Error returning data from centerToPoint');	
	}
	
	var keyword = document.getElementById('keyword').value;
	var user = document.getElementById('user').value;
	if(user == "undefined"){
		user = "";
	}
	if(validError == 1){
		alert("There was a problem with your search criteria... Search Aborted");	
	}
	else{
		var queryString = fromYear+'-'+fromMonth+'-'+fromDay+'|'+toYear+'-'+toMonth+'-'+toDay+'|'+region+'|'+keyword+'|'+user;
		ajaxRequest('getSearchResults', queryString, 'Error returning data from getSearchResults');	
		if(showPaging == 1){
			new Ajax.Updater('reportAreaBody', './map/switchcontent/map_reports_paging.php?user='+user+'&search='+queryString, { method: 'get' });
		}
		else{
			new Ajax.Updater('reportAreaBody', './map/switchcontent/map_reports.php?user='+user+'&search='+queryString, { method: 'get' });
		}
	}
}

function pageReport(page, parent, search, user){
	if(parent > 0){
		getReports("0,7,"+this.id);
	}
	new Ajax.Updater('reportAreaBody', './map/switchcontent/map_reports_paging.php?search='+search+'&region_id='+parent+'&page='+page+'&user='+user, { method: 'get' });	
}

function showSubscribe(subscriber, author){
	if (confirm('Are you sure you want to subscribe to this person\'\s report center?'))
		{
		new Ajax.Updater('capSubscribe', './map/switchcontent/cap_subscribe.php?subscriber='+subscriber+'&author='+author, { method: 'get' });
		return true;
		}
}

function showUnsubscribe(subscriber, author){
	if (confirm('Are you sure you want to Unsubscribe from this person\'\s report center?'))
		{
		new Ajax.Updater('capSubscribe', './map/switchcontent/cap_unsubscribe.php?subscriber='+subscriber+'&author='+author, { method: 'get' });
		return true;
		}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0

  window.open(theURL,winName,features);

}

function sendEmail(toUser, fromEmail, message){
	new Ajax.Updater('sendEmailDisplay', './map/switchcontent/cap_email_send.php?to_user='+toUser+'&from_email='+fromEmail+'&message='+message, { method: 'get' });	
	showEmailBox(toUser);
}

function showEmailBox(user){
	var profileView = document.getElementById("profileView");
	if(emailOn == 1){
		new Ajax.Updater('sendEmail', './map/switchcontent/cap_email.php?email=0&user='+user, { method: 'get' });
		emailOn = 0;
		if(bioOn == 0){
			profileView.className = "divVisible";
		}
	}
	else{
		new Ajax.Updater('sendEmail', './map/switchcontent/cap_email.php?email=1&user='+user, { method: 'get' });
		emailOn = 1;
		profileView.className = "divInvisible";
		if(bioOn == 1){
			showProfileBio(user);
		}
	}
}

function showProfileBio(user){
	var profileView = document.getElementById("profileView");
	if(bioOn == 1){
		new Ajax.Updater('profileBio', './map/switchcontent/profile_bio.php?bio=0&user='+user, { method: 'get' });
		bioOn = 0;
		if(emailOn == 0){
			profileView.className = "divVisible";
		}
	}
	else{
		new Ajax.Updater('profileBio', './map/switchcontent/profile_bio.php?bio=1&user='+user, { method: 'get' });
		bioOn = 1;
		profileView.className = "divInvisible";
		if(emailOn == 1){
			showEmailBox(user);
		}
	}
}

function pageCalendar(year, month, user){
	new Ajax.Updater('calArea', './map/switchcontent/cap_calendar.php?thisyear='+year+'&thismonth='+month+'&user='+user, { method: 'get' });	
}

function pageGallery(page, user){
	new Ajax.Updater('galleryArea', '../phpsource/profile_view_gallery.php?page='+page+'&user='+user, { method: 'get' });	
}

function pageIndexGallery(page, location, user){
	new Ajax.Updater('indexGallery', '../phpsource/index_gallery.php?page='+page+'&location='+location+'&user='+user, { method: 'get' });	
}

function pageArticles(page, user){
	new Ajax.Updater('articleArea', '../phpsource/profile_view_docs.php?page='+page+'&user='+user, { method: 'get' });	
}

//Initialize the map layers
ajaxRequest('getMapLayers', '', 'Error returning data from getMapLayers');