﻿/* KIT vars */
var currentInputFieldType = 1;
var currentInputFieldId = "";
var currentUpdatePanelId = "";

/*Kartena vars*/
var map = null;
var ici;
var itemCanvas;
var mapLoaded = 0;
var mapHandler;
var standbyParameters = {};
var mapsToShow = {};
var searchMapExpanded = false;

var fromObject;
var toObject;
var viaObject;
var comElement;

var customerAreaId;
var siteUrl;

/*Auocomplete event handlers*/
function AutoCompleteItemSelected(source, eventArgs) {
    HandleHiddenField(eventArgs.get_value(), eventArgs.get_text());
}

function DropDownListItemSelected(source) {
    var selectedValue = source.options[source.options.selectedIndex].value;
    var selectedText = source.options[source.options.selectedIndex].text;
    HandleHiddenField(selectedValue, selectedText);
}

function HandleHiddenField(stopAndCoord, friendlyName) {
    var array = stopAndCoord.split("|");

    if (array.length > 2) {
        if (array[1].length > 0 && array[2].length > 0) {
            if (map) {
                //If an address is selected try to center over coords for stop.
                if (friendlyName.toLowerCase().indexOf("(adress)") != -1) {
                    switch (GetCurrentInputField()) {
                        case 1:
                            if (typeof (window['fromObject']) != "undefined") {
                                if (fromObject != null)
                                    fromObject.clearStop();
                            }
                            break;
                        case 2:
                            if (typeof (window['toObject']) != "undefined") {
                                if (toObject != null)
                                    toObject.clearStop();
                            }
                            break;
                        case 3:
                            if (typeof (window['viaObject']) != "undefined") {
                                if (viaObject != null)
                                    viaObject.clearStop();
                            }
                            break;
                        default:
                            break;
                    }
                    centerOn(array[1], array[2], array[1], array[2]);
                }
                else {
                    SelectStop(array[0].split("!")[0], array[1], array[2], friendlyName, GetCurrentInputField());                
                    centerOnItems(true);
                }
            }
            switch (GetCurrentInputField()) {
                case 1:
                    if (typeof (window['hiddenFieldFromId']) != "undefined") {
                        SetHiddenField(hiddenFieldFromId, stopAndCoord + '#' + friendlyName);
                    }
                    break;
                case 2:
                    if (typeof (window['hiddenFieldToId']) != "undefined") {
                        SetHiddenField(hiddenFieldToId, stopAndCoord + '#' + friendlyName);
                    }
                    break;
                case 3:
                    if (typeof (window['hiddenFieldViaId']) != "undefined") {
                        SetHiddenField(hiddenFieldViaId, stopAndCoord + '#' + friendlyName);
                    }
                    break;
                default:
                    break;
            }

        }
        else {
            /*no coordinates*/

            switch (GetCurrentInputField()) {
                case 1:
                    if (typeof (window['fromObject']) != "undefined") {
                        if (fromObject != null)
                            fromObject.clearStop();
                    }
                    break;
                case 2:
                    if (typeof (window['toObject']) != "undefined") {
                        if (toObject != null)
                            toObject.clearStop();
                    }
                    break;
                case 3:
                    if (typeof (window['viaObject']) != "undefined") {
                        if (viaObject != null)
                            viaObject.clearStop();
                    }
                    break;
                default:
                    break;
            }
        }
    }
}

function SetHiddenField(id, value) {
    if (document.getElementById(id) != null)
        document.getElementById(id).value = value;
}

