﻿var mapState = 1;
var mapStopBox = 1;
var sugFocusId = -1;

//Globale Variables for Cookies (more)
var destOdvs;
var usageOdvs;
var odvControl;
var lastDMTime;
var triggerDMRequest;
//controll nummber for the information to fil the input in odv
var odvInfoContr = 0;

$(window).load(function() {
    if($('#mdvMap')[0]){
        onLoadMapHandler('navteq');
    }
    //mdvCookie = new MDVCookie();
});

// some functions which will be called when the document is ready
$(document).ready(function() {

    // request ical links
    getICalLinks();

    mdvCookie = new MDVCookie();
    /*Safari hack*/
    if(navigator.userAgent.indexOf("Safari") != -1){
        $("#selectHour").css("width", "44px");
        $("#selectMinute").css("width", "44px");
        $("#dateTimeBox").css("margin-left", "-11px");
        $("#datepicker").css("width", "66px");
        
        /*Versenden / Verlinken brechen in am Ende der Zeile um*/
        if($(".sendJourneySpan")){
            $(".sendJourneySpan").css("margin-left", "80px");
        }
    }

    $("#cssSmallSize")[0].disabled = true;
    $("#cssLargeSize")[0].disabled = true;
    
    focusDestination();
    
    // Führt zu einem Fehler im IE9
    /*
    if (navigator.appName.indexOf("Internet Explorer") != -1){
        $('.simple_overlay').bgiframe(); 
        $('.mapDiv').bgiframe(); 
    }
    */

    // the individual behaviors when some keys will be pressed
    $(document).keyup(function(event){
        if($('#sug_0')[0] && (event.keyCode == 40 || event.keyCode == 38)){        
            var parentSg = $('#odvSg')[0];
            var counter = parentSg.childNodes.length;
            // check if cursor key were used
            //down
        	if(event.keyCode == 40){
                if(sugFocusId < counter -1){
                    sugFocusId++;
                    $('div.actSug').removeClass('actSug');
                    $('#sug_' + sugFocusId)[0].className='actSug';
                    $('#sug_' + sugFocusId)[0].firstChild.focus()
                }
        	}
            //up
            else if(event.keyCode == 38 && sugFocusId > 0){
                sugFocusId--;
                $('div.actSug').removeClass('actSug');
                $('#sug_' + sugFocusId)[0].className='actSug';
                $('#sug_' + sugFocusId)[0].firstChild.focus()  
            }
        }
        if(($('#sug_0')[0] && event.keyCode == 27)){
            var from = $("#name_origin")[0];
            var to = $("#name_destination")[0];
            
            var sug = $(".odvSg");  
            for(i = 0; i < sug.length; i++){
                sug[i].style.display = "none";
            }
        }   
    });
      
    $('.enterPoint').focus(function() {
        sugFocusId = -1
    });

    if(displayCookies == "true" && lastOdvPoints == "true"){
        mdvCookie.odvCookies(cookieControl, 'origin');
        mdvCookie.odvCookies(cookieControl, 'destination');
    }
    
    if(displayCookies == "true"){
        mdvCookie.lastTrips();
        if($("#recentTrips")[0]){
            var recentBox = $("#contentplusLastJourneys")[0];
            if(recentBox.childElementCount < 1){
                $("#recentTrips")[0].style.display = "none";
            }
        }
    }
    
    // close login overlay first
    $('#passwordLink').click(function() {
        $('#newPasswordContent').css('display', 'block');
        $('#checkMailNewPassword').css('display', 'none');
       closeAllOverlays();
    });
    
    // close login overlay first
    $('#registerLink').click(function() {
        // new function reset register overlay !!!!!!!!!!
        $('.textReg').val('');
        $('.regStateRight').removeClass('regStateRight');
        $('#alreadyExists').css('display', 'none');
        $('#registerContent').css('display', 'block');
        $('#checkMailContent').css('display', 'none');
        $('#alreadyExists').css('display', 'none')
        closeAllOverlays();
    });
    
    $('#signIn a').click(function() {
        // new function reset login overlay !!!!!!!!!!
        $('#loginDivContent .error').remove();
        $('#loginUsername').val('');
        $('#loginPassword').val('');
    });
    
    $('#username').keyup(function() {
        if($('#username').val().length < 6){
            $('#usernameState').removeClass('regStateRight');
        }
        else{
            $('#usernameState').addClass('regStateRight');
        }
    });
    

    $('#password').keyup(function() {
        if($('#password').val().length < 6){
            $('#pwState').removeClass('regStateRight');
        }
        else{
            $('#pwState').addClass('regStateRight');
        }
        
        if($('#confirmPassword').val()!=$('#password').val() || $('#confirmPassword').val()==''){
            $('#confirmPwState').removeClass('regStateRight');
        }
        else{
            $('#confirmPwState').addClass('regStateRight');
        }
    });
    
    
    $('#confirmPassword').keyup(function() {
        if($('#confirmPassword').val()!=$('#password').val() || $('#confirmPassword').val()==''){
            $('#confirmPwState').removeClass('regStateRight');
        }
        else{
            $('#confirmPwState').addClass('regStateRight');
        }
    });
    
    
    $('#firstname').keyup(function() {
    
        if($('#firstname').val().length < 1){
            $('#firstnameState').removeClass('regStateRight');
        }
        else{
            $('#firstnameState').addClass('regStateRight');
        }
    });
    
    $('#surname').keyup(function() {
        if($('#surname').val().length < 1){
            $('#surnameState').removeClass('regStateRight');
        }
        else{
            $('#surnameState').addClass('regStateRight');
        }
    });
    
    $('#email').keyup(function() {
        var emailRegEx = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    
        if($("#email").val().search(emailRegEx) == -1){
            $('#emailState').removeClass('regStateRight');
        }
        else{
            $('#emailState').addClass('regStateRight');
        }
    });
    
    // sets the options for the overlays
    $("a[rel]").overlay({
        //top: 50,
        speed: 300,
        load: true,
        expose: {
            // you might also consider a "transparent" color for the mask
            color: '#AEAEAE', 
            // load mask a little faster
            loadSpeed: 300,
            position: 'fixed',
            closeOnEsc:'true',
            scaling: 'fit',
            // highly transparent
            opacity: 0.65 
        },        
        onBeforeLoad: function(event) {
        
            if(document.body.style.overflowY == "hidden"){
                $('body').css('overflow-y',  'hidden')
            }
            else{
                $('body').css('overflow-y',  'auto')
            }
            
            if(this.getContent().selector == '.mapDiv'){
                openMapOverlay()
            }
        },
        onClose: function(event) {
            if(this.getContent().selector == '.mapDiv'){
                closeMapOverlayOnClose();
                
                if($(".mapSelectDiv").css("display") == "inline"){
                    closeMapOverlay()
                }
            }
            $('body').css('overflow-y',  'auto')
        }
    }); 

    if($("#notConnected")){
        $('#triggerAlert').trigger('click');  
    }
   
    //  Ajax Request for the departure monitor
    if($("#personalJourneyBox")[0]){
        //do nothing
    }
    else if($("#nameState_origin").val() == "identified" && $("#dmId")[0]){
        getDepartureMonitor();
    }
    
    if(tooltipDef == 'true'){
        // $(".helpSpan").tooltip({
        $(".helpSpan").tooltip({
            // use the "slide" effect
            effect: 'slide',
            delay: '300',
            position: 'center left',
            events: {
                def:     "mouseenter,mouseleave",    // default show/hide events for an element
                input:   "focus,blur",               // for all input elements
                widget:  "focus mouseenter,blur mouseleave",  // select, checkbox, radio, button
                tooltip: "mouseenter,mouseleave"     // the tooltip element
            }


            // add dynamic plugin with optional configuration for bottom edge
        });
    }
    
});

