function initialize() {
    //googleIconProperties();
    //initMap();
    document.getElementById("mapContainer").className = 'mapContainerShowMapImage';
    initSearch();
    //initDirections();
}

var map;
var directionDisplay;
var infoWin;
var infoWinHTML;
var jsonMarkerList;
var jsonInfoWinHTML;
var directionClosedInfoWindow = false;
var mapInitialized = false;

var LIST_MARKERS = [];
var LIST_INFOWINHTML = [];

var imgPath = "App_Themes/Default/Images/";
var iconATMCBA = imgPath + "iconATM-CBA.png";
var iconATMBW = imgPath + "iconATM-BW.png";
var iconBranchGeneral = imgPath + "iconBranch-General.png";
var iconSize = null;
var iconPosition = null;
var infoWindowAnchor = null;
var iconHotSpotOffset = null;
var m_lastMarkerIndex = -1;
var markerNum;

var directionsService = new google.maps.DirectionsService();
var directionsDisplay;

var EndLat;
var EndLng;
var CalculatedStartPoint;
var CalculatedEndPoint;



function googleIconProperties()
{
	iconSize = new google.maps.Size(34, 38);
	iconPosition = new google.maps.Point(0, 0);
	infoWindowAnchor = new google.maps.Point(15, 0);
	iconHotSpotOffset = new google.maps.Point(15, 0);
}

/* 
 * initMap - Initialize google map with base options
**/

function initMap() {
    mapInitialized = true;
    directionsDisplay = new google.maps.DirectionsRenderer(); //Create Directions 
    geocoder = new google.maps.Geocoder(); //Create GeoCoder
    var mapLatLng = new google.maps.LatLng(-28.22118510173754, 134.332108);
    var mapOptions = {
        zoom: 4,
        center: mapLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
    draggable: false,
    navigationControl: false,
    mapTypeControl: false,
    disableDoubleClickZoom: true,
    scrollwheel: false
    };
    map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
    google.maps.event.addListener(map, 'dragend', centerChanged);
    initDirections();
}

/* 
 * CentreMapByAddress - Geocodes address, and applies further options to the map
**/

function CentreMapByAddress(address) {
    if (geocoder) {
        geocoder.geocode({ 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                map.setOptions({
                    zoom: 15,
                    draggable: true,
                    navigationControl: true,
                    mapTypeControl: true,
                    disableDoubleClickZoom: false,
                    scrollwheel: true
                });
                OpenFirstCBAPopUp(); 
                var firstMarker = new google.maps.LatLng(jsonMarkerList[0].Latitude, jsonMarkerList[0].Longitude);
                if (!map.getBounds().contains(firstMarker)) {
                    var bounds = map.getBounds();
                    bounds.extend(firstMarker);
                    map.fitBounds(bounds);
                }
            } 
        });
    }
}

