/* ---- Put your site specific functions in here --- */

/* Events */
var all_bcs = false;
var zoomlenslevel = 9;
var filterSubmit = true;

$(window.document).ready(function () {


$("#add_car").hide();
	 
$("#add_car_cta").click(function() {
  $("#add_car").show();
  $(this).hide();
})

$("#add_car a").click(function() {
  $("#add_car").hide();
  $("#add_car_cta").show();
})

$(".edit_license form").hide();

$(".edit_license a").click(function() {
  $(this).parent().next().show();
  $(this).parent().hide();
  return false;
});
 



    if ($('#merk').length > 0 && $('#search-form').length > 0) {
        var fields = new Array('merk', 'model', 'carrosserievorm', 'brandstof');
        for (var i = 0; i < fields.length; i++) {
            $('#'+fields[i]).bind('change', loadSearchFieldsJs);
        }
        $('#merk').trigger('change');
    }

    if ($('#search-form').length > 0) {
        $('#advanced_link').click(function () {
            filterSubmit = false;
            var form = $('#search-form');
            form.attr('action', $(this).attr('href'));
            form.submit();
            return false;
        });
    }

    function filterSubmit() {
        if (!filterSubmit) return;
        var form = $(this);
        if (form.find('select#model').val() != 0) {
            var merk = $('select#merk option:selected').text().replace(' ', '-').toLowerCase();
            var model = $('select#model option:selected').text().replace(' ', '-').toLowerCase();
            form.attr('action', $(this).attr('action')+merk+'/'+model+'/');
        }
        else if (form.find('select#merk').val() != 0) {
            var merk = $('select#merk option:selected').text().replace(' ', '-').toLowerCase();
            form.attr('action', $(this).attr('action')+merk+'/');
        }
        form.find('button').attr('disabled', true);
    }
    $(document).ready(function () {
        $('#search-form').submit(filterSubmit);
    });

    // Mail a friend
    if ($('#form_carmailafriend').length > 0) {
        $('.remove_friend').click(function () {
            var input = $($(this).siblings('input')[0]);
            var num = input.attr('name').split('_')[2];
            input.parent().remove();
            $('#name_extrafriend_'+num).parent().remove();
        });

        var friend_count = $('#friend_to_list dd').length / 2;
        var span = $(document.createElement('span'));
        span.attr('class', 'add_friend');
        var a = $(document.createElement('a'));
        a.attr('href', 'javascript:void(0);');
        a.html('Nog een vriend mailen');
        a.click(function () {
            var dd_name = $(document.createElement('dd'));
            var label = $(document.createElement('label'));
            // Input for name
            var name = 'naam_friend_'+friend_count;
            label.attr('for', name);
            label.html('Naam: *');
            dd_name.append(label);
            var input = $(document.createElement('input'));
            input.attr('id', name);
            input.attr('name', 'name_extrafriend_'+friend_count);
            dd_name.append(input);
            $('#friend_to_list').append(dd_name);
            // Input for email
            var dd_email = $(document.createElement('dd'));
            var label = $(document.createElement('label'));
            var name = 'email_friend_'+friend_count;
            label.attr('for', name);
            label.html('E-mailadres: *');
            dd_email.append(label);
            var input = $(document.createElement('input'));
            input.attr('id', name);
            input.attr('name', 'email_extrafriend_'+friend_count);
            dd_email.append(input);
            var a = $(document.createElement('a'));
            a.attr('href', 'javascript:void(0);');
            a.attr('class', 'remove_friend');
            a.html('Verwijderen');
            a.click(function () {
                dd_name.remove();
                dd_email.remove();
            });
            dd_email.append(a);
            $('#friend_to_list').append(dd_email);
            friend_count++;
        });
        span.append(a);
        $('#friend_to_list').after(span);
    }
});