// changes the date value for the options
function changeDate(step){
    var dateInput = $('#datepicker')[0];
    var dateDayString = dateInput.value.split(".");
    var day = Number(dateDayString[0]);
    var month = Number(dateDayString[1]) -1;
    var year = Number(dateDayString[2]);
    var today = new Date(year, month, day, 12, 0, 0);
    var millisec = today.getTime();
    
    if(step == "up"){
        millisec = millisec + (24*60*60*1000);
    }
    else if(step == "down"){
        millisec = millisec - (24*60*60*1000);
    }
    today.setTime(millisec);

    day = today.getDate();
	if (day > 0 && day < 10){
        day = '0' + day;
    }

    month = today.getMonth() + 1;
    if (month > 0 && month < 10){
        month = '0' + month;
    }
    
    year = today.getFullYear();
    dateInput.value = day + '.' + month + '.' + year;
}

function triggerBox(id){
    var picture = document.getElementById(id)

    var start =  document.getElementById(id).src.indexOf('images/') + 7
    var end = document.getElementById(id).src.lastIndexOf('/')
        
    var dir = picture.src.substring(start, end);

    var object = document.getElementById(id)
    var objParent = object.parentNode.parentNode;
    var header = object.parentNode;
    var fill = ".";
    if(object.src.indexOf("left")!='-1'){
        fill = "_left.";
    }

    if(object.src.indexOf("plus")!='-1'){
        object.src = "images/" + dir + "/minus_corner" + fill + "gif";
        var content = document.getElementById("content"+id);
        $(content).slideDown("normal");
        
        objParent.className = "brf";
        
        if(object.src.indexOf("left")!='-1'){
            fill = "_left.";
            objParent.className = "br";
        }
        
        $(header).toggleClass("rightHeader");

        object.alt = closeBox;
    }
    else{
        document.getElementById(id).src = "images/" + dir + "/plus_corner" + fill + "gif";
        var content = document.getElementById("content"+id);
        $(content).slideUp("normal", myBorder);
        object.alt = openBox;
    }
    function myBorder(){
        $(header).toggleClass("rightHeader");
        var objParent = object.parentNode.parentNode;
        objParent.className = "br";
    }
}

