var tmpUsage = '';
var printElem = function(options, myId) {
    $("#"+myId).printElement(options);
};


/* Tooltip Qtip2 */
$(document).ready(function () {
    
    var qtipClass = function () {
        
        this.show = {
            event : 'click',
            solo: true
        };
        this.hide = {
            event : 'false'
        };
        this.position = {
            adjust : {
                x : 3,
                y : -6
            }
        };
        this.style = {
            classes : 'ui-tooltip-light',
            tip : {
                corner : 'left top'
            }
        };
        this.content = {
            title : {
                text : function (api) {
                    return $(this).attr('title');
                },
                button : 'Schliessen'
            },
            text : function (api) {
                var myElement = $(this).attr("id") + "-content";
                return $("#" + myElement);
            }
        };
    };
    
    var m,
    ext = {},
    qtipDefault = new qtipClass();
    
    // inline style onclick doesn't fire in IE9,
    // so use qtip show event (fires BEFORE show)
    $('.tooltip').each(function (idx, elem) {
        m = elem.id.match(/^verlauf_(\w+)/);
        if (m) {
            ext = {
                events : {
                    show : (function (usg) {
                        return function () {
                            mdvCookie.insertOdvCookie(usg);
                            return true;
                        }
                    })(m[1])
                }
            };
            $.extend(qtipDefault, ext);
        }
        $(elem).qtip(qtipDefault);
    });
    
    var qtipBus = new qtipClass();
    qtipBus.style.classes += " tooltipBusHead";
    qtipBus.style['width'] = 270;
    qtipBus.style['height'] = 370;
    $('.tooltipBus').qtip(qtipBus);
    
    var qtipU = new qtipClass();
    qtipU.style.classes += " tooltipUHead";
    $('.tooltipU').qtip(qtipU);
    
    var qtipS = new qtipClass();
    qtipS.style.classes += " tooltipSHead";
    $('.tooltipS').qtip(qtipS);
    
    var qtipWP = new qtipClass();
    qtipWP.style.classes += " tooltipWPHead";
    $('.tooltipWP').qtip(qtipWP);
    
    var qtipPure = new qtipClass();
    qtipPure.style.classes += " tooltipPureHead";
    $('.tooltipPure').qtip(qtipPure);
    
});

/* /Tooltip Qtip2 */

/* Tarifzonen */
$(document).ready(function () {
    $(".zone").click(function () {
        $(this).toggleClass("active");
    });
    $("#allzones").click(function () {
        $(".zone").addClass("active");
        return false;
    });
    $("#nozone").click(function () {
        $(".zone").removeClass("active");
        return false;
    });
});

$(document).ready(function() {
	 $(".simplePrint").click(function() {
		 printElem({ 'overrideElementCSS': ['css/content.css', { 'href': 'css/printlink.css', 'media':'all' }]}, 
                   $(this).parents(".tarif-dialog").attr("id"));
	 });	         
});

/* UI Diaglog Netzplan */
$(document).ready(function () {
    // Dialog
    $('#np-dialog').dialog({
        autoOpen : false,
        width : 870,
        modal : false,
        resizable : false,
        beforeClose : function () {
            // always reset tubemap
            onUnloadMapHandler('tube', 'overlay');
            $('#ui_w_overlay').remove();
            return true;
        }
    });
    
    // Dialog Link
    $('.np-opener').click(function () {
        tmpUsage = $(this).attr('id').split('_')[1];
        $('#np-dialog').dialog('open');
        // jQuery dialog with modal:true removes click handler from context menu entries
        // so set modal false, add overlay manually and remove it beforeClose
        $('<div id="ui_w_overlay"></div>').addClass('ui-widget-overlay').appendTo(document.body).css({
            width : $(window).width(),
            height : $(window).height()
        });
        $('.ui-tooltip').each(function(){
            $(this).hide();
        });
        onLoadMapHandler('tube', 'overlay');
        return false;
    });
    
});

/* UI Diaglog Wichtige Ziele */
$(document).ready(function () {
    // Dialog
    $('#ziele-dialog').dialog({
        autoOpen : false,
        width : 600,
        modal : true,
        buttons : {
            "Übernehmen" : function () {
                var poiValue = $("#flyoutContent li.Active").attr('id');
                
                // submit selected poi value
                $('#nameInfo_' + tmpUsage).val(poiValue);
                $('#typeInfo_' + tmpUsage).val('any');
                var lc = $('#lastCommand').val();
                if (/changeRequest|tripGoOn|tripRetoure/.test(lc)) {
                    $('#execInst').val('verifyOnly');
                }
                submitEFAForm();
            }
        }
    });
    // Dialog Link
    $('.ziele-opener').click(function () {
        tmpUsage = $(this).attr('id').split('_')[1];
        $('.ui-tooltip').each(function(){
            $(this).hide();
        });
        $('#ziele-dialog').dialog('open');
        return false;
    });
    
});

