/**
 * central jQuery init block
 * @project WHITE-LABEL
 * @notes alle CSS-AbhÃ¤ngigkeiten sind ggf. projektspezifisch anzupassen!
 * @see http://docs.jquery.com/Selectors
 */

var currentFancybox = ''; 

// cookie functions http://www.quirksmode.org/js/cookies.html
jQuery.fn.createCookie = function(name,value,days) {
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
    
    //alert('Click-createCookie: '+name);
}

jQuery.fn.readCookie = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) {
                //alert('Click-readCookie: '+c.substring(nameEQ.length,c.length));
                return c.substring(nameEQ.length,c.length);
        }
    }

    return null;
}

jQuery.fn.eraseCookie = function(name) {
    $(this).createCookie(name,"",-1);
    //alert('Click-eraseCookie');
}

// Language definition for QuickSearch
var quickSearchText = {
    "de" : "Sucheingabe",
    "en" : "Search Term"
};

// Language definition for ticketForm
var ticketFormText = {
    "de" : "Bahnhof / Haltestelle",
    "en" : "Station"
};

// Language definitions for jQuery.UI.Datepicker:
$.datepicker.regional['de'] = {
	closeText: 'schließen',
	prevText: '&#x3c;zurück',
	nextText: 'Vor&#x3e;',
	currentText: 'heute',
	monthNames: [
        'Januar',
        'Februar',
        'März',
	    'April',
	    'Mai',
	    'Juni',
	    'Juli',
	    'August',
	    'September',
	    'Oktober',
	    'November',
	    'Dezember'
	],
	monthNamesShort: [
	    'Jan',
	    'Feb',
	    'Mär',
	    'Apr',
	    'Mai',
	    'Jun',
	    'Jul',
	    'Aug',
	    'Sep',
	    'Okt',
	    'Nov',
	    'Dez'
	],
	dayNames: [
	    'Sonntag',
	    'Montag',
	    'Dienstag',
	    'Mittwoch',
	    'Donnerstag',
	    'Freitag',
	    'Samstag'],
	dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
	dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
	dateFormat: 'dd.mm.yy',
	firstDay: 1,
	isRTL: false
};

$.datepicker.regional['fr'] = {
	closeText: 'Fermer',
	prevText: '#x3c;Préc',
	nextText: 'Suiv&#x3e;',
	currentText: 'Courant',
	monthNames: [
	    'Janvier',
	    'Février',
	    'Mars',
	    'Avril',
	    'Mai',
	    'Juin',
	    'Juillet',
	    'Août',
	    'Septembre',
	    'Octobre',
	    'Novembre',
	    'Décembre'
	],
	monthNamesShort: [
	    'Jan',
	    'Fév',
	    'Mar',
	    'Avr',
	    'Mai',
	    'Jun',
	    'Jul',
	    'Aoû',
	    'Sep',
	    'Oct',
	    'Nov',
	    'Déc'
	],
	dayNames: [
	    'Dimanche',
	    'Lundi',
	    'Mardi',
	    'Mercredi',
	    'Jeudi',
	    'Vendredi',
	    'Samedi'
	],
	dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
	dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
	dateFormat: 'dd/mm/yy',
	firstDay: 1,
	isRTL: false
};

var timeRegional = {
    "de": {
        time: function (hour) { return " Uhr" },
        dateFormat: "dd.mm.yy"
    },
    "en": {
        time: function (hour) { return " h" },
        dateFormat: "dd/mm/yy"
    },
    "fr": {
        time: function (hour) { return " h" },
        dateFormat: "dd/mm/yy"
    }
};
var getNowFormatted = function () {

    // internal ~private~ function
    function /*String*/twoDigitNumber(/*{Number}*/number) {
        iNumber = parseInt(number);
        if (!isNaN(iNumber) && iNumber < 10) {
            number = "0" + iNumber;
        }
        return "" + number;
    }

    var dateTime = "01.01.1900, 00:00 Uhr";
    
    var today  = new Date();
    var year   = today.getFullYear();
    var month  = twoDigitNumber(today.getMonth() + 1); // +1, we do NOT want zero-based month index
    var day    = twoDigitNumber(today.getDate());
    var hour   = twoDigitNumber(today.getHours());
    var minute = twoDigitNumber(today.getMinutes());
    var curDateFormat = timeRegional[currentPageLanguage].dateFormat;

    dateTime = curDateFormat.replace("yy", year)
                            .replace("mm", month)
                            .replace("dd", day)
                            + ", "
                            + hour
                            + ":"
                            + minute
                            + timeRegional[currentPageLanguage].time(today.getHours());
    
    return dateTime;
}