// opens and closes the individual trips
function toogleTrips(id){
    var tripImg = $('#plus_' + id);
    var journey = $("#journey_"+id);
    
    // clear journeys on map
    if (displayedTrip === id + 1) {
        mdvJpMaps['navteq'].clearJourneys();
    }
    
    if(tripImg.attr('src').indexOf("plus")!='-1'){
        journey.slideDown("slow");
        tripImg.attr('src', 'images/'+specImgPath+'/minus.gif');
        journey.css('width' , '100%');
        tripImg.attr('alt', closeBox);
        
        //show trip on map
        if ($('sessionID') && $('requestID')) {
            mdvJpMaps['navteq'].displayJourney($('#sessionID').val(), $('#requestID').val(), id + 1, true);
        }
    }
    else{
        journey.slideUp("slow");
        tripImg.attr('src', 'images/'+specImgPath+'/plus.gif');
        tripImg.attr('alt', openBox);
    }
    
    var checkPlusState = 0;
    
    //check if one or more trips open
    for(var i=0, len = $(".journey").length; i< len; i++){
        var plus = $("#plus_" +i)[0];
        if(plus.src.indexOf("plus")!='-1'){
            checkPlusState++;
        }
    }
    
    var text = $("#triggerJourney")[0];
    
    if(checkPlusState >=1){
        text.innerHTML= $("#showDetails").val();
    }
    else if(checkPlusState==0){
        text.innerHTML= $("#hideDetails").val();
    }
}

// opens/close all trips at once
function triggerJourneys(){
    var text = $("#triggerJourney")[0];
    var journeys = $(".journey");
    var checkPlusState = $('.plusData img[src*=plus]').length;
    
    // clear journeys on map
    mdvJpMaps['navteq'].clearJourneys();

    // opens all
    if(checkPlusState >= 1){
        
        $(".journey").slideDown("normal");
        $(".journey").css('width' , '100%');
        $(".plus").attr('src', 'images/'+specImgPath+'/minus.gif');
        $(".plus").attr('alt', closeBox);
        text.innerHTML = $("#hideDetails").val();
        
        //show trip on map
        if (document.getElementById('sessionID') && document.getElementById('requestID')) {
            mdvJpMaps['navteq'].displayJourney($('sessionID').val(), $('requestID').val(), journeys.length, true);
        }
    }
    //close all
    else{
        $(".journey").slideUp("normal");
        $(".plus").attr('src', 'images/'+specImgPath+'/plus.gif');
        text.innerHTML = $("#showDetails").val();
    }
}

// changes onBlur the color and value of the odv inputfields
function odvStdText(id){
    var origin = $("#name_origin")[0];
    var destination = $("#name_destination")[0];
    var via = $("#name_via")[0];
    
    if(id == origin.id && origin.value == ""){
        origin.value = origValue;
        origin.style.color = "gray";
    }
    else if(id == destination.id && destination.value == ""){
        destination.value = destValue; 
        destination.style.color = "gray";
    }
    else if(via && id == via.id && via.value == ""){
        via.value = viaValue; 
        via.style.color = "gray";
    }
}

function openLink(link){
    window.open(link,'help','width=900,height=600,dependent=false,manubar=no,status=no,toolbar=no,scrollbars=yes')
}

// changes onFocus the color and value of the odv inputfields
function odvStdColor(id){
    var origin = $("#name_origin")[0];
    var destination = $("#name_destination")[0];
    var via = $("#name_via")[0];

    if(id == origin.id && origin.value != ""){
        origin.style.color = "black";
    }
    else if(id == destination.id && destination.value != ""){
        destination.style.color = "black";
    }
    else if(id == via.id && via.value != ""){
        via.style.color = "black";
    }
}

// switches between the options for dateTime and personal trip
function switchRequest(id) {
    if(jQuery('#stateless_origin').length > 0 && jQuery('#stateless_destination').length > 0){
        document.forms['efaForm'].sessionID.value='0';
        document.forms['efaForm'].requestID.value='0';
        jQuery('#nameInfo_origin').attr('value', jQuery('#stateless_origin').attr('value'));
        jQuery('#nameInfo_destination').attr('value', jQuery('#stateless_destination').attr('value'));
        document.forms['efaForm'].nameState_origin.value = 'empty';
        document.forms['efaForm'].nameState_destination.value = 'empty';
    }
    // personal schedule
    if(id == "personalTimeRadio"){
        jQuery('#efaForm').attr('action', 'XSLT_PS_REQUEST2');
        jQuery('#personalPlan').slideDown('normal');
        jQuery('#selectHour').attr('disabled', true);
        jQuery('#selectMinute').attr('disabled', true);
        jQuery('#datepicker').attr('disabled', true);
        jQuery('#SelectArriveDepart').attr('disabled', true);
    }
    // trip request
    else{
        jQuery('#efaForm').attr('action', 'XSLT_TRIP_REQUEST2');
        jQuery('#personalPlan').slideUp('normal');
        jQuery('#selectHour').attr('disabled', false);
        jQuery('#selectMinute').attr('disabled', false);
        jQuery('#datepicker').attr('disabled', false);
        jQuery('#SelectArriveDepart').attr('disabled', false);
    }
}

