// Delay plugin
$.fn.delay = function(time, callback){
    // Empty function:
    jQuery.fx.step.delay = function(){};
    // Return meaningless animation, (will be added to queue)
    return this.animate({
        delay:1
    }, time, callback);
}

//global vars, can be changed by another ajax function
var base = $('base').attr('href').toString();
var page = window.location.pathname;
//delete /
page = page.substr(1, page.length);
//delete .html
page = page.substr(0, page.lastIndexOf('.'));

// Onready
$(function(){
    //setting padding on ready
    setPagePadding();

    //setting new padding if window is resized
    $(window).resize(function() {
        setPagePadding();
    });

    // Hide Elements in the beginning
    $(".fade").hide();


    // Init Product galleries
    $("a.start-gallery").each(function(){
        $(this).click(function(e){
            e.preventDefault();
            $(this).parents("div").next("div.ce_gallery_products").find("a:first").trigger("click");
        });
    });


    
    if(!$('#window_layer').length) {
        $('a.open_window_layer').click(function(e){
            e.preventDefault();
            loadWindowLayer('body', 'left', this, $('a.open_window_layer'));
        });
    }

    setupExternalLinks();
    setupAjaxLoadingRetailers();
    setupBoxPopup(true);
    setupBannerStart(true);
    setupToggleMoreLinks();
    setupImagesLoad();
    showAwardLayer();
});

// Onload
window.onload = function(){
    // Slide in Elements in the beginning
    $(".slide").slideUp(0);
    fadeElements();
    setupBannerStart();
    setupBoxPopup();
    hoverImageLinks();
    setupLifestyleSliders();
}

// Fix for IE and all browser without natural Width and heigt attribute
var setupImagesLoad = function(){    
    if(!$('img:first').attr('naturalWidth')){
        $('#main img').each(function(){
            var oldimg = $(this);
            $(new Image()).attr({'src':this.src+"?", 'alt': "xyz"}).load(function(){
                oldimg.attr({"naturalWidth": this.width, "naturalHeight": this.height});
            });
        });
    }
}

var setPagePadding = function() {
$('#wrapper').css('visibility', 'hidden');
    if ($(window).width() >= 1020) {
        $('#wrapper').css('padding-left', (($(window).width() - 1020) * 0.45) + 'px');
        if($('#bg-landing')) {
            $('#bg-landing').css('left', (($(window).width() - 1020) * 0.45) + 'px');
        }
    } else {
        $('#wrapper').css('padding-left', '0');
        if($('#bg-landing')) {
            $('#bg-landing').css('left', '0');
        }
    }
$('#wrapper').css('visibility', 'visible');
//$('#wrapper').show(200);
}

var setupToggleMoreLinks = function() {
    $(document).find('.toggleMoreContent').hide();
    $(document).find('.toggleMore').click(function(e) {
        e.preventDefault();
        $(this).parent().parent().find('.toggleMoreContent').slideToggle(function() {
            if ($(this).css('display') == 'block') {
                $(this).parent().find('.toggleMore').html('Schließen'); 
            } else {
                $(this).parent().find('.toggleMore').html('mehr...');         
            }
        });
    })
}

var setupBannerStart = function(init){
    if(init == true){
        $("#banner a.banner").each(function(){
            $(this).attr("base_top", $(this).css("top"));
            $(this).css("top", (screen.height)+"px");
        });
    } else {
        var delay = 300, start = 0;
        $("#banner a.banner").each(function(){
            $(this).delay(start).animate({
                'top': $(this).attr('base_top')
            }, 1000);
            start = start + delay;
        });
    }
}

var setupBoxPopup = function(init){
    if(init == true){
        $(".box_popup").each(function(){
            $(this).removeAttr('style').hide().fadeOut(0);
        });
    } else {
        $(".box_popup").each(function(){
            $(this).show('fold', {}, 2500);
        });
    }
}

var setupLifestyleSliders = function() {
    /*$('#lifestyle-news .mod_newslist .first .slide').slideDown(function() {
        sliderAnimations($('#lifestyle-news .first p.more a'));
    });*/

    $('#lifestyle-news p.more a').click(function(e){
        sliderAnimations(this, e);
    });
}

var sliderAnimations = function(elem, e) {
        if (e != undefined) {
            e.preventDefault();
            // Slide text
            $(elem).parent().prev('div').find('.slide').slideToggle(function() {
                switchText(elem);
            });      
        } else {
            switchText(elem);

        }
        // Scale Image
        var img = $(elem).parent().prev('div').find('.image_container:first img');
        if(!img.attr('width_small')) img.attr({
            'width_small': img.css('width'),
            'height_small': img.css('height')
        }); //Save dimensions

//IE reports undefined for naturlWidth/ height?
        if(img.css('width') == (img.attr('width_small')) ) {
            img.animate({
                'width': (img.attr('naturalWidth')),
                'height': (img.attr('naturalHeight'))
            });
        } else {
            img.animate({
                'width': (img.attr('width_small')),
                'height': (img.attr('height_small'))
            });
        }
}

var switchText = function(elem) {
        if ($(elem).parent().prev('div').find('.slide').css('display') == 'block') {
            $(elem).html('Schließen'); 
        } else {
            $(elem).html('Weiterlesen...');         
        }
}

