var map = null;
var stops = null;
var markerCluster = null;

function map_initialize() {
    map = new GMap2(document.getElementById('gmap'));

    map.setCenter(new GLatLng(50.17689812200107, 20.56640625), 4);

    map.savePosition();

    map.enableScrollWheelZoom();
    map.enableContinuousZoom();

    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

    map.addControl(new MapDialog());

    var dep_cities_list = document.getElementById('dep_cities_list');
    var arr_cities_list = document.getElementById('arr_cities_list');

    GEvent.addDomListener(dep_cities_list, 'change', function() {
        map.returnToSavedPosition();

        var dep_city_id = this.options[this.selectedIndex].value;

        if (dep_city_id > 0) {
            var count = stops.length;

            for (i = 0; i < count; i++) {
                if (stops[i].id == dep_city_id) {
                    var marker = new GMarker(stops[i].getLatLng(), map_create_icon('red'));
                    marker.name  = stops[i].name;
                    marker.descr = stops[i].descr;

                    GEvent.addListener(marker, 'mouseover', function() {
                        this.openInfoWindowHtml('<h3>' + this.name + '</h3><p>' + this.descr + '</p>');
                    });

                    GEvent.addListener(marker, 'mouseout', function() {
                        this.closeInfoWindow();
                    });
                }
            }

            map_load_arr_stops(dep_city_id);

            map.addOverlay(marker);
        }
    });

    GEvent.addDomListener(arr_cities_list, 'change', function() {
        map.returnToSavedPosition();

        var dep_city_id = dep_cities_list.options[dep_cities_list.selectedIndex].value;
        var arr_city_id = this.options[this.selectedIndex].value;

        if (dep_city_id > 0 && arr_city_id > 0) {
            map_load_route(dep_city_id, arr_city_id);
        }
    });

    map_load_dep_stops();
}


function map_load_dep_stops() {
    map_set_dialog_text(MAP_LOADING);

    var dep_cities_list = document.getElementById('dep_cities_list');
    var arr_cities_list = document.getElementById('arr_cities_list');

    var opt1 = dep_cities_list.options[0];
    var opt2 = arr_cities_list.options[0];

    dep_cities_list.innerHTML = '';
    arr_cities_list.innerHTML = '';

    dep_cities_list.options[0] = opt1;
    arr_cities_list.options[0] = opt2;

    map.clearOverlays();

    if (markerCluster) {
        markerCluster.clearMarkers();
    }

    var request = GXmlHttp.create();

    request.open('GET', '/gmap/dep_stops.php', true);

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var response = request.responseXML.getElementsByTagName('stop');
            var count = response.length;

            var icon = map_create_icon('blue');

            var markers = new Array();

            for (i = 0; i < count; i++) {
                var id    = response.item(i).getAttribute('city-id');
                var name  = response.item(i).getAttribute('city-name');
                var descr = response.item(i).getAttribute('descr');
                var lat   = response.item(i).getAttribute('lat');
                var lng   = response.item(i).getAttribute('lng');

                dep_cities_list.options[i + 1] = new Option(name, id);

                var marker = new GMarker(new GLatLng(lat, lng), icon);
                marker.id    = id;
                marker.name  = name;
                marker.descr = descr;

                GEvent.addListener(marker, 'mouseover', function() {
                    this.openInfoWindowHtml('<h3>' + this.name + '</h3><p>' + this.descr + '</p>');
                });

                GEvent.addListener(marker, 'mouseout', function() {
                    this.closeInfoWindow();
                });

                GEvent.addListener(marker, 'click', function() {
                    map.returnToSavedPosition();

                    for (i = 0; i < dep_cities_list.length; i++) {
                        if (dep_cities_list.options[i].value == this.id) {
                            dep_cities_list.options[i].selected = true;
                            break;
                        }
                    }

                    map_load_arr_stops(this.id);

                    var marker = new GMarker(this.getLatLng(), map_create_icon('red'));
                    marker.name  = this.name;
                    marker.descr = this.descr;

                    GEvent.addListener(marker, 'mouseover', function() {
                        this.openInfoWindowHtml('<h3>' + this.name + '</h3><p>' + this.descr + '</p>');
                    });

                    GEvent.addListener(marker, 'mouseout', function() {
                        this.closeInfoWindow();
                    });

                    map.addOverlay(marker);
                });

                markers.push(marker);
            }
            
            stops = markers;

            markerCluster  = new MarkerClusterer(map, markers, {gridSize: 1, styles: [{width: 32, height: 32, url: '/gmap/markers/clusters/blue.png', opt_anchor: [1, 4], opt_textColor: '#fff'}]});

            map_set_dialog_text(MAP_STEP_1);
        }
    }

    request.send(null);
}