function CentreMapByLatLng(latLng) {
    if (geocoder) {
        geocoder.geocode({ 'latLng': latLng }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                map.setOptions({
                    zoom: 15,
                    draggable: true,
                    navigationControl: true,
                    mapTypeControl: true,
                    disableDoubleClickZoom: false,
                    scrollwheel: true
                });
                markerClicked(0);
            } else {
                //alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
}

function OpenFirstCBAPopUp() {
    if (SearchType == EnumSearchType.BranchsATMs) {
        var JSONQuery = JSON.decode(CurrentQuery);
        if (JSONQuery.IsBranches && JSONQuery.IsATMs) {
            for (var i = 0; i < jsonMarkerList.length; i++) {
                if (jsonMarkerList[i].HasBranch) {
                    markerClicked(i);
                    return;
                }
            }
        }
        else if (JSONQuery.IsATMs) {
            for (var i = 0; i < jsonMarkerList.length; i++) {
                if (jsonMarkerList[i].ATMType == 'CBA') {
                    markerClicked(i);
                    return;
                }
            }
        }
    }
    else if(SearchType == EnumSearchType.Services){
         var JSONQuery = JSON.decode(CurrentQuery);
         if(JSONQuery.ProductID == "1"){
             for (var i = 0; i < jsonMarkerList.length; i++) {
                 if (jsonMarkerList[i].ServiceId == 1) {
                    markerClicked(i);
                    return;
                }
             }
         }
         else if(JSONQuery.ProductID == "4"){
             for (var i = 0; i < jsonMarkerList.length; i++) {
                 if (jsonMarkerList[i].ServiceId == 2) {
                    markerClicked(i);
                    return;
                }
             }
         }
    }
    if (jsonMarkerList.length > 0) {
        markerClicked(0);
    }
}


/*
 *appendMarkersToMap: Loops through a JSON object, and drops relevant makers on the map.
**/
function appendMarkersToMap() {

    closeCurrentInfoWindow();
    if(typeof(geocoder) == 'undefined')
    {
        initMap();
        
    }
    map.clearMarkers();
    LIST_MARKERS = [];
	
	var infoWinHTML;
	
	for (var i=0; i < jsonMarkerList.length; i++)
	{
	    appendSingleMarkerToMap(i);
    }
}

function appendSingleMarkerToMap(i) {

    var infoWinHTML;

    var lat = jsonMarkerList[i].Latitude;
    var lng = jsonMarkerList[i].Longitude;
    var type = jsonMarkerList[i].ATMType;
    var hasBranch = jsonMarkerList[i].HasBranch;
    var address = jsonMarkerList[i].BuildingName;

    var markerLatLng = new google.maps.LatLng(lat, lng);
    var bounds = new google.maps.LatLngBounds();


    if (hasBranch) marker = createMarker(markerLatLng, iconBranchGeneral, infoWinHTML);
    else if (type == "CBA") marker = createMarker(markerLatLng, iconATMCBA, infoWinHTML);
    else if (type == "BW") marker = createMarker(markerLatLng, iconATMBW, infoWinHTML);

    marker.markerIndex = i;
    LIST_MARKERS.push(marker);
}

/*
* createMarker: Creates a new marker and attaches a listener on each one.
* @param {GLatLng} point - Point to create marker at
* @param {String} markerType - Which idon to use
* @param {String} infowWindowHtml - Content of infowindow
**/
function createMarker(myLatLng, markerType, infoWindowHtml) {

    var markerImage = new google.maps.MarkerImage(markerType, iconSize, iconPosition, iconHotSpotOffset);
    var markerShadow = new google.maps.MarkerImage(imgPath + 'iconShadow.png',
		new google.maps.Size(54, 38),  //dimensions: left,top
		new google.maps.Point(0, 0),  //offest: left,top
		new google.maps.Point(8, 38) //offest: left,top
	);

    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: markerImage,
        shadow: markerShadow
    });

    var myThis = this;
    google.maps.event.addListener(marker, "click", function() {
        myThis.markerClicked(this.markerIndex);
    });
    
    return marker;
}

/*
* clearMarkers
**/
(function() {
    google.maps.Map.prototype.clearMarkers = function() {
        if (infoWin) {
            infoWin.close();
        }
        for (var i = 0; i < LIST_MARKERS.length; i++) {
            LIST_MARKERS[i].setMap(null);
        }
    };
})();



/*
 * markerClicked - Returns the marker clicked
 * @param {Number} markerNum - returns the marker that was clicked from the array
**/
function markerClicked(MarkerNum) {
    markerNum = MarkerNum;
    if (jsonMarkerList[markerNum].HasBranch) {
        //PageMethods.GetBranchesDetails(jsonMarkerList[markerNum].BuildingServiceID,OnBranchComplete);
        OnBranchDetailsComplete( "{"+'"Branch"'+":" + JSON.encode(jsonMarkerList[MarkerNum]) + "}");
        
    }
    else {
    //alert(jsonMarkerList[MarkerNum]);
    OnBranchDetailsComplete( "{"+'"ATM"'+":" + JSON.encode(jsonMarkerList[MarkerNum]) + "}");
        //PageMethods.GetATMDetails(jsonMarkerList[markerNum].ATMID, OnBranchDetailsComplete);
    }
}