/**
 * Schriftvergroesseerung mit extra Files
 * - gebunden an 'title' vom 'rel="alternate stylesheet"'
 * @see CookieName: MSTstyle
 */
$.fn.switchStylestyle = function(styleName){

    $('link[rel*=style][title]').each(function(i) 
    {
        this.disabled = true;
        if (this.getAttribute('title') == styleName) this.disabled = false;
    });
    $(this).createCookie('VTstyle', styleName, 365);
}

/**
 * Schriftvergroesseerung in Stufen
 * - hier sind es 3
 * - gebunden an 'li class="AAA"'
 * @see CookieName: VTstyle
 */
var SchriftVT = {
    s_id:0,                     //internal Brain 4 status
    s: [12, 13, 15 ],   //here the 3 Fontsizes in px - or better in em?
    
    /* 4the future oso */
    init: function() {
    },
    next: function() {

            this.s_id = (this.s_id<2    ?   this.s_id+1 :   0);

            $('body').css('font-size', ''+this.s[this.s_id]+'px');
            $(this).createCookie('VTstyle', this.s_id, 365);
    },
    /* get the current Cookie and use it */
    get: function() {
        var c = $(this).readCookie('VTstyle');

        //0 is valid!!
        c = (c != '' && parseInt(c)<3 ? parseInt(c) : 0);

        this.s_id = c; //dort machen wir weiter
        $('body').css('font-size', ''+this.s[this.s_id]+'px');
    }
}

/**
 * All the rest for the navigation CSS can't do ...
 */
var tabNavigationFix = function () {
    /*
        Here could be checked the positioning of the layer for the second level
        navigation. I. e. wether the layer would overlap the right page limit in
        default position, this may be fixed here ... 
        
    */
    
    /* Fixes the missing LI:hover for IE6 ... */
    if (
        false && // nobody wants this ;-)
        $.browser.msie &&
        $.browser.version.indexOf("6") === 0
    ) {
        $(".TabNavigation>UL>LI").mouseover(
            function () {
                $(this).children("DIV.second-level").css("display", "block")
            }
        );
        $(".TabNavigation>UL>LI").mouseout(
            function () {
                $(this).children("DIV.second-level").css("display", "none")
            }
        );
    }
}


