﻿//Global values
var g_map;
var g_mgr;
var g_myOptions;
var g_latlng;
var g_markersArray = [];
var g_infoWindows = [];
var g_previousInfoWindow; 
var g_currentVet = [];
//Change WebServiceURL here
var WebServiceURL = "DentastixService.asmx/";


//Set event Dom listener to load the map on pageload
//Since its too slow ill move this trigger on dom ready
//google.maps.event.addDomListener(window, 'load', initialize);

//Initialize the map
function initialize() 
{

    //Set the location to australia and the zoom to see all of australia 
    g_latlng = new google.maps.LatLng(-25.300331,134.545897);
    g_myOptions = 
    {
      zoom: 4,
      center: g_latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      //Set navigation control options
      navigationControl: true,
      navigationControlOptions:{
        style: google.maps.NavigationControlStyle.LARGE
      }
    };
    
    g_map = new google.maps.Map(document.getElementById("map_canvas"),g_myOptions);
}

//Page code 
$(function()
{
    //Load Gmap
    initialize();
    
    //if its the first state change the css
    if(g_currentVet.length == 0)
    {
        $('#dentastix_body').css( 'height', '1100px');
        $('#dentastix_body').css( '*height', '1200px');
        $('#VetInformation').css('background-color','#FFC919');
    }
    
    //Create click event for the button search
    $('#Button_Search').click(function()
    {
        if(window.console){console.info("Text_Search textbox value is: " + $('#Text_Search').val());}
        
        //Verify if its a valid entry
        if($('#Text_Search').val().length != 4 )
        {
            if(window.console){console.warn("Poscode must be 4 digits, invalid entry ");}
            return;
        }
        //Numbers only Regex
        var numbersOnlyRegex = "^\\d+$";
        if(!$('#Text_Search').val().match(numbersOnlyRegex))
        {
            if(window.console){console.warn("Postcode must be numeric only, invalid entry");}
            return;
        }
        
        //Create a new Array to store the Vets
        var VetArray = [];
        VetArray = GetTopTenVets($('#Text_Search').val());
        
        //If array has values iterate through it and add markers to map
        if(VetArray.length !== 0)
        {
            //Delete previous markers if any
            deleteMarkers();
            //Add a new marker
            for(i=0; i < 10; i++)
            {
                addMarker(VetArray[i], i);
            }
            
            //Centre map to the source location (index 10 has the lat and lon of the source location)
            //g_map.setCenter(new google.maps.LatLng(VetArray[10].Lat,VetArray[10].Lon));
            //Centre map to the closest location (VetArray[0].Lat,VetArray[0].Lon)
            g_map.setCenter(new google.maps.LatLng(VetArray[0].Lat,VetArray[0].Lon));
            g_map.setZoom(11);
        }
               
        
    });
    
    //Create Click Event for email button
    $('#Button_SendEmail').click(function()
    {
        if(window.console){console.info("Text_Email textbox value is: " + $('#Text_Email').val());}
        
        //Verify if its a valid entry
        if($('#Text_Email').val().length == 0 )
        {
            if(window.console){console.warn("Email must be supplied, email not sent");}
            //Notify user
            $('#EmailSent').empty();
            $('#EmailSent').html("Please enter an email.");
            return;
        }
        
        //Numbers only Regex
        var emailOnlyRegex = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        if(!$('#Text_Email').val().match(emailOnlyRegex))
        {
            if(window.console){console.warn("Email is invalid, email not sent");}
            //Notify user
            $('#EmailSent').empty();
            $('#EmailSent').html("Please supply a valid email.");
            return;
        }
        //Check if they selected a vet
        if(g_currentVet.length == 0)
        {
            if(window.console){console.warn("They need to select a vet");}
            //Notify user
            $('#EmailSent').empty();
            $('#EmailSent').html("Please select a vet.");
            return;
        }
        
        //Save email
        var toEmail = $('#Text_Email').val();
        //Construct Email text
        var emailBody = g_currentVet[0] + "\n" + 
                        g_currentVet[1] + "\n" +
                        g_currentVet[2] + ", "+ g_currentVet[3] +"\n" +
                        "Phone: " + g_currentVet[4] + "\n" +
                        "Email: " + g_currentVet[5] + "\n\n" +
                        "Vet's description:\n" + 
                        g_currentVet[6];
        
        var result = SendTextEmail(toEmail, emailBody);
        if(result == false)
        {
            //Email not sent, notify user
            $('#EmailSent').empty();
            $('#EmailSent').html("Sorry your email could not be sent, please try again later.");
            return;
        }
        else
        {
            //Email sent successfully notify user
            $('#EmailSent').empty();
            $('#EmailSent').html("The details have now been sent to your inbox");
            return;
        }
        
    });
});

//////////////
//Add Marker//
//////////////