function loadSearchFieldsJs() {
    var merk = $('#merk').val();
    var temp = arrModels[merk];
    switch ($(this).attr('id')) {
        case 'merk':
            var modsel = $('#model');
            sel = $('#model option:selected').val();
            modsel.attr('length', 0);
            var option = $(document.createElement('option'));
            option.val(0);
            option.text('Alle modellen');
            modsel.append(option);

            if (merk == 0) {
                modsel.attr('disabled', true);
            } else {
                var model = '';
                var model_count = 0;

                for (var i = 0; i < temp.length; i++) {
                    if (model != temp[i][0]) {
                        var option = $(document.createElement('option'));
                        option.val(temp[i][0]);
                        option.text(temp[i][0]);

                        if (sel == temp[i][0]) {
                            option.attr('selected', true);
                        }

                        modsel.append(option);

                        model = temp[i][0];
                        model_count++;
                    }
                }
                modsel.attr('disabled', false);
            }
    		populateFuel();
            populateTypes();
            break;
        case 'model':
            var model = $('#model').val();
            var uitsel = $('#carrosserievorm');
            uitsel.attr('length', 0);
            var option = $(document.createElement('option'));
            option.val(0);
            option.text('Alle uitvoeringen');
            uitsel.append(option);

            if (model == 0) {
            } else {
            }
    		populateFuel();
            populateTypes();
            break;
        case 'uitvoering':
    		populateFuel();
            break;
    }
}

var origTypes = new Array();
function populateTypes() {
    var merk = $('#merk').val();
    //var temp = arrModels[merk];
    var model = $('#model').val();
    var uitsel = $('#carrosserievorm');

    var sel = $('#carrosserievorm option:selected').val();

    if (origTypes == 0) {
        var options = uitsel.attr('options');
        for (var i = 0; i < options.length; i++) {
            var option = $(options[i]);
            origTypes.push(new Array(option.val(), option.text()));
        }
    }

    uitsel.attr('length', 0);
    if (merk == 0) {
        // Just populate with all types
        for (var i = 0; i < origTypes.length; i++) {
            var option = $(document.createElement('option'));
            option.val(origTypes[i][0]);
            option.text(origTypes[i][1]);
            if (sel == origTypes[i][0]) {
                option.attr('selected', true);
            }
            uitsel.append(option);
        }
    }
    else {
        var option = $(document.createElement('option'));
        option.val(0);
        option.text('Alle uitvoeringen');
        uitsel.append(option);

        var temp = arrModels[merk];
        for (var i = 0; i < temp.length; i++) {
            if (model != 0 && temp[i][0] != model) {
                continue;
            }

            var options = uitsel.attr('options');

            // Prevent duplicates
            in_array = false;
            for (var j = 0; j < options.length; j++) {
                if ($(options[j]).val() == temp[i][1]) {
                    in_array = true;
                    break;
                }
            }
            if (!in_array) {
                var option = $(document.createElement('option'));
                option.val(temp[i][1]);
                option.text(getTypeName(temp[i][1]));
                if (sel == temp[i][1]) {
                    option.attr('selected', true);
                }
                uitsel.append(option);
            }
        }
    }
}

