DataLoader.prototype.mw;
DataLoader.prototype.map;

DataLoader.prototype.fishplaces;
DataLoader.prototype.photos;

DataLoader.prototype.fishplaces_layer;
DataLoader.prototype.photos_layer;

DataLoader.fishplace_info =
'<div style="color: #4A6384; font-size: 14px; font-weight: bold; margin-bottom: 5px; height: 28px;">' +
'   ${header}' +
'</div>' +
'<div style="overflow: auto; width: 100%; height: 130px;" id="place_info">' +
'   <div style="margin-bottom: 2px;"><b>Отловочный билет:</b> ${price}</div>' +
'   <div style="margin-bottom: 2px;"><b>Рыба:</b> ${fishes}</div>' +
'   <div style="margin-bottom: 2px;"><b>Максимальная глубина:</b> ${depth}</div>' +
'   <div style="margin-bottom: 2px;"><b>Площадь водоема:</b> ${square}</div>' +
'   <div style="margin-bottom: 5px; margin-top: 7px;"><b>Контакты владельца:</b><br/> ${contacts}</div>' +
'   <div><b>Описание:</b><br/> ${description}</div>' +
'</div>' +
'<div style="margin-top: 5px; font-size: 12px; font-weight: normal;">' +
'   <a target="_blank" href="/fishplace/${id}/">Паспорт водоема</a>' +
'   &nbsp;|&nbsp;' +
'   <a target="_blank" href="/fishplace/${id}/add_report">Добавить отчет</a>' +
'   &nbsp;|&nbsp;' +
'   <a href="javascript: DataLoader.zoom(${coords})">Приблизить</a>' +
'   <br/>' +
'   Маршрут' +
'   <a href="javascript: DataLoader.routeFrom(${coords})">отсюда</a>' +
'   &nbsp;|&nbsp;' +
'   <a href="javascript: DataLoader.routeTo(${coords})">сюда</a>' +
'</div>';

DataLoader.photo_info =
'<div>' +
'   <b>${name}</b><br/>' +
'   <img width="${width}" height="${height}" src="${filename}"><br/>' +
'   Добавил: <a target="_blank" href="/user/${user_id}/">${username}</a><br/><br/>' +
'   ${description}<br/>' +
'   <a target="_blank" href="/user/${user_id}/photo/${id}">Комментировать</a>' +
'   &nbsp;|&nbsp;' +
'   <a href="javascript: DataLoader.zoom(${coords})">Приблизить</a>' +
'   <br/>' +
'   Маршрут' +
'   <a href="javascript: DataLoader.routeFrom(${coords})">отсюда</a>' +
'   &nbsp;|&nbsp;' +
'   <a href="javascript: DataLoader.routeTo(${coords})">сюда</a>' +
'</div>';

DataLoader.info =
'<div>' +
'   Маршрут' +
'   <a href="javascript: DataLoader.routeFrom(${coords})">отсюда</a>' +
'   &nbsp;|&nbsp;' +
'   <a href="javascript: DataLoader.routeTo(${coords})">сюда</a>' +
'</div>';

DataLoader.poi_info =
'<div style="color: #4A6384; font-size: 14px; font-weight: bold; margin-bottom: 5px; height: 28px;">' +
'   ${header}' +
'</div>' +
'<div style="overflow: auto; width: 100%; height: 130px;" id="place_info">' +
'   <div>${description}</div>' +
'   <div style="margin-bottom: 5px; margin-top: 7px;">${contacts}</div>' +
'</div>' +
'<div style="margin-top: 5px; font-size: 12px; font-weight: normal;">' +
'   <a target="_blank" href="/poi/${id}/">Подробнее</a>' +
'   &nbsp;|&nbsp;' +
'   <a href="javascript: DataLoader.zoom(${coords})">Приблизить</a>' +
'</div>';


/**
 *  @constructor
 */
