/*
    Document   : frontend
    Created on : Jun 17, 2010, 12:14:25 PM
    Author     : Daniel Schwiperich & Mike vom Scheidt
    Description: Frontend JS Functions
 */

/* DomReady */
$(function(){
    $("#container .mod_article").hide(0);
    
    //$("#container .mod_article").css("opacity", 0);
    Shadowbox.init({
        useSizzle: false,
        troubleElements:[],
        flashParams: {
            bgcolor:'#ffffff',
            allowfullscreen: true
        }
    });

    Shadowbox.setup('#ads_gallery a.drag', {
        gallery: "Recent-Ads",
        handleOversize: "drag"
    });
    
    Shadowbox.setup('#khd_in_press a.drag', {
        gallery: "KHD-in-press",
        handleOversize: "drag"
    });
    
    $('.red_points.drag').click(function(e) {
        e.preventDefault();
        Shadowbox.open($(this).parent().find('div a').get(0));
    });
    
    $('.starting-page #header_gallery_big .image_container').click(function() {
        window.location = 'http://www.khd.com/clean-technology.html';
    });

 /*   $('#khd_banner').click(function() {
          window.location = "http://www.khd.com/clean-technology.html";
        Shadowbox.open({
            title: "KHD Banner",
            content: "tl_files/flash/800x900.swf",
            player: "swf",
            width: "800px",
            height: "900px",
            flashParams:  {
                bgcolor:"#ffffff",
                quality:"best"
            }
        });

    }); */

    //apply correct theme on page ready
    var image = $('#header_gallery_big .row_0 img');
    var altImage = image.attr('alt').split(" ").join("_");
    var newTheme = null;
    var newThemes = $("#header_gallery .ce_text");

    //try to determine a specific theme (the image alt has to specified as class in the text container
    if(altImage.length > 0) {
        var newTheme = $("#header_gallery .ce_text").filter('[class~="' + altImage + '"]');
    } 

    //choose a random one when no specific theme has been choosen
    if(newTheme.length < 1) { 
        var newTheme = newThemes.eq(Math.floor(Math.random() * newThemes.length));
    }
    
    newThemes.hide();
    newTheme.show();

    setupAOTW();
});

$(window).load(function () {
    fadeImages('#ads_gallery a.drag', 1000, 6000, 6000);
    fadeImages('#khd_in_press a.drag:not(.skip)', 1000, 6000, 6000);
    //$("#container .mod_article").show();
    $("#container .mod_article").fadeIn();
    newsGalleryKHD(".news_gallery", 500);
    galleryKHD("#slide_gallery", "#header_gallery_big .image_container", 1000, 7500);

    // SlideTwitterNews
    if($("#rss-reader .rss_items_only").size() > 0){
        //console.log("Starting RSS Animation at" + slideRSS_index);
        runSlideRss = setInterval('slideRSS($("#rss-reader .rss_items_only"))', 9000);
        $("#rss-reader a").mouseenter(function(){
            clearInterval(runSlideRss)
        });
        $("#rss-reader a").mouseleave(function(){
            runSlideRss = setInterval('slideRSS($("#rss-reader .rss_items_only"))', 9000);
        });
    }

    if($("#khd_slider .slide").size() > 0){
        //console.log("Starting RSS Animation at" + slideRSS_index);
        runSlideKhd = setInterval('slideKHD($("#khd_slider .slide"))', 9000);
        $("#khd_slider .slide").mouseenter(function(){
            clearInterval(runSlideKhd)
        });
        $("#khd_slider .slide").mouseleave(function(){
            runSlideKhd = setInterval('slideKHD($("#khd_slider .slide"))', 9000);
        });
    }

    // News switch
    if($("#news_lists_switch").size() > 0){
        var newsLists = $("#news_lists_switch .mod_newslist");
        var currentNewsList = 0;
        // Move forward in List
        $("#news_lists_switch a.forward").click(function(e){
            newsLists.eq(currentNewsList).hide();
            // Count one up and Go to first if there no one next
            if(! newsLists.eq(++currentNewsList).size() > 0) currentNewsList = 0;
            newsLists.eq(currentNewsList).show();
        })
        // Move backward in List
        $("#news_lists_switch a.back").click(function(e){
            newsLists.eq(currentNewsList).hide();
            // Count one down and Go to last if there no one previous
            if(--currentNewsList < 0) currentNewsList = newsLists.size() -1;
            newsLists.eq(currentNewsList).show();
        })
    }

    // Clear search fields
    $("#SearchUser,#SearchDocs,#ctrl_keywords").each(function(){
        $(this).click(function(){
            if($(this).attr("defaultValue") == $(this).attr("value")) $(this).attr("value", "");
        });
    });

});