var origFuels = new Array();
function populateFuel() {
    var brandsel = $('#brandstof');
    var sel = $('#brandstof option:selected').val();
    if (origFuels == 0) {
        var options = brandsel.attr('options');
        for (var i = 0; i < options.length; i++) {
            var option = $(options[i]);
            origFuels.push(new Array(option.val(), option.text()));
        }
    }
    brandsel.attr('length', 0);

    var merk = $('#merk').val();
    var model = $('#model').val();
    var uitvoering = $('#carrosserievorm').val();

    if (merk == 0) { // Going through the entire array is too slowwww
        for (var i = 0; i < origFuels.length; i++) {
            var option = $(document.createElement('option'));
            option.val(origFuels[i][0]);
            option.text(origFuels[i][1]);
            if (sel == origFuels[i][0]) {
                option.attr('selected', true);
            }
            brandsel.append(option);
        }
    } else {
        var option = $(document.createElement('option'));
        option.val(0);
        option.text('Alle brandstof');
        brandsel.append(option);

        for (tmerk in arrModels) {
            if (merk != 0 && merk != tmerk) {
                continue;
            }
            var temp = arrModels[tmerk];
            for (var i = 0; i < temp.length; i++) {
                if (model != 0 && temp[i][0] != model) {
                    continue;
                }
                if (uitvoering != 0 && temp[i][1] != uitvoering) {
                    continue;
                }

                var options = brandsel.attr('options');
                in_array = false;
                for (var j = 0; j < options.length; j++) {
                    if ($(options[j]).text() == temp[i][2]) {
                        in_array = true;
                        break;
                    }
                }
                if (!in_array) {
                    var option = $(document.createElement('option'));
                    option.val(temp[i][2]);
                    option.text(temp[i][2]);
                    if (sel == temp[i][2]) {
                        option.attr('selected', true);
                    }
                    brandsel.append(option);
                }
            }
        }
    }
}

/* Functions */

// Toon een element
function showID(id) {
    document.getElementById(id).style.display = "block";
    }

// Verberg een element
function hideID(id) {
    document.getElementById(id).style.display = "none";
    }

// Tabbladen
function tabblad (activeTab, name){
    tab_prefix = name ? 'tab_' + name + '_' : 'tab_';
    var i=1;
    while (element = document.getElementById(tab_prefix + i)){
        if (i == activeTab){
            element.className = 'current';
            document.getElementById('content' + tab_prefix + i).className = 'showit';
        }
        else{
            element.className = '';
            document.getElementById('content' + tab_prefix + i).className = 'hide';
        }
        i++;
    }
}

// This function formats numbers by adding commas
function numberFormat(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1))
    x1 = x1.replace(rgx, '$1' + '.' + '$2');
  return x1 + x2;
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
       num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));

    //return (((sign)?'':'-') + '$' + num + '.' + cents);
    return (((sign)?'':'-') + num);
}