// shows the return trip
function getReturnTrip(){
    var tempFrom = $("#stateless_origin").val();
    var tempTo =$("#stateless_destination").val();
    
    var tempFromPlace = $("#statelessPlace_origin").val();
    var tempToPlace =$("#statelessPlace_destination").val();
    
    $('#nameInfo_origin').val(tempTo);
    $('#nameInfo_destination').val(tempFrom);
    
    $('#placeInfo_origin').val(tempToPlace)
    $('#placeInfo_destination').val(tempFromPlace)

    document.forms[0].command.value='';  
    document.forms[0].submit();    
}

// changes onFocus the borderColor of inputfield for username and keyword
function inputFocus(inputId){
    $('#' + inputId).removeClass('defaultInputBorder')
    $('#' + inputId).removeClass('inputLogin')
    $('#' + inputId).addClass('focusInputBorder')
}

// changes onBlur the borderColor of inputfield for username and keyword
function inputFocusOut(inputId){
    var input = $("#" + inputId)[0];
    input.className = "defaultInputBorder";
}

// configures the image for the datepicker
$(function($){
    // the if is for the personal schedule
    if($("#plusOptions")[0]){
        var start =  $("#plusOptions")[0].src.indexOf('images/') + 7;
        var end = $("#plusOptions")[0].src.lastIndexOf('/');
    }
    
    var expireDay = expireDate.substring(6, 8);
    var expireMonth = expireDate.substring(4, 6)-1;
    var expireYear = expireDate.substring(0, 4);
    
    $("#datepicker").datepicker({
        showOn: 'both',
        buttonImage: 'images/'+specImgPath+'/button_calendar.png',
        buttonImageOnly: true,
        showButtonPanel: true,
        
        beforeShowDay: function(date){
            if(date.getFullYear() <= expireYear && date.getMonth() <= expireMonth){
                if(date.getMonth() == expireMonth && date.getFullYear() >= expireYear){
                    if(date.getDate() > expireDay){
                        return [false,""];
                    }else{
                        return [true,""];
                    }
                }else{
                    return [true,""];
                }
            }else {
                return [false,""];
            }
        }
    }); 
    
    var calendar = $(".ui-datepicker-trigger");
    if(calendar[0]){
        calendar[0].title = calendarText;  
    }
});

// closes the enlarged map window
function closeMapOverlay(){
    $('#divCloseMap').overlay();
        
    $('#divCloseMap').css("display", "none");
    $('.mapSelectDiv').css("display", "none");
    $('#closeMapImage').css("display", "none");

    closeAllOverlays()
}

// changes the font-size of the whole page
function changeSize(size){
    var small = $("#cssSmallSize")[0];
    var medium = $("#cssMediumSize")[0];
    var large = $("#cssLargeSize")[0];
    
    if(size == "small"){
        medium.disabled = true;;
        large.disabled = true;;
        small.disabled = false;
    }
    else if(size == "medium"){
        small.disabled = true;
        large.disabled = true;
        medium.disabled = false;
    }
    else if(size == "large"){
        small.disabled = true;
        medium.disabled = true;
        large.disabled = false;
    }
}

//this function is called if the user clicked on last point
function submitPoint(stateless, usage){
    $('#name_' +usage).css('color', '#ffffff');
    
    if($("#nameState_" + usage).val() == "empty"){
        $('#name_' +usage).val(stateless);
    }
    else{
        $('#nameInfo_' +usage).val(stateless);
    }
    document.forms[0].submit();
}

// send an Ajax Request for the TTB and appends the answer in a box
function getTTB(type, usage){
    if(type=='line'){
        var line = '';
        if($('#lineName').val()){
            line = $('#lineName').val();
        }
        $.ajax({
            type:       "POST",
            url:        "XSLT_TTB_REQUEST",
            data:       {   contentFilter:'TIMINGPOINTS',
                            language:$('#language').val(),
                            mode:'line',
                            lineName: line
                            },
          
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        });
    }else if(type=='stop'){
        // var ID = $("#dmId")[0].value;
        // var anyType = $("#dmType")[0].value;
        
        if(usage =='origin' || usage == 'destination'){
            var ID = $("#stateless_"+usage)[0].value;
            var anyType = $("#stateless_"+usage)[0].value;
        }
        
        $.ajax({
            type:       "POST",
            url:        "XSLT_TTB_REQUEST",
            data:       {   contentFilter:'TIMINGPOINTS',
                            deleteAssignedStops_ttb:'0',
                            language:$('#language').val(),
                            locationServerActive:'1',
                            lsShowTrainsExplicit:'1',
                            mode:'odv',
                            name_ttb: ID,
                            type_ttb: anyType
                            },
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        });
     }
     else if($('#servingLines') && type=='PDF'){
        $('#ajaxLoader').css('display', 'inline');

        var line = document.getElementById('servingLines').options[document.getElementById('servingLines').selectedIndex].value.split(':');        
          
        $.ajax({
            type:       "POST",
            url:        "XSLT_TTB_REQUEST",
            data:       {   contentFilter:'TIMINGPOINTS',
                            language:$('#language').val(),
                            command:'direct',
                            net: line[0].toLowerCase(),
                            line:line[1],
                            sup:line[2],
                            project:line[4]
                            },
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        });
     }
     else{
        $.ajax({
            type:       "POST",
            url:        "XSLT_TTB_REQUEST",
            data:       {  language:$('#language').val()},
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        });
    }
}

