﻿var map;
var waitingOnServer = false;
var cachedResult;
var pageNumber;
var isUsat = true;
var pageSize = 50;

function initPopups() {
    $('#coachDialog').jqm();

    $('#filterDialogTrigger').click(function() {
        $('#filterDialog').toggle();
        if ($(this).attr('class') == 'opened')
            var closr = true
        $(this).removeClass('opened').end();
        if (closr != true)
            $(this).addClass('opened');
    });  

}

function initMap(latitude, longitude, zoomLevel, queryUsat) {

    isUsat = queryUsat;
    google.maps.Map.prototype.markers = new Array();
    google.maps.Marker.prototype.personId = 0;

    google.maps.Map.prototype.addMarker = function(offset, coach) {
        var personId = coach.PersonId;
        //create a new marker
        var icon = new google.maps.MarkerImage("/images/tp_map_icon.png", new google.maps.Size(12, 20), new google.maps.Point(0, 0), new google.maps.Point(6, 20));
        var shadow = new google.maps.MarkerImage("/images/tp_map_icon_shadow.png", new google.maps.Size(22, 20), new google.maps.Point(0, 0), new google.maps.Point(6, 20));
        var latlng = new google.maps.LatLng(coach.Latitude, coach.Longitude);
        var marker = new google.maps.Marker({ position: latlng, map: map, personId: personId, icon: icon, shadow:shadow });
        google.maps.event.addListener(marker, "click", function() {
            showCoachInformation(personId);
        });
        this.markers[this.markers.length] = marker;
    };

    google.maps.Map.prototype.getMarkers = function() {
        return this.markers
    };

    google.maps.Map.prototype.clearMarkers = function() {
        for(var i=0; i<this.markers.length; i++){
          this.markers[i].setMap(null);
        }
        this.markers = new Array();
    };
    
    //initialize gmap
    var latlng = new google.maps.LatLng(latitude, longitude);
    var myOptions = {
        zoom: zoomLevel,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapDiv"), myOptions);
    google.maps.event.addListener(map, 'bounds_changed', function() {
        var bounds = map.getBounds();
        if (bounds) {
            var ne = bounds.getNorthEast();
            var sw = bounds.getSouthWest();
            var maxLat = ne.lat();
            var minLat = sw.lat();
            var maxLng = ne.lng();
            var minLng = sw.lng();
            var discipline = $('#filterDiscipline').val();
            var location = $('#filterLocation').val();
            var certificationLevel = $('#filterCertificationLevel').val();
            getCoachesInDirectoryAdvanced(true, minLat, maxLat, minLng, maxLng, discipline, location, certificationLevel);
        }
    });
}

function doSearch() {
    waitingOnServer = true;
    var proxy = new CoachDirectoryService.ICoachDirectoryService();
    var filterByMap = $('#filterByMap').is(':checked');
    var maxLat = 0, maxLng = 0, minLat = 0, maxlat = 0;
    var bounds = map.getBounds();
    if (bounds) {
        var ne = bounds.getNorthEast();
        var sw = bounds.getSouthWest();
        maxLat = ne.lat();
        minLat = sw.lat();
        maxLng = ne.lng();
        minLng = sw.lng();
    }
    var discipline = $('#filterDiscipline').val();
    var location = $('#filterLocation').val();
    var certificationLevel = $('#filterCertificationLevel').val();
    proxy.GetCoachesInDirectoryAdvanced(isUsat, filterByMap, minLat, maxLat, minLng, maxLng, discipline, location, certificationLevel, onSuccess, onFail, null);
    if (!filterByMap) {
        $('#mapDiv').hide();
    }
    else {
        $('#mapDiv').show();
    }
    //$("#filterDialog").jqmHide();
}

function getCoachesInDirectoryByBoundingBox(minLat, maxLat, minLng, maxLng) {
    if (!waitingOnServer) {
        waitingOnServer = true;
        var proxy = new CoachDirectoryService.ICoachDirectoryService();
        proxy.GetCoachesInDirectoryByBoundingBox(isUsat, minLat, maxLat, minLng, maxLng, onSuccess, onFail, null);
    }
}

function getCoachesInDirectoryAdvanced(filterByMap, minLat, maxLat, minLng, maxLng, discipline, location, certificationLevel) {
    if (!waitingOnServer) {
        waitingOnServer = true;
        var proxy = new CoachDirectoryService.ICoachDirectoryService();
        proxy.GetCoachesInDirectoryAdvanced(isUsat, filterByMap, minLat, maxLat, minLng, maxLng, discipline, location, certificationLevel, onSuccess, onFail, null);
    }
}

function goToPage(number) {
    printResults(number);
}

function printResults(number) {
    pageNumber = number;
    var result = cachedResult;
    var showing = Math.min(result.length - 1, pageSize);
    var resultsHtml = "";
    var pages = Math.ceil(result.length / pageSize);
    if (pageNumber > 0) {
        $("#pagePrev").show();
    }
    else {
        $("#pagePrev").hide();
    }
    var first = ((pageNumber * pageSize) + 1);
    var last = Math.min(first + pageSize - 1, result.length);
    resultsHtml += "<strong>" + first + " - " + last + "</strong> of <strong>" + result.length + "</strong>";


    if (pageNumber + 1 < pages) {
        $("#pageNext").show();
    }
    else {
        $("#pageNext").hide();
    }
    $("#results").html(resultsHtml);
    $("#dataDiv table tbody tr").remove();
    map.clearMarkers();
    var html;
    if (result.length == 0) {
        html = "<tr><td class=\"coachDataRowCell\"><div class=\"coachDataRowHeader\"><strong>No Results</strong></td></tr>";
        $("#dataDiv table tbody").append(html);  
    }
    else {
        for (var i = first; i <= last; i++) {
            var offset = i - 1;
            html = "<tr><td class=\"coachDataRowCell\"><div class=\"coachDataRowHeader\">"
                        + "<a href=\"javascript:showCoachInformation(" + result[offset].PersonId + ")\">" 
                        + result[offset].FirstName + " "
                        + result[offset].LastName + "</a> - "
                        + result[offset].CompanyName + "</div><div class=\"coachDataRowBody\">"
                        + result[offset].CoachSpeciality + "</div>"
                        + "</td></tr>";
            $("#dataDiv table tbody").append(html);   
            map.addMarker(offset, result[offset]);
        }
    }
}

function showCoachInformation(id) {
    for (var i = 0; i < cachedResult.length; i++)
    {
        var coach = cachedResult[i];
        if (coach.PersonId == id) {
            if (coach.CompanyName) {
                $("#coachFullNameAndCompany").html(coach.FirstName + " " + coach.LastName + " - " + coach.CompanyName);
            }
            else {
                $("#coachFullNameAndCompany").html(coach.FirstName + " " + coach.LastName);
            }
            $("#coachPhoto").attr("src", "");
            $("#coachPhoto").attr("src", coach.PhotoUrl);
            $("#coachStory").html(coach.Story);
            $("#coachServices").html(coach.Services);
            $("#coachUrl").attr("href", coach.Url);
            $("#coachUrl").html(coach.Url);
            $("#coachDisciplines").html(coach.Disciplines);
            $("#coachSpeciality").html(coach.CoachSpeciality);
            $("#coachLocation ").html(coach.City + ", " + coach.State);
            $("body").append($(".jqmWindow")) //modal window needs to be a direct child of <body> for ie6
            $("#coachDialog").jqmShow();

            break;
        }        
    }
}

// This is the callback function that
// processes the Web Service return value.
function onSuccess(result) {
    cachedResult = result;
    printResults(0);
    waitingOnServer = false;
}

function onFail() {
    waitingOnServer = false;
}