/* UI Diaglog Stoerung */
$(document).ready(function () {
    
    // Dialog
    $(".stoerung-dialog").dialog({
        autoOpen : false,
        width : 870,
        modal : true
    });
    // Dialog Link
    $(".stoerung-dialog-opener").click(function () {
        var stoerungDialogTrig = $(".stoerung-dialog-opener").index(this);
        var url, jqm, m, msgId, arr = this.id.split('_');
            if (arr.length > 1 && arr[1] !== '') {
            msgId = arr[1];
        } else {
            jqm = $('span', this.parentNode);
            if (jqm.length) {
                url = $(jqm[0]).text();
                m = /infoID=([\d\w_]+)&/.exec(url);
                if (m.length && m.length===2) {
                    msgId = m[1];
                }
            }
        } 
        addinfoAjaxRequest(this.id, msgId);
        
        $(".stoerung-dialog:eq(" + stoerungDialogTrig + ")").dialog("open");
        $('.ui-tooltip').each(function(){
            $(this).hide();
        });
        return false;
    });
});

function addinfoAjaxRequest(containerId, msgId) {
    
    var host = 'XML_ADDINFO_REQUEST'
    var _params = {
        outputFormat : 'JSON',
        filterInfoID : msgId
    };
    
    var infoContainer = containerId.replace('stoerung-opener', 'stoerung-dialog-');
    
    $.ajax({
        type : "POST",
        url : 'XML_ADDINFO_REQUEST',
        data : _params,
        success : function (response) {
            
            eval('efa = ' + response + ';');
            
            var infoLink = efa.additionalInformation.travelInformations.travelInformation[0].infoLink
                
                var htmlText = infoLink.htmlText
                var subtitel = infoLink.subtitle;
            
            $('#' + infoContainer + ' h2').html(subtitel)
            $('#' + infoContainer + ' div.htmlTxt').html(htmlText)
            
        }
    });
    
}

/* UI Diaglog Tarif */
$(document).ready(function () {
    // Dialog
    $(".tarif-dialog").dialog({
        autoOpen : false,
        width : 670,
        modal : true
    });
    // Dialog Link
    $(".tarif-dialog-opener").click(function () {
        var tarifDialogTrig = parseInt(this.id.split('_')[1]) - 1;
        $(".tarif-dialog:eq(" + tarifDialogTrig + ")").dialog("open");
        $('.ui-tooltip').each(function(){
            $(this).hide();
        });
        return false;
    });
});

/* UI Diaglog Legende */
$(document).ready(function () {
    // Dialog
    $(".legend-dialog").dialog({
        autoOpen : false,
        width : 600,
        modal : false
    });
    // Dialog Link
    $(".legend-dialog-opener").click(function () {
        var tarifDialogTrig = $(".legend-dialog-opener").index(this);
        $(".legend-dialog:eq(" + tarifDialogTrig + ")").dialog("open");
        $('.ui-tooltip').each(function(){
            $(this).hide();
        });
        return false;
    });
});

