﻿google.load("maps", "2");
var Tanq = new Object();

Tanq.Initialize = function() 
{
    Tanq.NoZoom = false;
    Tanq.Stations = new Object();
    Tanq.Map = null;
    Tanq.Fade = 300;
    if (GBrowserIsCompatible()) 
    {
        Tanq.DefaultIcon = new GIcon();
        Tanq.DefaultIcon.image = "/fftanken/img/companies/default.png";
        Tanq.DefaultIcon.iconAnchor = new GPoint(14,30);
        Tanq.DefaultIcon.shadow = "/fftanken//img/shadow.png";
        Tanq.DefaultIcon.shadowSize = new GSize(40,40);
        Tanq.DefaultIcon.iconSize = new GSize(40, 36);
        Tanq.DefaultIcon.infoWindowAnchor = new GPoint(5, 1);
    
        Tanq.Map = new GMap2(document.getElementById("map"));
        //Tanq.Map.setMapType(G_PHYSICAL_MAP);
    }
    
    if (Get_Cookie("Fuel") && $("#ddlFuel").selectedIndex == 0)
    {
        $("#ddlFuel").val(Get_Cookie("Fuel"));
        $("#legenda1").hide();
        $("#legenda2").show();
    }
    else if ($("#ddlFuel").selectedIndex > 0)
    {
        $("#legenda1").hide();
        $("#legenda2").show();
    }
}
    