function PlotHiddenCoordinates() {
    if (document.getElementById(hiddenFieldFromId) != null) {
        if (document.getElementById(hiddenFieldFromId).value != '') {
            PlotHiddenCoordinate(hiddenFieldFromId, 1);
        }
    }
    if (document.getElementById(hiddenFieldToId) != null) {
        if (document.getElementById(hiddenFieldToId).value != '') {
            PlotHiddenCoordinate(hiddenFieldToId, 2);
        }
    }
    if (document.getElementById(hiddenFieldViaId) != null) {
        if (document.getElementById(hiddenFieldViaId).value != '') {
            PlotHiddenCoordinate(hiddenFieldViaId, 3);
        }
    }

    switch (GetCurrentInputField()) {
        case 1:
            if (fromObject)
                fromObject.selected();
            break;
        case 2:
            if (toObject)
                toObject.selected();
            break;
        case 3:
            if (viaObject)
                viaObject.selected();
            break;
        default:
            break;
    }

}

function PlotHiddenCoordinate(field, id) {
    var element = document.getElementById(field);

    var value_text_array = element.value.split("#");

    if (value_text_array.length > 1) {
        var array = value_text_array[0].split("|");

        if (array.length > 2) {
            if (array[1].length > 0 && array[2].length > 0) {
                if (map) {
                    if (value_text_array[1].toLowerCase().indexOf("(adress)") == -1)
                        SelectStop(array[0].split("!")[0], array[1], array[2], value_text_array[1], id);
                    else
                        centerOn(array[1], array[2], array[1], array[2]);
                }
            }
        }
    }
}


function ReturnSearchTrip(source, eventArgs) {
    swap(fromObject, toObject);
}

function NewTripSearch(source, eventArgs) {
    clearAll();
}

function ResetObjects(newelmentid, clearstop) {
    if (newelmentid.indexOf("From") != -1) {
        if (fromObject != null) {
            fromObject.myElement = document.getElementById(newelmentid);
            if (clearstop == true)
                fromObject.clearStop();
        }
    }
    if (newelmentid.indexOf("To") != -1) {
        if (toObject != null) {
            toObject.myElement = document.getElementById(newelmentid);
            if (clearstop == true)
                toObject.clearStop();
        }
    }
    if (newelmentid.indexOf("Via") != -1) {
        if (viaObject != null) {
            viaObject.myElement = document.getElementById(newelmentid);
            if (clearstop == true)
                viaObject.clearStop();
        }
    }
}

function OnDropDownVisible(source, eventArgs) {
    ResetObjects(source, true);
    if (eventArgs != null) {
        var array = eventArgs.split("#");
        if (array.length > 1)
            HandleHiddenField(array[1], array[0]);
    }
}

function OnTextBoxVisible(source, eventArgs) {
    ResetObjects(source, false);
}


function MunicipalityChanged(source, eventArgs) {
    if (eventArgs != null) {
        var coordsArray = eventArgs.split("|");

        if (coordsArray.length > 3) {
            //set current bounding box coordinates
            if (typeof (window['xcoordleft']) != "undefined")
                xcoordleft = coordsArray[0];
            if (typeof (window['ycoordleft']) != "undefined")
                ycoordleft = coordsArray[1];
            if (typeof (window['xcoordright']) != "undefined")
                xcoordright = coordsArray[2];
            if (typeof (window['ycoordright']) != "undefined")
                ycoordright = coordsArray[3];

            centerOn(coordsArray[0], coordsArray[1], coordsArray[2], coordsArray[3]);
        }
    }
}

/*stub methods (Kartena supplies)*/