/* Kalender (UI Datepicker)*/
$(document).ready(function () {
    $("#itdDateDay").datepicker("getDate");
    $(".date").datepicker({
        showOn : "button",
        buttonImage : "images/icon.calendar.gif",
        buttonImageOnly : true,
        dateFormat : 'dd.mm.yy',
        monthNames : ['Januar', 'Februar', 'M&auml;rz', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
        dayNamesMin : ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
        firstDay : 1
    });
});

/* Ausklappen */
$(document).ready(function () {
    
    var b = $.browser;
    
    $(".boxExpand").css("display", "none");
    
    if (b.msie && b.version==='7.0') {
        $(".expand").click(function () {
            var index = $('.expand').index(this);
            $(".boxExpand:eq(" + index + ")").toggle();
            this.src = this.src.replace(/(plus|minus)/, function(m, cg) {
                return cg==='plus' ? 'minus' : 'plus';
            });
            if (/Karte/.test(this.parentElement.innerHTML)) {
                onLoadMapHandler('navteq', 'list');
            }
        });
    } else {
        $(".expand").click(function () {
            var index = $('.expand').index(this);
            $(".boxExpand:eq(" + index + ")").slideToggle("slow", function () {
                ($(".expand:eq(" + index + ")").attr("src") == "images/icon.minus.gif") ? $(".expand:eq(" + index + ")").attr("src", "images/icon.plus.gif") : $(".expand:eq(" + index + ")").attr("src", "images/icon.minus.gif");
                if ($(".expand:eq(" + index + ")").attr("id") == 'toggleMapForList') {
                    onLoadMapHandler('navteq', 'list')
                }
            });
        });
    }
    
    $(".expandMore").click(function () {
        var index = $('.expandMore').index(this);
        
        $(".boxExpandMore:eq(" + index + ")").slideToggle("slow", function () {
            
            if ($(".expandMore:eq(" + index + ")").attr("src") == "images/icon.minus.gif") {
                $(".expandMore:eq(" + index + ")").attr("src", "images/icon.plus.gif")
            } else {
                $(".expandMore:eq(" + index + ")").attr("src", "images/icon.minus.gif");
            }
        });
    });
    
    $('#toolBox1 img.expand').click()
});

/* Karte ein/ausklappen */
$(document).ready(function () {
    
    $(".boxTripMap").css("display", "none");
    $(".showMap").click(function () {
        
        if (this.id.indexOf('overview') != '-1') {
            showOverviewMap(this.id);
        } else {
            showDetailMap(this.id);
        }
    });
});

/* Eingabefelder leeren - Fahrziel tauschen */
$(document).ready(function () {
    
    var mnDefault = [],
        reDefaultTexts = /^(Ort, Haltestelle, Adresse|Linie|Haltestelle)/;
    
    $(".dialog[type='text']").each(function () {
        $(this).blur(function () {
            if ($(this).val() == "") {
                $(this).val(mnDefault[$(this).attr("id")]);
            }
        });
        $(this).focus(function () {
            var v = $(this).val();
            if (!reDefaultTexts.test(v)) {
                return;
            }
            if (mnDefault[$(this).attr("id")] == null) {
                mnDefault[$(this).attr("id")] = v;
            }
            if (v == mnDefault[$(this).attr("id")]) {
                $(this).val("");
            }
            $(this).select();
        });
    });
    
    $('.switch a').click(function () {
        switchOrigDest()
    });
});

/* Button Switch An-Abfahrt */
$(document).ready(function () {
    $('.box button').click(function () {
        if ($("#btdep").hasClass("selected")) {
            $("#btdep").removeClass("selected");
            $("#btdep").removeAttr("disabled").css("cursor", "pointer");
            $("#btarr").addClass("selected");
            $("#btarr").attr("disabled", "disabled").css("cursor", "default");
        } else {
            $("#btarr").removeClass("selected");
            $("#btarr").removeAttr("disabled").css("cursor", "pointer");
            $("#btdep").addClass("selected");
            $("#btdep").attr("disabled", "disabled").css("cursor", "default");
        };
    });
});

/* Tabellenzeilen farbig markieren */
$(document).ready(function () {
    
    $("tr").hover(
        function () {
        $(this).addClass("trOn");
    },
        function () {
        $(this).removeClass("trOn");
    });
    
    $(".ausgabe tr td:not(:has(>*))'").click(function (event) {
        var anchor = $(this).parent().attr('id');
        
        goToByScroll('detail' + anchor)
    });
    
});

/* additional params for bikeTakeAlong */
$(document).ready(function () {
    
    var f,
    append,
    chb_bike = $('#formSettingsConBike');
    
    if (!chb_bike) {
        return;
    }
    
    f = chb_bike.closest('form');
    append = function () {
        $('<input/>', {
            'type' : 'hidden',
            'id' : 'trITArrMOTvalue102',
            'name' : 'trITArrMOTvalue102',
            'value' : '15'
        }).appendTo(f);
        $('<input/>', {
            'type' : 'hidden',
            'id' : 'trITDepMOTvalue102',
            'name' : 'trITDepMOTvalue102',
            'value' : '15'
        }).appendTo(f);
    };
    
    if (chb_bike.is(':checked') === true) {
        append();
    }
    
    chb_bike.click(function () {
        if (this.checked === true) {
            append();
        } else {
            $('#trITArrMOTvalue102').remove();
            $('#trITDepMOTvalue102').remove();
        }
    });
});

function goToByScroll(id) {
    $('html,body').animate({
        scrollTop : $("#" + id).offset().top
    }, 'slow');
}

