var login_active = 0;

$(function(){

    var imgsrc = null;
    var layer = null;
    var active = null;
    var infoact = null;
    
    $("ul.sf-menu").superfish({
        autoArrows: false,
        dropShadows: false,
        speed: "fast",
        delay: 250
    });
    
    $("ul.sf-menu a img").hover(function(e){
        $(this).attr("src", $(this).attr("src").replace(/.png$/, '_o.png'));
    }, function(e){
        $(this).attr("src", $(this).attr("src").replace(/_o.png$/, '.png'));
    });
    
    $("#body .rounded").piano(function(el){
        window.clearTimeout(oPageToggle);
        
        if (infoact) {
            var $e = $(el);
            while (!$e.hasClass("rounded")) 
                $e = $e.parent();
            var id = $e.attr("id").substr(3, 1);
            
            if (infoact.attr('id') == 'info' + id) {
                hideProductLayer();
                return false;
            }
            
            infoact.hide();
        }
        
        var $e = $(el);
        while (!$e.hasClass("rounded")) 
            $e = $e.parent();
        
        $("#mainvisual-categories .rounded").removeClass("active");
        $e.addClass("active");
        var id = $e.attr("id").substr(3, 1);
        $("#mainvisual .image").fadeOut("slow");
        $("#mainvisual .item").hide();
        infoact = $("#mainvisual #info" + id).fadeIn("slow");
    });
    
    $(document.body).click(function(){
       hideProductLayer();
    });
    
    function hideProductLayer(){
        var zindex = 0;
        /* Main product teaser on startpage */
        $("#mainvisual-categories .rounded").removeClass("active");
        $("#mainvisual .prodinfo").fadeOut("slow");
        $("#mainvisual .image").fadeIn("slow");
        $("#mainvisual-categories .rounded").each(function(){
            $(this).css("z-index", zindex++);
        });
        if (infoact) {
            infoact.fadeOut("slow");
            $("#mainvisual .item").show();
            infoact = null;
        }
        /* Function navigation right top: Login | Sprache | Suche */
        if (login_active == 0) {
            if (layer) { 
                $(layer).children('*').fadeOut('slow', function() {
                    $(layer).slideToggle("slow");
                    layer = null;
                });                
            }
           
            if (active) {
                active.css("color", "#FFFFFF");
                active = null;
                $("#service").removeClass('opened');
            }
        }
        
        $("#mainvisual-categories .rounded").removeClass("active");
        
        window.clearTimeout(oPageToggle);
        oPageToggle = window.setTimeout('toggleStartpageImageByTime()', 10000);
    }
    
    $("#closecontact").click(function(){
        $($(this).attr("href")).slideUp("medium");
        $("#contactbutton").attr('class', '');
        $("#productbutton").attr('class', '');
        return false;
    });
    
    $("#closeproduct").click(function(){
        $($(this).attr("href")).slideUp("medium");
        $("#contactbutton").attr('class', '');
        $("#productbutton").attr('class', '');
        return false;
    });
    
    $("#contactbutton").click(function(){
        if ($("#contact").css('display') == 'block') {
            $("#contact").slideUp("medium");
            $("#contactbutton").attr('class', '');
        }
        else {
            $("#contact").slideDown("medium");
            $("#contactbutton").attr('class', 'active');
        }
        
        $("#contact").css("z-index", "100");
        $("#product").css("z-index", "0");
        $("#contactbutton").css("z-index", "101");
        $("#productbutton").css("z-index", "0");
    });
    
    $("#productbutton").click(function(){
        if ($("#product").css('display') == 'block') {
            $("#product").slideUp("medium");
            $("#productbutton").attr('class', '');
        }
        else {
            $("#product").slideDown("medium");
            $("#productbutton").attr('class', 'active');
        }
        $("#contact").css("z-index", "0");
        $("#product").css("z-index", "100");
        $("#contactbutton").css("z-index", "0");
        $("#productbutton").css("z-index", "101");
    });
    
    $("div.close").click(function(e){
        var target = "#" + $(e.target).parent().attr("id");
        $(target).slideUp("slow");
    });
    
    $("#service a").click(function(e){
        if (active == null || ( active.attr("target") !=  $(this).attr("target")) ) {                   
            if (active) 
                active.css("color", "#FFFFFF");
            var target = "#" + $(this).attr("target");

            $(target).children('*').hide();
            if ($("#service").hasClass('opened')) {
                if (layer) {
                    layer.children('*').fadeOut("slow");
                    layer.hide();
                }
                $(target).show();
                $(target).children('*').fadeIn('slow');
            } else {
                $(target).slideToggle("slow", function() {
                    $(target).children('*').fadeIn('slow');
                });
            }
            
            
            $(target).click(function(e){
                //e.stopPropagation();
                //return false;
            });
            
            
            $(this).css("color", "#000000");
            
            layer = $(target);
            active = $(this);
            
            $("#service").addClass('opened');
        }
        return false;
        
    });
    
    
    
    $('#div-login, #div-lang, #div-search, #service').mouseover(function(){
        login_active = 1;
    });
    
    $('#div-login, #div-lang, #div-search, #service').mouseout(function(){
        login_active = 0;
    });
    
    $('#gc-search-submit').mouseover(function(){
        $("#gc-search-submit").attr('src', 'images/buttons/btn_search_o.png');
    })
    
    $('#gc-search-submit').mouseout(function(){
        $("#gc-search-submit").attr('src', 'images/buttons/btn_search.png');
    });
    
    if ($("#contact-nav li a").length > 2) {
        var sSelector = "#contact-nav li a:eq(1), #contact-nav li a:eq(2)";
    } else {
        var sSelector = "#contact-nav li a:eq(0), #contact-nav li a:eq(1)";
    }
    
    $(sSelector).click(function(){
        if ($(this).hasClass('tab_location')) {
            $('#contact-germany').css('display', 'none');
        }
        $("#contact #contact-germany").css('display', 'none');
        $("#contact #contact-countries").css('display', 'none');
        $("#contact-details").css('display', 'none');
        $("#contact-details #contact-navi li a").removeClass("active");
        
        var href = $(this).attr("href").split("?")[1];
        var id = href.match(/^ajaxcontact=(\d{1,3})/)[1];
        
        $("#contact-details").fadeOut('fast', function(){
            $("#contact-details").html();
        });
        $("#contact-nav li a").removeClass("active");
        
        $.get("front_content.php", {
        
            idcat: id,
            method: "contacts_for_country"
        
        }, function(data){
            var html = '';
            
            $("#contact-countries .countrylist").empty();
            $("#contact-countries").hide();
            
            $.each(data, function(i, o){
                $("#contact-countries .countrylist").append('<li><a rel="' + o.image_big + '" href="' + o.idartlang + '"><img src="' + o.image + '"/>' + o.name + '</a></li>');
            });
            
            $("#contact-countries").fadeIn("fast");
            
        }, "json");
        
        return false;
        
    });
    
    if ($("#contact-nav li a").length > 2) {
        $("#contact-nav li a:first").click(function(){
            $('contact-countries').fadeOut();
        });
    
        //  $("#contact-nav li a:first").unbind();
        $("#contact-nav li a:first").click(function(){
            $("#contact #contact-germany").css('display', 'none');
            $("#contact #contact-countries").css('display', 'none');
            $("#contact-details").css('display', 'none');
            $("#contact-details #contact-navi li a").removeClass("active");
            $('#contact-countries').fadeOut('fast');
            $("#contact-germany").fadeIn('fast');
            
            return false;
        });
    }
    
    $('#gc-search-submit').live("click", function(e){
        $("#contact-details #contact-navi li a").removeClass("active");
        e.stopPropagation();
        
        var sSearch = $("#gc-search").val();
        
        $.get("front_content.php", {
            idart: 903,
            searchterm: sSearch,
            method: "contact_for_germany"
        }, function(data){
            fillContactDetails(data);
            $("#contact-details #name").text('Deutschland');
            $("#contact-details #flag").attr("src", 'upload/flags/flag_germany_big.png');
            $("#contact-details").fadeIn("fast");
            cleanStructure();
        }, "json");
        
        return false;
    });
    
    $("#contact #contact-details #contact-navi li a").live("click", function(e){
        e.stopPropagation();
        var sLayer = $(e.target).attr("href");
        
        $("#contact-details #contact1, #contact-details #contact2, #contact-details #contact3").css('display', 'none');
        $("#contact-details #contact-navi li a").removeClass("active");
        $(e.target).addClass("active");
        
        $("#contact-details #" + sLayer).fadeIn("fast");
        return false;
    });
    

    function fillContactDetails(data){
        var j = 1;
        $.each(data, function(i, o){
            $("#contact-details #contact" + j).html(o);
            $("#contact-details a[href=contact" + j + "]").html('<img src="images/buttons/btn_radiobutton.gif" alt="" /> ' + i);
            $("#contact-details a[href=contact" + j + "]").parent().css('display', 'block');
            j++;
        });
        
        if (j > 1) {
            $("#contact-details p.contact-navi-head").css('display', 'block');
        }
        else {
            $("#contact-details p.contact-navi-head").css('display', 'none');
        }
    }
    
    function fillContactDetails(data){
        var j = 1;
        $.each(data, function(i, o){
            $("#contact-details #contact" + j).html(o);
            $("#contact-details a[href=contact" + j + "]").html('<img src="images/buttons/btn_radiobutton.gif" alt="" /> ' + i);
            $("#contact-details a[href=contact" + j + "]").parent().css('display', 'block');
            j++;
        });
        
        if (j > 1) {
            $("#contact-details p.contact-navi-head").css('display', 'block');
        }
        else {
            $("#contact-details p.contact-navi-head").css('display', 'none');
        }
    }
    
    $("#contact-countries .countrylist li").live("click", function(e){
        if (typeof(siteMode) != 'undefined') {
          /*  var oOffset = $(this).children('a').children('img').offset();
            
			$('#contact-details').offset({
                top: oOffset.top - 50
            });*/
        }
        $("#contact-details #contact-navi li a").removeClass("active");
        e.stopPropagation();
        
        $("#contact-details #contact-navi li").css('display', 'none');
        $("#contact-details #contact1, #contact-details #contact2, #contact-details #contact3").css('display', 'none');
        
        var idartlang = $(this).find('a').attr("href");
        var imageBig = $(this).find('a').attr("rel");
        var country = $(this).find('a').text();
        
        $("#contact-details").fadeOut("fast");
        
        $.get("front_content.php", {
            idart: 903,
            contact_id: idartlang,
            method: "contact_for_country"
        }, function(data){
            fillContactDetails(data);
            $("#contact-details #name").text(country);
            $("#contact-details #flag").attr("src", imageBig);
            $("#contact-details").fadeIn("fast");
            
            cleanStructure();
        }, "json");
        
        return false;
        
    });
    
});