function addMarker(Vet, number)
{
   //Adding a Marker//
   number = number +1;
   var image = "gmap_images/"+ number +".png";
   var shadow = "gmap_images/shadow.png";
   var marker = new google.maps.Marker(
                {
                    position: new google.maps.LatLng(Vet.Lat,Vet.Lon),
                    title: Vet.PracticeName,
                    map: g_map,
                    icon:image,
                    shadow:shadow
                });
   
   g_markersArray.push(marker);
   
   
   //Adding an InfoWindow//
   var content =  "<span style='font-family: Arial; font-size: 11px;'>" +
                  
                  "<strong>" + Vet.PracticeName +"</strong> <br />" +
                  Vet.PracticeStreet + "<br />" +
                  Vet.PracticeSuburb + ", " + Vet.Postcode + "<br />" +
                  "<strong>Phone: </strong>"+ Vet.PracticePhone + "<br />" +
                  "<strong>Email: </strong> "+ Vet.Email +
                  "</span>"
   
   var infowindow = new google.maps.InfoWindow(
                    {
                        content: content
                    });
   
   g_infoWindows.push(infowindow); 
   
   //Adding click event listener event
   google.maps.event.addListener(marker, 'click', function()
   {
        //Close any existing open windows if any
        if(g_previousInfoWindow)
        {
            g_previousInfoWindow.close();
        }
        
        //Open current info window
        infowindow.open(g_map,marker);
        
        //Store this infoWindow as a previous info window
        g_previousInfoWindow = infowindow;
        
        //Update page information
        $('#VetName').empty();
        $('#VetName').html(Vet.PracticeName);
        
        //Set VetDetails details
        $('#VetDetails').empty();
        var vetDetails = Vet.PracticeStreet + "<br />" +
                         Vet.PracticeSuburb + ", " + Vet.Postcode + "<br />" +
                         "Phone: " + Vet.PracticePhone + "<br />" +
                         "Email: " + Vet.Email;
        $('#VetDetails').html(vetDetails);
        
        //Set the VetInformation details
        $('#VetInformation').empty();
        $('#VetInformation').html(Vet.PracticeInfo);
        
        //Save current Vet in array (used to aid the construction of the email body)
        g_currentVet = [];
        g_currentVet = [Vet.PracticeName, Vet.PracticeStreet, Vet.PracticeSuburb, Vet.Postcode, Vet.PracticePhone, Vet.Email, Vet.PracticeInfo];
        
        //Change the css
        $('#dentastix_body').css( 'height', '1225px');
        $('#dentastix_body').css( '*height', '1325px');
        $('#VetInformation').css('background-color','White');
        
   });
   
}

////////////////////////
// Deletes all markers//
////////////////////////
function deleteMarkers()
{
  //Delete markers//
  if (g_markersArray)
  {
    for (i in g_markersArray)
    {
      g_markersArray[i].setMap(null);
    }
    g_markersArray.length = 0;
  }
  
  //Delete InfoWindows//
  if (g_infoWindows)
  {
    g_infoWindows = [];
  }
}

/////////////////////
//JQUERY AJAX CALLS//
/////////////////////

//Get the top 10 closest Vets around location (can be a suburb or a postcode)
function GetTopTenVets(location)
{
    if(window.console){console.info("In GetTopTenVets, passed location: " + location);}
    
    //Create array
    var Vets = [];
    
    //Set the posted parameters
    var postedParameters =  {
                              location: location
                            }
    $.ajax(
    {
         type: "POST",
         url: WebServiceURL + "SearchByPostCodeOrSuburb", //See top of file to modify
         data: JSON.stringify(postedParameters),
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         async: false,
         success: function(msg)
         {
             //Get resonse from webservice
             var data = eval("(" + msg.d + ")");
             if (data.Success == true) 
             {
                 //success
                 if (window.console){console.info("Sucessful response from webmethod SearchByPostCodeOrSuburb ");}
                 Vets = data.List;
             }
             else 
             {
                 //error
                 if (window.console){console.warn("Failed response from webmethod SearchByPostCodeOrSuburb");}
                 Vets = [];
                 
             }
         },
         error: function(msg)
         {
             //Error
             if (window.console){console.warn("Error reading response from webservice SearchByPostCodeOrSuburb");}
             Vets = [];
         }
    });
    
    return Vets;
}

function SendTextEmail(toEmail, emailBody)
{
    if(window.console){console.info("In SendTextEmail, passed toEmail: " + location + " email body: " + emailBody);}
    
    var result;
    //Set the posted parameters
    var postedParameters =  {
                              toEmail: toEmail,
                              emailBody: emailBody
                            }
    $.ajax(
    {
         type: "POST",
         url: WebServiceURL + "SendTextEmail", //See top of file to modify
         data: JSON.stringify(postedParameters),
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         async: false,
         success: function(msg)
         {
             //Get resonse from webservice
             var data = eval("(" + msg.d + ")");
             if (data == true) 
             {
                 //success
                 if (window.console){console.info("Sucessful response from webmethod SendTextEmail ");}
                 result = true;
             }
             else 
             {
                 //error
                 if (window.console){console.warn("Failed response from webmethod SendTextEmail");}
                 result = false
                 
             }
         },
         error: function(msg)
         {
             //Error
             if (window.console){console.warn("Error reading response from webservice SendTextEmail");}
             result = false;
         }
    });
    
    return result;
}