function loadSearchFields(changedElement){
    //loads all the data for the homepage search form and the extended search form
    select_merk       = $('#merk').val();
    select_model      = $('#model').val();
    select_uitvoering = $('#carrosserievorm').val();
    select_brandstof  = $('#brandstof').val();
    select_pricefrom  = $('#price_from').val();
    select_pricetill  = $('#price_till').val();
    select_buildfrom  = $('#build_from').val();
    select_buildtill  = $('#build_till').val();
    select_kmfrom     = $('#km_from').val();
    select_kmtill     = $('#km_till').val();
    select_ccfrom     = $('#cc_from').val();
    select_cctill     = $('#cc_till').val();
    select_kgfrom     = $('#kg_from').val();
    select_kgtill     = $('#kg_till').val();
    select_pkfrom     = $('#pk_from').val();
    select_pktill     = $('#pk_till').val();

    extended_search = false;

    url = 'ajax/getSearchFormFields.php?action='+changedElement+'&brand='+select_merk+'&model='+select_model+'&type='+select_uitvoering+'&fuel='+select_brandstof+'&buildfrom='+select_buildfrom+'&buildtill='+select_buildtill+'&kmfrom='+select_kmfrom+'&kmtill='+select_kmtill;

    if ($('#transmissie').length > 0){
        //extended search
        extended_search = true;

        url += '&ext=true';

        select_transmission= $('#transmissie').val();
        select_doors= $('#aantal_deuren').val();
        select_carrosserie= $('#carrosserievorm').val();
        select_color= $('#kleur').val();
        url += '&transmission='+select_transmission+'&doors='+select_doors+'&carrosserie='+select_carrosserie+'&color='+select_color;
    }

    $.getJSON(url,
        function(data){
            if (changedElement == 'MERK' ||
                changedElement == '' ||
                changedElement == 'BRANDSTOF' ||
                changedElement == 'BUILD_FROM' ||
                changedElement == 'BUILD_TILL' ||
                changedElement == 'KM_FROM' ||
                changedElement == 'KM_TILL' ||
                changedElement == 'TRANSMISSION' ||
                changedElement == 'DOORS' ||
                changedElement == 'CARROSSERIE' ||
                changedElement == 'COLOR'){
                $('#merk').empty();
                $('#merk').append('<option value="0">Alle merken</option>');
                $.each(data.brands, function(i,item){
                    if (item.value == select_merk){
                        strSelected = 'selected="selected"';
                    } else {
                        strSelected = '';
                    }
                    $('#merk').append('<option value="'+item.value+'" '+strSelected+'>'+item.content+'</option>');
                });
            }

            if (select_merk != 0){
                //enable Model select and get all the Models
                $('#model').empty();
                $('#model').append('<option value="0">Alle modellen</option>');
                $('#model').removeAttr("disabled");

                $.each(data.models, function(i,item){
                    if (item.value == select_model){
                        strSelected = 'selected="selected"';
                    } else {
                        strSelected = '';
                    }
                    $('#model').append('<option value="'+item.value+'" '+strSelected+'>'+item.content+'</option>');
                });
            } else {
                //no Merk is selected so disable the Model select
                $('#model').attr("disabled","disabled");
                $('#model').empty();
                $('#model').append('<option value="">Kies eerst een merk</option>');
            }

            if (select_model != 0){
                $('#uitvoering').empty();
                $('#uitvoering').append('<option value="0">Alle Uitvoeringen</option>');
                $('#uitvoering').removeAttr("disabled");
                $.each(data.types, function(i,item){
                    if (item.value == select_uitvoering){
                           strSelected = 'selected="selected"';
                       } else {
                           strSelected = '';
                       }
                       $('#uitvoering').append('<option value="'+item.value+'" '+strSelected+'>'+item.content+'</option>');
                });
            } else {
                //no Model is selected so disable the Uitvoering select
                $('#uitvoering').attr("disabled","disabled");
                $('#uitvoering').empty();
                $('#uitvoering').append('<option value="">Kies eerst een model</option>');
            }

            //Fuel
            $('#brandstof').empty();
            $('#brandstof').append('<option value="0">Alle Brandstof</option>');
            $.each(data.fuel, function(i,item){
                if (item.value == select_brandstof){
                    strSelected = 'selected="selected"';
                } else {
                    strSelected = '';
                }
                $('#brandstof').append('<option value="'+item.value+'" '+strSelected+'>'+item.content+'</option>');
            });

            //Year
            /*
            $('#build_from').empty();
            $('#build_till').empty();
            $('#build_from').append('<option value="" ></option>');
            $('#build_till').append('<option value="" ></option>');
            i = 0;
            $.each(data.years, function(i,item){
                //build_from
                if (item.value == select_buildfrom)
                    strSelected = 'selected="selected"';
                else
                    strSelected = '';

                if (i<data.years.length-1)
                    $('#build_from').append('<option value="'+item.value+'" '+strSelected+'>'+item.value+'</option>');

                //build_till
                if (item.value == select_buildtill)
                    strSelected = 'selected="selected"';

                if (i>0)
                    $('#build_till').append('<option value="'+item.value+'" '+strSelected+'>'+item.value+'</option>');

                i++;
            });
            */

            //Prices
            /*
            $('#price_from').empty();
            $('#price_till').empty();
            $('#price_from').append('<option value="" ></option>');
            $('#price_till').append('<option value="" ></option>');
            i = 0;
            $.each(data.prices, function(i,item){
                //price_from
                if (item.value == select_pricefrom)
                    strSelected = 'selected="selected"';
                else
                    strSelected = '';

                if (i<data.prices.length-1)
                    $('#price_from').append('<option value="'+item.value+'" '+strSelected+'>'+item.content+'</option>');

                //price_till
                if (item.value == select_pricetill)
                    strSelected = 'selected="selected"';

                if (i>0)
                    $('#price_till').append('<option value="'+item.value+'" '+strSelected+'>'+item.content+'</option>');

                i++;
            });
            */
            //KM
            /*
            $('#km_from').empty();
            $('#km_till').empty();
            $('#km_from').append('<option value="" ></option>');
            $('#km_till').append('<option value="" ></option>');
            i = 0;
            $.each(data.km, function(i,item){
                if (item.value <= 150000){
                    //km_from
                    if (item.value == select_kmfrom)
                        strSelected = 'selected="selected"';
                    else
                        strSelected = '';

                    if (i<data.km.length-1)
                        $('#km_from').append('<option value="'+item.value+'" '+strSelected+'>'+numberFormat(item.content)+'</option>');
                 }

                 if (item.value <= 200000){
                    //km_till
                    if (item.value == select_kmtill)
                        strSelected = 'selected="selected"';

                    if (i>0){
                       if (item.value >= 200000){
                           $('#km_till').append('<option value="'+data.km[data.km.length-1].value+'" '+strSelected+'>200.000 en hoger</option>');
                           if (select_kmtill != '' && select_kmtill > 200000)
                               select_kmtill = '';
                       } else {
                           $('#km_till').append('<option value="'+item.value+'" '+strSelected+'>'+numberFormat(item.content)+'</option>');
                       }
                    }

                    i++;
                }
            });
            */

            if (extended_search){
                /*
                //transmissie
                $('#transmissie').empty();
                $('#transmissie').append('<option value="0">Alle transmissies</option>');
                $.each(data.transmissions, function(i,item){
                    if (item.value == select_transmission)
                        strSelected = 'selected="selected"';
                    else
                        strSelected = '';
                    $('#transmissie').append('<option value="'+item.value+'" '+strSelected+'>'+item.content+'</option>');
                });

                //doors
                $('#aantal_deuren').empty();
                $('#aantal_deuren').append('<option value="0">Alle deuren</option>');
                $.each(data.doors, function(i,item){
                    if (item.value == select_doors)
                        strSelected = 'selected="selected"';
                    else
                        strSelected = '';
                    $('#aantal_deuren').append('<option value="'+item.value+'" '+strSelected+'>'+item.value+'</option>');
                });

                //carrosserie
                $('#carrosserievorm').empty();
                $('#carrosserievorm').append('<option value="0">Alle Carrosserie vormen</option>');
                $.each(data.carrosseries, function(i,item){
                    if (item.value == select_carrosserie)
                        strSelected = 'selected="selected"';
                    else
                        strSelected = '';
                    $('#carrosserievorm').append('<option value="'+item.value+'" '+strSelected+'>'+item.content+'</option>');
                });

                //colors
                $('#kleur').empty();
                $('#kleur').append('<option value="0">Alle kleuren</option>');
                $.each(data.colors, function(i,item){
                    if (item.value == select_color)
                        strSelected = 'selected="selected"';
                    else
                        strSelected = '';
                    $('#kleur').append('<option value="'+item.value+'" '+strSelected+'>'+item.content+'</option>');
                });

                //CC
                $('#cc_from').empty();
                $('#cc_till').empty();
                $('#cc_from').append('<option value="" ></option>');
                $('#cc_till').append('<option value="" ></option>');
                i = 0;
                $.each(data.cc, function(i,item){
                    //cc_from
                    if (item.value == select_ccfrom)
                        strSelected = 'selected="selected"';
                    else
                        strSelected = '';

                    if (i<data.cc.length-1)
                        $('#cc_from').append('<option value="'+item.value+'" '+strSelected+'>'+item.value+'</option>');

                    //cc_till
                    if (item.value == select_pricetill)
                        strSelected = 'selected="selected"';

                    if (i>0)
                        $('#cc_till').append('<option value="'+item.value+'" '+strSelected+'>'+item.value+'</option>');

                    i++;
                });

                //Kg
                $('#kg_from').empty();
                $('#kg_till').empty();
                $('#kg_from').append('<option value="" ></option>');
                $('#kg_till').append('<option value="" ></option>');
                i = 0;
                $.each(data.kg, function(i,item){
                    //kg_from
                    if (item.value == select_kgfrom)
                        strSelected = 'selected="selected"';
                    else
                        strSelected = '';

                    if (i<data.kg.length-1)
                        $('#kg_from').append('<option value="'+item.value+'" '+strSelected+'>'+item.value+'</option>');

                    //kg_till
                    if (item.value == select_kgtill)
                        strSelected = 'selected="selected"';

                    if (i>0)
                        $('#kg_till').append('<option value="'+item.value+'" '+strSelected+'>'+item.value+'</option>');

                    i++;
                });

                //Pk
                $('#pk_from').empty();
                $('#pk_till').empty();
                $('#pk_from').append('<option value="" ></option>');
                $('#pk_till').append('<option value="" ></option>');
                i = 0;
                $.each(data.pk, function(i,item){
                    //pk_from
                    if (item.value == select_pkfrom)
                        strSelected = 'selected="selected"';
                    else
                        strSelected = '';

                    if (i<data.pk.length-1)
                        $('#pk_from').append('<option value="'+item.value+'" '+strSelected+'>'+item.value+'</option>');

                    //pk_till
                    if (item.value == select_pktill)
                        strSelected = 'selected="selected"';

                    if (i>0)
                        $('#pk_till').append('<option value="'+item.value+'" '+strSelected+'>'+item.value+'</option>');

                    i++;
                });
                */
            }
        });
}

