﻿var selSubCat = '';
var selCat = '';

var mapLanguage = 'de';
var mapServerURL = 'http://map.vvs.de/maps/VVS/';
var odv = new Array();
var currentPage  = 'input';
var currentRoute;
var currentPartialRoute;

$(document).ready(function(){
    
    var ts_ref,
        ts_all,
        o_state = $('input[name=nameState_origin]'),
        d_state = $('input[name=nameState_destination]');
        
    if($("select[id^='name_']").length > 0){

        //$("#toggleMapForList").click();
        
        $("select[id^='name_']").change(function() {
          
          if($('option:selected', this).attr('id')!= ''){
              var id = $('option:selected', this).attr('id').split('$');
              var x =id[0];
              var y =id[1];
              
              mdvJpMaps['navteq:list'].zoomCoord(x,y)
          }
        });
    }

    $(".zone").click(function() {
        if($(this).attr('class').indexOf('active') == -1){
            $('#zone_' + $(this).text()).attr('name', 'deselectedTariffzones')
        }
        else{
            $('#zone_' + $(this).text()).attr('name', 'deselectedTariffzones_disabled')
        }
    });
    
    $("#allzones").click(function() {
        
        $('input[name^="deselectedTariffzones"]').attr('name', 'deselectedTariffzones_disabled')
    });
    
    $("#nozone").click(function() {
        $('input[name^="deselectedTariffzones"]').attr('name', 'deselectedTariffzones')
    });
    
    $('.efaArrowUp').click(function() {
       dateUpDown('up')
    });
    
    $('.efaArrowDown').click(function() {
       dateUpDown('down')
    });
    
    $('select[name="dmLineSelection"]').change(function() {
       if(this.value=='all'){
        $('#dmLineSelectionAll').val('1')
       }
       else{
        $('#dmLineSelectionAll').val('0')
       }
    });
    
    $('input[name="routeType"]').change(function() {
       if(this.value=='LEASTCOSTEX'){
        $('#zonesContainer').hide("slow");
       }
       else{
        $('#zonesContainer').show('slow')
       }
    });
    
    $('#itdTime').blur(function(event) {
        var v, p = /[ :\.]/;
        v = $.trim(this.value);
        if (p.test(v)===false) {
            v = parseInt(v, 10);
            if (isNaN(v)===false && v < 25) {
                v = v + ':00';
                this.value = v;
            }
        }
    });
    
    $('#request').submit(function() {
            $('#itdTime').blur();
            return true;
    });
    
    if (o_state.val() === 'identified' && d_state.val() === 'empty') {
        $('#name_destination').focus();
    }
    
    ts_refs = [];
    ts_all = $('#allefahrten');
    
    // "Drucken" tooltip. Set checkbox "alle"
    $(".tooltipContent input[name^='tripSelector']").each(function(idx, elem) {
        ts_refs.push(elem);
        elem.onclick = function(e){ 
            var all_selected = true;
            if (this.checked===false) {
                ts_all.attr('checked', false);
            }
            $(ts_refs).each(function(idx, el) {
                if (el.checked===false) {
                    all_selected = false;
                    //return false to break jQuery each loop
                    return false;
                }
            })
            ts_all.attr('checked', all_selected);
        };
    });
});

function printOverview(){

    var command = $('input[name="printCommand"]:checked').val();
    var fontSize = $('.tooltipContent input[name="fontSizeNormal"]:checked').val();

    $(".tooltipContent input[name^='tripSelector']").each(function(el) {
        $('#' + this.name + '_hidden').attr('checked', this.checked)
    });

    document.forms['request'].configurationFontSizeNormal.value = fontSize;   
    document.forms['request'].command.value = command;
    document.forms['request'].submit()
}


function reloadWithProfile() {
    
    var enabled = $('input[name=useProfile]:checked').val();
    
    var url = ['XSLT_TRIP_REQUEST2?',
             'sessionID=',
             $('#sessionID').val(),
             '&requestID=',
             $('#requestID').val(),
             '&noElevationSummary=',
             enabled,
             '&noElevationProfile=',
             enabled,
             '&outputOptionsActive=1'];
     window.location.href = url.join('');
}