function OnBranchDetailsComplete(result) {

    var jsonObject = JSON.decode(result);
    var l_myInfoWindow = new cba.InfoWindow();
    
    //Set EndPoint Address
   // EndPointAddress = 

    var popupType =
    {
        HasBranch: jsonMarkerList[markerNum].HasBranch,
        HasATM: jsonMarkerList[markerNum].HasATM,
        ATMType: jsonMarkerList[markerNum].ATMType
    };
    
    l_myInfoWindow.ParseXmlObject(jsonObject, popupType);

    var infoWinHTML = l_myInfoWindow.toHtmlString();

    var l_accordionGroupIndex = getGroupIndexByMarkerIndex(markerNum);
    showIssueListByGroupIndex(l_accordionGroupIndex);

    var l_accordionObj = getAccordionObjectByMarkerIndex(markerNum);
    var l_accordionMarkerIndex = getMarkerIndexInGroup(markerNum);
    l_accordionObj.display(l_accordionMarkerIndex);

    // set last marker index on complete of accordion
    m_lastMarkerIndex = markerNum;

    $("QuickLinks").setStyle("display", "");
    $("BranchDetails").setStyle("display", "none");
    map.setOptions({ draggable: false });
}

function GetSelectedProduct() {
        var servicesList = document.getElementsByName('ServicesFilter');
        for (var i = 0; i < servicesList.length; i++) {
            if (servicesList[i].checked) {
                return servicesList[i].value;
            }
        }
        return '';
    }
    

/*
* onLocationChangeOpenInfoWindow - Launches info window when the marker is accessed. Either directly, or by the accordion
**/
function onLocationChangeOpenInfoWindow(MarkerNum) {
    closeCurrentInfoWindow();
    markerNum = MarkerNum;
    if (jsonMarkerList[markerNum].HasBranch) {
        //PageMethods.GetBranchesDetails(jsonMarkerList[markerNum].BuildingServiceID, OnBranchAccordianComplete);
        OnBranchDetailsCompleteForAccordian( "{"+'"Branch"'+":" + JSON.encode(jsonMarkerList[MarkerNum]) + "}");
    }
    else {
        //PageMethods.GetATMDetails(jsonMarkerList[markerNum].ATMID, OnBranchDetailsCompleteForAccordian);
        OnBranchDetailsCompleteForAccordian( "{"+'"ATM"'+":" + JSON.encode(jsonMarkerList[MarkerNum]) + "}");
    }
    
}

function OnBranchDetailsCompleteForAccordian(result) {

    var jsonObject = JSON.decode(result);
    var l_myInfoWindow = new cba.InfoWindow();

    var popupType =
    {
        HasBranch: jsonMarkerList[markerNum].HasBranch,
        HasATM: jsonMarkerList[markerNum].HasATM,
        ATMType: jsonMarkerList[markerNum].ATMType
    };

    l_myInfoWindow.ParseXmlObject(jsonObject, popupType);

    var contentString;
    contentString = l_myInfoWindow.toHtmlString();

    var infowindow = new BFInfoWindow();
    infowindow.setHtmlContent(contentString);
    infowindow.open(map, LIST_MARKERS[markerNum]);
    setInfoWindow(infowindow);
    map.setOptions({
        scrollwheel: false,
        disableDoubleClickZoom: true,
        draggable: false
    });

    //m_lastMarkerIndex = -1;
    m_lastMarkerIndex = markerNum;


    $("QuickLinks").setStyle("display", "");
    $("BranchDetails").setStyle("display", "none");
}

function centerChanged() {

    closeCurrentInfoWindow();
    centerChangedLast = new Date();

    var Bound = {
        Lat1: map.getBounds().getSouthWest().lat(),
        Long1: map.getBounds().getSouthWest().lng(),
        Lat2: map.getBounds().getNorthEast().lat(),
        Long2: map.getBounds().getNorthEast().lng()
    }

    if (CurrentQuery != "" && map.getZoom() > 13) {
        if (SearchType == EnumSearchType.BranchsATMs) {
            PageMethods.GetLocationsForBranchesATMs(CurrentQuery, JSON.encode(Bound), OnLocateBranchATMWithBoundComplete);
        }
        else if (SearchType == EnumSearchType.Services) {
            PageMethods.GetLocationsForServices(CurrentQuery, JSON.encode(Bound), OnLocateServiceWithBoundComplete);
        }
    }
}