// send an Ajax Request for the STT and appends the answer in a box
function getSTT(type, usage){
    if(type=='line'){
        $.ajax({
            type:       "POST",
            url:        "XSLT_STT_REQUEST/index.php",
            data:       {   lsShowTrainsExplicit:'1',
                            language:$('#language').attr('value'),
                            lineName: $('#lineName').attr('value')
                            },
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        });
    }
    else if(type=='stop'){
        if(usage =='origin' || usage == 'destination'){
            var ID = $("#stateless_"+usage).attr('value');
            var anyType = 'any';
        }
        $.ajax({
            type:       "POST",
            url:        "XSLT_STT_REQUEST/index.php",
            data:       {   lsShowTrainsExplicit:'1',
                            locationServerActive: '1',
                            language:$('#language').attr('value'),
                            name_stt: ID,
                            type_stt: anyType
                       },
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        });
     }
     else{
     
        $('#ajaxLoader').css('display', 'inline');
        
        // var ID = $("#dmId").attr('value');
        var ID = $("#stateless_origin").attr('value');
        var anyType = $("#dmType").attr('value');

        var _params  = 'lsShowTrainsExplicit=1';
            _params  += '&locationServerActive=1';
            _params  += '&language=' + $('#language').attr('value');
            _params  += '&name_stt=' + ID;
            _params  += '&type_stt=' +anyType;
            _params  += '&mode=direct';
            _params  += '&noCache=1';
        
        $("#servingLines option:selected").each(function (i) {
            _params += '&line=' +$(this).attr('value');
        });
     
        $.ajax({
            type:       "POST",
            url:        "XSLT_STT_REQUEST/index.php",
            data:       _params,
            traditional: true,
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        });
    }
}

// send an Ajax Request for the ROP and appends the answer in a box
function getROP(type, usage){
    if(type=='line'){
        var line = '';
        if($('#lineName').val()){
            line = $('#lineName').val()
        }
        $.ajax({
            type:       "POST",
            url:        "XSLT_ROP_REQUEST",
            data:       {   language:$('#language').val(),
                            mode: 'line',
                            lineName: line
                            },
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        }); 
    }
    else if(type=='stop'){
        // var ID = $("#dmId")[0].value;
        // var anyType = $("#dmType")[0].value;
        if(usage =='origin' || usage == 'destination'){
            var ID = $("#stateless_"+usage)[0].value;
            var anyType = $("#stateless_"+usage)[0].value;
        }
        
         $('.downloadTrigger').trigger('click'); 
         var loadImg = "<img class='loadIt' src='"+loaderImg+"' alt='loading'/>";
         $('#downloadOverlayContent').html(loadImg);
        $.ajax({
            type: "POST",
            url:  "XSLT_ROP_REQUEST",
            data: {   
                    lsShowTrainsExplicit:'1',
                    locationServerActive:'1',
                    mode: 'odv',
                    reqType: 'spa',
                    language:$('#language').val(),
                    name_rop: ID,
                    type_rop: anyType
                  },
            success:    function(response){
                $('#downloadOverlayContent').html(response);  
            }
        });
    }
    else if(type=='lvp'){
        // var ID = $("#dmId")[0].value;
        // var anyType = $("#dmType")[0].value;
        if(usage =='origin' || usage == 'destination'){
            var ID = $("#stateless_"+usage)[0].value;
            var anyType = $("#stateless_"+usage)[0].value;
        }
        $.ajax({
            type: "POST",
            url:  "XSLT_ROP_REQUEST",
            data: {   
                    lsShowTrainsExplicit:'1',
                    locationServerActive: '1',
                    mode: 'odv',
                    reqType: 'lvp',
                    language:$('#language').val(),
                    name_rop: ID,
                    type_rop: anyType
                  },
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        });
    }
    else if($('#servingLines') && type=='PDF'){
        $('#ajaxLoader').css('display', 'inline');
        var line = document.getElementById('servingLines').options[document.getElementById('servingLines').selectedIndex].value.split(':');
        $.ajax({
            type:       "POST",
            url:        "XSLT_ROP_REQUEST",
            data:       {   language:$('#language').val(),
                            mode: 'line',
                            reqType: 'lvp',
                            command:'direct',
                            net: line[0].toLowerCase(),
                            line:line[1],
                            sup:line[2],
                            project:line[4]
                            },
            success:    function(response){
                $('#downloadOverlayContent').html(response);
                $('.downloadTrigger').trigger('click'); 
            }
        });
    }  
}

// focuses the inputfield for the destination if origin is identified
function focusDestination(){
    if($("#nameState_origin")[0]){
        var stateOrigin = $("#nameState_origin")[0].value;
        var stateDestination = $("#nameState_destination")[0].value;

        if(stateOrigin == 'identified' && stateDestination == 'empty'){
            var dest = $("#name_destination")[0];
            dest.focus();
            dest.value = "";
        }
    }
}