/*

        G  O  O  G  L  E         M  A  P  S

*/
var clicked_marker = false;
// var site_root = 'http://www.boschcarservice.nl/'; // In index.php, te irritant om elke keer te veranderen
var map = false;
var ws_index = new Array();
var gmapssession = '';
var boschicon = false;



function WorkshopIndexItem(coordinate, ws_id){
    this.coordinate = coordinate;
    this.visible = false;
    this.marker = false;
    this.ws_id = ws_id;

    this.show = function(){
        if (!this.marker)
            this.marker = this.createMarker();
        else{
            if (!this.visible)
                this.marker.show();
        }
        this.visible = true;

        // todo: implement
    }
    this.hide = function(){
        this.visible = false;
        if (this.marker)
            this.marker.hide();
        // todo: implement
    }
    this.createMarker = function(){
        // todo: implement
        //coord = new GLatLng(this.coordinate.lat()- (Math.random() / 10), this.coordinate.lng()- (Math.random()/10));
        marker = new GMarker(this.coordinate, boschicon);
        map.addOverlay(marker);
        marker.ws_id = this.ws_id;

        GEvent.addListener(marker, 'click', function(){

            clicked_marker = this;
            bounds = map.getBounds();
            ne = bounds.getNorthEast();
            sw = bounds.getSouthWest();

            distY = ne.lat() - sw.lat();

            p = new GLatLng(this.getLatLng().lat() + distY*.3, this.getLatLng().lng());

            map.panTo(p);

            this.openInfoWindowHtml('Wij rijden uw auto\'s nu voor. Een ogenblik geduld a.u.b.');

            jQuery.get(site_root + 'ajax/josse/getDealerHtml.php?id=' + this.ws_id, function(data){
                clicked_marker.openInfoWindowHtml(data);
            });

        });

        return marker;
    }
    this.click = function() {
            clicked_marker = this.marker;
            bounds = map.getBounds();
            ne = bounds.getNorthEast();
            sw = bounds.getSouthWest();

            distY = ne.lat() - sw.lat();

            p = new GLatLng(clicked_marker.getLatLng().lat() + distY*.3, clicked_marker.getLatLng().lng());

            map.panTo(p);

            clicked_marker.openInfoWindowHtml('Wij rijden uw auto\'s nu voor. Een ogenblik geduld a.u.b.');

            jQuery.get(site_root + 'ajax/josse/getDealerHtml.php?id=' + this.ws_id, function(data){
                clicked_marker.openInfoWindowHtml(data);
            });
    }
    this.isWithin = function(sw,ne){

        return (sw.lat() < this.coordinate.lat() && ne.lat() > this.coordinate.lat()
                &&
            sw.lng() < this.coordinate.lng() && ne.lng() > this.coordinate.lng()
        );


    }


}