function SelectStop(stopId, x, y, friendlyname, inputfield) {
    var name = friendlyname;

    var strId = db + "-" + parseInt(stopId, 10);
    if (!itemCanvas.getCached(strId)) {
        var item;
        if (!ici.getCached(strId)) {
            item = new ItemPointImage(Coordinate.create(x, y, CoordinateSystem.SYSTEM_RT90), 'http://api.geosition.com/resources/' + customerAreaId + '/hpl1.gif');
            item.myElement.onclick = function(e) {
                itemClicked(stopId, x, y, friendlyname);
            }
        } else {
            item = new ItemPointImage(ici.getCached(strId).getCoordinate(), ici.getCached(strId).getElement().src);
            item.myElement.onclick = function(e) {
                itemClicked(stopId, x, y, friendlyname);
            }
        }
        item.setTitle(friendlyname);
        itemCanvas.add(item, strId);

        //only used when selecting a object from map link
        if (typeof (window['selectFromMapInputFieldId']) != "undefined") {        
            parent.parent.window.opener.document.getElementById(selectFromMapInputFieldId).value = friendlyname;
            window.close();
        }
        
    }


    if (map) {
        switch (inputfield) {
            case 1: fromObject.setTitle(name);
                updateStopStatus(stopId, x, y, fromObject, name);
                break;
            case 2: toObject.setTitle(name);
                updateStopStatus(stopId, x, y, toObject, name);
                break;
            case 3: viaObject.setTitle(name);
                updateStopStatus(stopId, x, y, viaObject, name);
                break;
            default:
                break;
        }
    }
}

function updateStopStatus(stopId, x, y, obj, friendlyname) {
    var header = "Stop" + GetCurrentInputField() + "-";
    if (obj != null) {
        if (obj && obj.getImage()) {
            itemCanvas.remove(obj.getImage().getId());
        }
        //Adding an icon
        obj.setImage(header + stopId, x, y, friendlyname);
        // itemCanvas.add(image, stopId);    
    }
}

function centerOn(xCoord1, yCoord1, xCoord2, yCoord2) {
    var coords = new Array();

    if (window.Coordinate != null && map != null) {
        coords.push(Coordinate.create(xCoord1, yCoord1, CoordinateSystem.SYSTEM_RT90));
        coords.push(Coordinate.create(xCoord2, yCoord2, CoordinateSystem.SYSTEM_RT90));

        map.setToCoordinates(coords);

    }
}

function removeVia() {
    viaObject.clearImage();
}



/*functions supplied by KIT */
function SelectStopFromMap(stopId, x, y, friendlyname, inputfield) {

    /*put value in correct field attempt to set by javascript before doing a postback*/
    var currentInputField = document.getElementById(currentInputFieldId);

    var defaultInputField;    
    if (typeof (window['defaultInputFieldId']) != "undefined")     
        document.getElementById(defaultInputFieldId);

    var defaultSelectField;
    if (typeof (window['defaultSelectFieldId']) != "undefined")         
        document.getElementById(defaultSelectFieldId);

    if (map) {
        switch (inputfield) {
            case 1:                
                if (typeof (window['hiddenFieldFromId']) != "undefined")     
                SetHiddenField(hiddenFieldFromId, stopId + '!-1|' + x + '|' + y + '#' + friendlyname);
                break;
            case 2:
                if (typeof (window['hiddenFieldToId']) != "undefined")                     
                SetHiddenField(hiddenFieldToId, stopId + '!-1|' + x + '|' + y + '#' + friendlyname);
                break;
            case 3:
                if (typeof (window['hiddenFieldViaId']) != "undefined")                
                SetHiddenField(hiddenFieldViaId, stopId + '!-1|' + x + '|' + y + '#' + friendlyname);
                break;
            default:
                break;
        }
    }

    if (currentInputField != null && currentInputField.tagName.toLowerCase() == "input") {
        currentInputField.value = friendlyname;
        currentInputField.focus();
    }
    else if (currentInputField == null && defaultInputField != null && defaultInputField.tagName.toLowerCase() == "input") {
        document.getElementById(defaultInputFieldId).focus();
        document.getElementById(defaultInputFieldId).value = friendlyname;
    }
    else if (currentInputField != null && currentInputField.tagName.toLowerCase() == "select") {
        __doPostBack(currentUpdatePanelId, currentInputFieldId + ':' + stopId);
    }
    else if (defaultSelectField != null && defaultSelectField.tagName.toLowerCase() == "select") {
        __doPostBack(defaultUpdatePanelId, defaultInputFieldId + ':' + stopId);
    }


}

/*find which field that currently has focus */
function GetCurrentInputField() {
    return currentInputFieldType;
}