function toggleTripSelector(obj){

    $(".tooltipContent input[name^='tripSelector']").attr('checked', obj.checked)

}

// date arrows up / down
function dateUpDown(upOrDown) { 

    var date = $('#itdDateDay').val();
    var day = date.split('.')[0];
    var month = date.split('.')[1] -1;
    var year = date.split('.')[2];

    if (year >= 0 && year <= 75){ 
        year = 20 + year; 
    }
    else{
        if (year > 75 && year <= 99){ 
            year = 19 + parseInt(year); 
        }
    }

    var efadate = new Date(year, month, day);
    var milsec = efadate.getTime();

    if (upOrDown == 'up'){ 
        milsec = milsec + (24*60*60*1000);
    }

    if (upOrDown == 'down' ){ 
        milsec = milsec - (24*60*60*1000); 
    }

    efadate.setTime(milsec);

    day = efadate.getDate();

    if(day > 0 && day < 10){ 
        day = "0"+day; 
    }

    month = efadate.getMonth() + 1;

    if (month > 0 && month < 10){ 
        month = "0"+month; 
    }

    year = "" + efadate.getFullYear();

    $('#itdDateDay').val(day +'.' + month + '.' +year);
};


function switchOrigDest(){

    // origin and destination empty or notidentified
    if(($('#nameState_origin').val()=='empty' || $('#nameState_origin').val()=='notidentified')
        && ($('#nameState_destination').val()=='empty' || $('#nameState_destination').val()=='notidentified')){
        
        var origVal = $('#name_origin').val();
        var destVal = $('#name_destination').val();
        
        $('#name_origin').val(destVal);
        $('#name_destination').val(origVal);
    }
    // origin identified and destination empty or notidentified
    else if($('#nameState_origin').val()=='identified' 
    && ($('#nameState_destination').val()=='empty' || $('#nameState_destination').val()=='notidentified')){
        
        var origVal = $('#identified_origin').val();
        
        $('#nameInfo_origin').val(' ');
        $('#nameState_origin').val('empty');
        $('#nameInfo_destination').val(origVal);
        
        document.forms['request'].submit();
    }
     // destination identified and origin empty or notidentified
    else if(($('#nameState_origin').val()=='empty' || $('#nameState_origin').val()=='notidentified') && $('#nameState_destination').val()=='identified'){
        
        var destVal = $('#identified_destination').val();
        
        $('#nameInfo_origin').val(destVal);
        $('#nameInfo_destination').val(' ');
        $('#nameState_destination').val('empty');
        
        document.forms['request'].submit();
    }
    // origin list and destination empty or notidentified
    else if($('#nameState_origin').val()=='list' && ($('#nameState_destination').val()=='empty' || $('#nameState_destination').val()=='notidentified')){
        
        var origVal = $('#list_origin').val();
        
        $('#nameInfo_origin').val(' ');
        $('#nameState_origin').val('empty');
        $('#nameInfo_destination').val(origVal);
        
        document.forms['request'].submit();
    }
    // destination list and origin empty or notidentified
    else if(($('#nameState_origin').val()=='empty' || $('#nameState_origin').val()=='notidentified') 
        && $('#nameState_destination').val()=='list'){
        
        var destVal = $('#list_destination').val();
        
        $('#nameInfo_origin').val(destVal);
        $('#nameInfo_destination').val(' ');
        $('#nameState_destination').val('empty');
        
        document.forms['request'].submit();
    }
    // origin list and destination identified
    else if($('#nameState_origin').val()=='list' && $('#nameState_destination').val()=='identified'){
        
        var origVal = $('#list_origin').val();
        var destVal = $('#identified_destination').val();
        
        $('#nameInfo_origin').val(destVal);
        $('#nameInfo_destination').val(origVal);
        
        document.forms['request'].submit();
    }
    
    // destination list and origin identified
    else if($('#nameState_origin').val()=='identified' && $('#nameState_destination').val()=='list'){
        
        var origVal = $('#identified_origin').val();
        var destVal = $('#list_destination').val();
        
        $('#nameInfo_origin').val(destVal);
        $('#nameInfo_destination').val(origVal);
        
        document.forms['request'].submit();
    }
    
    // origin and destination identified
    else if($('#nameState_origin').val()=='identified' && $('#nameState_destination').val()=='identified'){
        
        var origVal = $('#identified_origin').val();
        var destVal = $('#identified_destination').val();
        
        $('#nameInfo_origin').val(destVal);
        $('#nameInfo_destination').val(origVal);
        
        document.forms['request'].submit();
    }
}

