﻿var map = {};
var infoWindow = {};
var markers = {};
var events = {}

/* Mappings for properties within events array */
var ID = 0;
var NAME = 1;
var DESCRIPTION = 2;
var CITY = 3;
var STATE = 4;
var STARTDATE = 5;
var ENDDATE = 6;
var LATITUDE = 7;
var LONGITUDE = 8;
var ZIP = 0;


$(document).ready(function () {
    GetUserLocation();
    initializeSubmitForm();
    initLoginForm();
    CallWebMethod("Default.aspx", "GetAllReenactments", "{}", initializePage);
});

function initializePage(events)
{
    //Draw the map.
    initializeMap(events)

    //Draw the data table.
    initializeDataTable(events);
}

function GetUserLocation() {
    /* Check for native WC3 geolocation browser support */
    if (navigator.geolocation) {
             navigator.geolocation.getCurrentPosition(function (position) {
             initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
             map.setCenter(initialLocation);
        });
    }
}

function initLoginForm() {
    $("#login-form").dialog({
        autoOpen: false,
        height: 250,
        width: 250,
        modal: true,
        buttons: {
            "Login": function () {
                    Login();
                    return false;
                   // $(this).dialog("close");
                }
            }
    });

    $("#login")
			.button()
			.click(function () {
		    ShowLoginDlg();
			});

    $("#lnkLogin").click(function(){
             ShowLoginDlg();
             return false;
            });
}

function Login(){

    var user = {};
    user.Email = $("#username").val();
    user.Password = $("#password").val();

    CallWebMethod("Default.aspx", "Login", user, AuthConfirmation);

}

function AuthConfirmation(msg)
{
    if(msg == true)
        $("#login-form").dialog("close");
    else
        $("#AuthMessage").html("Your username or password is incorrect.");
    
}

function ShowLoginDlg(){
   $("#login-form").dialog("open");
}

function ShowLoginMessage()
{
    $("#loginMessage").html("<p id='layoutdims'>Welcome back Chris</p>");
}

function initializeSubmitForm()
{
        $("#Startdate").datepicker();

        $("#Enddate").datepicker();

	    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
		//$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		var name = $( "#Name" ),
			description = $( "#Description" ),
			address = $( "#Address" ),
			allFields = $( [] ).add( name ).add( description ).add( address ),
			tips = $( ".validateTips" );

		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}

		$("#dialog-form").dialog({
		    autoOpen: false,
		    height: 750,
		    width: 600,
		    modal: true,
		    buttons: {
		        "Submit Event": function() {
		            var bValid = true;
		            //allFields.removeClass("ui-state-error");
		           

		            //bValid = bValid && checkLength( name, "name", 3, 16 );
		            //bValid = bValid && checkLength( description, "description", 6, 80 );
		            //bValid = bValid && checkLength( address, "Address", 5, 16 );

		            //bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
		            // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
		            //bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
		            //bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

		            if (bValid) {
		                OnClick_Submit();
		                $(this).dialog("close");
		            }
		        },
		        Cancel: function() {
		            $(this).dialog("close");
		        }
		    },
		    close: function() {
		        allFields.val("").removeClass("ui-state-error");

		    }
		});

		$( "#create-user" )
			.button()
			.click(function() {
				$( "#dialog-form" ).dialog( "open" );
			});
			
		$( "#geo-locate" )
		.button()
		.click(function() {
			GeoLocateAddress();
		});
}



/* Handle the click event for the submit button */
function OnClick_Submit(){

    var reenactment = {};
    reenactment.Name = $("#Name").val();
    reenactment.Description = $("#Description").val();
    reenactment.StartDate = $("#Startdate").val();
    reenactment.EndDate = $("#Enddate").val();
    reenactment.Address = $("#Address").val();
    reenactment.City = $("#City").val();
    reenactment.State = $("#State").val();
    reenactment.Zip = $("#Zip").val();
    reenactment.WebSite = $("#Url").val();
    reenactment.ContactEmail = $("#Contact").val();
    reenactment.Latitude = $("#latitude").val();
    reenactment.Longitude  = $("#longitude").val();
    reenactment.Addby = 12521;
    reenactment.AddDate = "1/1/2011";
    reenactment.Editby = 12521;
    reenactment.EditDate = "1/1/2011";
    reenactment.Approved = false;
    
    //Call the web method.
    CallWebMethod("Default.aspx", "SubmitReenactment", reenactment, Confirmation);


//    var glAddress = {};
//    glAddress.Address = "108 Bolling drive";
//    glAddress.City = "homer";
//    glAddress.State = "LA";
//    
//    CallWebMethod("Default.aspx", "GeolocateAddress", glAddress, displayGeolocation);       
   
    
}

function Confirmation()
{
    alert("Your event was added.");
    window.location.reload();
}

function ShowEvent(text)
{
    alert(text);
}