function OnLocateBranchATMWithBoundComplete(result) {
    var jsonObject = JSON.decode(result);
    mapSearch.ShowResults(jsonObject)
}

function OnLocateServiceWithBoundComplete(result) {
    var jsonObject = JSON.decode(result);
    mapSearch.ShowResults(jsonObject)
}


/* 
* getDirections
**/
function initDirections() {
    directionsDisplay.setPanel($("directionsPanel"));
}

function onDirectionsRequest(lat, lng) {

    $$('.searchPaneExtraInfo .cta').fireEvent('click');

    /* Omniture code begin */
    ResetKPI();
    s.pageName = 'cba:find-us:branch locator:get directions'; 
    s.prop4 = 'Locator: Get Directions'; 
    s.t();
    /* Omniture code end */

    directionClosedInfoWindow = true;
    EndLat = lat;
    EndLng = lng;
    $('EndPointOutput').innerHTML = ParseTemplate('EndPointTemplate', jsonMarkerList[m_lastMarkerIndex]);
    $("accordionModule").set("class", "accordionHidden");
    document.getElementById("divpage").style.display = 'none';
    
    $("GetDirections").setStyle("display", "");
    $('DirectionsInput').setStyle('display', '');
    $('directionsError').setStyle("display", "none");
    $('directionsEmpty').setStyle("display", "none");
    $('directionsDidYouMean').setStyle("display", "none");
    $("directionsPanel").set("html", "");
    markerClicked(m_lastMarkerIndex);
    map.clearMarkers();
    appendSingleMarkerToMap(m_lastMarkerIndex);
}