/**
 * RssSlider
 */
var slideRSS_index = 0;
var slideRSS = function(rss){
    var slideSpeed = 3000;
    if(rss.size() > 1){
        rss.eq(slideRSS_index).animate({
            left:'-510'
        },slideSpeed).animate({
            left: '510'
        }, 0);
        if(rss.eq(slideRSS_index+1).size()==0) slideRSS_index = -1;
        rss.eq(slideRSS_index+1).animate({
            left:'10'
        },slideSpeed);
        slideRSS_index++;
    }
}

/**
 * KHDSlider
 */
var slideKHD_index = 0;
var slideKHD = function(rss){
    var slideSpeed = 3000;
    if(rss.size() > 1){
        rss.eq(slideKHD_index).animate({
            left:'-510'
        },slideSpeed).animate({
            left: '510'
        }, 0);
        if(rss.eq(slideKHD_index+1).size()==0) slideKHD_index = -1;
        rss.eq(slideKHD_index+1).animate({
            left:'10'
        },slideSpeed);
        slideKHD_index++;
    }
}
/**
 * Adds onclick events to all a tags within the provided galleryContainer which will change the target img elements src/alt when the a tag is clicked
 * (an a tag can also include other elements like img elements)<br />
 * Remember that you still need to take care of properties like position: absolute to use the fade effect effectively<br /><br />
 * <strong>galleryContainer (jQuery Obj|jQuery Expression)</strong> - the gallery container<br />
 * <strong>targetImgElement (jQuery Obj|jQuery Expression)</strong> - the target img element which should be changed<br />
 * <strong>fadeTime (int)</strong> - the time to fade the element in in ms. Defaults to 1000ms.<br />
 * <strong>automatedSwitchTime (int)</strong> - the time to wait till an automated switch is done in ms. Defaults to 5000ms.
 */
var galleryKHD = function(galleryContainer, targetElement, fadeTime, automatedSwitchTime) {
    galleryContainer = $(galleryContainer);
    var targetImgElements = $(targetElement).find("img");
    var galleryImages = galleryContainer.find("a");

    //only needs to be executed when there's more than one image'
    if(galleryImages.length > 1) {
        var timeoutID = null;
        //check if fadeTime is set
        if(typeof fadeTime == 'undefined' || typeof fadeTime != 'number') {
            fadeTime = 1000;
        }
        if(typeof automatedSwitchTime == 'undefined' || typeof automatedSwitchTime != 'number') {
            automatedSwitchTime = 5000;
        }

        //assign onclick events
        galleryImages.click(function(e) {
            e.preventDefault();
            //check if a fading animation takes place currently
            if(!galleryContainer.hasClass('fading')) {
                var newThemes = null;
                var newTheme = null;
                //add class to prevent another animation
                galleryContainer.addClass('fading');
                //determine the image which should be faded in
                var imageToFade = targetImgElements.filter("img[src='" + $("base").attr("href") + $(this).attr("href")  + "']");
                var altImageToFade = imageToFade.attr('alt').split(" ").join("_");
                //determine which image(s) should be hidden
                var imagesToHide = targetImgElements.filter(":not(img[src=" + $("base").attr("href") + $(this).attr("href")  + "])");
                //add a z_index class to the parent container
                imageToFade.parent().addClass("z_index");

                //try to determine a specific theme (the image alt has to specified as class in the text container
                if(altImageToFade.length > 0) {
                     var newTheme = $("#header_gallery .ce_text").filter('[class~="' + altImageToFade + '"]');
                }

                //choose a random one when no specific theme has been choosen
                if(newTheme.length < 1) {
                    var newThemes = $("#header_gallery .ce_text").filter(":not(:visible)");
                    var newTheme = newThemes.eq(Math.floor(Math.random() * newThemes.length));
                }

                $("#header_gallery .ce_text").filter(":visible").fadeOut(fadeTime / 2);
                newTheme.fadeIn(fadeTime / 2);                

                //fade in image
                imageToFade.fadeIn(fadeTime, function() {
                    //hide all other images
                    imagesToHide.hide();
                    //remove z_index class
                    imageToFade.parent().removeClass("z_index");
                    //remove the fading class to allow another animation
                    galleryContainer.removeClass("fading");
                });
            }
        });

        //automate image change
        var automation = function(index) {
            timeoutID = setTimeout(function() {
                //trigger the click events
                $(galleryImages[index]).trigger('click');
                //make sure we don't go out of bounds
                if(index < galleryImages.length) {
                    automation(index+1);
                } else {
                    automation(0);
                }
            }, automatedSwitchTime);
        }

        //stops automated image switch when thumbs are hovered
        galleryImages.mouseover(function() {
            clearTimeout(timeoutID);
        });

        //restarts automated image switch
        galleryImages.mouseout(function() {
            automation(0)
        });

        //start automation once
        automation(1);

    }
};

