// Open Error-Message-Box
function showMessage(content, messageClass, isHTML) {

    // remove current message
    $("#message").remove();
	// create element
	var $message = $("<div id='message' class='" + messageClass + "'></div>").hide();
    // insert content
    if (typeof(isHTML) === "undefined") {
        $message.html("<p>" + content + "</p>");
    } else {
        $message.html(content);
    }
    // add element to page
    if ($(".content:first").find(".rightColumn").length > 0) {
        $element = $(".content:first").find(".rightColumn");
    } else {
        $element = $(".content:first");
    }
    $element.prepend($message).find("#message").slideDown();
	// scroll to top, so user can read the error message
	$(window).scrollTop(200);
    
}

// add bookmark
function bookmarkSite() {

    title   = document.title;
    url     = document.URL;

	if (window.sidebar)                         window.sidebar.addPanel(title, url, "");        // Mozilla Firefox Bookmark 
	else if (window.external)                   window.external.AddFavorite( url, title);       // IE Favorite
	else if (window.opera && window.print)      return true;                                    // Opera Hotlist => do nothing

}

var Roundabout = {
    init: function() {
        
        // position all elements
        var width = $("#roundabout .gridOverview:first").outerWidth() + parseInt($("#roundabout .gridOverview:first").css("marginRight"));
        $("#roundabout .gridOverview").each(function(i) {
            $(this).css("left", i * width);
        });

        var count = $("#roundabout .gridOverview").length;

        /* remove arrows if there are not enough items */
        if (count < 5) {
            $(".roundaboutBrowse a").hide();
        }

        /* LEFT */
        $("#roundaboutBrowseLeft a").click(function(event){
            event.preventDefault();
            // get last element and width
            var $element = $("#roundabout .gridOverview:last");
            var move = $element.outerWidth() + parseInt($element.css("marginRight"));
            // position of new insert
            var insertPosition = -$element.outerWidth();
            // clone and add to end
            $("#roundaboutContent").prepend($element.clone().css({
                left: insertPosition
            }));
            var i = 0;
            $("#roundabout .gridOverview").animate({
                left: "+=" + move
            }, function(){
                i++;
                if (i == count) {
                    $("#roundabout .gridOverview:last").remove();
                }
            });
        });
        /* RIGHT */
        $("#roundaboutBrowseRight a").click(function(event){
            event.preventDefault();
            // get first element and width
            var $element = $("#roundabout .gridOverview:first");
            var move = $element.outerWidth() + parseInt($element.css("marginRight"));
            // position of new insert
            var insertPosition = parseInt($("#roundaboutContent").css("paddingLeft"));
            $("#roundabout .gridOverview").each(function(){
                insertPosition+= $(this).outerWidth();
                insertPosition+= parseInt($(this).css("marginRight"));
            });
            // clone and add to end
            $("#roundaboutContent").append($element.clone().css({
                left: insertPosition
            }));
            var i = 0;
            $("#roundabout .gridOverview").animate({
                left: "-=" + move
            }, function(){
                i++;
                if (i == count) {
                    $("#roundabout .gridOverview:first").remove();
                }
            });
        });
        
    }
}

var Slideshow = {
    stopped: false,
    // setup class and bind events
    init: function() {
        Slideshow.$active = $("#headerSlideshow IMG.active");
        if (Slideshow.$active.length == 0 ) {
            Slideshow.$active = $("#headerSlideshow IMG:last");
        }
        // attack event to "back"-button (stops autoplay and selects previous image)
        $("#headerSlideshow a.back").click(function(event){
            event.preventDefault();
            $("#headerSlideshow img").stop(false, true);
            Slideshow.stopped = true;
            Slideshow.showPrevious();
        });
        // attack event to "forth"-button (stops autoplay and selects next image)
        $("#headerSlideshow a.forth").click(function(event){
            event.preventDefault();
            $("#headerSlideshow img").stop(false, true);
            Slideshow.stopped = true;
            Slideshow.showNext();
        });
    },
    // go to next image
    showNext: function() {
        Slideshow.$next =  Slideshow.$active.next("img").length ? Slideshow.$active.next("img") : $("#headerSlideshow IMG:first");
        Slideshow.$active.addClass("last-active");
        Slideshow.$next.css({opacity: 0.0})
            .addClass("active")
            .animate({opacity: 1.0}, 1000, function() {
                Slideshow.$active.removeClass("active last-active");
                Slideshow.$active = Slideshow.$next;
            });
        if (!Slideshow.stopped) {
            window.setTimeout(function(){
                Slideshow.showNext();
            }, 4000);
        }
    },
    // go to previous image
    showPrevious: function() {
        Slideshow.$previous =  Slideshow.$active.prev("img").length ? Slideshow.$active.prev("img") : $("#headerSlideshow IMG:last");
        Slideshow.$active.addClass("last-active");
        Slideshow.$previous.css({opacity: 0.0})
            .addClass("active")
            .animate({opacity: 1.0}, 1000, function() {
                Slideshow.$active.removeClass("active last-active");
                Slideshow.$active = Slideshow.$previous;
            });
    },
    // start autoplay
    autoplay: function() {
        Slideshow.init();
        window.setTimeout(function(){
            Slideshow.showNext();
        }, 3000);
    }
}