function calcRoute() {

    $('directionsEmpty').setStyle('display', 'none');
    if ($("txtSuburbStart").value == 'Enter postcode or suburb') {
        $('directionsError').setStyle('display', 'none');
        $('directionsEmpty').setStyle('display', '');
       return;
    }
    
    var txtStreetStart = $("txtStreetStart").value != 'Enter street name' ? $("txtStreetStart").value : '';
    var txtSuburbStart = $("txtSuburbStart").value != 'Enter postcode or suburb' ? $("txtSuburbStart").value : '';
    var startPoint = txtStreetStart + " " + txtSuburbStart;

    var endPoint = EndLat + "," + EndLng;
    var request = {
        origin: startPoint + " Australia", 
        destination: endPoint,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    
    directionsService.route(request, function(result, status)     
    {
        if (status == google.maps.DirectionsStatus.OK) {
            
            CalculatedStartPoint = result.routes[0].legs[0].start_address
            CalculatedEndPoint = result.routes[0].legs[0].end_address


            directionsDisplay.setDirections(result);
            $('directionsPanel').setStyle('display', '');
            $('directionsDidYouMean').setStyle('display', 'none');
            $('directionsError').setStyle('display', 'none');
            $('directionsEmpty').setStyle("display", "none");
            $('DirectionsInput').setStyle('display', 'none');
            $('PrintDirectionsLink').setStyle('display', '');
            directionsDisplay.setMap(map);
            map.clearMarkers()
        }
        else {
            $('PrintDirectionsLink').setStyle('display', 'none');
            PageMethods.GetDidYouMean(txtSuburbStart, OnGetDidYouMeanGetDirectionsComplete, OnError);
        }
    });
}

function OnGetDidYouMeanGetDirectionsComplete(result) {
    var address = JSON.decode(result);
    if (address != null && address.length > 0) {
        $('directionsDidYouMean').innerHTML = ParseTemplate('DidYouMeanGetDirectionsTemplate', address);

        $('directionsPanel').setStyle('display', 'none');
        $('directionsDidYouMean').setStyle('display', '');
        $('directionsError').setStyle('display', 'none');
    }
    else {
        $('directionsPanel').setStyle('display', 'none');
        $('directionsDidYouMean').setStyle('display', 'none');
        $('directionsError').setStyle('display', '');
    }
}

function OnDidYouMeanGetDirectionsClick(address) {
    $('txtSuburbStart').value = address;
    calcRoute();
}


/*
* detailsAccordionHideShow - RHSAccordion with location details
**/
function detailsAccordionHideShow() {
    var classOpened = "opened";
    var classClosed = "closed";
    var toggler = "div.toggler";
    var element = "div.details";
    var accordionContainer = $("accordionModule");
    if (accordionContainer) {
        accordionContainer.setStyle("display", "block");
    }

    var detailsAccordion = new Accordion($('toggleModules'), toggler, element, {
        opacity: false,
        initialDisplayFx: false,
        alwaysHide: true,
        display: -1,
        onActive: function(toggler) {
            removeAndAddClass(toggler, classClosed, classOpened);
            onLocationChangeOpenInfoWindow(toggler.togglerIndex);
            //Will close the open modules on the page you are not on
            for (var i = 0; i < ACCORDION_OBJECT_CREATED_LIST.length; i++) {
                if (CURRENT_DISPLAY_GROUP_INDEX != i) {
                    if(ACCORDION_GROUP_CREATED_LIST[i] != false)
                    {
                        ACCORDION_OBJECT_CREATED_LIST[i].display(-1);
                    }
                }
            }
        },
        onBackground: function(toggler) {
            removeAndAddClass(toggler, classOpened, classClosed);
        },
        onComplete: function(toggler) {
            if ($$('.detailsToggler .toggler.opened').length == 0) {
                closeCurrentInfoWindow();
            }
        }
    });

    return detailsAccordion;
}


/*
* setInfoWindow: Will only allow one infoWindow to be open at a time
**/
function setInfoWindow(newInfowindow) {

    closeCurrentInfoWindow();
    infoWin = newInfowindow;

    //infoWin.set_content(infowindow);
}

function closeCurrentInfoWindow(closeAccordionToo) {
    if (infoWin) {

        infoWin.close();
        //m_lastMarkerIndex = -1;
        if (!directionClosedInfoWindow) {
            map.setOptions({
                scrollwheel: true,
                disableDoubleClickZoom: false,
                draggable: true
            });
        }

        // close corresponding accordion
        if (closeAccordionToo) $$(".detailsToggler .toggler.opened").fireEvent('click');
    }
    infoWin = null;
}

function openInfoWindowAtServiceProduct() {
    var JSONQuery = JSON.decode(CurrentQuery);
    if (SearchType == EnumSearchType.Services) {
       if(JSONQuery.ProductID != "4"){
            if(JSONQuery.ProductID == "1" && jsonMarkerList[markerNum].ServiceId == "2")
                  return;
            cba.InfoWindow.showWindowContent("InfoWindow_2"); //Services tab
            cba.ServicesContent.showContentPageById("InfoWindow_2_contentPage_" + JSONQuery.ProductID);
       }
       else if(JSONQuery.ProductID == "4" && jsonMarkerList[markerNum].ServiceId == "1"){
            cba.InfoWindow.showWindowContent("InfoWindow_2"); //Services tab
            cba.ServicesContent.showContentPageById("InfoWindow_2_contentPage_1");
       }
    }
}

/*
* Open pop up windows
**/
function openWindow(url, name, w, h) {
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    var settings = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=yes,toolbar=no';
    window.open(url, name, settings);
}

function openFullWindow(url, name) {
    var h = 500;
    var w = 800;
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    var settings = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl;
    window.open(url, name, settings);
}

function OnError(error) {
    var errorString = "ExcetionType: " + error.get_exceptionType() + "\n\rMessage: " + error.get_message();
}

function removeAndAddClass(thisElement, removeThisClass, addThisClass) {
    thisElement.removeClass(removeThisClass);
    thisElement.addClass(addThisClass);
}