function DataLoader(mw, map) {
    this.mw = mw
    this.map = map
    DataLoader.map = map

    this.fishplaces = []
    this.photos = []
    this.pois = []

    this.fishplaces_layer = new mw.Layer()
    this.photos_layer = new mw.Layer()
    this.pois_layer = new mw.Layer()
    
    this.map.add(this.fishplaces_layer)
    this.map.add(this.photos_layer)
    this.map.add(this.pois_layer)

    var _this = this;
    this.mw.Events.addListener(this.map, "dragend",
        function() {
            _this.loadFishplaces()
            _this.loadPhotos()
            _this.loadPois()
        }
    )

    this.mw.Events.addListener(this.map, "zoomchange",
        function() {
            _this.loadFishplaces()
            _this.loadPhotos()
            _this.loadPois()
        }
    )

    this.mw.Events.addListener(this.map, "mouseclick",
        function(coords) {
            var info = DataLoader.info
            info = info.replace(/\$\{coords\}/g, "[" + coords[0] + "," + coords[1] + "]")
            _this.map.openInfoWindow(coords, info)
        }
    )
    
    return this;
}

DataLoader.map
DataLoader.zoom = function(coords) {
    DataLoader.map.center(coords, 18)
}

DataLoader.fromCoords
DataLoader.toCoords
DataLoader.route

DataLoader.routeFrom = function(coords) {
    DataLoader.fromCoords = coords
    DataLoader.repaintRoute()
}

DataLoader.routeTo = function(coords) {
    DataLoader.toCoords = coords
    DataLoader.repaintRoute()
}

DataLoader.repaintRoute = function() {
    if (!DataLoader.fromCoords || !DataLoader.toCoords) return
    if (DataLoader.route) DataLoader.map.remove(DataLoader.route)

    DataLoader.route = new mw.Route(DataLoader.map, [DataLoader.fromCoords, DataLoader.toCoords],
        function() {
            DataLoader.map.add(DataLoader.route)
            DataLoader.map.repaint()
        }
    )
}

DataLoader.prototype.init = function() {
    this.loadFishplaces()
    this.loadPhotos()
    this.loadPois()
}

DataLoader.prototype.loadFishplaces = function() {
    var bounds = this.map.bounds()
    var sw = bounds.southwest()
    var ne = bounds.northeast()
    
    var param = sw[1].toPrecision(8) + ',' + sw[0].toPrecision(8) + ';' + ne[1].toPrecision(8) + ',' + ne[0].toPrecision(8);
    
    var _this = this;
    call('/map/fishplaces/' + param + '/' + ((this.map.zoom() < 9) ? 50 : ''),
        function(data) {
            try {
                data = eval("(" + data + ")");
            } catch (err) {return;}
            
            _this.showFishplaces(data);
        }
    );

}

DataLoader.prototype.loadPhotos = function() {
    var bounds = this.map.bounds();
    var sw = bounds.southwest();
    var ne = bounds.northeast();

    var param = sw[1].toPrecision(8) + ',' + sw[0].toPrecision(8) + ';' + ne[1].toPrecision(8) + ',' + ne[0].toPrecision(8);

    var _this = this;
    call('/map/photos/' + param + '/' + ((this.map.zoom() < 9) ? 20 : ''),
        function(data) {
            try {
                data = eval("(" + data + ")");
            } catch (err) {return;}

            _this.showPhotos(data);
        }
    );
}

DataLoader.prototype.loadPois = function() {
    var bounds = this.map.bounds();
    var sw = bounds.southwest();
    var ne = bounds.northeast();

    var param = sw[1].toPrecision(8) + ',' + sw[0].toPrecision(8) + ';' + ne[1].toPrecision(8) + ',' + ne[0].toPrecision(8);
    
    var _this = this;
    call('/map/pois/' + param + '/' + ((this.map.zoom() < 9) ? 20 : ''),
        function(data) {
            try {
                data = eval("(" + data + ")");
            } catch (err) {return;}

            _this.showPois(data);
        }
    );
}

