if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

var log = function() {
    console.log(arguments);
};

var compile = function(string, dict) {
    var string = unescape(string);
    for (var p in dict) {
        var re = new RegExp('\\${'+p+'}', 'g');
        string = string.replace(re, dict[p]);
    }
    return string;
};

var getCookie = function(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return false;        
};
var setCookie = function(c_name,value,expiredays,path) {
    if (!path) path="/";
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    var c = c_name+ "=" +value;
    if (expiredays != null) c+=";expires="+exdate.toGMTString();
    c+=";path="+path;
    document.cookie=c;
};

StartGallery = {
    STARTPAGE_ID : 28,
    COLORS : [
        //bcolor, tcolor
        ['#F5F7C8', '#D7DF23'], //gruengelb
        ['#FDF0E8', '#F37021'], //rot
        ['#D4F0F1', '#6FCDD0']  //blau
    ],
    IMAGEBASE : '/fileadmin/images/',
    IMAGES : [
        //img, text, colors
        ['bild1_gruen_zeitreise.jpg', 'Zeitreise?', 0],
        ['bild2_rot_muesli.jpg', 'Müsli?', 1],
        ['bild3_blau_reizwaesche.jpg', 'Reizwäsche?', 2],
        ['bild4_gruen_dingsda.jpg', 'Dingsda?', 0],
        ['bild5_rot_schallplatte.jpg', 'Schallplatte?', 1],
        ['bild6_blau_horizont.jpg', 'Horizont?', 2],
        ['bild7_blau_spurensuche.jpg', 'Spurensuche?', 2],
        ['bild8_rot_steinzeit.jpg', 'Steinzeit?', 1],
        ['bild9_blau_spareribs.jpg', 'Spareribs?', 2]
    ],
    DURATION : 8000,
    IMG_TRANSITION : 2500,
    TEXT_TRANSITION : 2500,
    _onSubPage : function() {
        var href = window.location.href;
        var idm = href.match(/id=(\d+)/);
        return idm && idm.length == 2 && idm[1] != this.STARTPAGE_ID;
    },
    _getImage : function(index) {
        index = typeof(index) == "number" ? index : Math.floor(Math.random()*this.IMAGES.length);
        var img = this.IMAGES[index];
        return {
            url : this.IMAGEBASE + img[0],
            text : img[1],
            color : this.COLORS[img[2]][0],
            tcolor : this.COLORS[img[2]][1],
            index : index
        };
    },
    items : [],
    imageData : null,
    imageIndex : null,
    allLoaded : false,
    interval : null,
    animatingToIndex : null,
    init : function(context) {
        this.context = context;
        this.head = context.children('.headElement');
        this.textElements = $('.headElementText', this.context);

        this.head.css('zIndex', 200);
        this.content = $('#inhaltContainer');
        this.loader = $('#loading');
        
        this.startup();
        this.applyActions();
    },
    
    startup : function() {
        //check if we are on the startpage
        if (this._onSubPage()) {
            //we are on a subpage
            var data = this.getSavedImage();
            if (!data) data = this._getImage();
        } else {
            //we are on the homepage
            var data = this._getImage();
        }
        this.addImage(data);
        this.showImage(data);
        
        //start animation on subpage
        if (!this._onSubPage()) {
            var self=this;
            this.interval = setInterval(function() {
                if (!self.allLoaded) return;
                self.next();
            }, this.DURATION);
        }
        
        return data;
    },
    addImage : function(data) {
        if (!this.items[data.index]) {
            console.log("add image: ", data.index, data);
            var self = this;
            var item = new StartGalleryItem(this, data);
            item.build(function() {
                //preload images as sequence
                if (!self._onSubPage()) {
                    var next = data.index + 1;
                    if (next >= self.IMAGES.length) next = 0;
                    self.addImage(self._getImage(next));
                }
            });
            this.items[data.index] = item;
        } else {
            this.onAllImagesLoaded();
        }
    },
    showImage : function(data) {
        this.imageData = data;
        this.imageIndex = data.index;
        this.items[data.index].show();

        this.head.css('color', data.tcolor);
        $('body').css('backgroundColor', data.color);
        this.animatingToIndex = null;
        Cufon.refresh();
    },
    onAllImagesLoaded : function() {
        this.allLoaded = true;
        this.loader.hide();
    },
    next : function() {
        this.crossFade(this.imageIndex + 1);
    },
    crossFade : function(toIndex) {
        if (toIndex >= this.IMAGES.length) toIndex = 0;
        this.items[this.imageIndex].fadeOut();
        var self=this;
        this.items[toIndex].fadeIn(function() {
            self.showImage(self._getImage(toIndex));
        });

        this.textElements.fadeOut(this.TEXT_TRANSITION);
        this.animatingToIndex = toIndex;
    },
    applyActions : function() {
        var self = this;
        this.context.bind('click', function() {
            clearInterval(self.interval);
            $('#weiss').hide();
            
            //manually story the image, in case a transition is running
            if (self.animatingToIndex) self.saveImage(self._getImage(self.animatingToIndex));
            else self.saveImage();

            self.loader.hide();
            self.context.animate({height: "117"}, "slow");
            $("#inhaltContainer").animate({opacity: "show"}, 'slow', function() {
                self.context.css('cursor', 'default');
            });
        });
    },
    getSavedImage : function() {
        var img = getCookie('vlmimage');
        if (img == false) return undefined;
        else return this._getImage(parseInt(img, 10));
    },
    saveImage : function(data) {
        var img = data || this.imageData;
        setCookie('vlmimage', img.index);
    }

};