function SetCurrentInputField(id) {
    currentInputFieldType = id;
}


/*map util*/
function SetActiveClass(classname, element) {
    var inputContainer = document.getElementById(element);

    if (inputContainer != null) {
        if (inputContainer.className.indexOf(classname) == -1) {
            inputContainer.className = inputContainer.className + ' ' + classname;
        }
    }
}

function ClearActiveClass(classname, element) {
    var inputContainer = document.getElementById(element);

    if (inputContainer != null)
        inputContainer.className = inputContainer.className.replace(' ' + classname, '');
}

function ClearActiveClassOnAll(classname, element) {
    if (element != null && document.getElementById(element)) {
        var tags = document.getElementById(element).getElementsByTagName('input');

        for (i = 0; i < tags.length; i++) {
            tags[i].className = tags[i].className.replace(' ' + classname, '');
        }

        var selects = document.getElementById(element).getElementsByTagName('select');

        for (j = 0; j < selects.length; j++) {
            selects[j].className = selects[j].className.replace(' ' + classname, '');
        }
    }
}

function SetCurrentInputType(id, updatepanelid) {

    ClearActiveClassOnAll('TravelPlannerActiveTextBox', 'TravelPlannerBoxContainer');

    if (id.indexOf("From") != -1) {
        currentInputFieldType = 1;

        SetActiveClass('TravelPlannerActive', 'mapDiv');
        SetActiveClass('TravelPlannerActiveTextBox', id);
        if (fromObject)
            fromObject.selected();
    }
    else if (id.indexOf("To") != -1) {
        currentInputFieldType = 2;

        SetActiveClass('TravelPlannerActive', 'mapDiv');
        SetActiveClass('TravelPlannerActiveTextBox', id);
        if (toObject)
            toObject.selected();
    }
    else if (id.indexOf("Via") != -1) {
        currentInputFieldType = 3;

        SetActiveClass('TravelPlannerActive', 'mapDiv');
        SetActiveClass('TravelPlannerActiveTextBox', id);
        if (viaObject)
            viaObject.selected();
    }
    else {
        currentInputFieldType = -1;

        ClearActiveClass('TravelPlannerActiveBorder', 'mapDiv');
    }

    currentInputFieldId = id;
    currentUpdatePanelId = updatepanelid;
}



/*Load map functions*/
function pageLoad(sender, args) {
    if ($find("CPExtenderMap") != null) {
            
            //Try to remove handler first to avoid several handlers beeing attached
            $find("CPExtenderMap").remove_expandComplete(expandHandler);
            $find("CPExtenderMap").add_expandComplete(expandHandler);

            //Try to remove handler first to avoid several handlers beeing attached
            $find("CPExtenderMap").remove_collapseComplete(collapseHandler);
            $find("CPExtenderMap").add_collapseComplete(collapseHandler);
        
    }
}


function collapseHandler(sender, args) {
    DisposeTravelPlannerMap();
}

function expandHandler(sender, args) {    
    var searchMapExpanded = true;
    initLoaderImage('mapDiv',map);
    lateLoadScript('mapDiv');    
}

function initLoaderImage(mapdivid, mapobject) {    
    if (mapobject == null) {
        var mapDiv = document.getElementById(mapdivid);
        if (mapDiv) {
            mapDiv.style.backgroundImage = "url(/CustomerTemplates/Public/Images/Travelmap/ajax-loader.gif)";
            mapDiv.style.backgroundRepeat = "no-repeat";
            mapDiv.style.backgroundPosition = "50% 50%";
        }
    }

}

function DisposeTravelPlannerMap() {
}