function showPOISubCat(id, imgid, hierarchy){

    var myC = toggle($('#' + id));
    
    // create sub categories 
    if($('#' + id + '-0').length==0){
        var host = 'XML_STOPFINDER_REQUEST'
        // JSON REQUEST ???????
        var _params = { 
            language: 'de', 
            nameHierarchy_sf: 'poiHierarchy:' + hierarchy, 
            nameInfo_sf: 'poiHierarchy:' + hierarchy, 
            type_sf: 'poi', 
            placeInfo_sf: '-1:-1' 
        };
        
        var _ajax = mdvLib.ajax({ host: host, parameters: _params, onComplete: MDVEFAPOISub_onAjaxComplete});
    }
    
    if($('#' + imgid)){
        if(myC == "tabRouteLED"){ 
            $('#' + imgid).attr('src', "./images/icon.plus.gif");
            selCat.replace(hierarchy + ':', '');
        }
        else{ 
            $('#' + imgid).attr('src', "./images/icon.minus.gif");
             selCat += hierarchy + ':';
        }
    }
}


function MDVEFAPOISub_onAjaxComplete(request){

    var xml = request.responseXML;
    var poiNodes = request.responseXML.getElementsByTagName('itdPoiNode');
    var html = '';
    
    var poiContainerId = '';
    
    if(xml.getElementsByTagName('odvNameInput')[0].textContent){
        poiContainerId = 'tabZieleLED-0-' + xml.getElementsByTagName('odvNameInput')[0].textContent.split(':')[1]
    }
    else if(xml.getElementsByTagName('odvNameInput')[0].text){
        poiContainerId = 'tabZieleLED-0-' + xml.getElementsByTagName('odvNameInput')[0].text.split(':')[1]
    }

    if(poiNodes.length==0){
        
        var catName = '[alle]';
        var catId = poiContainerId + '-0';
        var catHier = poiContainerId +'none';
            
        html += '<div id="' + catId +'" class="tabRouteLEDEActive">';
        html += '<p class="tabZieleCB">';
        html += '<input type="checkbox" class="radio" value="1" id="L" name="type" checked="checked"/>'
        html += '<label for="' + catHier + '">' + catName +'</label></p>'
        html += '<br/></div>'
        
        MDVEFAPOIsInCat_onAjaxComplete(request);
        
    }
    else{
    
    
        for(var i =0; i < poiNodes.length; i++){
        
            var catName = poiNodes[i].textContent || poiNodes[i].text;
            var catId = poiContainerId + '-' + i;
            var catHier = poiNodes[i].getAttribute('hierarchy');
            
            html+='<div id="' + catId +'" class="tabRouteLEDE'
            if($('#itdLPxx_poiSubCat').val().indexOf(catHier +':')!='-1'){
                html += 'Active';
            }
            html += '">';

            html+='<p class="tabZieleCB">';

            if($('#itdLPxx_poiSubCat').val().indexOf(catHier +':')!='-1'){
            
                $('#itdLPxx_poiSubCat').value = $('#itdLPxx_poiSubCat').val().replace(catHier +':', '');
            
                html += '<input type="checkbox" class="radio" value="1" id="' + catHier +'" name="type" checked="checked"/>'
                showPOIsInCat(catHier, true)
            }
            else{
                html += '<input type="checkbox" class="radio" value="1" id="' + catHier +'" name="type"/>'
            }
            
            html += '<label for="' + catHier + '">' + catName +'</label></p>'
            html += '<br/></div>' 
        } 
    
    }
    
   $('#' + poiContainerId).html(html);

    $("#tabZieleLegScroller .tabRouteLEDE").each(function(el) {
    
        $(this).click(function() {
            iTargets.toggle(this);
        });
        
    });
    
    $("#tabZieleLegScroller .tabRouteLEDEActive").each(function(el) {
    
        $(this).click(function() {
            iTargets.toggle(this);
        });
        
    });
}