function initializeDataTable(events)
{
    var oTable = $('#dtEvents').dataTable( {
        bRetrieve: true,
        bJQueryUI:true,
        "aaData": eval(events),
        "aoColumns":
        [
            {"sTitle": "Id",
             "bSearchable": false,
             "bVisible": false
            },
       	    {"sTitle": "Name"},
            { "sTitle": "Description",
              "bSearchable": true,
              "bVisible": false
              },
             {
                 "sTitle": "City"
             
             },
              {
                  "sTitle": "State"
               
              },
            {"sTitle": "StartDate" },
            {"sTitle": "EndDate" },
            {
             "sTitle": "Latitude",
             "bSearchable": true,
             "bVisible": false
             },
            { 
             "sTitle": "Longitude",
             "bSearchable": true,
             "bVisible": false
            }
        ]
	} );


	$("#dtEvents tbody tr").click(function (event) {

	    // Upon deselect of a row, turns that row's highlighting off
	    $(oTable.fnSettings().aoData).each(function () {
	        $(this.nTr).removeClass('row_selected');
	    });

	    // Highlights selected row
	    $(event.target.parentNode).addClass('row_selected').text();

	    // Expands right pane panels when row is selected. Also closes panels if already expanded.
	    //$('#eastMultiOpenAccordion h3').trigger('click');

	    // Using fnGetData()
	    var aData = oTable.fnGetData(this);
	    //Get marker with this ID
        var Id = aData[0];
	    var Lat = aData[LATITUDE];
	    var Lng = aData[LONGITUDE];
	    //    var Name = aData[1];
	    //    //alert(Lat  + ', ' +  Lng); 
	    var marker = new google.maps.Marker({map:map,position: new google.maps.LatLng(Lat,Lng)});
	    //    infoWindow.setContent("<h1>"+Name+"</h1>");
	    infoWindow.open(map, marker);


	});
}



function initializeMap(events) 
{

    /* Set up the map */
    InitGoogleMap();
    
    //bounds of the map
    var bounds = new google.maps.LatLngBounds();

    /* Initialize our InfoWindow */
    InitInfoWindow();

    /* This is an array, not just text */
    events = eval(events);
    
    //Loop through my events and create markers
    for(var i = 0; i < events.length; i++) {

        /* Create the marker */
        var marker = CreateMarkerFromEvent(events[i]);
        
        /* Extend the bounds of the map per marker */
        bounds.extend(marker.position);

        /* Set a click event on this marker */
        SetMarkerClick(marker, events[i]);

        /* Place the marker on the map */
        marker.setMap(map);
    }
    
    /* now that we have all markers rebound the map to fit them all */
    map.fitBounds(bounds);
}

function InitGoogleMap() {

    /* Get start postion */

    var latlng = new google.maps.LatLng(31.980123, -92.715454);

    /* Map options */
    var myOptions = {
        zoom: 6,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    /* Init the map and save it to a global. */
    map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
}

function CreateMarkerFromEvent(event) {

    /* Map lat and long's position in the event array */
    var name = 0;
    var description = 1;
    var latitude = 4;
    var longitude = 5;

    //Get a position from the event.
    var latLng = new google.maps.LatLng(event[LATITUDE], event[LONGITUDE]);
    
    //Create a marker to display on the map
    var marker = new google.maps.Marker({
        position: latLng,
        map: map,
        name: event[NAME],
        title: event[NAME],
        html: event[DESCRIPTION]
    });

    return marker;
}

function SetMarkerClick(marker, event) {
    google.maps.event.addListener(marker, "click", function () {
        /* Get content to be displayed when marker is clicked */
        infoWindow.setContent(GetInfoWindowContent(event));
        /* Open the info window when the marker is clicked */
        infoWindow.open(map, this);
    });
}

function InitInfoWindow() {
    //Init our info window.    
    infoWindow = new google.maps.InfoWindow({
        content: "loading...",
        maxWidth: 200,
        maxHeight: 300
    });
}

function GeoLocateAddress()
{
    //pull in the address.
    var address = $('#Address').val();
    var city = $('#City').val();
    var state = $('#State').val();
    
//    var glAddress = {};
//    glAddress.Address = address;
//    glAddress.City = city;
    //    glAddress.State = state;

    glAddress = address + " " + city + " " + state;

    CallWebMethod("Default.aspx", "GeoLocateAddress", glAddress, displayGeolocation);
}

function GetInfoWindowContent(event) {
   var html = "<table>";
	html = html + "<tr><td><h1>" +  event[NAME] + "</h1><br>";
	html = html + "<p>" + event[DESCRIPTION] + "</p><br/>";
	html = html + "<p>Begins: " + event[STARTDATE] + "<br/>";
	html = html + "Ends: " + event[ENDDATE] + "</p>";
	html = html + "</td><td valign='top'><img src='images/sasha.gif'/></td>";
	html = html + "</tr></table>";
	return html;
}

function displayGeolocation(geoLocation) {

    var geoLocation = JSON.parse(geoLocation);

    $('#latitude').val(geoLocation.results[0].geometry.location.lat);
    $('#longitude').val(geoLocation.results[0].geometry.location.lng);
}
  
 