function cleanStructure() {
    if ($("#contact_inner #contact-details #contact-navi").length > 0) {
        var headline = $("#contact_inner #contact-details p.contact-navi-head").text();
        headline = headline.replace(/^\s+/g, '');
        headline = headline.replace(/\s+$/g, '');
        
        headline = headline.replace(':', '');
        var i = 1;
        $("#contact_inner #contact-details #contact-navi li").each(function() {
            var text = $(this).text().replace(/\s+/g, '');
            var line = headline+' '+text;

            $("pre#contact"+i).prepend('<div class="disp_head">'+line+'</div>');
            $("pre#contact"+i).show();
            i++;
        });
        
        $("#contact_inner #contact-details #contact-navi").hide();
        $("#contact_inner #contact-details p.contact-navi-head").hide();
    }
}

var dold_zaehler = 0;

function dold_js_loadMatrix(select, filter, value){
    $(select).parent().parent().parent().parent().parent().load('../../datenblatt/pa/pa_loader.php', {
        'filter': filter,
        'value': value
    }, function(){
        dold_js_reinit();
    });
}

function dold_change_matrix(select, filter, value){
    //alert(family + ' - ' + filter + ' - ' + value);
    select = $('#' + select);
    //alert(select);
    $(select).load('../../datenblatt/pa/pa_loader.php', {
        'filter': filter,
        'value': value
    }, function(text){
        dold_js_reinit();
    });
    
}