/**
 * Sets up scroll functionality for the KHD news gallerys
 * <strong>galleryContainer (jQuery Obj|jQuery Expression)</strong> - the gallery container<br />
 * <strong>animationTime (int)</strong> - the time the animation takes in ms. Defaults to 1000ms.
 */
var newsGalleryKHD = function(galleryContainer, animationTime) {
    galleryContainer = $(galleryContainer);
    var galleryImages = galleryContainer.find(".image_container");

    //only needs to be executed when there's more than three image (else why would we want to scroll?)
    if(galleryImages.length > 3) {
        var maxWidth = 0;
        var singleImageWidth = galleryImages.eq(0).outerWidth(true);
        var maxAllowedMargin = 0;
        var imageWrapperInner = galleryContainer.find(".image_wrapper_inner");

        //check if animationTime is set
        if(typeof animationTime == 'undefined' || typeof animationTime != 'number') {
            animationTime = 1000;
        }

        galleryImages.each(function() {
            //get width inclusive margin and compute overall width of all elements
            maxWidth += $(this).outerWidth(true);
        });

        //maxAllowedWidth = maxWidth - (visibleImages * singleImageWidth)
        maxAllowedMargin = maxWidth - (3 * singleImageWidth);

        //set imageWrapperInner to the computed max width (helps with scrolling later on)
        imageWrapperInner.css("width", maxWidth + "px");

        //action to execute when previous button is clicked
        galleryContainer.find(".gallery_previous").click(function(e) {
            e.preventDefault();
            //make sure that the margin is not larger than 0 (stops scrolling when last image is visible)
            //if for some reason margin is larger, reset it to 0
            //the parsed margin-left returns a negative value (we scroll the images by margin-left)
            if(!imageWrapperInner.hasClass("scrolling"))  {
                if(parseInt(imageWrapperInner.css('margin-left')) < 0) {
                    imageWrapperInner.addClass("scrolling");
                    imageWrapperInner.animate({
                        marginLeft: '+=' + singleImageWidth
                    }, {
                        duration: animationTime,
                        complete:  function() {
                            imageWrapperInner.removeClass("scrolling");
                        }
                    });
                } else {
                    imageWrapperInner.css('margin-left', 0);
                    //remove class if exists
                    $(this).removeClass("hoverable");
                }
            }
        });

        //action to execute when next button is clicked
        galleryContainer.find(".gallery_next").click(function(e) {
            e.preventDefault();
            //make sure that the margin is not larger than maxAllowedMargin (stops scrolling when last image is visible)
            //if for some reason margin is larger, reset it to maxAllowedMargin
            //the parsed margin-left returns a negative value (we scroll the images by margin-left)
            if(!imageWrapperInner.hasClass("scrolling"))  {
                if(parseInt(imageWrapperInner.css('margin-left')) > -maxAllowedMargin) {
                    imageWrapperInner.addClass("scrolling");
                    imageWrapperInner.animate({
                        marginLeft: '-=' + singleImageWidth
                    }, {
                        duration: animationTime,
                        complete: function() {
                            imageWrapperInner.removeClass("scrolling");
                        }
                    });
                } else {
                    imageWrapperInner.css('margin-left', -maxAllowedMargin + "px");
                    //remove class if exists
                    $(this).removeClass("hoverable");
                }
            }
        });

        //add a class "hoverable" to indicate that there are further images (can be used for css styling)
        galleryContainer.find(".gallery_next, .gallery_previous").hover(function() {
            //check if the currently hovered element is gallery_next, else you can assume its gallery_previous
            //then just check the same thing as in the above click actions to determine wether or not there are further images
            if($(this).hasClass("gallery_next")) {
                if(parseInt(imageWrapperInner.css('margin-left')) > -maxAllowedMargin) {
                    $(this).addClass("hoverable");
                } else {
                    $(this).removeClass("hoverable");
                }
            } else {
                if(parseInt(imageWrapperInner.css('margin-left')) < 0) {
                    $(this).addClass("hoverable");
                } else {
                    $(this).removeClass("hoverable");
                }
            }
        });
    }
};