StartGalleryItem = function(gallery, data) {
    this.data = data;
    this.gallery = gallery;
}

StartGalleryItem.prototype.build = function(cb) {
    this.cb = cb;
    this.createImage();
    $('IMG', this.image).bind('load', cb);
    this.hide();
}

StartGalleryItem.prototype.show = function() {
    this.image.show();
}
StartGalleryItem.prototype.hide = function() {
    this.image.hide();
}
StartGalleryItem.prototype.createImage = function() {
    if (this.image) this.image.remove();
    
    var template = '<div class="headElementText">';
    template +=        '<h1>Der See erz&auml;hlt ...</h1>';
    template +=        '${headtext}';
    template +=        '<h2>${alt}</h2>';
    template +=        '<img src="${src}" alt="${alt}"/>';
	template +=    '</div>'
    
    this.image = $(compile(template, {src : this.data.url,
                                      alt : this.data.text,
                                      headtext: $('.jsHeadtext').html() || ''}));

    this.image.css({'position' : 'absolute',
                    'zIndex'   : 0 });
    this.h1 = $('h1', this.image);
    this.h2 = $('h2', this.image);

    this.image.css('color', this.data.tcolor);
    this.h1.css('color', this.data.tcolor);
    this.h2.css('color', this.data.tcolor);
    this.gallery.context.children('.headElement').append(this.image);
    Cufon.refresh();
}
StartGalleryItem.prototype.fadeOut = function(cb) {
    this.image.fadeOut(StartGallery.IMG_TRANSITION, function() {
        $(this).css('zIndex', 0);
        if (cb) cb.call(this);
    });
    this.image.css('zIndex', 9);
}
StartGalleryItem.prototype.fadeIn = function(cb) {
    this.image.css('zIndex', 8);
    this.image.fadeIn(StartGallery.IMG_TRANSITION, cb);
}


$(function() {
    var hc = $("#headContainer");
    StartGallery.init(hc);
    setHeight();
    //setInterval(setHeight, 1000);
    
    //copy lightbox links and set target in ie6
    $('a[rel=lightbox]').each(function() {
        var node = $(this);
        if (node.children('img').length) {
            node.next().children('a.lightbox-enabled').attr('href', node.attr('href'));
        }
        
        if ($.browser.msie && $.browser.version == '6.0') {
            var href = node.attr('href');
            href = '/popup.php?image=' + href;
            var config = 'height=584,width=584,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no';
            //js = "javascript:window.open('"+href+"', 'popup', '"+config+"');";
            node.bind('click', function(event) {
                event.preventDefault();
                var imgpop = window.open(href, 'image', config);
                imgpop.focus();
            })
            node.attr('href', '#');
        }
        
    })
    
});

vSpacing = function(element) {
    var pt = parseInt(element.css('paddingTop'), 10) || 0;
    var pb = parseInt(element.css('paddingBottom'), 10) || 0;
    var mt = parseInt(element.css('martinTop'), 10) || 0;
    var mb = parseInt(element.css('martinBottom'), 10) || 0;
    return pt + pb + mt + mb;
}


//Höhe setzen
setHeight = function() {
	var element = $('#weiss');
	var offsettop = 638;

	var wh = $(window).height();
	var bh = $('body').height();

	var h = Math.max(wh, bh);
    var toHeight = h-offsettop;
    element.height(toHeight);
};