function drawZoomLocations(){
    var zoomlocations = new Array();

    var icon = new GIcon();
    icon.iconSize = new GSize(35, 35);
    icon.iconAnchor = new GPoint(17.5, 17.5);
    icon.image = site_root + 'images/googlemaps/bosch-vglas.png';

    zoomlocations.push(new GLatLng(53.199452,5.795288));
    zoomlocations.push(new GLatLng(53.215079,6.565704));
    zoomlocations.push(new GLatLng(52.994950,6.558838));
    zoomlocations.push(new GLatLng(52.515803,5.480118));
    zoomlocations.push(new GLatLng(51.984880,5.917511));
    zoomlocations.push(new GLatLng(50.851908,5.700531));
    zoomlocations.push(new GLatLng(51.691288,5.309143));
    zoomlocations.push(new GLatLng(52.378953,4.633484));
    zoomlocations.push(new GLatLng(52.512878,6.095352));
    zoomlocations.push(new GLatLng(52.091531,5.117226));
    zoomlocations.push(new GLatLng(51.498271,3.612442));
    zoomlocations.push(new GLatLng(52.068111,4.297714));

    for(var i=0; i<zoomlocations.length; i++){
        zoommarker = new GMarker(zoomlocations[i], icon);
        GEvent.addListener(zoommarker, 'click', function(){
            map.setCenter(this.getLatLng(), map.getZoom()+2);
        });
        map.addOverlay(zoommarker);
    }

}