function lateLoadScript(mapdivid) {

    if (!window.gjsf) {
        var root = document.getElementsByTagName('head')[0];

        //Adding the styleSheet
        var styleSheet = document.createElement('link');
        styleSheet.setAttribute('type', 'text/css');
        styleSheet.setAttribute('rel', 'stylesheet');
        styleSheet.setAttribute('href', 'http://api.geosition.com/' + customerAreaId + '/components/styles?id=7&name=' + mapdivid);
        root.appendChild(styleSheet);

        //Adding the MapSettings
        var jsScript = document.createElement('script');
        jsScript.type = 'text/JavaScript';
        jsScript.src = 'http://api.geosition.com/' + customerAreaId + '/components/settings?id=7&name=mapSettings';
        root.appendChild(jsScript);

        //Adding the Kartena API
        var api = document.createElement('script');
        api.type = 'text/JavaScript';
        api.src = 'http://api.geosition.com/' + customerAreaId + '/components';
        root.appendChild(api);

        loadGjsf();
    } else {
        ///this will veirfy if the stylesheet has been loaded or not
        var root = document.getElementsByTagName('head')[0];
        var links = root.getElementsByTagName("link");
        var bCssLoaded = false;
        var i = 0;
        while (i < links.length) {
            if (links[i].href == 'http://api.geosition.com/' + customerAreaId + '/components/styles?id=7&name=mapDiv') {
                bCssLoaded = true;
                break;
            }
            i++;
        }
        if (!bCssLoaded) {
            //Adding the styleSheet
            var styleSheet = document.createElement('link');
            styleSheet.setAttribute('type', 'text/css');
            styleSheet.setAttribute('rel', 'stylesheet');
            styleSheet.setAttribute('href', 'http://api.geosition.com/' + customerAreaId + '/components/styles?id=7&name=mapDiv');
            root.appendChild(styleSheet);
        }
        onLoadGeosition();
    }


}

//Adding and strapping
function addStraps() {                 
    
    strap("com.geosition.map.gui.InfoBalloon");
    strap("com.geosition.util.BoundingBox");
    strap("com.geosition.util.Point");
    strap("com.geosition.util.gui.tooltip.TemplateTooltip");
    strap("com.geosition.util.gui.Template");
    strap("com.geosition.net.Web2Connection");
    strap("com.geosition.map.item.ItemCanvasIndexed");
    strap("com.geosition.map.GeositionMap");
    strap("com.geosition.map.util.ZoomSlider");

    addClassPath("JavaScripts",  siteUrl + "CustomerUtil/Common");
    strap("JavaScripts.StopItem");
    strap("JavaScripts.MapGroupHandler"); 

}

function onLoadGeosition() {
    LoadTravelPlannerMap();

    //adding the zoomSlider
    if (map) {
        var zoomsliderDiv = document.createElement("div");
        zoomsliderDiv.className = "zoomSliderAddon";
        map.getElement().appendChild(zoomsliderDiv);
        var zs = new ZoomSlider(map);
        zs.attach(zoomsliderDiv);
    }

}

function loadGjsf() {
    if ((window.gjsf) && (gjsf.initStrap)) {
        addStraps();
        gjsf.initStrap();
    } else {
        setTimeout('loadGjsf();', 50);
    }
}

function itemClicked(stopId, x, y, text) {
    if (GetCurrentInputField()) {
        var name = unescape(decodeURI(text)).replace(/\+/g, ' ');

        SelectStop(stopId, x, y, name, GetCurrentInputField());

        centerOnItems(false);

        SelectStopFromMap(stopId, x, y, name, GetCurrentInputField());
    }
}

function centerOnItems(zoomtofirstitem) {
    var arr = new Array();
    if (typeof (window['fromObject']) != "undefined") {
        if (fromObject.getImage()) {
            arr.push(fromObject.getImage());
        }
    }
    if (typeof (window['toObject']) != "undefined") {
        if (toObject.getImage()) {
            arr.push(toObject.getImage());
        }
    }
    if (typeof (window['viaObject']) != "undefined") {
        if (viaObject.getImage()) {
            arr.push(viaObject.getImage());
        }
    }
    if (arr.length > 1) {
        map.centerItems(arr);
    }
    else if (arr.length == 1 && zoomtofirstitem) {
        var itemCoord = arr[0].getCoordinate();
        centerOnCoordinate(itemCoord.x, itemCoord.y, 5);
    }
}

