﻿// promenne aplikace
var Application = new function() {

    // inicializace
    this.init = function(comb, lang) {
        this.comb = comb;
        this.lang = lang;
    }
}


// lokalizace - preklady
var Localization = new function() {
    var lstr = [];
    lstr['ObjectIdentification.C'] = 'Probíhá nalezení nejbližších zastávek ...';
    lstr['ObjectIdentification.G'] = 'Die nächstliegenden Haltestellen werden gefunden ….';
    lstr['ObjectIdentification.E'] = 'Searching for nearest stops...';    
    lstr['AjaxNoData.C'] = 'Data se nepodařilo převzít.';
    lstr['AjaxNoData.G'] = 'Übernahme der Daten ist gescheitert.';
    lstr['AjaxNoData.E'] = 'Failed to retrieve the data.';
    
    // vraci lokalizovany retezec
    this.getString = function(stringId) {
        return lstr[stringId + '.' + Application.lang];
    }
        
}


// zobrazeni cekani na akci
var WaitingDiv = new function() {
    var $ = jQuery;

    // zobrazeni divu pres celou stranku
    this.show = function(text, showWaitDiv) {
        showWaitDiv = showWaitDiv == undefined ? false : showWaitDiv;

        var waitDiv = document.getElementById('waitingdiv');
        if (showWaitDiv && waitDiv) {
            waitDiv.style.display = 'block';
            waitDiv.style.width = window.document.documentElement.clientWidth + 'px';       // only for ie6
            waitDiv.style.height = window.document.documentElement.clientHeight + 'px';     // only for ie6
        }

        var textDiv = document.getElementById('waitingdivtext');
        if (textDiv) {
            textDiv.innerHTML = text;
            textDiv.style.display = 'block';
            textDiv.style.top = (window.document.documentElement.clientHeight / 2 - (textDiv.offsetHeight / 2)) + 'px';
            textDiv.style.left = (window.document.documentElement.clientWidth / 2 - (textDiv.offsetWidth / 2)) + 'px';
            $(document.body).addClass("ajaxwait");
        }
    }

    // skryti divu pres celou stranku
    this.hide = function() {
        var waitDiv = document.getElementById('waitingdiv');
        var textDiv = document.getElementById('waitingdivtext');
        if (waitDiv) { waitDiv.style.display = 'none'; }
        if (textDiv) { $(document.body).removeClass("ajaxwait"); textDiv.style.display = 'none'; }
    }
    
}


// zpracovani AJAX pozadavku
var AjaxRequest = new function() {

    // chyba zpracovani pri AJAX pozadavku
    this.failed = function(xhr, status) {
        if (xhr.status == 0) { return; }
        var detail = 'status: ' + xhr.status;
        if (status == 'timeout') detail += ', timeout';
        alert(Localization.getString('AjaxNoData') + ' (' + detail + ')');
    }

}