function drawWS(callback){

    if (!callback){

        getWS();

    }

    for (var i=0; i<ws_index.length; i++){
        if (ws_index[i].isWithin(sw,ne)){
            ws_index[i].show();
        }
        else
            ws_index[i].hide();
    }

}

function getWS(){
    ws_index = new Array();

    // our server knows which workshops have been indexed offline so it wont return these
    // our server returns 50 workshops at max

    // check the index
    bound = map.getBounds();
    sw = bound.getSouthWest();
    ne = bound.getNorthEast();

    // todo: make ajax call
    var request = GXmlHttp.create();
    request.open("GET", site_root + "ajax/josse/getDealers.php?sw=" + sw + '&ne=' + ne + '&session=' + gmapssession + (all_bcs ? '&all_bcs=true' : ''), true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            map.clearOverlays();
            tmp  = request.responseText.split(/[\r\n]+/);
            for (var i=0; i<tmp.length; i++){
                if (tmp[i]!=''){
                    if (tmp[i].substring(0,12) == 'GMapsSession'){
                        gmapssession = tmp[i].substring(13,tmp[i].length);
                    }
                    else{
                        ws = tmp[i].split(/\s*\,\s*/);
                        ws_index.push(new WorkshopIndexItem(new GLatLng(ws[0]*1,ws[1]*1), ws[2]));
                    }
                }
            }
            drawWS(true);
        }
    }
    request.send(null);
}

function initBoschIcon() {
    boschicon = new GIcon();
    boschicon.image = site_root+"images/googlemaps/logo_bosch.png";
    boschicon.iconSize = new GSize(53, 38);
    boschicon.iconAnchor = new GPoint(16, 38);
    boschicon.infoWindowAnchor = new GPoint(16, 38);
}