function swap(obj1, obj2) {
    if (obj1 != null && obj2 != null) {
        var auxTitle;
        var auxCoordinate;

        //Switching names
        auxTitle = obj1.getTitle();
        obj1.setTitle(obj2.getTitle());
        obj2.setTitle(auxTitle);

        //Switching coordinates
        if (obj1.myImage != null && obj2.myImage != null) {
            auxCoordinate = obj1.getImage().getCoordinate();
            obj1.getImage().setCoordinate(obj2.getImage().getCoordinate());
            obj2.getImage().setCoordinate(auxCoordinate);

            obj1.getImage().correctToMap(map);
            obj2.getImage().correctToMap(map);
        }

        switch (GetCurrentInputField()) {
            case 1:
                if (fromObject)
                    fromObject.selected();
                break;
            case 2:
                if (toObject)
                    toObject.selected();
                break;
            case 3:
                if (viaObject)
                    viaObject.selected();
                break;
            default:
                break;
        }
    }

    //Swap hidden field values
    if (typeof (window['hiddenFieldFromId']) != "undefined" && typeof (window['hiddenFieldToId']) != "undefined") {
        if (document.getElementById(hiddenFieldFromId) != null && document.getElementById(hiddenFieldToId) != null) {
            var auxHiddenField = document.getElementById(hiddenFieldToId).value;
            document.getElementById(hiddenFieldToId).value = document.getElementById(hiddenFieldFromId).value;
            document.getElementById(hiddenFieldFromId).value = auxHiddenField;

        }
    }
}

function clearAll() {

    if (typeof (window['fromObject']) != "undefined") {
        if (fromObject != null)
            fromObject.clearStop();
    }

    if (typeof (window['toObject']) != "undefined") {
        if (toObject != null)
            toObject.clearStop();
    }

    if (typeof (window['viaObject']) != "undefined") {
        if (viaObject != null)
            viaObject.clearStop();
    }

    //clear hidden fields
    if (typeof (window['hiddenFieldFromId']) != "undefined") {
        if (document.getElementById(hiddenFieldFromId) != null)
            document.getElementById(hiddenFieldFromId).value = '';
    }

    if (typeof (window['hiddenFieldToId']) != "undefined") {
        if (document.getElementById(hiddenFieldToId) != null)
            document.getElementById(hiddenFieldToId).value = '';
    }

    if (typeof (window['hiddenFieldViaId']) != "undefined") {
        if (document.getElementById(hiddenFieldViaId) != null)
            document.getElementById(hiddenFieldViaId).value = '';
    }
}

function clearstop(id) {

    switch (id) {
        case 1:
            if (typeof (window['fromObject']) != "undefined") {
                if (fromObject != null)
                    fromObject.clearStop();
                if (typeof (window['hiddenFieldFromId']) != "undefined") {
                    SetHiddenField(hiddenFieldFromId, '');
                }
            }
            break;
        case 2:
            if (typeof (window['toObject']) != "undefined") {
                if (toObject != null)
                    toObject.clearStop();
                if (typeof (window['hiddenFieldToId']) != "undefined") {
                    SetHiddenField(hiddenFieldToId, '');
                }
            }
            break;
        case 3:
            if (typeof (window['viaObject']) != "undefined") {
                if (viaObject != null)
                    viaObject.clearStop();
                if (typeof (window['hiddenFieldViaId']) != "undefined") {
                    SetHiddenField(hiddenFieldViaId, '');
                }
            }
            break;
        default:
            break;
    }
}

function centerOnCoordinate(x, y, zoomLevel) {
    if (map != null) {
        map.setZoom(zoomLevel);
        map.setCenter(Coordinate.create(x, y, CoordinateSystem.SYSTEM_RT90));
    }
}