// mapa
var MapView = new function() {
    var $ = jQuery;

    this.objects = [];
    this.routes = [];

    // inicializace map
    this.init = function(minX, minY, maxX, maxY, colorMap, showPOIs, showStations, chooseStation, choosePosition, inputObjectId) {
        this.showPOIs = showPOIs;
        this.showStations = showStations;
        this.chooseStation = chooseStation;
        this.choosePosition = choosePosition;
        this.inputObjectId = inputObjectId;
        this.colorMap = colorMap;

        // inicializace mapy
        var mapSize = this._getMapSize();
        this.cfg = new Joms.AppConf();
        this.cfg.width = mapSize.width;
        this.cfg.height = mapSize.height;

        this.app = new Joms.App('mapImage', this.cfg);
        if (minX > 0) {
            this.defaultMapRect = new Joms.Rect(new Joms.Coord(minX, minY), new Joms.Coord(maxX, maxY));
            this.app.initRect(this.defaultMapRect, 'chaps');

        } else {
            this.app.init('chaps', 3, new Joms.Coord(459646, 5548311));
        }

        new Joms.MoveControl(this.app);       // posuvnik
        new Joms.ZoomControl(this.app);       // zoom
        if (!colorMap) { this.switchOpacity(colorMap); }

        //zobrazeni objektu, stanic, drah, cest, ...
        this._showObjects();
        this._showRoutes();
        this.app.hooks.register('mapChanged', this.mapChanged, this);

        // vyber pozice na mape
        if (this.choosePosition) {
            this.app.hooks.register('mapClicked', this.mapClicked, this);
            $('#mapJomsmapImage img').css('cursor', 'pointer');
        };

        $(window).bind('load', function() { MapView.pageLoad(); });
        $(window).bind('resize', function() { MapView.resizeWindow(); });
    }

    // nacteni stranky
    this.pageLoad = function() {
        WaitingDiv.hide();
    }

    // zmena velikosti okna
    this.resizeWindow = function() {
        var mapSize = this._getMapSize();
        this.app.setMapSize(mapSize.width, mapSize.height);
    }

    // vypocita velikost mapy
    this._getMapSize = function() {
        var mapMain = document.getElementById('mapMain');
        var mapBottom = document.getElementById('mapBottom');
        var border = (mapMain.offsetWidth - mapMain.clientWidth);
        return {
            width: window.document.documentElement.clientWidth - border,
            height: mapBottom.offsetTop - mapMain.offsetTop - border + 1
        };
    }

    // zmena pruhlednosti mapy
    this.switchOpacity = function(colorMap) {
        this.colorMap = colorMap;
        this.app.map.switchOpacity();
        this._showAllObjects(this.dynamicObjects);
        if (colorMap) {
            $('#switchMonoMap').show();
            $('#switchColorMap').hide();
        } else {
            $('#switchMonoMap').hide();
            $('#switchColorMap').show();
        }
    }

    // vycentrovat
    this.center = function() {
        if (!this.defaultMapRect) { this.app.map.setCenter(new Joms.Coord(459646, 5548311), 3); return; }
        this.app.map.zoomToRect(this.defaultMapRect);
    }


    // osetreni udalosti pri kliknuti na mapu
    this.mapClicked = function(pp, cp, rClick) {
        // if (rClick) { $('#mapSearch').html(cp.x + ' ' + cp.y + ' ' + this.app.map.getCurrentZoomMppx()); return; }
        var ajaxData = { comb: Application.comb, lang: Application.lang, x: cp.x, y: cp.y };

        $.ajax({
            dataType: 'json',
            url: '../AJAXService.svc/CheckChosenObject',
            timeout: 3 * 1000,
            data: ajaxData,
            success: function(data) { MapView._setChosenObject(data.d, cp); },
            error: function(xhr, status, exception) { AjaxRequest.failed(xhr, status); }
        });
    }

    // vysledek kontroly vybrane pozice na mape
    // nastaveni vybraneho objektu
    this._setChosenObject = function(result, cp) {
        if (result.length > 0) { alert(result); return; }
        SetObjectChoiceMapValue(this.inputObjectId, cp.x, cp.y);
    }


    // osetreni udalosti pri zmene mapy - je nutne provadet se zpozdenim, aby se zbytecne nezatezoval server
    this.mapChanged = function() {
        if (this._mapChangeTimeOut) clearTimeout(this._mapChangeTimeOut);
        this._mapChangeTimeOut = setTimeout(function() { MapView._showObjects(); }, 200);
        if (this.choosePosition) { $('#mapJomsmapImage img').css('cursor', 'pointer'); };
    }

    // nacteni objektu pro dany vyrez mapy
    this._showObjects = function() {
        var mppx = this.app.map.getCurrentZoomMppx();
        var showStations = this.showStations && (mppx <= 4);
        var showPOIs = this.showPOIs && (mppx <= 4);
        if (!(showPOIs || showStations)) { this._showAllObjects(null); return; }
        var rect = this.app.map.getViewRect();          // obtain map rect
        var ajaxData = { comb: Application.comb, lang: Application.lang, mppx: mppx,
            minX: rect.lb.x, maxX: rect.rt.x, minY: rect.lb.y, maxY: rect.rt.y,
            showStations: showStations, chooseStation: this.chooseStation,
            showPOIs: showPOIs
        };

        $.ajax({
            dataType: 'json',
            url: '../AJAXService.svc/GetObjects',
            timeout: 3 * 1000,
            data: ajaxData,
            success: function(data) { MapView._showAllObjects(data.d); },
            error: function(xhr, status, exception) { AjaxRequest.failed(xhr, status); }
        });
    }

    // zobrazeni objektu v danem vyrezu mapy
    this._showAllObjects = function(dynamicObjects) {
        if (!this.objectsLayer) { this.objectsLayer = new Joms.CustomLayer(this.app, 'objects'); }
        this.objectsLayer.clear();
        if (dynamicObjects) {
            this.dynamicObjects = dynamicObjects;
            this._addObjects(dynamicObjects);
        }
        if (this.objects) { this._addObjects(this.objects); }
    }

    // pridani objektu do mapy
    this._addObjects = function(objects) {
        for (var i = 0; i < objects.length; i++) {
            var point = new Joms.Marker(this.app, new Joms.Coord(objects[i].x, objects[i].y), this._getIcon(objects[i]));
            if (objects[i].station && this.chooseStation) {
                point.setClickAction(SetObjectChoiceStationName, this.inputObjectId, objects[i].station.name, objects[i].station.virtListID, objects[i].station.code);
            }
            if (objects[i].description) {
                point.setClickAction(function(description) { this.openTextBox(description); }, objects[i].description);
            } else if (this._isPOI(objects[i]) && !this.choosePosition) {
                point.setClickAction(function(object) { MapView.showPOIDescription(this, object); }, objects[i]);
            }
            if (objects[i].title) { point.setTitle(objects[i].title); }
            this.objectsLayer.add(point);
        }
    }

    // pro dany objekt vraci odpovidajici ikonu
    this._getIcon = function(object) {
        if (!this.icons) this.icons = [];
        if (object.station) { return this._getStationIcon(object); }

        var id = object.type;
        if (this._isPOI(object)) id += this.colorMap ? '' : 'l';
        if (!this.icons[id]) this.icons[id] = this._getIconByType(id);
        return this.icons[id];
    }

    // pro dany objekt vraci odpovidajici ikonu
    this._getIconByType = function(id) {
        switch (id) {
            case 'cursor': return new Joms.Icon('../img/Map/cursor.png', 24, 24, Joms.IconCenter.TOP_LEFT, 'png');
            case 'selected': return new Joms.Icon('../img/Map/selected.png', 24, 24, Joms.IconCenter.CENTER, 'png');
            default: return new Joms.Icon('../img/Map/' + id + '.png', 16, 16, Joms.IconCenter.CENTER, 'png');
        }
    }

    // pro danou stanici vraci odpovidajici ikonu
    this._getStationIcon = function(object) {
        // nazev ikony
        var id = object.type;
        var colors = ['FF0000', 'FF8080', '008000', '80FF80', '0000FF', '8080FF',
            '808000', 'C0C064', 'FF00FF', 'FF80FF', '00BA00', '80BA80',
            '800080', 'E050E0', '808080', 'C0C0C0', 'A52A2A'];
        for (var i = 0; i < colors.length; i++) {
            if (object.station.color == colors[i]) { id = object.station.color; break; }
        }

        // velikost ikony
        var mppx = this.app.map.getCurrentZoomMppx();
        var zoom = [1, 2, 4, 8, 16, 32];
        var iconSize = [15, 14, 12, 12, 10, 7];
        var size = iconSize[iconSize.length - 1];
        for (var i = 0; i < zoom.length; i++) {
            if (mppx <= zoom[i]) { size = iconSize[i]; break; }
        }

        var stationUrl = '../Resource.ashx?type=mapicon&name=' + id + '&width=' + size + '&height=' + size;
        if (!this.icons[id + size]) this.icons[id + size] = new Joms.Icon(stationUrl, size, size, Joms.IconCenter.CENTER, 'png');
        return this.icons[id + size];
    }


    // vraci true, pokud se jedna o objekt zajmu
    this._isPOI = function(object) {
        return !isNaN(parseInt(object.type));
    }
    
    // nacteni popisu objektu zajmu
    this.showPOIDescription = function(marker, object) {
        $.ajax({
            dataType: 'json',
            url: '../AJAXService.svc/GetPOIDescription',
            timeout: 3 * 1000,
            data: { id: object.id, type: object.type },
            success: function(data) { MapView._showPOIDescription(marker, data.d); },
            error: function(xhr, status, exception) { AjaxRequest.failed(xhr, status); }
        });
    }

    // zobrazeni bubliny s popisem objektu zajmu
    this._showPOIDescription = function(marker, data) {
        marker.openTextBox(data);
    }
    

    // zobrazeni drah/cest
    this._showRoutes = function() {
        for (var i = 0; i < this.routes.length; i++) {
            this._showRoute(this.routes[i], 'route' + i);
        }
    }

    // zobrazeni drahy/cesty
    this._showRoute = function(route, routeId) {
        var polyline = new Joms.Polyline(this.app, routeId, Joms.Polyline.Type.LINE, new Joms.PolylineBrowserRenderer(this.app));
        polyline.setWidth(4);
        polyline.setStroke(Joms.Polyline.Stroke.SOLID);
        polyline.setColor(route.color);

        for (var i = 0; i < route.x.length; i++) {
            var coor = new Joms.Coord(route.x[i], route.y[i]);
            polyline.addPoint(coor);
        }

        polyline.redraw();
    }

}