function dold_js_reinit(){
    $("#innercontent_complex .pa_filter2").each(function(){
        $(this).change(function(){
            dold_js_loadMatrix(this, $(this).id(), this.value);
            $(this).attr('oldval', this.value);
        });
    });
    
    
    if ($('ul.jd_menu').jdMenu) {
        $('ul.jd_menu').jdMenu();
    }
}

function toggleStartpageImage(oClicked, bAuto){
    if (oClicked.parent().hasClass('active')) {
        return false;
    }
    
    $('#mainvisual .item').removeClass('active');
    
    $('#mainvisual .image').fadeOut('fast', function(){
        $('#mainvisual .image').css('background-image', 'url("' + oClicked.attr('href') + '")');
        $('#mainvisual .image a').attr('href', oClicked.attr('rel'));
        $('#mainvisual .image').fadeIn('fast');
    });
    
    oClicked.parent().addClass('active');
    
    
    if (bAuto == false) {
        window.clearTimeout(oPageToggle);
        oPageToggle = window.setTimeout('toggleStartpageImageByTime()', 10000);
    }
    
    return false;
}

function toggleStartpageImageByTime(){
    if ($('#mainvisual .item.active').prev().hasClass('item')) {
        toggleStartpageImage($('#mainvisual .item.active').prev().find('a'), true);
    }
    else {
        toggleStartpageImage($('#mainvisual .item:last').find('a'), true);
    }
    
    window.clearTimeout(oPageToggle);
    oPageToggle = window.setTimeout('toggleStartpageImageByTime()', 10000);
}