function Get_Cookie(name) 
{
	var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length)))
    {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

Tanq.ShowInfo = function(i)
{
    Tanq.CurrentStation = Tanq.Stations[i];
    Tanq.ShowStationInfo(Tanq.Stations[i]);
}

Tanq.ShowStationInfo = function(station)
{
    var html = "";
    html += "<h3><a href='" + station.Url + "' title='Klik voor meer informatie - openingstijden - prijsinformatie'>" + station.Name + "</a></h3>";
    if (station.CurrentPrices != null)
    {
        var p = station.CurrentPrices;
        var datum = new Date(p.Datum);
        var datumFormat = datum.getDate() + " " + Months[datum.getMonth()] + ". " + datum.getFullYear();
        html += "<strong>Actuele prijzen</strong>";
        html += "<span class='priceupdated'>Laatste update: " + datumFormat + "</span>";
        html += "<div class='pricetable'><table>";
        if (p.Euro95 > 0) html += "<tr" + ($("#ddlFuel").val() == "Euro95" ? " class='selected p" + station.Price + "'" : "") + "><td>Euro 95</td><td class='price'>" + p.sEuro95 + "</td></tr>";
        if (p.Super > 0) html += "<tr" + ($("#ddlFuel").val() == "Super" ? " class='selected p" + station.Price + "'" : "") + "><td>Super</td><td class='price'>" + p.sSuper + "</td></tr>";
        if (p.Diesel > 0) html += "<tr" + ($("#ddlFuel").val() == "Diesel" ? " class='selected p" + station.Price + "'" : "") + "><td>Diesel</td><td class='price'>" + p.sDiesel + "</td></tr>";
        if (p.LPG > 0) html += "<tr" + ($("#ddlFuel").val() == "LPG" ? " class='selected p" + station.Price + "'" : "") + "><td>LPG</td><td class='price'>" + p.sLPG + "</td></tr>";
        html += "</table></div>";
    }
    if (station.Address || station.City || station.PostCode)
    {
        html += "<div class='infoAddress infoItem'>" + station.Address + "<br />";
        html += "" + station.PostCode + " " + station.City + "</div>";
    }
    if (station.H24 == 1)
    {
        html += "<div class='infoOpen infoItem'>24 uur per dag</div>";
    }
    if (station.H24 == 0 && station.Open != "0:00 - 0:00")
    {
        html += "<div class='infoOpen infoItem'>" + station.Open + "</div>";
    }
    html += "<br />";
    html += "<div id='routeInfo'><a class='info' href='#' onclick='Tanq.CalcRoute();'>Bereken route</a></div>";
    html += "<div id='moreInfo'><a class='info' href='"+station.Url+"'>Meer informatie - prijzen, tijden en locatie</a></div>";
    $("#stationinfo").html(html);
    $("#stationinfo").fadeIn(Tanq.Fade);
    $("#c3").hide();
    $("#c2").fadeIn(Tanq.Fade);
}

Tanq.CloseInfo = function(info)
{
    $(info).parent().hide();
    $("#c3").fadeIn(Tanq.Fade);
}

Tanq.HideInfo = function()
{
    $("#stationinfo").fadeOut(Tanq.Fade);
}
    
Tanq.LatLongCallback = function(coordinates)
{
    Tanq.Map.setCenter(coordinates, 13);
    Tanq.getStationData();
}

   
Tanq.getZoom = function(acc)
{
    if (acc == 0) return 6;
    if (acc == 1) return 6;
    if (acc == 2) return 6;
    if (acc == 3) return 7;
    if (acc == 4) return 11;
    if (acc == 5) return 14;
    if (acc == 6) return 14;
    if (acc == 7) return 15;
    if (acc >= 8) return 15;
    return 6;
}
    
Tanq.getStationData = function(fuelType)
{
    fuelType = $("#ddlFuel").val();
    $("#loader").show();
    var bounds = Tanq.Map.getBounds();
    var x0 = bounds.getSouthWest().x;
    var y1 = bounds.getNorthEast().y;
    var x1 = bounds.getNorthEast().x;
    var y0 = bounds.getSouthWest().y;
    
    if (fuelType && Tanq.CurrentStation)
    {
        Tanq.ShowStationInfo(Tanq.CurrentStation);
    }
    
    $.ajax({
          type: "POST",
          contentType: "application/json; charset=utf-8",
          url: "/Services/StationService.asmx/GetStations",
          data: "{'x0':'" + x0 + "','y0':'" + y0 + "','x1':'" + x1 + "','y1':'" + y1 + "','fuel':'"+fuelType+"'}",
          dataType: "json",
          success: function(data, status)
          {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
            Tanq.getStations(data.d);
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            
          }
    });
}
    
Tanq.getStations = function(stations)
{
    if (document.getElementById("allstations"))
    {
        document.getElementById("allstations").innerHTML = "";
    }
    Tanq.Stations = stations;
    for (var i = 0; i < stations.length && i < 200; i++)
    {
        Tanq.addStation(stations[i].Company.Name + ".png", stations[i], i);
    }
    $("#loader").hide();
}

Tanq.addStation = function(img, station, i)
{
    var ll = new GLatLng(station.Lat,station.Long)
    var compIcon = new GIcon(Tanq.DefaultIcon);
    compIcon.image = "/fftanken/img/Marker.ashx?p=" + station.Price + "&c=" + station.Company.Name;
    markerOptions = { icon:compIcon};
    var m = new GMarker(ll, markerOptions);
    GEvent.addListener(m, "click", function() {
        Tanq.CurrentStation = station;
        Tanq.ShowStationInfo(station);
    });
    Tanq.Map.addOverlay(m);
    
    station.Marker = m;
    var price = "";
    if (station.CurrentPrices)
    {
        if ($("#ddlFuel").val())
        {
            if (station.CurrentPrices[$("#ddlFuel").val()] > 0)
            {
                price = station.CurrentPrices["s" + $("#ddlFuel").val()] + "";
            }
        }
        else
        {
            if (station.CurrentPrices["Euro95"])
            {
                price = station.CurrentPrices["sEuro95"] + "";
                if (station.CurrentPrices["Diesel"])
                {
                    price += "<br />" + station.CurrentPrices["sDiesel"] + "";
                }
            }
        }
    }
    
    if (price)
    {
        price = "<span class='pricebox'>" + price + "</span>";
    }
    
    var html = "<a class='stationinfo' href='javascript:Tanq.ShowInfo(" + i + ");'><strong class='p" + station.Price + "'>" + price + station.Name + "</strong>";
    if (station.Address) 
    {
        html += station.Address
        if (station.City)
        {
            html += ", ";
        }
    }
    html += "<em>" + station.City + "</em></a>";
    document.getElementById("allstations").innerHTML += html;
}

Tanq.showSingleStation = function(company, lat, lng)
{
    var ll = new GLatLng(lat,lng)
    var compIcon = new GIcon(Tanq.DefaultIcon);
    compIcon.image = "/fftanken/img/Marker.ashx?p=0&c=" + company;
    markerOptions = { icon:compIcon};
    var m = new GMarker(ll, markerOptions);
    Tanq.Map.addOverlay(m);
}
        
Tanq.LocationChanged = function()
{
    var geo = new GClientGeocoder();
    geo.getLocations(document.getElementById("tbAddress").value + ", netherlands", Tanq.LocationCallback);
    Set_Cookie("MyAddress", $("#tbAddress").val(), 1);
    return false;
}

Tanq.CenterMapOnAddress = function(address)
{
    var geo = new GClientGeocoder();
    geo.getLocations(address + ", netherlands", Tanq.LocationCallback);
    return false;
}

Tanq.FuelChanged = function()
{
    Set_Cookie("Fuel", $("#ddlFuel").val(), 1);
    if ($("#ddlFuel").val())
    {
        $("#legenda1").hide();
        $("#legenda2").show();
    }
    else
    {
        $("#legenda2").hide();
        $("#legenda1").show();
    }
    Tanq.Map.clearOverlays();
    Tanq.getStationData($("#ddlFuel").val());
    return false;
}

Tanq.LocationCallback = function(data)
{
    var placemark;
    for (var i = 0; i < data.Placemark.length; i++)
    {
        var pm = data.Placemark[i];
        if (placemark == null || placemark.AddressDetails.Accuracy < pm.AddressDetails.Accuracy)
        {
            placemark = pm;
        }
    }

    if (placemark != null)
    {
        var coord = placemark.Point.coordinates;
        var latlong = new GLatLng(coord[1],coord[0]);
        Tanq.Map.clearOverlays();
        var zoom = 13;
        if (!Tanq.NoZoom)
        {
            zoom = Tanq.getZoom(placemark.AddressDetails.Accuracy);
        }
        else
        {
            Tanq.NoZoom = false;
        }
        Tanq.Map.setCenter(latlong, zoom);
    }
}

Tanq.ZoomIn = function()
{
    if (Tanq.Map.getZoom() < 16)
    {
        Tanq.Map.zoomIn();
    }
}

Tanq.ZoomOut = function()
{
    if (Tanq.Map.getZoom() > 7)
    {
        Tanq.Map.zoomOut();
    }
}

var Months = new Object();
Months[0] = "jan";
Months[1] = "feb";
Months[2] = "maa";
Months[3] = "apr";
Months[4] = "mei";
Months[5] = "jun";
Months[6] = "jul";
Months[7] = "aug";
Months[8] = "sep";
Months[9] = "oct";
Months[10] = "nov";
Months[11] = "dec";

$(document).ready(function() {
    $(".cols table tr").hover(function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); });
    $(".cols table tr.link").click(function() { $(this).find("a").click(); } );
});