// send an Ajax Request for the DM and appends the answer in a box
function getDepartureMonitor(){

    var _param = {   
        language:$('#language').val(),
        itdLPxx_depOnly: '1',
        itdTime: $('#selectHour').val() + $('#selectMinute').val(),
        itdDateDayMonthYear: $('#datepicker').val(),
        locationServerActive:'1',
        useRealtime:'1',
        lsShowTrainsExplicit:'1',
        limit: '15',
        deleteAssignedStops_dm:'1',
        mode:'direct',
        useAllStops:'1',
        maxAssignedStops:'1',
        itOptionsActive:'1',
        trITMOTvalue100:'10',
        ptOptionsActive:'1',
        useProxFootSearch:'0',
        anyObjFilter_dm:'126',
        type_dm: 'any',
        name_dm:    $("#stateless_origin").val(),
        includedMeans: 'checkbox'
    }
                      
    for(var i =0; i < $('#exludedMeans input:checked').length;i++){
        _param[$('#exludedMeans input:checked')[i].name] = '1'
    }
                    
    $.ajax({
        type:       "POST",
        url:        "XSLT_DM_REQUEST",
        data: _param,
        success:    function(response){
        
            // new function dm response !!!!!!!!
            $('#myDepartures').html(response);
        
            $('#saveDeparture').click(function() {
                mdvProfile.getOverlay('departure');
            });
            
            $('#monitorDeparture').click(function() {
                mdvProfile.getOverlay('monitorDeparture');
            });
            
            var dmCheckbox = $("#dmCheckbox")[0];
            if(document.cookie){
            
                var checkStateDM = $.cookie("dmCheck");     
                
                if(checkStateDM == "checkTrue"){
                    $("#dmCheckbox").checked = true;
                    updateDM();
                }
                else if(checkStateDM == "checkFalse"){
                    $("#dmCheckbox").checked = false;
                }   
            }
            
            $("#helpDM.helpSpan").tooltip({
                // use the "slide" effect
                effect: 'slide',
                delay: '300',
                position: 'center left',
                events: {
                    def:     "mouseenter,mouseleave",    // default show/hide events for an element
                    input:   "focus,blur",               // for all input elements
                    widget:  "focus mouseenter,blur mouseleave",  // select, checkbox, radio, button
                    tooltip: "mouseenter,mouseleave"     // the tooltip element
                }
                // add dynamic plugin with optional configuration for bottom edge
            });
        }
    });
}

// sends an other DM Request and appends it to the end of the existing dm table
function moreDep(stopId){
    //opens DM if closed
    var img = document.getElementById("plus_"+stopId);
    
    if(img){
        if(img.src.indexOf("plus")!='-1'){
            img.src = 'images/'+specImgPath+'/minus.gif';
             $('.stopId_'+stopId).fadeIn("slow");
            img.alt = openBox;
        }
    }
    
    var anyType = $("#dmType")[0].value;
    var time = $(".stopId_"+stopId + "> .time");
    var rowsNr = time.length-1;
    var timeInt = time[rowsNr].innerHTML.split(":");   
    
    timeInt [1] = parseInt(timeInt[1]);
    if(timeInt[1] != "59"){
        timeInt[1] = timeInt[1]+1;
    }
    else if(timeInt[1] == "59"){
    
        if(timeInt[0] != "23"){
            timeInt[0] = parseInt(timeInt[0]);
            timeInt[0] = timeInt[0]+1;
            timeInt[1] = "00";
        }
        else if(timeInt[1] == "23"){
            timeInt[0] = "00";
            timeInt[1] = "00";
        }
    }
    var lastTimeValue = timeInt[0]+":"+timeInt[1];
    var lastDMTime = lastTimeValue;

    var dateInput = $("#datepicker").val().split(".");
    if(dateInput[0].indexOf("0") == 0){
        dateInput[0] = dateInput[0].charAt(1);
    }
    
    var lastDep = $('input[name="lastDepDay"]:last').val();
    
    var _params = { 
        language: $('#language').val(),
        itdLPxx_moreDep: '1',
        locationServerActive:'1',
        useRealtime:'1',
        anySigWhenPerfectNoOtherMatches:'1',
        limit: '10',
        deleteAssignedStops_dm:'1',
        mode:'direct',
        useAllStops:'1',
        maxAssignedStops:'1',
        itOptionsActive:'1',
        trITMOTvalue100:'10',
        ptOptionsActive:'1',
        useProxFootSearch:'0',
        type_dm: 'any',
        itdTime: lastDMTime,
        itdDateDay: lastDep,
        itdLPxx_today : dateInput[0],// das datum vom inputfeld wird genommen
        name_dm: stopId
    }

    $.ajax({
        type:     "POST",
        url:      "XSLT_DM_REQUEST",
        data:     _params,
        success:  function(response){
            var stopIdTr = $(".stopId_"+stopId);
            var rowsNr = stopIdTr.length-1;
            $(stopIdTr[rowsNr]).after("<tr>"+response+"</tr>");
        }
    });
}

