$(document).ready(function(){
    /* Red Crosses */
    var foundProduct = $('.submenu span, .greybox-mid, .whitebox-mid, .sf-menu a, .chead, p.bodytext:contains("+S"), p.bodytext:contains("+C")');
    $(foundProduct).each(function() {
        var foundProducts = $(this).html().replace('+S', '<span style="color: #e20030; display: inline; padding:0px;">+</span>S').replace('+C', '<span style="color: #e20030; display: inline; padding:0px;">+</span>C');
        $(this).html(foundProducts);
    });
    
    /* Prämientabellen */
    $('.pramieDataTable .pramieRow:last-child').css('border', 'none');
    if($.browser.msie) {
        $('.dual').next().css('width', '213px').css('float', 'left').next().css('width', '213px').css('float', 'left');
    };
    
    $('.pramieEnglish .pramieLabelDays, .pramieEnglish .pramieSolo, .pramieEnglish .pramieFamily, .pramieEnglish .pramieMultiple').each(function() {
        var backgroundImage = $(this).css('background-image').replace('.jpg', 'Eng.png');
        $(this).css('background-image', backgroundImage);
    });
    
    $('ul.rte > p, li > p').each(function() {
        $(this).replaceWith('');
    });
        
    jQuery.fn.extend({
      slideRightShow: function() {
        return this.each(function() {
          jQuery(this).animate({width: 'show'}, 1500);
        });
      },
      slideLeftHide: function() {
        return this.each(function() {
          jQuery(this).animate({width: 'hide'}, 1500);
        });
      }
    });
    
    
        var msie = jQuery.browser.msie;      // Internet Explorer Win / Mac
    
    /* ::: hover H2 ::: */
    
        var lastClass = '';
        $('.hoverh2').mouseover(function(){
            lastClass = $(this).find('h2').attr('class');
            $(this).find('h2').attr({
                className: "dark " + lastClass
            })
        }).mouseout(function(){
            $(this).find('h2').attr({
                className: lastClass
            })
        });
    
    /* ::: Buchungsbox ::: */
    
        $('#pr-p').click(function(){
            $('#prodselect-options div').remove();
            for(var id in products.p) {
                $('<div>')
                    .attr({
                        id: "prod-"+products.p[id].prodId
                    })
                    .html(products.p[id].title)
                    .appendTo($('#prodselect-options'))
            }
            delegateSelectProductHover();
            delegateSelectProducts();
        })
        $('#pr-g').click(function(){
            $('#prodselect-options div').remove();
            for(var id in products.b) {
                if(products.b[id].prodId != 'cti') {
                    $('<div>')
                        .attr({
                            id: "prod-"+products.b[id].prodId
                        })
                        .html(products.b[id].title)
                        .appendTo($('#prodselect-options'))
                }
            }
            delegateSelectProductHover();
            delegateSelectProducts();
        })
        $('#prodselect').click(function(){
            showHideProdSelect();
        })
        $('#prodselected-option').click(function(){
            showHideProdSelect();
        })
        delegateSelectProductHover();
    
        function showHideProdSelect() {
            if($('#prodselect-options').css("display") == "none") {
                $('#prodselect-options').css({
                    display:    "block",
                    position:   "absolute",
                    top:        $('#prodselect').position().top*1+18,
                    left:       $('#prodselect').position().left,
                    background: "white",
                    zIndex:     99
                })
                delegateSelectProducts();
            } else {
                $('#prodselect-options').css({  display:    "none" })
            }
        }
        function delegateSelectProductHover() {
            $('#prodselect-options div').unbind('mouseenter');
            $('#prodselect-options div').unbind('mouseleave');
            $('#prodselect-options div').bind('mouseenter', function(){
                $(this).css({
                    background: "#01347a",
                    color:      "white"
                })
            })
            $('#prodselect-options div').bind('mouseleave', function(){
                $(this).css({
                    background: "white",
                    color:      "#555555"
                })
            })
        }
        function delegateSelectProducts() {
            $('#prodselect-options div').unbind('click');
            $('#prodselect-options div').bind('click', function(){
                $('#pr-produkt').val( $(this).attr("id").split('-')[1] );
                $('#prodselected-option').html( $(this).html() ).css({
                    display:    "block",
                    position:   "absolute",
                    top:        $('#prodselect').position().top*1+3,
                    left:       $('#prodselect').position().left*1+3
                })
                if(jQuery.browser.msie && jQuery.browser.version <= 6) {
                    $('#prodselected-option').css({
                        top:        $('#prodselect').position().top*1+5
                    })
                }
                $('#prodselect-options').css({  display:    "none" })
            })
        }
        $("#book-form").submit(function(){
            if($('#pr-produkt').val() == "") {
                return false;
            }
            var href = '/index.php?type=4&prodId='+$('#pr-produkt').val()+'&lang='+lang;
            popUpCenter(href,600,750,'toolbar=no,menubar=no,scrollbars=yes,resizable=yes');
            $('#prodselected-option').hide();
            return false;
        })
    
    /* ::: Top Navigation ::: */
    
    
            jQuery('ul.sf-menu').supersubs({
                minWidth: 12,   // minimum width of sub-menus in em units
                maxWidth: 35,   // maximum width of sub-menus in em units
                extraWidth: 1     // extra width can ensure lines don't sometimes turn over
                                   // due to slight rounding differences and font-family
            }).superfish({
                autoArrows: false,
                animation: {opacity:'show'},
                speed: 10
            });
    
    
        $('.sf-menu > li').mouseenter(function(){
            if(!$(this).hasClass('act')) {
                $(this).css({
                    background: "url('/fileadmin/img/topnavi-bg-l_RO.jpg') 0px 0px no-repeat"
                })
                $(this).children(':first-child').find('span').css({
    
                    background: "url('/fileadmin/img/topnavi-bg-r_RO.jpg') right 0px no-repeat"
                })
            }
        }).mouseleave(function(){
            if(!$(this).hasClass('act')) {
                $(this).css({
                    background: "url('/fileadmin/img/topnavi-bg-l.jpg') 0px 0px no-repeat"
                })
                $(this).children(':first-child').find('span').css({
                    background: "url('/fileadmin/img/topnavi-bg-r.jpg') right 0px no-repeat"
                })
            }
        })
    
    /* ::: History klappmenu ::: */
    
        function historyUpAll() {
            $('.history-entry .up').each(function(){
                historyDown(this);
            });
            $('body').css({height:""});
        }
        function historyDownAll() {
            $('.history-entry .up').each(function(){
                historyUp(this);
            });
            $('body').css({height:""});
        }
    
        $('.history-entry .up').each(function(){
            historyDown(this);
        })
    
        $('.history-entry .up').click(function(){
            historyDown(this);
            return false;
        })
        $('.history-entry .down').click(function(){
            historyUp(this);
            return false;
        })
    
        function historyDown(elem) {
            $(elem).parents('.history-entry').removeClass('open');
            $(elem).parents('.history-entry').find('.history-facts').animate({
                    height: "38px"
                }, function(){
                    $(this).parents('.history-entry').find('.history-facts p:first').css({
                        width:"250px",
                        height: "18px",
                        paddingBottom: "0px",
                        marginBottom: "10px",
                        overflow:"hidden"
                    });
            });
        }
    
        function historyUp(elem) {
            $(elem).parents('.history-entry').addClass('open');
            $(elem).parents('.history-entry').find('.history-facts p:first').css({
                width:"",
                height: "",
                paddingBottom: "10px",
                marginBottom: "0px",
                overflow:"auto"
            });
            $(elem).parents('.history-entry').find('.history-facts').animate({
                height:"72px"
            }, function(){
                $(this).css({height:""});
            })
        }
    
    /* ::: Lightboxen ::: */
    
        $(".lb2").click(function(){
            var href = $(this).attr('href');
            $.colorbox({
                href:href,
                width:"795px",
                initialHeight:"100px",
                onComplete:function(){
                    setTimeout(function(){ $('#cboxClose').show() }, 1000);
                    $('#cboxOverlay').css({ opacity: 0.5 });
                    $('#hs-plus-info-lang').change(function(){
                        HotelStornoLangSelect();
                    })
                    $('.hs-plus-info-lang-send').click(function(){
                        HotelStornoLangSelect();
                        return false;
                    })
                    HotelStornoLangSelect();
                },
                onLoad: function(){ $('#cboxClose').hide(); }
            })
            return false;
        })
        $(".lb").colorbox({
            width:"665px",
            initialHeight:"100px",
            onComplete:function(){
                setTimeout(function(){ $('#cboxClose').show() }, 1000);
                $('#cboxOverlay').css({ opacity: 0.5 });
            },
            onLoad: function(){ $('#cboxClose').hide(); }
        });
    
        function resizeIframe(iframeID) {
            if(self==parent)
                return false; /* Checks that page is in iframe. */
            else if(document.getElementById&&document.all) /* Sniffs for IE5+.*/
                var FramePageHeight = framePage.scrollHeight + 10; /* framePage
            is the ID of the framed page's BODY tag. The added 10 pixels prevent an
            unnecessary scrollbar. */
    
            parent.document.getElementById(iframeID).style.height=FramePageHeight;
            /* "iframeID" is the ID of the inline frame in the parent page. */
        }
    
    
    
    /* ::: QTip Tooltips ::: */
    
        $('.tt').click(function(){ return false; })
        $('.tt').each(function() {
            var ttposx = 0;
            var ttposy = -25;
    
            $(this).qtip({ //TO BE UPDATED IN FUTURE http://craigsworks.com/projects/forums/thread-qtip-1-0-0-rc3-jquery-1-4
               content: $(this).next('.tt-cnt').html(),
               show: 'mouseover',
               hide: 'mouseout',
               position: {
                  corner: {
                     target: 'topLeft',
                     tooltip: 'topRight'
                  },
                  adjust: {
                      x: ttposx,
                      y: ttposy
                  }
               },
               style: {
                    width: 262,
                    border: {
                     width: 0
                  }
               }
            });
        });
    
    /* ::: Klapp menu functions ::: */
    
        $('.klapp-head, .klapp-subhead').click(function() {
            if($(this).next().css('display') == "block") {
                $(this).parent('.klapp-item').removeClass('act');
            } else {
                $(this).parent('.klapp-item').addClass('act');
            }
            $('body').css({height:"4000px"});
            if($(this).next().css('display') == "block") {
                theight = $('.content-reiter-middle').css("height");
            }
            $(this).next().slideToggle(1000, function(){
                $('body').css({height:""});
            });
            return false;
        });
        // open/close all "klappmenues"
        initCloseKlappmenu();
        function initCloseKlappmenu() {
            $('.klapp-subcontent').css({"display":"none"});
            $('.klapp-content').css({"display":"none"});
        }
        $('.klappall-close').click(function(){
            $('body').css({height:"4000px"});
            $('.klapp-head, .klapp-subhead').each(function() {
                $(this).next().slideUp(1000, function(){
                    $('body').css({height:""});
                });
                $(this).parent('.klapp-item').removeClass('act');
            });
            historyUpAll();
            return false;
        })
        $('.klappall-open').click(function(){
            $('body').css({height:"4000px"});
            $('.klapp-head, .klapp-subhead').each(function() {
                $(this).next().slideDown(1000, function(){
                    $('body').css({height:""});
                });
                $(this).parent('.klapp-item').addClass('act');
            });
            historyDownAll();
            return false;
        })
    
        $('.mlbox-reiter-gr').click(function() {
            $('#prod-pr').slideUp(1500);
            $('#prod-gr').slideDown(1500);
            $(this).addClass('mlbox-reiter-gr-act');
            $('.mlbox-reiter-pr').removeClass('mlbox-reiter-pr-act');
            return false;
        });
        $('.mlbox-reiter-pr').click(function() {
            $('#prod-gr').slideUp(1500);
            $('#prod-pr').slideDown(1500);
            $(this).addClass('mlbox-reiter-pr-act');
            $('.mlbox-reiter-gr').removeClass('mlbox-reiter-gr-act');
            return false;
        });
    
    /* ::: Boxen klickbar machen ::: */
        // whitebox
        makeBoxClickableIfOneLink($('.whitebox'));
        // greybox
        makeBoxClickableIfOneLink($('.greybox'));
        // greybox in content
        makeBoxClickableIfOneLink($('.box-si-grau'));
        // small box in content
        makeBoxClickableIfOneLink($('.box-si'));
        // box in channelheader
        makeBoxClickableIfOneLink($('.mlbox-over'));
        // news item
        makeBoxClickableIfOneLink($('.aktuelles-item'));
        // if one link
        function makeBoxClickableIfOneLink(elem) {
            $(elem).each(function(){
                if($(this).find('a').length == 1) {
                    $(this).click(function(){
                        boxOpen($(this));
                        return false;
                    })
                    $(this).addClass('hand');
                }
            })
        }
    
        // contentbox
        $('.contentbox').each(function(){
            if($(this).find('.box-cs').length > 0) {
                $('.box-cs').each(function(){
                    boxClick($(this));
                })
                $('.aktuelles-item').each(function(){
                    boxClick($(this));
                })
                $('.box-cb').each(function(){
                    if($(this).find('.box-cb-left')) {
                        var cbl = $(this).find('.box-cb-left');
                        var cbr = $(this).find('.box-cb-right');
                        boxClick(cbl);
                        boxClick(cbr);
                    } else {
                        boxClick($(this));
                    }
                })
                $('.box-cb-red').each(function(){
                    if($(this).find('.box-cb-left').length > 0) {
                        var cbl = $(this).find('.box-cb-left');
                        var cbr = $(this).find('.box-cb-right');
                        boxClick(cbl);
                        boxClick(cbr);
                    } else {
                        boxClick($(this));
                    }
                })
            } else {
                boxClick($(this));
            }
        })
    
        function boxClick(elem) {
            $(elem).find('img').click(function(){
                boxOpen(elem);
            })
            $(elem).find('h3').click(function(){
                boxOpen(elem);
            })
            $(elem).find('h4').click(function(){
                boxOpen(elem);
            })
            /*
            $(elem).find('a').click(function(){
                //boxOpen(elem);
            })
            */
            $(elem).find('p').click(function(){
                if($(this).find('a.lb').length == 0) {
                    boxOpen(elem);
                }
            })
        }
        function boxOpen(elem) {
            var url = $(elem).find('a').attr('href');
            if(url.indexOf('http') == -1) {
                    url = 'http://www.europaeische.at/'+url;
            }
    
            if($(elem).find('a.lb').length > 0) {
                $.fn.colorbox({
                    href: url,
                    width:"665px",
                    initialHeight:"100px",
                    onComplete:function(){
                        setTimeout(function(){ $('#cboxClose').show() }, 1000);
                        $('#cboxOverlay').css({ opacity: 0.5 });
                    },
                    onLoad: function(){ $('#cboxClose').hide(); }
                });
            } else if($(elem).find('a.lb2').length > 0) {
                $.fn.colorbox({
                    href:$(elem).find('a.lb2').attr('href'),
                    width:"795px",
                    initialHeight:"100px",
                    onComplete:function(){
                        setTimeout(function(){ $('#cboxClose').show() }, 1000);
                        $('#cboxOverlay').css({ opacity: 0.5 });
                        $('#hs-plus-info-lang').change(function(){
                            HotelStornoLangSelect();
                        })
                        $('.hs-plus-info-lang-send').click(function(){
                            HotelStornoLangSelect();
                            return false;
                        })
                        HotelStornoLangSelect();
                    },
                    onLoad: function(){ $('#cboxClose').hide(); }
                })
            } else if($(elem).find('a.download').length > 0) {
                window.open(url);
            } else if($(elem).find('a[target="_blank"]').length > 0) {
                window.open(url);
            } else {
                if(url.split('//')[0] == 'http:' || url.split('//')[0] == 'https:') {
                    top.location.href = url;
                } else {
                    top.location.href = "/"+url;
                }
            }
        }
    
    /* ::: Aktuelles box slider ::: */
    
        $('.aktuelles-menu a').click(function() {
    
            var padLeft = 25;
            if($('.aktuelles').hasClass('aktuelles')) {
                padLeft = 25;
            } else if($('.aktuelles-service').hasClass('aktuelles-service')) {
                padLeft = 10;
            }
    
            var $aic = $('.aktuelles-item:eq(' + $(this).index() + ')');
            var $aiv = $('.aktuelles-item:visible');
    
            if($(this).hasClass('act')) {
                return false;
            }
    
            $(this).addClass('act').siblings().removeClass('act');
            $aiv.animate({
              left: -$aiv.outerWidth()
            },500,function(){
                $(this).hide();
            });
    
            $aic.css({left:$aic.outerWidth()}).show().animate({
              left: padLeft
            },500,function(){
            });
    
            return false;
        });
    
    /* ::: Zoom funktion ::: */
    
        $('.zoom-in').colorbox({
            maxWidth:"100%",
            maxHeight:"100%",
            onComplete:function(){
                $('#cboxOverlay').css({ opacity: 0.5 });
            }
        });
    
    /* ::: Presse ::: */
    
        $('.pu-presse').click(function(){
            var href = $(this).attr('href');
            popUpCenter(href,847,650,'toolbar=no,menubar=no,scrollbars=yes,resizable=yes')
            //var new_window = window.open(href,"popup",'width=847,height=650,toolbar=no,menubar=no,scrollbars=yes,resizable=yes');
            return false;
        })
    
    /* ::: Eigentümer und Töchter Länderkarte ::: */
    
        $('#koop-slk').mouseenter(function(){ $('#kooplaender img').attr({src:"fileadmin/img/koop_SLK.gif"})
        }).mouseleave(function(){ $('#kooplaender img').attr({src:"clear.gif"}) }).click(function(){return false;})
    
        $('#koop-slo').mouseenter(function(){ $('#kooplaender img').attr({src:"fileadmin/img/koop_SLO.gif"})
        }).mouseleave(function(){ $('#kooplaender img').attr({src:"clear.gif"}) }).click(function(){return false;})
    
        $('#koop-kro').mouseenter(function(){ $('#kooplaender img').attr({src:"fileadmin/img/koop_KRO.gif"})
        }).mouseleave(function(){ $('#kooplaender img').attr({src:"clear.gif"}) }).click(function(){return false;})
    
        $('#koop-hu').mouseenter(function(){ $('#kooplaender img').attr({src:"fileadmin/img/koop_HU.gif"})
        }).mouseleave(function(){ $('#kooplaender img').attr({src:"clear.gif"}) }).click(function(){return false;})
    
        $('#koop-stir').mouseenter(function(){ $('#kooplaender img').attr({src:"fileadmin/img/koop_STIR.gif"})
        }).mouseleave(function(){ $('#kooplaender img').attr({src:"clear.gif"}) }).click(function(){return false;})
    
        $('#koop-at').mouseenter(function(){ $('#kooplaender img').attr({src:"fileadmin/img/koop_AT.gif"})
        }).mouseleave(function(){ $('#kooplaender img').attr({src:"clear.gif"}) }).click(function(){return false;})
    
        $('#koop-cz').mouseenter(function(){ $('#kooplaender img').attr({src:"fileadmin/img/koop_CZ.gif"})
        }).mouseleave(function(){ $('#kooplaender img').attr({src:"clear.gif"}) }).click(function(){return false;})
    
    
        $('.tt-koop').each(function() {
            var ttposx = 0;
            var ttposy = -25;
    
            var land = $(this).attr("id").split('-')[1];
    
            $(this).qtip({ //TO BE UPDATED IN FUTURE http://craigsworks.com/projects/forums/thread-qtip-1-0-0-rc3-jquery-1-4
               content: $('.tt-cnt-'+land).html(),
               show: 'mouseover',
               hide: 'mouseout',
               position: {
                  corner: {
                     target: 'topLeft',
                     tooltip: 'topRight'
                  },
                  adjust: {
                      x: ttposx,
                      y: ttposy
                  }
               },
               style: {
                    width: 262,
                    border: {
                     width: 0
                  }
               }
            });
        });
    
    /* ::: Bookmark this page ::: */
    
        // add a 'rel' attrib if Opera 7+
        if(window.opera) {
            if ($('#favor').attr('rel') != ""){ // don't overwrite the rel attrib if already set
                $('#favor').attr('rel','sidebar');
            }
        }
    
        $('#favor').click(function(event){
            event.preventDefault(); // prevent the anchor tag from sending the user off to the link
            var url = this.href; // e|vo this.href
            var title = this.title;
    
            if (window.sidebar && window.sidebar.addPanel) { // Mozilla Firefox Bookmark
                window.sidebar.addPanel(title, url, '');
            } else if( window.external ) { // IE Favorite
                window.external.AddFavorite( url, title);
            } else if(window.opera) { // Opera 7+
                return false; // do nothing - the rel="sidebar" should do the trick
            } else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
                 alert('Unfortunately, this browser does not support the requested action,'
                 + ' please bookmark this page manually.');
            }
        });
    
        $('#form_press #year').change(function() {
            $('#form_press').submit();
        });
    
    /* ::: Downloads ::: */
        $('#privatreise').click(function (){
            makeProdOptions('p');
        })
        $('#geschaeftsreise').click(function (){
            makeProdOptions('g');
        })
        function makeProdOptions(porg) {
            if(porg != 0) {
                $('#produkt optgroup').remove();
                $('#produkt option').remove();
                $('<option>').html('Bitte auswählen').val('0').appendTo($('#produkt'));
                for(var key in products[porg]) {
                    var optgrp = $('<optgroup>');
                    $(optgrp).attr({ label: products[porg][key]['name']}).appendTo('#produkt');
                    for(var id in products[porg][key]['ids']) {
                        $('<option>').val(products[porg][key]['ids'][id])
                        .html(productCodes[products[porg][key]['ids'][id]])
                        .appendTo($(optgrp));
                    }
                }
            }
        }
        $('#produkt').change(function(){
            var prodId = $(this).val();
            $('.info-download').html("")
            .append($('<h4>').html("Info-Blatt zum Download:"));
            showDownloads(prodId);
        })
        function showDownloads(prodId) {
            $('<div>').addClass('waiting').appendTo($('.info-download'));
            $.ajax({
                url: "/index.php",
                type: "post",
                data: {
                    eID: "ervbooking",
                    getdoc: "1",
                    prodid: prodId,
                    type: "dl"
                },
                dataType: "html",
                success: function(data){
                    $('.waiting').remove();
                    $('.info-download').append(data);
                }
            })
        }
    
        function HotelStornoLangSelect() {
            $('.info-lang-result').html("")
            .append(
                $('<ul>').addClass('ul-bluedot').append(
                    $('<li>').html("Info-Blatt zum Download:")
                    .append(
                        $('<div>')
                        .addClass('info-download')
                        .html(" ")
                    )
                )
            );
            showDownloadsHotelStorno($('#hs-plus-info-lang').val());
        }
        function showDownloadsHotelStorno(lang) {
            $('<div>').addClass('waitingblue').appendTo($('.info-download'));
            $.ajax({
                url: "/index.php",
                type: "post",
                data: {
                    eID: "ervbooking",
                    getdoc: "1",
                    prodid: 'in931',
                    type: "dl",
                    lang: 'all'
                },
                dataType: "html",
                success: function(data){
                    var tmpArr = data.split('</p><p>');
                    tmpArr[0] = tmpArr[0].split('<p>').join('');
                    tmpArr[tmpArr.length-1] = tmpArr[tmpArr.length-1].split('</p>').join('');
                    for(var i in tmpArr) {
                        if(strpos(tmpArr[i], "_"+lang+"_")!==false) {
                            $('.waitingblue').remove();
                            $('.info-download').append(tmpArr[i]);
                        }
                    }
                }
            })
        }
    
    /* ::: Helper functions ::: */
    
        var popwin;
        function popUpCenter(url,breite,hoehe,options) {
            if(popwin && popwin.closed==false) {
                popwin.close()
            }
            var l = (screen.availWidth - breite) / 2;
            var t = (screen.availHeight - hoehe) / 2;
            var opt = (options == "") ? "width=" + breite + ",height=" + hoehe + ",left=" + l + ",top=" + t + ";" : "width=" + breite + ",height=" + hoehe + ",left=" + l + ",top=" + t + "," + options + ";";
            popwin =window.open(url,"newwindow", opt);
            popwin.focus();
        }
})


function strpos (haystack, needle, offset) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman
    // +   bugfixed by: Daniel Esteban
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