Tanq.CalcRoute = function()
{
    if (Get_Cookie("MyAddress") != null && false)
    {
         Tanq.ShowRoute(Get_Cookie("MyAddress"));
    }
    else
    {
        var html = "<div class='prompt'><p>Voer een startadres of postcode in<br /><span class='vb'>vb.: 4837 PD - of - Hoofdstraat 88, Driehuis</span><br /><input id='myRoute' type='text' /></p></div>";
        $.prompt(html,{ buttons: { "Toon route": true, "Terug": false}, opacity: 0.9, loaded: function() {
                $("#myRoute").focus();
                if (Get_Cookie("MyAddress") != null)
                {
                    $("#myRoute").val(Get_Cookie("MyAddress"));
                } 
          }, submit: function(v,m) {
                if (v)
                {
                    var val = $("#myRoute").val();
                    Set_Cookie("MyAddress", val, 1);
                    Tanq.ShowRoute(val);
                }
                return true;
            }
         });
    }
    return false;
}

Tanq.ShowRoute = function(from)
{
    if (Tanq.CurrentStation)
    {
        var directions = new GDirections(Tanq.Map, document.getElementById("directions"));
        var sloc = "from: " + from + ", Netherlands to: " + Tanq.CurrentStation.Lat + "," + Tanq.CurrentStation.Long;
        $("#directions").html("");
        directions.load(sloc);
        $("#directions").html("<img src=\"/img/close.png\" alt=\"X\" onclick=\"Tanq.CloseInfo(this);\" class=\"close\" /><h2>" + Tanq.CurrentStation.Name + "</h2><div id=\"routeInfo2\"></div>" + $("#directions").html()).fadeIn(Tanq.Fade);
        $("#routeInfo2").html("<a href='javascript:Tanq.CloseDirections();' class='opClose'>Sluit routebeschrijving</a><a href='javascript:Tanq.PrintDirections();' class='opPrint'>Print routebeschrijving</a>");
    }
}