function load(){
    if (el = document.getElementById('googlemapoverview')){
        all_bcs = (el.className == 'all_bcs');
        // this page has google maps overview!
        // init map
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById('googlemapoverview'));

            if ($('#selected_dealer').length > 0) {
                initBoschIcon();
                // find and set center of garage
                var lat = $('#latitude').val();
                var lon = $('#longitude').val();
                var latlng = new GLatLng(lat, lon);
                map.setCenter(latlng, 12);
                // create and active pin
                var ws_item = new WorkshopIndexItem(latlng, $('#selected_dealer').val());
                ws_item.show();
                ws_item.click();
            }
            else{
                map.setCenter(new GLatLng(52.500000,5.300000), 8);
            }
            map.addControl(new GLargeMapControl());
            drawZoomLocations();

            GEvent.addListener(map, "zoomend", function(prevZoom, currZoom) {

                if (currZoom<=zoomlenslevel){
                    map.clearOverlays();
                    drawZoomLocations();
                }
                else{
                    if (prevZoom<=zoomlenslevel){   // zoomlensjes worden getoond, we gaan garages tonen
                        map.clearOverlays();

                    }

                    drawWS();
                }

            });

            GEvent.addListener(map, 'dragend', dragendfunction = function(){
                // Met moveend gaat het fout als een ballon geopend wordt,
                // eerst uitvogelen hoe we dat kunnen fixen
                if (map.getZoom()<=zoomlenslevel)
                {}
                else{
                    drawWS();
                }
            });

	//		GEvent.addListener(map, 'moveend', dragendfunction);

            boschicon = new GIcon();
            boschicon.image = site_root+"images/googlemaps/logo_bosch.png";
            boschicon.iconSize = new GSize(53, 38);
            boschicon.iconAnchor = new GPoint(16, 38);
            boschicon.infoWindowAnchor = new GPoint(16, 38);
            if ($('#province_id').length > 0) {
                zoomProvince($('#province_id').val());
            }

        }

    }

}
$('document').ready(function(){load();});

function initGoogleMapDetail(lat_txt,lng_txt,user_id){
    initBoschIcon();

    map = new GMap2(document.getElementById('detailmap'));
    map.setCenter(new GLatLng(lat_txt*1,lng_txt*1), 8);
    map.addControl(new GLargeMapControl());
    ws_index[0] = new WorkshopIndexItem(new GLatLng(lat_txt*1, lng_txt*1), user_id);
    ws_index[0].show();
}
function emptySelectBox(el){
    len = el.options.length;
    for (var i=0; i<len; i++)
        el.options[len-i-1] = null;
}
function findModels(brand_index){
    // empty model list
    listitem = document.getElementById('model');
    emptySelectBox(listitem);

    if (brand_index<1){
        // no brand selected
        listitem.disabled = true;
        listitem.options[0] = new Option('Kies eerst een merk', 0);
        listitem.selectedIndex=0;
    }
    else{
        //options = brand_options[brand_index-1];
        options = new Array()
        listitem.options[0] = new Option('Alle modellen', 0);
        for (var i=0; i<options.length; i++){
            listitem.options[i+1] = new Option(options[i], options[i]);
        }
        listitem.disabled = false;
    }
}

function zoomProvince(province_id) {
        var lats =         new Array(53.199452,   53.215079,    52.994950, 52.515803,   51.984880,    50.851908, 51.691288,       52.378953,       52.512878,    52.091531, 51.498271, 52.068111);
        var lons =         new Array(5.795288,    6.565704,     6.558838,  5.480118,    5.917511,     5.700531,  5.309143,        4.633484,        6.095352,     5.117226,  3.612442,  4.297714);
        var provinces =    new Array('Friesland', 'Groningen', 'Drente',   'Flevoland', 'Gelderland', 'Limburg', 'Noord-Brabant', 'Noord-Holland', 'Overijssel', 'Utrecht', 'Zeeland', 'Zuid-Holland');
        var province_ids = new Array(1,           3,            2,         6,           5,            10,        11,              7,               4,            12,        9,         8);

        for (var i = 0; i < province_ids.length; i++) {
            if (province_ids[i] == province_id) {
                var point = new GLatLng(lats[i], lons[i]);
                map.setCenter(point, 10);
                break;
            }
        }
}