var oPageToggle = null;

$(document).ready(function(){
    if (typeof($.browser.msie) != 'undefined') {
        if ($.browser.version == '6.0') {
            iPosLeft = Math.floor(($(window).width() - 560) / 2);
            var sWarningLayer = '<div id="warning_browser_layer" style="text-align:center;cursor:pointer;padding:20px;position:absolute;z-index=1001;left:' + iPosLeft + 'px;top:80px;width:600px;height:300px;background-color:#dd7200;"></div>';
            sWarningLayer += '<div style="background-color:#fff;position:absolute;left:0px;top:0px;z-index:1000" id="alpha_layer">&nbsp;</div>';
            
			$('body').append(sWarningLayer);
		    
			$.get('front_content.php?idart=200248', function(data){
                $('#warning_browser_layer').html('<h1><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>'+$(data).text()+'</h1>');
            });
            
           
            $('#alpha_layer').css('width', $(window).width());
            $('#alpha_layer').css('height', $(document).height());
            
        }
    }
    $('#warning_browser_layer').live('click', function(){
        $(this).fadeOut('fast', function(){
            $('#alpha_layer').fadeOut('fast');
        });
    });
    $("#mainvisual .item a").each(function(){
        var oImage = new Image();
        oImage.src = $(this).attr('href');
    });
    
    $("#mainvisual .item a").click(function(){
        return toggleStartpageImage($(this), false);
    });
    
    window.clearTimeout(oPageToggle);
    oPageToggle = window.setTimeout('toggleStartpageImageByTime()', 10000);
    
    dold_js_reinit();
    
    dold_zaehler = 0;
    
    $("#innercontent_complex table").each(function(){
        var z = 0;
        z = dold_zaehler;
        if ($(this).is('.pa_matrix') || $(this).find("colgroup").length) {
            if (z) 
                $(this).hide();
            $(this).addClass('produktauswahl');
            $(this).attr({
                dold_num: z
            });
            dold_zaehler++;
            
            $('a', this).each(function(){
                if ($(this).attr('target') == '') 
                    $(this).attr('target', '_blank');
            });
            
        }
    });
    
    if (dold_zaehler) {
        dold_zaehler = 0;
        $("#innercontent_complex img").each(function(){
            var z = 0;
            z = dold_zaehler;
            
            $(this).attr({
                dold_num: z
            });
            $(this).addClass('productmatrix_selection_img_normal');
            if (!z) 
                $(this).addClass('productmatrix_selection_img_selected');
            
            $(this).click(function(){
                dold_hide_productTable($(this).attr("dold_num"));
                $("#innercontent_complex img").removeClass('productmatrix_selection_img_selected');
                
                $(this).addClass('productmatrix_selection_img_selected');
            });
            dold_zaehler++;
            
        });
    }
    
    if ($('#searchbox').length > 0) {
        $('div.matrix').hide();
        $('div.matrix').css('clear', 'both');
        
        if ($('div.matrix div').length == 0) {
            $('#search_tabs').remove();
        }
        
        if ($('#search_results div.search_result').length == 0 && $('div.matrix div').length != 0) {
            $('#search_tabs').remove();
            $('#search_results').hide();
            $('div.matrix').show();
        }
    }
    
    $('#login-form #button').click(function() {
        $('#login-form #input_submit').click();
    });
    
    $('#login_form #login_inline').click(function() {
        $('#login_form #input_submit_inline').click();
        return false;
    });
    
    $('#pw_request_form #pw_request_inline').click(function() {
        $('#pw_request_form #input_submit_inline').click();
        return false;
    });
    
    
    
    
});

