(function($) {
$.fn.getHiddenDimensions = function(includeMargin) {
    var $item = this,
        props = { position: 'absolute', visibility: 'hidden', display: 'block' },
        dim = { width:0, height:0, innerWidth: 0, innerHeight: 0,outerWidth: 0,outerHeight: 0 },
        $hiddenParents = $item.parents().andSelf().not(':visible'),
        includeMargin = (includeMargin == null)? false : includeMargin;

    var oldProps = [];
    $hiddenParents.each(function() {
        var old = {};

        for ( var name in props ) {
            old[ name ] = this.style[ name ];
            this.style[ name ] = props[ name ];
        }

        oldProps.push(old);
    });

    dim.width = $item.width();
    dim.outerWidth = $item.outerWidth(includeMargin);
    dim.innerWidth = $item.innerWidth();
    dim.height = $item.height();
    dim.innerHeight = $item.innerHeight();
    dim.outerHeight = $item.outerHeight(includeMargin);
    dim.offset = $item.offset();

    $hiddenParents.each(function(i) {
        var old = oldProps[i];
        for ( var name in props ) {
            this.style[ name ] = old[ name ];
        }
    });

    return dim;
}
}(jQuery));

(function($){
    function debug(mixed)
    {
        if(window.console&&window.console.debug)window.console.debug(mixed);
    }
	
    function log(string)
    {
        if(window.console&&window.console.log)window.console.log(string);
    }
	
    $.fn.cpGallery = function(opts)
    {
        return this.each(function() { 
            new cpGallery(this, $.extend({},cpGallery.fn.defOpts, opts)); 
        }
        );
    }
	
    var cpGallery = function(el,opts)
    {
        this.id=this.uid();
        var t=window[this.id]=this;
        this.$el= $(el);
        this.opts = opts;
        this.init();
    }
	
    cpGallery.prototype = cpGallery.fn = {
        name: 'cpGallery',
        version: 0.1,
        id:0,
        opts: {},
        markers: [],
        uid:function()
        {
            return this.name+(new Date().getTime())+''+(Math.round(Math.random()*1000));
        },
        init:function()
        {
            var data = this.data = new Array();
            this.$el.children('li').each(function(){
                var tmpObj = {};
                var t = $(this);
                tmpObj.categories = t.attr('rel').split(',');
                var img = t.children('img');
                tmpObj.img = {
                    src: img.attr('src'), 
                    title:img.attr('title')
                    };				
                tmpObj.links = [];
                t.children('a').each(function(){
                    var link = {};
                    var ta=$(this);
                    link.title = ta.attr('title');
                    link.coords = ta.attr('rel').split(',');
                    link.url = ta.attr('href');
                    tmpObj.links.push(link);
                });
                tmpObj.description = t.children('p:first').html();
                data.push(tmpObj);
            });
            var holder = this.holder = $('<div/>',{
                'class':this.opts.classMain,
                css:{
                    position:'relative'
                }
            }).insertBefore(this.$el);
        this.$el.remove();
        this.build();
    },
    setLoading:function(a){
        this.mHolder.css({
            'background-image': (a?'url(\''+this.opts.loadIcon+'\')':''),
            'background-repeat': 'no-repeat',
            'background-position': 'center'
        });
    },
    build:function()
    {
        var t=this;
        if(!t.data.length)return;
			
        var mHolder = t.mHolder = $('<div/>',{
            css:{
                position:'relative',
                width:t.opts.itemWidth+'px',
                height:t.opts.itemHeight+'px'
                }
            });
    var tHolder = t.tHolder = $('<div/>',{
        css:{
            position:'absolute',
            top:0,
            left:0,
            width:(t.data.length*t.opts.thumbnailWidth)+'px'
            }
        });
        
var tHolderMask = t.tHolderMask = $('<div/>',{
    css:{
        position:'relative',
        width:t.opts.itemWidth+'px',
        height:t.opts.thumbnailHeight+'px',
        overflow:'hidden'
    }
})

t.setLoading(true);
			
    t.itemsLoaded = 0;
			
    for(var i=0;i<t.data.length; ++i)
    {
        var itemId = this.id+'_img'+i;
        t.data[i].id = itemId;
        t.data[i].index = i;
        t.data[i].loaded = false;
        mHolder.append(t.makeMainItem(t.data[i]));
        tHolder.append(t.makeThumbnail(t.data[i]));
    }
			
    mHolder.children('div').hide();
    tHolderMask.append(tHolder.append($('<div/>',{
        css:{
            'clear':'both'
        }
    })));
			
if(t.opts.scrollbarOnTop)
{
    t.holder.append(tHolderMask).append(mHolder);
}else{
    t.holder.append(mHolder).append(tHolderMask);
}

if(tHolder.outerWidth(true)>tHolderMask.width()) {
    t.enableScrolling(false);
} else if(tHolder.getHiddenDimensions(true).outerWidth > tHolderMask.getHiddenDimensions().width) {
    t.enableScrolling(true);
}

debug(t);
			
if(t.opts.categories.length)t.sidebar();
t.load();
},
sidebar:function()
{
    var t=this;
    var sidebar = $('<div/>',{
        'class':t.opts.classSidebar,
        css:{
            position:'absolute',
            'z-index':2000,
            top:0,
            left:0
        }
    });
var sidebarContent = t.sidebarContent = $('<div/>',{
    'class':t.opts.classSidebarItems
    }).appendTo(sidebar);
var first = true;
for(var c=0;c<t.opts.categories.length;++c)
{
    sidebarContent.append(link = $('<a/>',{
        'href':'javascript:void(0)',
        'rel':t.opts.categories[c].id
        }).click(function(){
        sidebarContent.children('a').removeClass('active');
        t.setCategory($(this).addClass('active').attr('rel'));
    }).html(t.opts.categories[c].title));
    if(first)link.addClass('active');
    first = false;
}
			
var expander = $('<a/>',{
    href:'javascript:void(0);',
    'class':t.opts.classSidebarExpander
    }).click(function(){
    sidebarContent.animate({
        width:'toggle'
    },300,'easeOutExpo');
    var img = $(this).children('img:first');
    img.attr('src',((img.attr('src')==t.opts.sidebarIconOpen)?t.opts.sidebarIconClose:t.opts.sidebarIconOpen));
});
			
expander.append($('<img/>',{
    src:t.opts.sidebarIconClose
    })).append($('<div/>',{
    css:{
        clear:'both'
    }
}));
            			
t.holder.append(sidebar.append(expander));
//sidebarContent.animate({width:'toggle'},0);
},
setCategory:function(cat,img)
{
			
    if(cat === '' || cat === null)return;
    var t=this;
    if(t.currentCat == cat)return;
    t.currentCat = cat;
			
    t.setLoading(true);
						
    var first = (img!==undefined&&img>-1)?img:-1;
    t.numTotal = 0;
			
    t.tHolder.stop().animate({
        opacity:0
    },200,'easeInExpo',function(){
				
        for(var i=0;i<t.data.length;++i){
            var inCat = false;
            if(t.data[i].categories.length)
            {
                for(var j=0;j<t.data[i].categories.length;++j){
							
                    if(t.data[i].categories[j]==cat){
                        inCat=true;
                        break;
                    }
                }
            }
            if(inCat)
            {
					   
                if(first===-1)first=i;
                $('#'+t.data[i].id+'_thumb').stop().show();
                ++t.numTotal;
            }else{
                $('#'+t.data[i].id+'_thumb').stop().hide();
            }
        }				
        t.tHolder.animate({
            opacity:1
        },200,'easeOutExpo',function()

        {
            t.updateScrolling();
            t.setLoading(false);
            if(first>-1)
                t.switchImage(first);
					
					
					
        });
    });
			
			
			
},
updateScrolling:function(){
    var t=this;
    t.maxX = (t.numTotal*t.opts.thumbnailWidth)-t.w;
    if(t.maxX<0)
    {
        t.isScrolling=false;
        t.tHolder.css('left','0px');
    }else{
        t.isScrolling=true;
    }
},
enableScrolling:function(useHidden){
			
    var t=this;
    t.isScrolling = true;
    
    if(useHidden == false) {
        var offset = t.tHolderMask.offset();
        var outerWidth = t.tHolder.outerWidth(true);
        var width = t.tHolderMask.width();
    } else {
        var offset = t.tHolderMask.getHiddenDimensions().offset;
        var outerWidth = t.tHolder.getHiddenDimensions(true).outerWidth;
        var width = t.tHolderMask.getHiddenDimensions().width;
    }

    
    var mouseX = 0;
    var newX = 0;
    t.w = width;
    t.maxX = outerWidth-t.w;
				
    t.tHolderMask.mousemove(function(e){
        mouseX = e.pageX-(t.opts.thumbnailWidth/2)-offset.left;
    });
			
    function scrollInterval(){
        if(!t.isScrolling)return;
        var mx = mouseX/(t.w-t.opts.thumbnailWidth);
        if(mx<0)mx=0;
        if(mx>1)mx=1;
        newX += ((t.maxX*mx)-newX)/40;
        t.tHolder.css('left',(-newX)+'px');
    }
        
    var int=setInterval(scrollInterval,40);
},
load:function(){
    var t=this;
    t.setLoading(false);
			
    var startCat = (t.opts.categories.length)?t.opts.categories[0].id:null;
    var startImg = 0;
    if(t.opts.startPos)
    {
        var posArr = t.opts.startPos.split(',');
        startCat = parseInt(posArr[0]);
        startImg = parseInt(posArr[1]);
    }
			
    t.activeItem =$('#'+t.data[startImg].id).show();
    $('#'+t.data[startImg].id+'_thumb').stop().animate({
        opacity:t.opts.thumbOpacityActive
        },0);
    t.activeIndex = startImg;
			
    if(t.opts.categories.length)
    {
        t.setCategory(startCat,t.activeIndex);
        if(t.sidebarContent)
        {
            t.sidebarContent.children('a').removeClass('active');
            t.sidebarContent.children('a[rel="'+startCat+'"]').addClass('active');
        }
    }
			
},
switchImage:function(index)
{
    var t=this;
    if(index == t.activeIndex )return;
			
    if(index>=t.data.length)t.activeIndex = 0;
    else if(index<0)t.activeIndex = t.data.length-1;
    else t.activeIndex = index;
			
    if(t.activeItem)
    {
        $('#'+t.activeItem.attr('id')+'_thumb').stop().animate({
            opacity:t.opts.thumbOpacityNormal
            },t.opts.animation.thumbnailDurationOut,t.opts.animation.thumbnailEaseOut);
        t.activeItem.stop().animate({
            opacity:0
        },t.opts.animation.durationOut,t.opts.animation.easeOut,function(){
            t.activeItem.hide();
            t.activeItem = $('#'+t.data[t.activeIndex].id).stop().css({
                'display':'block',
                'opacity':0
            }).animate({
                opacity:1
            },t.opts.animation.durationIn,t.opts.animation.easeIn);
            $('#'+t.activeItem.attr('id')+'_thumb').stop().animate({
                opacity:t.opts.thumbOpacityActive
                },t.opts.animation.thumbnailDurationIn,t.opts.animation.thumbnailEaseIn);
        });
    }else{
        t.activeItem = $('#'+t.data[t.activeIndex].id).stop().css({
            'display':'block',
            'opacity':0
        }).animate({
            opacity:1
        },t.opts.animation.durationIn,t.opts.animation.easeIn);
        $('#'+t.activeItem.attr('id')+'_thumb').stop().animate({
            opacity:t.opts.thumbOpacityActive
            },t.opts.animation.thumbnailDurationIn,t.opts.animation.thumbnailEaseIn);
    }
},
makeMainItem:function(data)
{
    var t=this;
    var item = $('<div/>',{
        'id':data.id,
        css: {
            width:t.opts.itemWidth+'px',
            height:t.opts.itemHeight+'px',
            position:'absolute',
            top:'0',
            left:'0'
        }
    });
			
var img = $('<img />',{
    rel: data.index,
    css: {
        'position' : 'absolute',
        'top':'0',
        'left':'0'
    }
}).load(function(){
    t.data[$(this).attr('rel')].loaded = true;
    ++t.itemsLoaded;
    if(t.itemsLoaded >= t.data.length){
// t.load();
}
}).attr('src',data.img.src).appendTo($('<div/>',{
    css:{
        overflow:'hidden',
        width:t.opts.itemWidth+'px',
        height:t.opts.itemHeight+'px',
        position:'absolute',
        top:'0',
        left:'0'
    }
}).appendTo(item));
		
if(data.links.length){
    var linkHolder = $('<div/>',{
        css:{
            position: 'absolute',
            width:t.opts.itemWidth+'px',
            height:t.opts.itemHeight+'px',
            left:0,
            top:0
        }
    });
t.makeImageLinks(linkHolder,data.links);
item.append(linkHolder);
}
			
return item;
},
makeThumbnail:function(data)
{
    var t=this;
    var item = $('<div/>',{
        id:data.id+'_thumb',
        css:{
            opacity:t.opts.thumbOpacityNormal, 
            float:'left',
            cursor:'Pointer',
            width:t.opts.thumbnailWidth+'px',
            height:t.opts.thumbnailHeight+'px',
            overflow:'hidden'
        }
    });
var img = $('<img/>',{
    rel:data.index,
    /*src:data.img.src,*/
    src:"fileadmin/php/cp_imageresize.php?img=" + data.img.src + "&size=1",
    css:{
        width:t.opts.thumbnailWidth+'px',
        height:t.opts.thumbnailHeight+'px'
    }
} ).click(function(){
    t.switchImage($(this).attr('rel'));
}).appendTo(item).hover(function(){
    var target = $(this).parent('div');
    target.stop().css({
        opacity:t.opts.thumbOpacityActive
        });
},function(){
    var target = $(this).parent('div');
    if(!t.activeItem||t.activeItem.attr('id')+'_thumb'!=target.attr('id'))
        $(this).parent('div').stop().css({
            opacity:t.opts.thumbOpacityNormal
            });
});		
return item;
},
makeImageLinks:function(target,links)
{
    if(this.opts.linkIconNormal == '') {
        return;
    }
    var t=this;
    for(var i=0;i<links.length;++i)
    {
        var link = $('<a />',{
            href: 'javascript:void(0);',
            rel: links[i].url,
            css:{
                'display':'block',
                'position':'absolute',
                'z-index':'1000',
                'left':links[i].coords[0]+'px',
                'top':links[i].coords[1]+'px'
                }
        })
        link.bind('click',function(){
            t.dispatchLink($(this).attr('rel'));
        });
        link.append($('<img/>',{
            css:{
                border:0,
                width:'46px',
                height:'46px'
            },
            src:this.opts.linkIconNormal
            }));
        if(links[i].title){
            link.append($('<img/>',{
                css:{
                    border:0,
                    display:'block',
                    position:'relative',
                    'z-index':'1000'
                },
                src:links[i].title
                }).hide());
            link.hover(
                function(){
                    $(this).children('img:first').hide();
                    $(this).children('img:last').show();
                },
                function(){
                    $(this).children('img:first').show();
                    $(this).children('img:last').hide();
                });
        }
        target.append(link);
    }
},
dispatchLink:function(url)
{
    var appendix = '';
    if(this.opts.usePosParam)
        appendix += this.opts.posParam.split('|').join(this.currentCat+','+this.activeIndex);
    location.href=url+appendix;
				
}
		
};
	
cpGallery.fn.defOpts = {
    itemWidth: 718,
    itemHeight: 400,
    thumbnailWidth: 160,
    thumbnailHeight: 90,
    scrollbarOnTop:false,
    linkIconNormal: 'img/interaktiver_button_normal.png',
    loadIcon: 'img/loadinfo.net.gif',
    sidebarIconClose: 'img/navipoint_more_ani.gif',
    sidebarIconOpen: 'img/navipoint_more_ani.gif',
    slideShowInterval:2000,
    animation:{
        easeIn: 'easeOutExpo',
        easeOut:'easeInExpo',
        durationIn: 500,
        durationOut: 300,
        thumbnailEaseIn: 'easeOutQuart',
        thumbnailEaseOut:'easeOutQuart',
        thumbnailDurationIn: 200,
        thumbnailDurationOut: 150
    },
    thumbOpacityNormal:.5,
    thumbOpacityActive:1,
    categories:[],
    classSidebar: 'sidebar',
    classSidebarItems: 'items',
    classSidebarExpander: 'expand',
    classMain: 'cpGallery',
    usePosParam: true,
    posParam: '?tx_cptabs_pi1[backPid]=0&tx_cptabs_pi1[backparams]=|',
    startPos: ''
};
})(jQuery);