function map_load_arr_stops(dep_city_id) {
    map_set_dialog_text(MAP_LOADING);

    var arr_cities_list = document.getElementById('arr_cities_list');
    var opt = arr_cities_list.options[0];
    arr_cities_list.innerHTML = '';
    arr_cities_list.options[0] = opt;

    map.clearOverlays();
    markerCluster.clearMarkers();

    var request = GXmlHttp.create();

    request.open('GET', '/gmap/arr_stops.php?dep_city_id=' + dep_city_id, true);

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var response = request.responseXML.getElementsByTagName('stop');
            var count = response.length;

            var icon = map_create_icon('green');

            var markers = new Array();

            for (i = 0; i < count; i++) {
                var id    = response.item(i).getAttribute('city-id');
                var name  = response.item(i).getAttribute('city-name');
                var descr = response.item(i).getAttribute('descr');
                var lat   = response.item(i).getAttribute('lat');
                var lng   = response.item(i).getAttribute('lng');

                arr_cities_list.options[i + 1] = new Option(name, id);

                var marker = new GMarker(new GLatLng(lat, lng), icon);
                marker.id    = id;
                marker.name  = name;
                marker.descr = descr;

                GEvent.addListener(marker, 'mouseover', function() {
                    this.openInfoWindowHtml('<h3>' + this.name + '</h3><p>' + this.descr + '</p>');
                });

                GEvent.addListener(marker, 'mouseout', function() {
                    this.closeInfoWindow();
                });

                GEvent.addListener(marker, 'click', function() {
                    map.returnToSavedPosition();

                    for (i = 0; i < arr_cities_list.length; i++) {
                        if (arr_cities_list.options[i].value == this.id) {
                            arr_cities_list.options[i].selected = true;
                            break;
                        }
                    }

                    map_load_route(dep_city_id, this.id);
                });

                markers.push(marker);
            }

            stops = markers;

            markerCluster  = new MarkerClusterer(map, markers, {gridSize: 1, styles: [{width: 32, height: 32, url: '/gmap/markers/clusters/green.png', opt_anchor: [1, 4], opt_textColor: '#fff'}]});
            map_set_dialog_text(MAP_STEP_2);
        }
    }

    request.send(null);
}

function map_load_route(dep_city_id, arr_city_id) {
    map_set_dialog_text(MAP_LOADING);

    map.clearOverlays();
    markerCluster.clearMarkers();

    var request = GXmlHttp.create();

    request.open('GET', '/gmap/routes.php?dep_city_id=' + dep_city_id + '&arr_city_id=' + arr_city_id, true);

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var response = request.responseXML.getElementsByTagName('route');
            var count = response.length;

            for (i = 0; i < count; i++) {
                var polyline = new GPolyline.fromEncoded({
                    points: response.item(i).getAttribute('points'),
                    levels: response.item(i).getAttribute('levels'),
                    zoomFactor: 32,
                    numLevels: 1,
                    color: '#ff0000'
                });

                map.addOverlay(polyline);
            }

            var response = request.responseXML.getElementsByTagName('stop');
            var count = response.length;

            var icon = map_create_icon('red');

            for (i = 0; i < count; i++) {
                var city  = response.item(i).getAttribute('city-name');
                var descr = response.item(i).getAttribute('descr');
                var lat   = response.item(i).getAttribute('lat');
                var lng   = response.item(i).getAttribute('lng');

                var marker = new GMarker(new GLatLng(lat, lng), icon);
                marker.city  = city;
                marker.descr = descr;

                GEvent.addListener(marker, 'mouseover', function() {
                    this.openInfoWindowHtml('<h3>' + this.city + '</h3><p>' + this.descr + '</p>');
                });

                GEvent.addListener(marker, 'mouseout', function() {
                    this.closeInfoWindow();
                });

                map.addOverlay(marker);
            }

            map_set_dialog_text(MAP_STEP_3);
        }
    }

    request.send(null);
}