function showPOIsInCat(cat, state){

    if(selSubCat.indexOf(cat+':') !='-1' && state==true){
        return false;
    }

    selSubCat = '';
    $(".tabZieleCB input[type='checkbox']:checked").each(function(){
        selSubCat +=  $(this).attr('id') + ':'
    });
    
    if(state==true){
        // create sub categories 
        var host = 'XML_STOPFINDER_REQUEST'
        // change to JSON request ?????
        var _params = { 
            language: 'de', 
            nameHierarchy_sf: 'poiHierarchy:' + cat, 
            nameInfo_sf: 'poiHierarchy:' + cat, 
            type_sf: 'poi', 
            placeInfo_sf: '-1:-1' 
        };
        
        var _ajax = mdvLib.ajax({ host: host, parameters: _params, onComplete: MDVEFAPOIsInCat_onAjaxComplete});
    }
    else{
        MDVEFAPOIsInCat_onAjaxComplete(state, cat);
    }
   
}

var checkedPOIs = new Array;

function MDVEFAPOIsInCat_onAjaxComplete(request, cat){

    var html = '';
    
    if(request == false){
        var tmpPOIs = new Array;
    
        for(var a =0; a < checkedPOIs.length; a++){

            if(checkedPOIs[a][1].indexOf(cat)=='-1'){
                tmpPOIs.push([checkedPOIs[a][0], checkedPOIs[a][1], checkedPOIs[a][2]])
            }
        }   

        checkedPOIs = tmpPOIs;     
        
    }
    else{

        var poiNodes = request.responseXML.getElementsByTagName('odvNameElem');
        var input = request.responseXML.getElementsByTagName('odvNameInput')[0]
        var catHier = input.textContent || input.text;
 
        for(var i =0; i < poiNodes.length; i++){
            var poiName = poiNodes[i].textContent || poiNodes[i].text;

            if(poiName){
                if(checkedPOIs.toString().indexOf(poiName + ',' +catHier)=='-1'){
                    checkedPOIs.push([poiName, catHier, poiNodes[i].getAttribute('stateless')])
                }
            
            }
        } 
    }
    
    checkedPOIs.sort()
    
    for(var s =0; s < checkedPOIs.length; s++){
        var poiName = checkedPOIs[s][0];
        var stateless = checkedPOIs[s][2];
        html+='<li class="" id="'+stateless +'">';
        html+='<a title="' + poiName+'">' + poiName+'</a>';
        html+='</li>';
    } 
    
    if(html ==''){
        iTargets.hide();
    }
    
    $('#flyoutList').html(html);

    $("#flyoutContent li").each(function(el){
    
        $(this).click(function() {
        
          $("#flyoutContent li.Active").removeClass('Active');
          $(this).addClass('Active')

        });
    });
}



var iTargets = iTargets?iTargets:{

    el:false,
    init:function() {
        if($("#flyout")) {
            this.el = $("#flyout");
            
            if($("#flyoutAOpen")){
                $("#flyoutAOpen").click(function(e) {

                    e.stop();
                    iTargets.show();
                });
            }
            
            $("#flyoutAClose").click(function(e) {
                e.stop();
                iTargets.hide();
            });
            
            this.el.fade("hide");
            $("#flyoutContent li").each(function(el){
                el.click(function() {
                
                    // zoom to coord
                    $("#flyoutContent li.Active").each(function(li){
                        li.removeClass("Active");
                        
                    });
                    
                    el.toggleClass("Active");
                });
            });
        }
    },
    toggle: function(obj) {
    
        var checked = false;
        if(obj.className.lastIndexOf("Active") != -1 && $('#' +obj.id + ' input').not(':checked')) {
            obj.className = obj.className.substring(0,obj.className.lastIndexOf("Active"))
            
        } 
        else if($('#' +obj.id + ' input').is(':checked')){
        
            if(obj.className.lastIndexOf("Active") == -1){
                obj.className = obj.className + "Active";
            }
            checked = true;
        }

        
        var cat =  $('#' +obj.id + ' input').attr('id');
        showPOIsInCat(cat, checked);
        
        if(checked==true && !this.open()){  
            this.show();
        }
        
        //$('#' +obj.id + ' input').attr('checked', checked)
    },
    show:function() {
        if(this.el) {
            this.el.fade("in");
            $("flyoutAOpen").fade("out");
        }
    },
    hide:function() {
    
        if(this.el) {
            this.el.fade("out");
            $("flyoutAOpen").fade("in");
        }
    },
    open:function() {
        var open=false;
        if(this.el && this.el.get("opacity")==1) open=true;
        return open;
    },
    setHeight:function(){
        if($("#flyout")&&mh>0) {
            $("#flyout").css("height", mh+"px");
            $("#flyoutContent").css("height", mh-41+"px");
        }
    }
};