var FullscreenImage = {
    galleryList: new Array(),
    gallery: false,
    currentIndex: 0,
    change: function(href) {
    
        if ($("img.popupImage").length > 0) {
            $("img.popupImage").fadeOut(function(){
                $(this).remove();
                FullscreenImage.show(href);
            });
        } else {
            FullscreenImage.show(href);
        }
      
    },
    show: function(href) {
        
        $element = $("<img src=" + href + " class='popupImageDummy' />");
        
        $element.load(function(){
            $('body').append($element);
            // determine dimensions (by displaying it outside of the viewport)
            var elementWidth = $element.width();
            var elementHeight = $element.height();
            // larger than viewport?
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();
            // adjust width
            if (elementWidth > (windowWidth * 0.8)) {
                var factor = (windowWidth * 0.8) / elementWidth;
                elementWidth = elementWidth * factor;
                elementHeight = elementHeight * factor;
            }
            // adjust height
            if (elementHeight > (windowHeight * 0.8)) {
                var factor = (windowHeight * 0.8) / elementHeight;
                elementHeight = elementHeight * factor;
                elementWidth = elementWidth * factor;
            }
            // show element and set size
            $element.removeClass("popupImageDummy").hide().addClass("popupImage").css({
                width: elementWidth,
                height: elementHeight,
                marginTop: -(elementHeight/2),
                marginLeft: -(elementWidth/2)
            }).fadeIn();

        });
        
    },
    init: function(link) {
        // show first image
        FullscreenImage.show($(link).attr("href"));
        // is there a gallery?
        if ($("a.gallery").length > 1) {
            // set gallery
            FullscreenImage.gallery = true;
            $("a.gallery").each(function(i, imageLink){
                FullscreenImage.galleryList[i] = $(imageLink).attr("rel");
                // set index of current image
                if ($(imageLink).attr("rel") == $(link).attr("rel")) {
                    FullscreenImage.currentIndex = i;
                }
            });
        }
        // overlap background & show image
        $("body").append("<div id='fade'></div><div id='popupImageClose'><a href='#'>Close</a></div>");
        $("#fade").css({"filter" : "alpha(opacity=90)"}).fadeIn();
        // show next-/prev-links
        if (FullscreenImage.gallery == true) {
            $("body").append("<div id='popupImageGalleryLinks'><a href='#' id='galleryLinkPrev' class='galleryLinks'><span class='sprite arrow leftLightXLWhite'></span></a><a href='#' id='galleryLinkNext' class='galleryLinks'><span class='sprite arrow rightLightXLWhite'></span></a></div>");
            $("#galleryLinkPrev").click(function(event){
                event.preventDefault();
                FullscreenImage.currentIndex = (FullscreenImage.galleryList.length + FullscreenImage.currentIndex - 1) % FullscreenImage.galleryList.length;
                FullscreenImage.change(FullscreenImage.galleryList[FullscreenImage.currentIndex]);
            })
            $("#galleryLinkNext").click(function(event){
                event.preventDefault();
                FullscreenImage.currentIndex = (FullscreenImage.currentIndex + 1) % FullscreenImage.galleryList.length;
                FullscreenImage.change(FullscreenImage.galleryList[FullscreenImage.currentIndex]);
            })
        }
        
        // assign closing and remove afterward
        $('#popupImageClose').live('click', function(event) {
            event.preventDefault();
            $('#fade, .popupImage, #popupImageGalleryLinks, #popupImageClose').fadeOut(function() {
                $('#fade, .popupImage, #popupImageGalleryLinks, #popupImageClose').remove();
            });
        });

    }
    
}

function initQuickSearch() {

    var defaultValueQuery = $("#query").attr("value");
    $("#query").focus(function(){
        if ($(this).attr("value") == defaultValueQuery) {
            $(this).attr("value", "");
        }
    }).blur(function(){
        if ($(this).attr("value") == "") {
            $(this).attr("value", defaultValueQuery);
        }
    });
    // prevent submitting default value
    $("#quickSearchSubmit").click(function(){
        if ($("#query").attr("value") == defaultValueQuery) {
            $("#query").attr("value", "");
        }
    });
    
}