var setupAOTW = function() {
    $("#aotw").click(function(e){
        e.preventDefault();
        $("#image_map").fadeIn(500);
        //IE doesn't know the opacity css setting so we "fade" it to 0.5
        $("#imagemap_background").fadeTo(500, 0.5);
        //use tooltip addition to show html tooltips
        $("#imagemap_container a:not(.close)").tooltip({ effect: 'fade', relative: true, opacity: 0.75});
        //set up close functions
        $("#image_map .close, #imagemap_background").click(function(e) {
            e.preventDefault();
            $("#image_map").fadeOut(500);
        });
    });
};

/**
 * Fades elements into each other (all img elements you specified)<br />
 * Does not fade if only one image is given<br />
 * Adds a class "add_z_index" to the more important element<br /><br />
 * <strong>elements (jQuery Obj|string)</strong> - the elements to be used in the fading animation<br />
 * <strong>fadeTime (int)</strong> - the time it takes to fade over to the next element<br />
 * <strong>[waitTime (int)]</strong> - the time the current element is shown before fading restarts. Defaults to 2000ms<br />
 * <strong>[firstWaitTime (int)]</strong> - the time to wait before starting the animation. Defaults to 2000ms<br />
 * <strong>[hideAllButFirst (bool)]</strong> - whether to hide all elements but the first in the beginning. Defaults to false<br />
 */
var fadeImages = function(elements, fadeTime, waitTime, firstWaitTime, hideAllButFirst) {
    var jQEls = $(elements);
    if(jQEls.length > 1) {
        if(typeof fadeTime == "undefined") {
            fadeTime = 1000;
        }
        if(typeof waitTime == "undefined") {
            waitTime = 2000;
        }
        if(typeof firstWaitTime == "undefined") {
            firstWaitTime = 2000;
        }
        if(typeof hideAllButFirst == "undefined") {
            hideAllButFirst = false;
        }
        //fade out all but the first image if hideAllButFirst is true
        if(hideAllButFirst == true) {
            jQEls.each(function(index) {
                if(index > 0) {
                    $(this).css("display", "none");
                }
            })
        }
        var run = function(i) {
            //fade in the next image
            $(jQEls[i+1]).addClass("add_z_index");
            $(jQEls[i+1]).fadeIn(fadeTime, function() {
                $(jQEls[i]).fadeOut(0, function() {
                    $(jQEls[i+1]).removeClass("add_z_index");
                });
                i++;
                //wait for n seconds
                setTimeout(function() {
                    //check if the end of the jQEls array is reached
                    if(jQEls.length == i+1) {
                        //if yes fade current image out and the first array image in
                        //then wait for n seconds and call run with i set to 0
                        $(jQEls[0]).addClass("add_z_index");
                        $(jQEls[0]).fadeIn(fadeTime, function(){
                            $(jQEls[i]).fadeOut(0, function() {
                                $(jQEls[0]).removeClass("add_z_index");
                            });
                            setTimeout(function() {
                                run(0);
                            }, waitTime);
                        });
                    } else {
                        //else just call "run" with the current i
                        run(i);
                    }
                }, waitTime);
            });
        }
        //first time fade - show first image for waittime before starting animation
        setTimeout(function() {
            run(0);
        }, firstWaitTime);
    }
};