function toggle(obj){

    if($(obj).attr('class') && $(obj).attr('class').lastIndexOf("Active") != -1){ 
        $(obj).attr('class', $(obj).attr('class').substring(0,$(obj).attr('class').lastIndexOf("Active")))
    }
    else{ 
        $(obj).attr('class', $(obj).attr('class') + 'Active');
    }
    
    return $(obj).attr('class');
}


function checkDwellTime(obj){

    if(obj.value > 0){
        document.getElementById('calcFare').value=0
    }
    else{
        document.getElementById('calcFare').value=1
    }
}

// display overview map 
function showOverviewMap(obj){
    
    var overviewID = obj.substring(obj.indexOf('overview'));
    var route = overviewID.split('_')[1];
    currentRoute = route;

    if($(".boxTripMap[id='boxTripMap_overview']").css('display')=='none'){
        $(".boxTripMap[id='boxTripMap_overview']").slideToggle(1000);
    }
    
    $(".boxTripMapHead img.mClose").click(function() {
        var closeTrig=$(".boxTripMapHead img.mClose").index(this);
        $(".boxTripMap:eq("+closeTrig+")").slideUp(1000);
    });
    
    onLoadMapHandler('navteq', 'overview', true, route);
    
    var link = $("#routePDF_" + route).attr('value');

    $("a[id='overview_print']").attr('href', link);
}

// display detail map 
function showDetailMap(obj){

    var detailID = obj.substring(obj.indexOf('detail'))
    var openTrig = 'boxTripMap_' + detailID;

    var route = detailID.split('_')[1];
    var pRoute = detailID.split('_')[2];
    currentRoute = route;

    
    if($(".boxTripMap[id='" + openTrig + "']").css('display')=='none'){
        $(".boxTripMap[id='" + openTrig + "']").slideToggle(1000);
    }
    
    $(".boxTripMapHead img.mClose").click(function() {
        var closeTrig=$(".boxTripMapHead img.mClose").index(this);
        $(".boxTripMap:eq("+closeTrig+")").slideUp(1000);
    });
    
    onLoadMapHandler('navteq', detailID, false);

    var point = '';
    var linkContainer = ''
    
    if(obj.indexOf('showMapStart_detail')!='-1'){
        point = $("input[name='" + detailID + "_point1']").val().split('|');
        linkContainer =  $(".tooltipContent[id='tripInfo" + route + "_" + pRoute + "_1-content']");
    }
    else{
        point = $("input[name='" + detailID + "_point2']").val().split('|');
        linkContainer =  $(".tooltipContent[id='tripInfo" + route + "_" + pRoute + "_2-content']");
    }
    
    var x = point[1];
    var y = point[2];
    
    mdvJpMaps['navteq:' + detailID].tripDetailView(x,y);
    
    $(".boxTripMap[id='" + openTrig + "'] h6").html(point[0]);
    
    var link1 = $('a.spa', linkContainer).attr('href');
    var link2 = $('a.map', linkContainer).attr('href');
    var link3 = $('a.mapMe', linkContainer).attr('href');
    var link4 = $('a.point_detail_pdf', linkContainer).attr('href');
    
    //spa
    if($('a.spa', linkContainer).length==1){
        $("a[id='" + detailID + "_link1']").attr('href', link1);
        $("a[id='" + detailID + "_link1']").parent().css('display', 'inline');
    }
    else{
        $("a[id='" + detailID + "_link1']").parent().css('display', 'none');
    }
    
    // map
    if($('a.map', linkContainer).length==1){
        $("a[id='" + detailID + "_link2']").attr('href', link2);
        $("a[id='" + detailID + "_link2']").parent().css('display', 'inline');
    }
    else{
        $("a[id='" + detailID + "_link2']").parent().css('display', 'none');
    }
    
    //map me
    if($('a.mapMe', linkContainer).length==1){
        $("a[id='" + detailID + "_link3']").attr('href', link3);
        $("a[id='" + detailID + "_link3']").parent().css('display', 'inline');
    }
    else{
        $("a[id='" + detailID + "_link3']").parent().css('display', 'none');
    }
    $("a[id='" + detailID + "_print']").attr('href', link4 || link1);
}