Tanq.CloseDirections = function() {
    $("#directions").fadeOut(Tanq.Fade);
}

Tanq.PrintDirections = function() {
    Tanq.Printer = window.open('', 'TanqPrinter', 'height=480,width=640', false);
    Tanq.Printer.document.write ("<html><head><style>body{overflow: auto;font-family: arial, sans-serif;font-size:11px;color: black;}#routeInfo2{display: none;}</style></head><body>" + $("#directions").html() + "</body></html>");
    Tanq.Printer.window.print();
    Tanq.Printer.focus();
}

Tanq.Start = function()
{
    Tanq.Initialize();
    var loc = new GLatLng(52.256401,4.765501)
    var zoom = 13;
    var box = document.getElementById("tbAddress");
    if (Get_Cookie("MyAddress") != null && Get_Cookie("MyAddress") != "undefined" && (!box || $("#tbAddress").val() == ""))
    {
        Tanq.NoZoom = true;
        Tanq.CenterMapOnAddress(Get_Cookie("MyAddress"));
        if (box)
        {
            $("#tbAddress").val(Get_Cookie("MyAddress"));
        }
        
        //var geo = new GClientGeocoder();
        //geo.getLocations(Get_Cookie("MyAddress"), Tanq.LocationCallback);
    }
    else if (box && $("#tbAddress").val() != "")
    {
        Tanq.NoZoom = true;
        Tanq.CenterMapOnAddress($("#tbAddress").val());
        Set_Cookie("MyAddress", $("#tbAddress").val(), 1);
    }
    else
    {
        if (google.loader.ClientLocation)
        {
            var cl = google.loader.ClientLocation;
            if (cl.address && cl.address.city) 
            {
                if (box)
                {
                    $("#tbAddress").val(cl.address.city);
                }
            }
            zoom = 12;
            loc = new GLatLng(cl.latitude,cl.longitude);
        }
        Tanq.Map.setCenter(loc, zoom);
        Tanq.getStationData();
    }
   
    GEvent.addListener(Tanq.Map, "moveend", function() 
    {
        Tanq.Map.clearOverlays();
        Tanq.getStationData();
    });
}

Tanq.ShowHighLight = function(address)
{
    Tanq.Initialize();
    if (address)
    {
        Tanq.CenterMapOnAddress(address);
    }
    else
    {
        if (Get_Cookie("MyAddress") != null)
        {
            Tanq.CenterMapOnAddress(Get_Cookie("MyAddress"));
        }
        else
        {
            Tanq.Map.setCenter(new GLatLng(52.256401,4.925501), 7);
        }
    }
}

Tanq.ShowStationInfoAndCenter = function(id)
{
    $.ajax({
          type: "POST",
          contentType: "application/json; charset=utf-8",
          url: "/Services/StationService.asmx/GetStation",
          data: "{'id':'" + id + "'}",
          dataType: "json",
          success: function(data, status)
          {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
             Tanq.ShowStationInfoAndCenterCallback(data.d);
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            
          }
    });
}

Tanq.ShowStationInfoAndCenterCallback = function(station)
{
    Tanq.CurrentStation = station;

    var latlong = new GLatLng(station.Lat,station.Long);
    Tanq.Map.clearOverlays();
    Tanq.Map.setCenter(latlong, 14);

    Tanq.getStationData();
    Tanq.ShowStationInfo(Tanq.CurrentStation);
}

function getListStations(letter)
{
    $("#overview").after("<div id='overviewLayer'><img src='/img/ajax.gif' /></div>");
    $("#overviewLayer").css({"width":$("#overviewContainer").width() + "px","height":$("#overviewContainer").height()});
    $.load("/Stations.aspx?ajax=1&letter=" + letter, "", getListStationsCallback);
}

function getListStationsCallback(responseText, textStatus, XMLHttpRequest)
{
    $("#overview").html(responseText);
    $("#overviewLayer").remove();
}

Tanq.Rss = new Object();
Tanq.Rss.RefreshLink = function()
{
    var fuel = $("#ddlFuel").val();
    var loc = $("#" + Tanq.Rss.Loc).val();
    var url = "http://www.fftanken.nl/RSS/" + loc + "/" + fuel + ".ashx";
    if (loc == "")
    {
        url = "http://www.fftanken.nl/RSS/" + fuel + ".ashx";
    }
    $("#linkUrl").html(url).attr("href", url);
    
}