function map_create_icon(color) {
    var path = '/gmap/markers/stops/';

    var icon = new GIcon();
    icon.image            = path + color + '/image.png';
    icon.shadow           = path + color + '/shadow.png';
    icon.iconSize         = new GSize(16,32);
    icon.shadowSize       = new GSize(32,32);
    icon.iconAnchor       = new GPoint(8,32);
    icon.infoWindowAnchor = new GPoint(8,0);
    icon.printImage       = path + color + '/printImage.gif';
    icon.mozPrintImage    = path + color + '/mozPrintImage.gif';
    icon.printShadow      = path + color + '/printShadow.gif';
    icon.transparent      = path + color + '/transparent.png';
    icon.imageMap         = [14,0,14,1,14,2,14,3,14,4,14,5,14,6,14,7,14,8,14,9,14,10,14,11,14,12,14,13,14,14,14,15,9,16,9,17,9,18,9,19,9,20,9,21,9,22,9,23,9,24,9,25,9,26,9,27,9,28,9,29,9,30,9,31,6,31,6,30,6,29,6,28,6,27,6,26,6,25,6,24,6,23,6,22,6,21,6,20,6,19,6,18,6,17,6,16,1,15,1,14,1,13,1,12,1,11,1,10,1,9,1,8,1,7,1,6,1,5,1,4,1,3,1,2,1,1,1,0];

    return icon;
}

function map_reset() {
    map.returnToSavedPosition();
    map_load_dep_stops();
}

function map_view_schedule(err_text) {
    var dep_cities_list = document.getElementById('dep_cities_list');
    var arr_cities_list = document.getElementById('arr_cities_list');

    var dep_city_id = dep_cities_list.options[dep_cities_list.selectedIndex].value;
    var arr_city_id = arr_cities_list.options[arr_cities_list.selectedIndex].value;

    if (dep_city_id > 0 && arr_city_id > 0) {
        window.location = window.location + '&show=1&cd=' + dep_city_id + '&ca=' + arr_city_id;
    } else {
        alert(err_text);
    }
}

function map_view_prices(err_text) {
    var dep_cities_list = document.getElementById('dep_cities_list');
    var dep_city_id     = dep_cities_list.options[dep_cities_list.selectedIndex].value;
    var arr_cities_list = document.getElementById('arr_cities_list');
    var arr_city_id     = arr_cities_list.options[arr_cities_list.selectedIndex].value;

    if (dep_city_id > 0 && arr_city_id > 0) {
        document.body.innerHTML = '<form style="display: none" name="priceform" action="" method="post">' +
            '<input name="prices" value="1" /><input name="sector1_o" value="a' + dep_city_id + '" /><input name="sector1_d" value="' + arr_city_id + '" /></form>';
        document.priceform.submit();
    } else {
        alert(err_text);
    }
}

function map_buy_tickets(lang_id, err_text) {
    var s;

    switch (lang_id) {
    case 1:
        s = 16;
        break;
    case 2:
        s = 84;
        break;
    case 3:
        s = 55;
        break;
    case 4:
        s = 514;
        break;
    case 5:
        s = 526;
        break;
    case 6:
        s = 594;
        break;
    case 7: 
        s = 718;
        break;
    case 9:
        s = 938;
        break;
    }

    var dep_cities_list = document.getElementById('dep_cities_list');
    var dep_city_id = dep_cities_list.options[dep_cities_list.selectedIndex].value;
    var arr_cities_list = document.getElementById('arr_cities_list');
    var arr_city_id = arr_cities_list.options[arr_cities_list.selectedIndex].value;

    if (dep_city_id > 0 && arr_city_id > 0) {
        document.body.innerHTML = '<form style="display: none" name="buyform" action="http://www.ecolines.net/index.php?s=' + s + '" method="post">' +
            '<input name="lang" value="' + lang_id + '" /><input name="sector2_o" value="a' + dep_city_id + '" /><input name="sector2_d" value="' + arr_city_id + '" /></form>';
        document.buyform.submit();
    } else {
        alert(err_text);
    }
}

function map_set_dialog_text(text) {
        document.getElementById('dialog').innerHTML = text;
}