function toggleToSiteSearch(clicked){
    $('#search_tabs div').removeClass('active');
    $(clicked).addClass('active');
    $('div.matrix').fadeOut('fast', function(){
        $('#search_results').fadeIn('fast');
    });
}

function toggleToProductSearch(clicked){
    $('#search_tabs div').removeClass('active');
    $(clicked).addClass('active');
    $('#search_results').fadeOut('fast', function(){
        $('div.matrix').fadeIn('fast');
    });
}

$.fn.hoverClass = function(c){
    return this.each(function(){
        $(this).hover(function(){
            $(this).addClass(c);
        }, function(){
            $(this).removeClass(c);
        });
    });
};



// Hides a specific table
function dold_hide_productTable(num){

    // find all table-elements in #innercontent_complex
    $("#innercontent_complex table").each(function(){
    
        // if custom attribute "dold_num" is not null..
        if ($(this).attr("dold_num") != null) 
            // show the table, if it is the corresponding one to "num" argument, or...
            if ($(this).attr("dold_num") == num) {
                $(this).show();
            }
            // otherwise hide the table
            else {
                $(this).hide();
            }
        
    });
    
    
}

function changeLanguage(){
    var sCurUrl = location.href;
    sCurUrl = sCurUrl.replace(/\??&?changelang=(\d*)/, '');
    var iCurLangId = $('#input_language option:selected').val();
    if (iCurLangId > 0) {
        if (sCurUrl.indexOf('?') == -1) {
            location.href = sCurUrl + '?changelang=' + iCurLangId;
        }
        else {
            location.href = sCurUrl + '&changelang=' + iCurLangId;
        }
        
    }
}

function bookmark(url, title){
    // ist keine Url angegeben, wird der aktuelle Hostname genutzt
    var url = url || location.protocol + '//' + location.host;
    // um die aktuelle Url zu bookmarken, die vorherige Zeile
    // auskommentieren und die nächste einkommentieren.
    // var url = url || location.href;
    
    // kein Titel angeg. wird der aktuelle Hostname benutzt
    var title = title || location.host;
    // um den Titel aktuelle Url zu bookmarken, die vorherige Zeile
    // auskommentieren und die nächste einkommentieren.
    // var title = document.title;
    
    // Internet Explorer
    if (document.all) {
        window.external.AddFavorite(url, title);
    }
    // Firefox
    else 
        if (window.sidebar) {
            window.sidebar.addPanel(title, url, '');
        }
    // false zurückliefern, fall die Funktion
    // über das "onlick"-Event des <a>-Tags
    // aufgerufen wurde
    return false;
}



/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
(function($) {
    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
            options = $.extend({}, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

        var pairs = document.cookie.split('; ');
        for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
        }
        return null;
    };
})(jQuery);