DataLoader.prototype.showFishplaces = function(data) {
    var fishplaces = [];
    var icon = new this.mw.Icon("/images/markers/fishka.gif", 20, 20);
    
    for (var i = 0; i < data.length; i++) {
        fishplaces[data[i].id] = [];
        fishplaces[data[i].id]["data"] = data[i];

        if (this.fishplaces[data[i].id] != null) continue;

        var info = DataLoader.fishplace_info;
        info = info.replace(/\$\{header\}/g, data[i].fishplace_name);
        info = info.replace(/\$\{price\}/g, Common.price_with_cutrrency(data[i].price, data[i].currency));
        info = info.replace(/\$\{fishes\}/g, data[i].fishes);
        info = info.replace(/\$\{depth\}/g, data[i].depth);
        info = info.replace(/\$\{square\}/g, data[i].square);
        info = info.replace(/\$\{contacts\}/g, data[i].contacts);
        info = info.replace(/\$\{description\}/g, data[i].description);
        info = info.replace(/\$\{coords\}/g, "[" + data[i].coords[0] + "," + data[i].coords[1] + "]");
        info = info.replace(/\$\{id\}/g, data[i].id);

        var marker = new this.mw.Marker(data[i].coords, {icon: icon});
        //var marker = new this.mw.Marker(data[i].coords);

        marker.info(info, {width: 500, height: 210});
        marker.hint(data[i].fishplace_name);

        fishplaces[data[i].id]["marker"] = marker;

        this.fishplaces_layer.add(marker);
    }
    
    for (i in this.fishplaces) {
        if (fishplaces[i]) continue;

        marker = this.fishplaces[i]["marker"];
        this.fishplaces_layer.remove(marker);
        this.fishplaces[i] = null;
    }
    
    this.map.repaint();
}

DataLoader.prototype.showPhotos = function(data) {
    var photos = [];
    var icon = new this.mw.Icon("/images/markers/picture.png", 16, 16);

    for (var i = 0; i < data.length; i++) {
        photos[data[i].id] = [];
        photos[data[i].id]["data"] = data[i];

        if (this.photos[data[i].id] != null) continue;

        var info = DataLoader.photo_info;
        info = info.replace(/\$\{name\}/g, data[i].name);
        info = info.replace(/\$\{filename\}/g, data[i].filename);
        info = info.replace(/\$\{width\}/g, data[i].width);
        info = info.replace(/\$\{height\}/g, data[i].height);
        info = info.replace(/\$\{description\}/g, data[i].description);
        info = info.replace(/\$\{coords\}/g, "[" + data[i].coords[0] + "," + data[i].coords[1] + "]");
        info = info.replace(/\$\{id\}/g, data[i].id);
        info = info.replace(/\$\{user_id\}/g, data[i].user_id);
        info = info.replace(/\$\{username\}/g, data[i].username);

        var marker = new this.mw.Marker(data[i].coords, {icon: icon});
        marker.info(info);
        marker.hint(data[i].fishplace_name);

        photos[data[i].id]["marker"] = marker;

        this.photos_layer.add(marker);
    }

    for (i in this.photos) {
        if (photos[i]) continue;

        marker = this.photos[i]["marker"];
        this.photos_layer.remove(marker);
        this.photos[i] = null;
    }

    this.map.repaint();
}

DataLoader.prototype.showPois = function(data) {
    var pois = []
    
    for (var i = 0; i < data.length; i++) {
        pois[data[i].id] = []
        pois[data[i].id]["data"] = data[i]

        if (this.pois[data[i].id] != null) continue

        var info = DataLoader.poi_info
        info = info.replace(/\$\{header\}/g, data[i].name)
        info = info.replace(/\$\{contacts\}/g, data[i].contacts)
        info = info.replace(/\$\{description\}/g, data[i].description)
        info = info.replace(/\$\{coords\}/g, "[" + data[i].coords[0] + "," + data[i].coords[1] + "]")
        info = info.replace(/\$\{id\}/g, data[i].id)
        
		var icon = new this.mw.Icon("/images/markers/poi_" + data[i].rubric + ".png", 32, 37)
        var marker = new this.mw.Marker(data[i].coords, {icon: icon})
        //var marker = new this.mw.Marker(data[i].coords);

        marker.info(info, {width: 500, height: 210});
        marker.hint(data[i].name);

        pois[data[i].id]["marker"] = marker;

        this.pois_layer.add(marker);
    }

    for (i in this.pois) {
        if (pois[i]) continue;

        marker = this.pois[i]["marker"];
        this.pois_layer.remove(marker);
        this.pois[i] = null;
    }

    this.map.repaint();
}