/**
 * Open external links in a new window/tab
 */
var setupExternalLinks = function() {
    $("a.target_new").each(function(){
        $(this).click(function(e){
            e.preventDefault();
            window.open($(this).attr('href'));
        });
    });
}

// Fade Elements in on Page loading
var fadeElements = function(index){
    if(!index) index = 0;
    $('.fade').eq(index).fadeIn("fast", function(){
        index++;if(index < $('.fade').length) fadeElements(index);
    });
}

// Auto Hover Images
var hoverImageLinks = function(){
    $("a.hover_image").each(function(a){
        var a = $(this);        
        var defaultImage = a.find("img:first");
        var path = defaultImage.attr("src").substr(0, defaultImage.attr("src").lastIndexOf("/")+1);
        
        var file = "ac-" + defaultImage.attr("src").substr(path.length);
        
        a.css({
            // "position": "relative",
            "min-height": defaultImage.attr("height")+"px",
            "min-width": defaultImage.attr("width")+"px"
        });
        var activeImage = $(new Image());
        activeImage.attr({
            'id': ('ac-'+defaultImage.attr("id")),
            'title':defaultImage.attr("title"),
            'alt': defaultImage.attr("alt"),
            'src': path + file
        });
        activeImage.css({
            'display': 'none'
        });
        activeImage.load(function(){            
            defaultImage.parent().append(activeImage);            
            $(this).parent().mouseover(function(){
                defaultImage.fadeOut(0);activeImage.fadeIn(0);
            });
            $(this).parent().mouseleave(function(){
                defaultImage.fadeIn(0);activeImage.fadeOut(0);
            });
        });
    });
}


// Get the Window Layer
var loadWindowLayer = function(updateEl, column, activatorEl, otherActivators) {
    var url = activatorEl.href;
    var urlextend = url+'?section='+column;
    //delete the base
    page = activatorEl.href.substring(activatorEl.href.lastIndexOf('/')+1, activatorEl.href.lastIndexOf('.html'));
    //var wrapper = $(new Element('div', {id: 'window_layer'}));
    var wrapper = $('<div id="window_layer"></div>');
    wrapper.load(urlextend, {}, function(){
        $(updateEl).append($(this));

        setupWindowLayer(otherActivators);
        setupAjaxLoadingRetailers();
    });
}

/**
 * Sets up the window layer
 * @author Mike vom Scheidt
 */
var setupWindowLayer = function(element) {

    //remove the ajax loading event of the widow_layer
    $(element).unbind('click');
    $(element).click(function(e){
        e.preventDefault();$("#window_layer").fadeIn('slow');$('#windowlayer_background').fadeTo('slow', 0.8);
    });
    $("#window_layer").fadeIn('slow');//.fadeTo('slow', 0.97);
    $('.windowlayer_background').fadeTo('slow', 0.8);
  

    // init close links for window_layer
    $("#window_layer a.close").click(function(e){
        e.preventDefault();
        $('#window_layer').fadeOut();
    });
}

var showAwardLayer = function() {
    $(".awardlayer a.close").click(function(e){
        e.preventDefault();
        $('.awardlayer').fadeOut();
    });

    $('.awardLayerOpener').click(function(e) {
        $(".awardlayer").fadeOut(500);
        name = $(this).attr("id").substring(0, $(this).attr("id").indexOf("_"));
        $("#" + name).css({ "left" : (e.pageX - 50) + "px", "top" : (e.pageY - 50) + "px"});
        $("#" + name).fadeIn(500);
    });
}

/**
 * Sets up the ajax loading of retailers
 * @author Mike vom Scheidt
 */
var setupAjaxLoadingRetailers = function() {
    if($('#retailer_search').length) {
        //base & page are global variables
        var updateUrl = base + page + '/ajax/true.html';

        $('#retailer_search').submit(function(e) {            
            e.preventDefault();
            $('#retailer_list').load(updateUrl, $("#retailer_search").serializeArray(), function(){
                var max = $('#retailers').height() - $('#retailer_list_container_ajax').height();
                if(max > 0){
                    $('#slider_container').slider({
                        orientation: 'vertical', min: -max-50, max: 0, value: 0, animate: true,
                        slide: function(event, ui){$('#retailers').css('top', ui.value);},
                        change: function(event, ui){$('#retailers').css('top', ui.value);}
                    });
                    //set -max ( because the above part is only executed when no slider is present
                    //reset slider to top
                    $('#slider_container').slider('option', 'min', -max-50);
                    $('#slider_container').slider('value', 0);
                    $('#slider_container,#button_container').fadeIn();
                }
                var step = Math.round(max / 10);
                $('#slider-up').click(function(e){
                    e.stopPropagation();
                    $('#slider_container').slider('value', $('#slider_container').slider('value')+step );
                });
                $('#slider-down').click(function(e){
                    e.stopPropagation();
                    $('#slider_container').slider('value', $('#slider_container').slider('value')-step );
                });
                setupExternalLinks();
            });
        });

        //automatically fire the submit event when the user has finished pressing a key
        $('#retailer_search .input_container input#zipcode').keyup(function() {
            $('#retailer_search').triggerHandler('submit');
        });

        $('#retailer_search .input_container select#country').change(function() {
            $('#retailer_search').triggerHandler('submit');
        });
    }
}