// nastaveni vyhledaneho objektu do vyhledavaciho formulare
function SetObjectChoiceMapValue(formItemName, x, y) {
	if (window.top.opener == null) {window.top.close(); return;};
	if (window.top.opener.closed) {window.top.close(); return;};
	var cboObject = window.top.opener.document.getElementById(formItemName + '_cboObject');
	var txtObject = window.top.opener.document.getElementById(formItemName + '_txtObject');
	var cboCategory = window.top.opener.document.getElementById(formItemName + '_cboCategory');
	var txtFormAction = window.top.opener.document.getElementById(formItemName + '_txtFormAction');
	var ctlErrorRow = window.top.opener.document.getElementById(formItemName + '_ctlErrorRow');
	
	if (txtObject && cboObject && (cboObject.style.display != 'none')) {	
		cboObject.style.display = 'none';
		txtObject.style.display = 'inline';
		txtFormAction.value = '1';
		if (cboCategory) {cboCategory.disabled = false;}
	}
	
	if ((txtObject == null) || cboCategory == null) {return;}
	if (ctlErrorRow) {ctlErrorRow.style.display = 'none';}
	txtObject.value = 'm:' + x + ',' + y
	cboCategory.selectedIndex = 0;
	window.top.close();
}

// nastaveni vyhledaneho nazvu zastavky do vyhledavaciho formulare
function SetObjectChoiceStationName(formItemName, stationName, stationVirtListID, sVirtListItemCode) {
	if (window.top.opener == null) {window.top.close(); return;};
	if (window.top.opener.closed) {window.top.close(); return;};
	
	var cboObject = window.top.opener.document.getElementById(formItemName + '_cboObject');
	var txtObject = window.top.opener.document.getElementById(formItemName + '_txtObject');
	var cboCategory = window.top.opener.document.getElementById(formItemName + '_cboCategory');
	var txtVirtListItemCode = window.top.opener.document.getElementById(formItemName + '_txtVirtListItemCode');
	var txtFormState = window.top.opener.document.getElementById(formItemName + '_txtFormState');
	var txtFormAction = window.top.opener.document.getElementById(formItemName + '_txtFormAction');
	var ctlErrorRow = window.top.opener.document.getElementById(formItemName + '_ctlErrorRow');
	
	if (txtObject && cboObject && (cboObject.style.display != 'none')) {	
		cboObject.style.display = 'none';
		txtObject.style.display = 'inline';
		txtFormAction.value = '1';
		if (cboCategory) {cboCategory.disabled = false;}
	}
	
	if ((txtObject == null) || (cboCategory == null) || (txtVirtListItemCode == null) || (txtFormState == null)) {return;}
	if (ctlErrorRow) {ctlErrorRow.style.display = 'none';}
	txtObject.value = stationName;
	txtFormState.value = stationName + ';' + stationVirtListID;
	txtVirtListItemCode.value = sVirtListItemCode;
	for (var i = 0; i < cboCategory.options.length; i++) {
		if (cboCategory.options[i].value == stationVirtListID) {
			cboCategory.selectedIndex = i;
			break;
		}
	}
	window.top.close();
}

// zkontroluj zda formular pro vyhledavani obsahuje alespon dva znaky
function CheckSearchForm(message) {
	var phrase = document.getElementById('phrase');
	if (phrase.value.length < 2) {
		alert(message);
		phrase.focus();
		return false;
	}
	return true;
}