// updates every minute the DM table
function updateDM(){
    var checkBox = $("#dmCheckbox")[0];
    var a = new Date();
    a = new Date(a.getTime() +1000*60*60*24*365);
        
    if(checkBox.checked == true){
        // jquery cookies!!!!
        document.cookie = "dmCheck="+ "checkTrue"+ ";expires="+ a.toGMTString()+";";    
        triggerDMRequest = setInterval("dmInterval()", 60000);        
    }
    else{
        // jquery cookies!!!!
        document.cookie = "dmCheck="+ "checkFalse"+ ";expires="+ a.toGMTString()+";";   
        clearInterval(triggerDMRequest);
    }   
}

// sends the DM request that updates every minute
function dmInterval(){
    var now = new Date();
    var h   = now.getHours();
    var min = now.getMinutes();
    var dmTime = h+":"+min;
    
    var _params =  {   
        language: $('#language').val(),
        itdLPxx_depOnly: '1',
        locationServerActive:'1',
        useRealtime:'1',
        anySigWhenPerfectNoOtherMatches:'1',
        limit: '15',
        deleteAssignedStops_dm:'1',
        mode:'direct',
        useAllStops:'1',
        maxAssignedStops:'1',
        itOptionsActive:'1',
        trITMOTvalue100:'10',
        ptOptionsActive:'1',
        useProxFootSearch:'0',
        anyObjFilter_dm:'126',
        itdTime: dmTime,
        type_dm: 'any',
        name_dm:    $("#stateless_origin").val()
    }

    $.ajax({
        type:       "POST",
        url:        "XSLT_DM_REQUEST",
        data:       _params,
        success:    function(response){
            $('#myDepartures').html(response);
            var checkBox = $("#dmCheckbox")[0];
            checkBox.checked = "checked";
        }
    });
}

// sends a Trip Request when the fields aren´t empty
function sendTripRequest(){
    var origInput = $("#name_origin")[0].value;
    var destInput = $("#name_destination")[0].value;
    if((origInput == origValue && destInput == destValue) && odvInfoContr == 0 ){
        var button = $("#journeySubmit")[0];
        button.type = "button";
        var box = $(".sendPlace");
        if(odvInfoContr == 0){
            if($("#monitor")[0]){
                $("#newJourneyLink").remove();
            }
            $(box[0]).append('<div id="typeOrigDest">'+enterPoint+'</div>');
            odvInfoContr = 1;   
        }
    }else if(origInput != origValue || destInput != destValue){
    
        if(destInput == destValue){
            $('#nameState_destination').val('empty');
            $('#placeState_destination').val('empty');
            $('#place_destination').val('');
        }
    
        var button = $("#journeySubmit")[0];
        button.type = "submit";
    }
}

function openMapOverlay(){

    var originState = $("#nameState_origin")[0].value;
    var destinationState = $("#nameState_destination")[0].value;
    
    if($('#contentplusMap').css('display') == 'none'){
        $('#contentplusMap').css('display', 'block')
        mapState = 2;
    }
    
    $('#enlargeMapDiv').css('display', 'none')
    $('#mdvMap').css('width', '645px')//761px
    $('#mdvMap').css('height', '470px')
    $('#mdvMap').css('border', '1px solid #FFF4DC')
    $('#mdvMap').css('margin-top', '0px')
    $('#closeMapImage').css('display', 'block')
    $('#closeMapImage').css('z-index', '99999')
    $('#closeMapImage').css('position', 'relative')
    $('.mapDiv').css('position', 'absolute')
    
    if(mapStopBox == 1){
        $('.mapDiv').append('<div class="mapSelectDiv"> </div>')
        $('.mapSelectDiv').append($('.selectBoxMapDiv'));
        mapStopBox = mapStopBox + 1;
    }

    $('.selectBoxMapDiv').css('display', 'inline')
    $('.mapSelectDiv').css('display', 'inline');
   
    mdvJpMaps['navteq'].size='big';
    mdvJpMaps['navteq'].mdvMap.resize();
    $('#divCloseMap').css("display", "inline");
    $('.mapSelectDiv').css("display", "inline");
    $('#closeMapImage').css("display", "block");
}

function closeMapOverlayOnClose(){
    if(mapState == 2){
        $('#contentplusMap').css('display', 'none')
        $('#mapSelectDiv').css('display', 'none');
        $('.selectBoxMapDiv').css('display', 'none');
        mapState = 1;
    }
    
    $('#mdvMap').css('width', '278px')
    $('#mdvMap').css('height', '263px')
    $('#mdvMap').css('border', '0px solid #93a0c3')
    $('.mapDiv').css('position', 'relative')
    $('.mapDiv').css('left', '0px')
    $('.mapDiv').css('top', '0px')
    $('#enlargeMapDiv').css('display', 'block')
    $('#closeMapImage').css('display', 'none')
    $('.mapDiv').css('display', 'block')
    
    mdvJpMaps['navteq'].size='small'
    mdvJpMaps['navteq'].mdvMap.resize();
}

function closeAllOverlays() {
	$("a[rel]").each(function() {
		$(this).overlay().close();
	});
}