function mo(url){
    window.open(url, "efahelp", 'height=540,width=444,scrollbars=1,status=0');
}


function displaySelectedLine(mapType, request){

    var coord= document.getElementById('coord').value;

    $('.boxMap').css('display', 'block');
    
    onLoadMapHandler(mapType , 'lvp');
    
    var line = $('select[name="lineSelIndexBox"] option:selected').html().split('- ')[0];
    var dir =  $('select[name="lineSelIndexBox"] option:selected').html().replace(line + '- ', '');
    
    $('.mapHead h6').html('Verlauf der Linie ' + line);
    
    $('.mapFoot p').html(dir);
    
    mdvJpMaps[mapType +':lvp'].mapIt('submitLines', 3, document.forms['request'].lineSelIndexBox.value.split('_')[0], coord);

    $('#lineSelection').css('display', 'none');
    $('button[id="submit"]').css('display', 'none');
    
    $('button[id="change"]').css('display', '');
    $('button[id="new"]').css('display', '');
}

function changeSelectedLine(){

    $('.boxMap').css('display', 'none');
    
    $('#lineSelection').css('display', 'block');
    $('button[id="submit"]').css('display', 'inline');
    
    $('button[id="change"]').css('display', 'none');
    //$('button[id="new"]').css('display', 'none');

    if(mdvJpMaps['navteq:rop']){
        mdvJpMaps['navteq:rop'].clear();
    }
    else if(mdvJpMaps['city:rop']){
        mdvJpMaps['city:rop'].clear();
    }
    else if(mdvJpMaps['aerial:rop']){
        mdvJpMaps['aerial:rop'].clear();
    }
}

function getDepartures(stopID, container){
    this.container = container;
    
    var _params = { 
        name_dm: stopID, 
        type_dm: 'stopID', 
        mode: 'direct', 
        limit: '5', 
        deleteAssignedStops_dm: '1', 
        useRealtime: '1',
        itdLPxx_page: 'tooltip'
    };
    
    var _ajax = mdvLib.ajax({ host: 'XSLT_DM_REQUEST', parameters: _params, onComplete: getDepartures_onAjaxComplete.bind(this)});
    
}

function getDepartures_onAjaxComplete(request) {

    if (request) {
        var text = request.responseText;
        if(document.getElementById(this.container)){
            var target = document.getElementById(this.container);
                target.innerHTML = text;
        }
    }
}

function getROPPDF(){
    var value = $('#lineSelIndexBox').val().split('_')[1]
    $('#lineSelIndex').val(value)
    $('#submitImg').click()
}


function prevPartialTrip(route, pos){

    document.forms['request'].command.value='prevPartialTrip';
    document.forms['request'].trip.value=route;
    document.forms['request'].partialTrip.value=pos;
    document.forms['request'].submit();
}

function nextPartialTrip(route, pos){
    document.forms['request'].command.value='nextPartialTrip';
    document.forms['request'].trip.value=route;
    document.forms['request'].partialTrip.value=pos;
    document.forms['request'].submit();
}



/* submit the form */
function submitEFAForm(){
    document.forms['request'].submit();
}

function tmi(obj){
    obj.src=(obj.src.indexOf("icon.arrow.up.gif")!='-1')?obj.src.replace(/icon.arrow.up.gif/, "icon.arrow.down.gif"):obj.src.replace(/icon.arrow.down.gif/, "icon.arrow.up.gif");

}

function trigger_href(elem) {
    var el = $(elem);
    if (el.attr('href')) {
        window.location.href = el.attr('href');
    }
}