function initNlSubscribe() {

    var defaultValue = $("#emailSubscribeFooter").attr("value");
    $("#emailSubscribeFooter").focus(function(){
        if ($(this).attr("value") == defaultValue) {
            $(this).attr("value", "");
        }
    }).blur(function(){
        if ($(this).attr("value") == "") {
            $(this).attr("value", defaultValue);
        }
    });
    
}

// insert live search-resuls / selection to page
function addLiveSearchResultToList(data, selector) {
    
    $("#jquery-live-search").hide();

    // already present?
    if ($(selector).find("a[rel=" + data.ID + "]").length > 0) {
        return false;
    }

    // transfer differences between items and news
    if (typeof data.productTerm !== 'undefined')        var term = data.productTerm;
    else                                                var term = data.headline;

    var element = "<li>"

        if (data.imageUrl != false) {
        element+= "<img src='" + data.imageUrl + "' alt='" + term + "' />";
        }
    
        element+= "<span><a href='" + data.compiledLink + "' target='_blank'>" + term + "</a></span>";

        element+= "<a class='removeResult' href='#' rel='" + data.ID + "'><img src='" +  IMG + "icon_remove.gif' alt='" + langElementDelete + "' /></a>";
        element+= "<br class='clear'>";
        element+= "</li>";
    
    $(selector).append(element);
    
}

// check all non-technical categories
function initCheckAllNonTechnicalCategories() {
    
    var count = $("input.nonTechnical").length;
        
    // all checked?
    if (count == $("input.nonTechnical").serializeArray().length) {
        $("#checkAllNonTechnical").attr("checked", "checked");
        $.uniform.update();
    }
    
    // update via single check
    $("input.nonTechnical").click(function(){
        if (count == $("input.nonTechnical").serializeArray().length) {
            $("#checkAllNonTechnical").attr("checked", "checked");
        } else {
            $("#checkAllNonTechnical").removeAttr("checked");
        }
        $.uniform.update();
    });
    
    // all / none
    $("#checkAllNonTechnical").click(function(){
        var checked = this.checked;
        // checked? => uncheck all others
        if (checked) {    
            $("input.nonTechnical").attr("checked", checked);
        } else {
            $("input.nonTechnical").removeAttr("checked");
        }
        $.uniform.update();        
    });
    
}

// jQuery Ready-Handler
$(function() {

    if ($("#liveSearchItemForm input[name='q']").length > 0) {
        // only active?
        if ($("#liveSearchItemForm input[name='activeOnly']").length > 0) {
            var url = HTTP_AJAX_ADMIN + "?live-search=true&activeOnly=true&q=";
        } else {
            var url = HTTP_AJAX_ADMIN + "?live-search=true&activeOnly=false&q=";
        }
        $("#liveSearchItemForm input[name='q']").liveSearch({
            url: url
        });
    }
    // bookmark site
    $("a#addSiteAsBookmark").click(function(event) {
        event.preventDefault();
        bookmarkSite();
    });

    // uniform
    if ($("input:checkbox").length > 0)     $("input:checkbox").uniform();
    if ($("input:radio").length > 0)        $("input:radio").uniform();
    if ($("select.default").length > 0)     $("select.default").uniform({selectClass: "selector"});
    if ($("select.small").length > 0)       $("select.small").uniform({selectClass: "selector selectorSmall"});
    if ($("select.gray").length > 0)        $("select.gray").uniform({selectClass: "selector selectorGray"});

    /* opens an image as fullscreen */
    
    $('a.imageAsFullscreen').click(function(event) {
        event.preventDefault();
        FullscreenImage.init(this);
    });
    
    /* countdown */

    // add class "red" to finished countdown and update status ("Status: beendet.")
	function countdownFinished() {
        $(this).closest("p").addClass("red").html(langStatusFinished);
	}
	// highlight last hour
	function countdownLastHour(periods) { 
        if ($.countdown.periodsToSeconds(periods) < 3600 && !$(this).hasClass("red")) { 
            $(this).addClass("red"); 
        } 
    }
	// start countdown of auctions
    $(".countdown").each(function(){
        var endTime = new Date(parseInt($(this).metadata().endTime));
        $(this).countdown({
            until: endTime,
            onExpiry: countdownFinished,
            onTick: countdownLastHour,
            layout: langIn + ' {hnn}{sep}{mnn}{sep}{snn}'
        });
    });	
	
});