function closeAllOverlays2() {
    $('#profileOverlay').overlay().close();
}

// shows all general infos
function moreGeneralInfo(){
    var addInfoClass = jQuery('#showAddBannerBox').css("display");
    if(addInfoClass != "none"){
        jQuery('#showAddBannerBox').hide();
        jQuery('#closeAddBannerBox').show();
        jQuery('.inactiveBanner').slideDown('normal');
        jQuery('#firstGenInfoDetail').show();
    }
    else{
        jQuery('#firstGenInfoDetail').hide();
        jQuery('#closeAddBannerBox').hide();
        jQuery('.inactiveBanner').slideUp('normal');
        jQuery('#showAddBannerBox').show();
    }
}

// shows all addInfos
function moreAddInfo(){
    var addInfoClass = $('.inactiveAddInfo').css("display")
    if(addInfoClass == "none"){
        $('.inactiveAddInfo').slideDown('normal');
        $('#moreAddInfo').html(lessCookiesText);
    }else{
        $('.inactiveAddInfo').slideUp('normal');
        $('#moreAddInfo').html(moreCookiesText);
    }
}

// puts the addInfo text in a box and triggers its overlay
function showAddInfo(position){
  // sets the options for the overlays
    $("#addInfoTextBox").html("");
    var content = $("#infoTextSpan_"+position)[0].innerHTML;
    $("#addInfoTextBox").html(content);
    $('#showAddInfoTrigger').trigger('click'); 
}

// puts the addInfo text in a box and triggers its overlay
function showJourneyInfo(position){
  // sets the options for the overlays
    $("#addInfoTextBox").html("");
    var content = $("#journeyTextSpan_"+position+"_"+position)[0].innerHTML;
    $("#addInfoTextBox").html(content);
    $('#showAddInfoTrigger').trigger('click'); 
}

// opens and close stops on the departure screen
function toogleDMStops(stopId){
    var img = $("#plus_"+stopId);
    if(img.attr('src').indexOf("plus")!='-1'){
        $(img).attr('src', 'images/'+specImgPath+'/minus.gif');
        $('.stopId_'+stopId).fadeIn("fast");
        $('.stopId_'+stopId).css('display', 'table-row');
        $(img).attr('alt', closeBox);
    }
    else{
        $(img).attr('src','images/'+specImgPath+'/plus.gif');
        $('.stopId_'+stopId).fadeOut("fast");
        $(img).attr('alt', openBox);
    }
}

// Get iCal links
function getICalLinks () {
    if (jQuery('.iCal').length > 0){
        jQuery('.iCal').each(function () {
            var id = jQuery(this).attr('id');
            var idx = id.substr(id.indexOf('.'));
                
              var _params =  {   
                language: jQuery('#language').attr('value'),
                sessionID: jQuery('#sessionID').attr('value'),
                requestID: jQuery('#requestID').attr('value'),
                command: 'iCal:' + idx
              }

              $.ajax({
                type:       "POST",
                url:        "XSLT_TRIP_REQUEST2",
                data:       _params,
                success:    function(response) {
                            if (response != '') {
                                jQuery('#iCal_' + idx).show();
                                jQuery('#iCal_' + idx).attr('href',response);
                            }
                }
            });
        })
    }
}




var completeLink = true;
var journeyLink = "";
var origin = "";
var destination = "";

function refreshLink(item){

    if (completeLink == true){
        journeyLink = $("#linkContentText").val();
        origin = $("#stateless_origin").val();
        destination = $("#stateless_destination").val();
        completeLink = false;
    }
    
    var language =   "language="+$("#language").val();
    var permaParam = "&sessionID=0&locationServerActive=1&stateless=1";
    var myUrl = liveUrl+"XSLT_TRIP_REQUEST2?" + language + permaParam;
    
    if($("#originLink").attr("checked") == true){
        myUrl += "&name_origin=" + origin + "&type_origin=any";
    }
    
    if($("#destinationLink").attr("checked") == true){
        myUrl += "&name_destination=" + destination + "&type_destination=any";
    }
    
    if($("#timeLink").attr("checked") == true){
        var hour = $("#selectHour").attr("selectedIndex");
        var minute = $("#selectMinute").attr("selectedIndex");
        var date = $("#datepicker").val();
        var depArr = $("#SelectArriveDepart option:selected").val();
        myUrl += "&itdTimeHour="+hour+"&itdTimeMinute="+minute+"&itdDateDayMonthYear="+date+"&itdTripDateTimeDepArr="+depArr;
    }
    
    if($("#optionsLink").attr("checked") == true){
        
        var tripOptions = '';

        $(".journeyOptions:input:checkbox:checked").each(function() {
            tripOptions +=  "&" + this.name + '='+ this.value;
        });

        $(".journeyOptions:input:radio:checked").each(function() {
            tripOptions += "&" + this.name + '='+ this.value;
        });

        $("#lineRestriction").each(function() {
            tripOptions += "&" + this.name + '='+ this.value;
        });
        
        myUrl += tripOptions;
    }
    
    $("#linkContentText").val(myUrl);
}