$(document).ready(
    function(){

        if (typeof(jsPathPrefix) === "undefined") {
            jsPathPrefix = "";
        }

        //supersleight
        if (
            $.browser.msie &&
            parseFloat($.browser.version) < 7
        ) {
            $('div#PageWrapper').supersleight();
        }

		//Menuelayer geht nach links auf wenn der Menuepunkt zu weit rechts steht, damit der Layer nicht nach rechts rausragt
		var offsetDiv = $('div.TabNavigation').offset();
		$('div.TabNavigation>ul>li').each(function(){
			var offsetLi = $(this).offset();
			//alert(offsetLi.left - offsetDiv.left);
			if ((offsetLi.left - offsetDiv.left) > 456) {
				$(this).find('div.second-level').attr({style: "left: auto; right: 0px; background-position: right bottom !important;"});
			}
		});


        //Tabellen einfaerben
        $('div#ContentContainer div.ContentCol table tr:nth-child(2n)').addClass("even");
        $('div#ContentContainer div.ContentCol table tr:first-child').addClass("head");
        //kein Trenner nach im ersten Sitetool
        $('ul.Sitetools li:first-child').attr({style: "background-image: none;"});

        //Teaser automatisch ausrichten: hier für 2- und 3-spaltige Ausgabe!
        if (!$('div#ContentContainer').hasClass("Wide")) {
            var boxWidthCounter = 0;
            $('div#ContentContainer div.ContentCol div.Content2Cols,div#ContentContainer div.ContentCol div.Content>div.DownloadTeaser,div#ContentContainer div.ContentCol>div.Box').each(
                function (idx, elm) {
                    if ($(elm).hasClass("Content2Cols")) {
                        boxWidthCounter++;
                    } else if ($(elm).hasClass("DownloadTeaser") || $(elm).hasClass("Box")) {
                       boxWidthCounter = 0;
                    }
                    if (boxWidthCounter == 2) {
                        $(elm).addClass("RightContentCol").after('<br class="clear" />');
                        boxWidthCounter = 0;
                    }
                }
            );
        } else {
            // Ausnahmen fuer die breite Seite
            $('div#ContentContainer.Wide div.ContentCol div.Content2Cols').each(
                function (idx, elm) {
                    if (idx % 3 == 2) {
                        $(elm).addClass("RightContentCol").after('<br class="clear" />');
                    }
                }
            )
        }
        //Wenn Navigationspunkt Unterpunkte enthaelt, dann Pfeil nach unten
        $('div#Navigation li ul').parent().addClass("open"); // hier für FIONA dann addClass("active open")
        $('div#Navigation ul ul li ul').parent().removeClass("open");
        $('div#Navigation li.active ul li.active').parent().parent().removeClass("active");
        //kein Margin oben bei ContentImg am Anfang
        $('div#ContentContainer div.ContentCol div.Content div.ContentImage:first').attr({style: "margin-top: 0px;"});
        //Abstand nach Galerie-Thumbs
        $('div#ContentContainer div.gallery-image:last-child').attr({style: "margin-bottom: 30px;"}).after('<br class="clear" />');

        //Inline-editing: disable sortbuttons
        $('div.ContentCol div.editContent:first div.inlinebuttons a.editbutton.sort-up').addClass("disabled");
        $('div.ContentCol div.editContent:last div.inlinebuttons a.editbutton.sort-down').addClass("disabled");
        $('div#Navigation li.editContent:first-child > div.inlinebuttons > a.editbutton.sort-up').addClass("disabled");
        $('div#Navigation li.editContent:last-child > div.inlinebuttons > a.editbutton.sort-down').addClass("disabled");

//Downloads(uä Links) via CSS-Klasse mit Typ-Icon versehen: hier ist der Link innerhalb eines li und die class muss dort ran! 
        $('ul.LinkList li > a[href$=.pdf]').parent().addClass("PDF");
        $('ul.LinkList li > a[href$=.doc]').parent().addClass("DOC");
        $('ul.LinkList li > a[href$=.rtf]').parent().addClass("DOC");
        $('ul.LinkList li > a[href$=.xls]').parent().addClass("XLS");
        $('ul.LinkList li > a[href$=.zip]').parent().addClass("ZIP");
        $('ul.LinkList li > a[href$=.mov]').parent().addClass("MOV");
        $('ul.LinkList li > a[href$=.mp3]').parent().addClass("MP3");
        $('ul.LinkList li > a[href$=.txt]').parent().addClass("TXT");
        $('ul.LinkList li > a[href$=.png]').parent().addClass("IMG");
        $('ul.LinkList li > a[href$=.jpg]').parent().addClass("IMG");
        $('ul.LinkList li > a[href$=.gif]').parent().addClass("IMG");
        $('ul.LinkList li > a[href$=.bmp]').parent().addClass("IMG");
        //alle absoluten URIs im extra Fenster öffnen
        $("a[href^='http'],area[href^='http']").click(
            function () {
                this.target = "_blank";
            }
        );

        //PageTop
        $('#Totop').animate( { scrollTop: 0 }, 'slow' );


        //Schriftgrößen: Variante mit festen Größen
        //a) größe setzen
        SchriftVT.get();
        //b) größe aendern
        $('li.AAA').click(function() {
                SchriftVT.next();
        });

        // Banner-Tabs
        //$('#tabs').tabs({ fx: { opacity: 'toggle', duration:'normal'} });
        $('#tabs').tabs({ fx: {} });
        $("#tabs UL LI.tabs A").click( // pimpin' tabs to change the tabs-content's bg color
            function () {
                $("div#tabs").removeClass("White40 White60 White80 White100 Black40 Black60 Black80 Black100")
                             .addClass(this.rel);
            }
        );

        $("A.fancybox").fancybox({
            'titleShow'     : true,
            'transitionIn'  : 'elastic',
            'transitionOut' : 'elastic',
            'easingIn'      : 'easeOutBack',
            'easingOut'     : 'easeInBack',
            'titleFormat'   : function (title) {
                var retValue = "";
                retValue += '<span id="fancybox-title-wrap"><span id="fancybox-title-left"></span><span id="fancybox-title-main"><p>';
                retValue += title;
                retValue += '</p>';
                var parentContainer = $(this.orig[0]).parent().parent().parent().parent();
                if (parentContainer.hasClass("DownloadTeaser")) {
                    retValue += "<ul class=\"LinkList\">" + $("DIV.content UL.LinkList", parentContainer).html() + "</ul>";
                }
                retValue += '</span><span id="fancybox-title-right"></span></span>';
                // <div class="Corners"><div class="BottomLeft"></div><div class="BottomRight"></div></div> 
                return retValue;
            }
        });
        $("DIV.fancybox").click(
            function () {
                $("A.fancybox", $(this).parent()).click();
            }
        );

        // forms and default iframe
        $("A.fancybox-iframe").fancybox({
            'autoScale'     : true,
            'autoDimensions': true,
            'width'			: 540,
            'height'        : 720,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'easingIn'      : 'easeOutBack',
            'easingOut'     : 'easeInBack',            
            'type'			: 'iframe',
            'titleShow'     : false,
            'scrolling'     : 'auto'
        });
        $("A.fancybox-ajax").fancybox({
            'autoScale'     : true,
            'autoDimensions': true,
            'transitionIn'  : 'fade',
            'transitionOut' : 'fade',
            'easingIn'      : 'easeOutBack',
            'easingOut'     : 'easeInBack',            
            'type'			: 'ajax',
            'titleShow'     : false,
            'onComplete'    : function () {
                $("fancybox-inner").css("overflow-x", "hidden");
                $.fancybox.resize();
            }
        });
        // Disruption
        $("A.fancybox-iframe-disruption").fancybox({
            'autoScale'     : true,
            'width'			: 540,
            'height'        : 185, //690,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'easingIn'      : 'easeOutBack',
            'easingOut'     : 'easeInBack',            
            'type'			: 'iframe',
            'titleShow'     : false,
            'scrolling'     : 'no'
        });
        $("A.fancybox-iframe-bookmarks").fancybox({
            'autoScale'     : true,
            'width'			: 260,
            'height'        : 35, //350,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'easingIn'      : 'easeOutBack',
            'easingOut'     : 'easeInBack',            
            'type'			: 'iframe',
            'titleShow'     : false,
            'scrolling'     : 'no',
            'onComplete'    : function () {
                $("#fancybox-frame").addClass("bookmarks");
            },
            'onClosed'    : function () {
                $("#fancybox-frame").removeClass("bookmarks");
            }
        });
        $("A.fancybox-ajax-bookmarks").fancybox({
            'autoScale'     : true,
            'autoDimensions': true,
            'width'			: 260,
            'height'        : 35, //350,
            'transitionIn'  : 'fade',
            'transitionOut' : 'fade',
            'easingIn'      : 'easeOutBack',
            'easingOut'     : 'easeInBack',            
            'type'			: 'ajax',
            'titleShow'     : false,
            'scrolling'     : 'no',
            'onComplete'    : function () {
                $("#fancybox-frame").addClass("bookmarks");
            },
            'onClosed'    : function () {
                $("#fancybox-frame").removeClass("bookmarks");
            }
        });
        /* * /
        if (
            $('body').hasClass("Form") &&
            top.currentFancybox != self.location.href // resizing fancybox procate a new content loading, so we have to check, to prevent eternal loop!
        ) {
            //alert("height: " + document.body.offsetHeight);
            //alert("width: " + document.body.offsetWidth);
            top.$('#fancybox-frame').css('height', document.body.offsetHeight + 10 + 'px');
            top.$('#fancybox-frame').css('width', document.body.offsetWidth + 10 + 'px');
            top.currentFancybox = self.location.href;
            top.$('#fancybox-frame').src = self.location.href;
            //top.$("#fancybox-outer").width(document.body.offsetWidth + 10);
            //top.$("#fancybox-outer").height(document.body.offsetHeight + 10);
            parent.$.fancybox.resize();
        }
        /* */

        $(".accordion").accordion({ animated: 'slide' });
        
        tabNavigationFix();

        var datePickerLanguage = '';
        if (
            typeof(currentPageLanguage) !== "undefined" &&
            currentPageLanguage !== "en" &&
            typeof($.datepicker.regional[currentPageLanguage].closeText) !== "undefined"
        ) {
            datePickerLanguage = currentPageLanguage;
        }
        $.datepicker.setDefaults($.datepicker.regional[datePickerLanguage]);
        $("INPUT.DateField").datepicker(
            {
                showOn: 'button',
                buttonImage: ($.browser.msie && $.browser.version.indexOf("6") === 0) ? jsPathPrefix+'images/icon_calendar.gif' : jsPathPrefix+'images/icon_calendar.png',
                buttonImageOnly: false
            }
        );

        $(".Disruptions DIV.BoxContent H5").html(getNowFormatted());

        $("INPUT#QuickSearch").val(quickSearchText[currentPageLanguage]);
        $("INPUT#QuickSearch").focus(
            function () {
                if (this.value === quickSearchText[currentPageLanguage]) {
                    this.value = "";
                }
                $("div.TabNavigation ul li.QuickSearch div.suggest-layer").css("top", $("div.TabNavigation").height()).show();
                $("div.TabNavigation ul li.QuickSearch DIV.tagcloud").tagcloud(
                    {
                        //type: "sphere", power: .3, // power only works with 'sphere'
                        //type: "cloud", seed: 23, // seed only works with 'cloud'!
                        type: "list", 
                        sizemin: 11,
                        sizemax: 20,
                        colormin: "2A3F9E",
                        colormax: "2A3F9E",
                        height: 120
                    }
                );
            }
        );
        $("INPUT#QuickSearch").keyup(
            function () {
                if (this.value.length >= 3) {
                    // get by ajax the suggestions
                    var query = this.value;
					if (typeof(suggestUrl) !== "undefined") {
						
					
	                    $.ajax(
	                        {
	                            url: suggestUrl + "?q=" + query,
	                            context: $(".QuickSearch .suggest-layer .content"),
	                            dataType: "html",
	                            success: function (data, txtStatus, xhr) {
	                                this.html(
										data.replace(
											(
												new RegExp(
													'(href="[^"]*">)([^<]*)(' + query + ')([^<]*<)',
													"gim"
												)
											),
											'$1$2<span class="TermHighlight">$3</span>$4'
										)
	
	                                );
	                                $("div.TabNavigation ul li.QuickSearch div.suggest-layer div.content P.head").show();
	                                $("div.TabNavigation ul li.QuickSearch div.suggest-layer div.content UL.suggestions").show();
	                            }
	                        }
	                    );
					}
					
                }
                if (this.value.length < 3) {
                    $("div.TabNavigation ul li.QuickSearch div.suggest-layer div.content UL.suggestions").hide();
                    $("div.TabNavigation ul li.QuickSearch div.suggest-layer div.content P.head").hide();
                }
            }
        );
        $("INPUT#QuickSearch").blur(
            function () {
                window.setTimeout(
                    function () {
                        if (this.value === "") {
                            this.value = quickSearchText[currentPageLanguage];
                        }
                        $("div.TabNavigation ul li.QuickSearch div.suggest-layer").hide();
                    },
                    1000
                );
            }
        );

        $("INPUT#from,INPUT#to").focus(
            function () {
                if (this.value === ticketFormText[currentPageLanguage]) {
                    this.value = "";
                }
            }
        ).blur(
            function () {
                if (this.value === "") {
                    this.value = ticketFormText[currentPageLanguage];
                }                
            }
        ).val(ticketFormText[currentPageLanguage]);

        $("div.ContentCol DIV.tagcloud").tagcloud(
            {
                //type: "sphere", power: .3, // power only works with 'sphere'
                //type: "cloud", seed: 23, // seed only works with 'cloud'!
                type: "list", 
                sizemin: 11,
                sizemax: 20,
                colormin: "2A3F9E",
                colormax: "2A3F9E",
                height: 120
            }
        );

        // initiating the imagemap with swapping images in the footer
        // structure of information for image swapping in alt attribute of area-tag:
        // DefactoAltText<SPACE>{img: #<imageId>, def: <defaultImageSrc>, hover: <hoverImageSrc>}
        // For all but IE6:
        if (
            !(
                $.browser.msie &&
                $.browser.version.indexOf("6") === 0
            )
        ) {
            $("MAP#Map AREA").mouseover(
                function () {
                    var infos = this.alt.replace(/^[^\{]*\s?\{/, "{");;
                    try {
                        infos = eval("(" + infos + ")");
                        // targetImageId = rel.split('|')[0]
                        var targetImageId = infos.img;
                        // hoverImageSrc = rel.split('|')[2]
                        var hoverImageSrc = infos.hover;
                        $(targetImageId).attr("src", hoverImageSrc);
                    } catch(parseException) {/*ignore silently*/}
                }
            ).mouseout(
                function () {
                    var infos = this.alt.replace(/^[^\{]*\s?\{/, "{");
                    try {
                        infos = eval("(" + infos + ")");
                        // targetImageId = rel.split('|')[0]
                        var targetImageId = infos.img;
                        // defaultImageSrc = rel.split('|')[1]
                        var defaultImageSrc = infos.def;
                        $(targetImageId).attr("src", defaultImageSrc);
                    } catch(parseException) {/*ignore silently*/}
                }
            );
        }
        
        $("INPUT.NumberField").keyup(function() {
          $(this).val(this.value.replace(/\D/, ""));
        });

        /* outlet list an accordion */
        $(".outlet-list.accordion H3 A").click(
            function (evnt) {
                evnt.stopPropagation();
                return true;
            }
        );
        if (self.location.search.indexOf("outletid") !== -1) {
            var outletId = self.location.search.replace(/[\?\&]outletid=([^\&\#]*)/, "$1");
            $("H3#" + outletId).click();
        }


    }
);

$(window).load(
    function(){
        /*  */
        // ContentImages in Content with caption / legend needs a width fix
        // found @http://www.blogrammierer.de/jquery-bildbreite-ermitteln-um-bildunterschriften-korrekt-darzustellen/ 
        $(".ContentImage").each(
            function(){
                var width = $(this).children(".ContentImageWrapper").children("IMG").width() || $(this).children(".ContentImageWrapper").children("A").children("IMG").width();
                $(this).css("width", width);
                $(this).children("SPAN").css("width", width - $(this).children("DIV.fancybox").width() - 1);
            }
        ); 
        /*  */
    }
);
