;(function($) {
    defaults  = {
        width:640,
        height:236,
        index:0,
        time:4000,
        title:false,
        titleshow:false,
        panel:false,
        play:true,
        loop:true,
        effect:'fade',
        effecttime:2000,
        filter:true,
        nextclick:false,
        playclick:false,
        playhover:false,
        playhoverr:false,
        playframe:false,
        fullscreen:false,
        imgresize:false,
        imgcenter:true,
        imgajax:true,
        linkajax:false,        
        help:'',

        controls :{
            'hide':true, 
            'first':true,
            'prev':true,
            'play':true,
            'next':true,
            'last':true,
            'help':true,
            'counter':true
        }

    };    

    $.fn.slideshow = function(settings) {

        var _slideshow = this;

		this.each(function(){
		    
            var ext = $(this);
            
            this.playFlag = false;
            this.playId   = null;
            this.length   = 0;
            this.inited   = new Array();

            this.build    = function () {
                var _self = this;
                
                ext.wrapInner('<div class="slideshow"><div class="slideshow-content"></div></div>');
                ext = ext.find('.slideshow');
                
                if (this.options.filter) {
                    ext.find('.slideshow-content > br').remove();
                    ext.find('.slideshow-content > p:empty').remove();
                    ext.find('.slideshow-content > div:empty').remove();                    
                }
                

                
                this.length = ext.find('.slideshow-content > *').length;

                ext.css('width',    this.options.width + 'px');

                ext.find('.slideshow-content').css('width',  this.options.width);
                ext.find('.slideshow-content').css('height', this.options.height);

                ext.find('.slideshow-content > *').each(function(){
                    _self._build($(this));
                });
                
                this.init(this.options.index);
                
                ext.find('.slideshow-content > *:not(:eq('+this.options.index+'))').hide();
                
                this.label();
                
                if (this.options.playframe) {
                    ext.find('.slideshow-content').append('<div class="slideshow-shadow slideshow-opacity"><div class="slideshow-frame"></div></div>');
                }
                
                this.events();
                
                return true;
            };

            this._build = function(el){            
                el.css({margin   :0,
                            position :'absolute',
                            display  :'block',
                            overflow:'hidden'
                            });
                
                if (el.is('img') && this.options.imgresize || el.is(':not(img)')){
                    el.css({width:'100%',height:'100%'});
                } 
            };

            this.events = function() {

                if (this.options.playframe) 
                ext.find('.slideshow-frame').click(function(){
                    ext.find('.slideshow-frame').remove();
                    ext.find('.slideshow-shadow').remove();
                    
                    if (_self.options.playclick)
                        setTimeout(function(ms){ _self.play() }, _self.options.time);
                    return false;  
                });


            };

            this.label = function () {
                if (!this.options.title) return false;
                
                label = '';
                
                current = ext.find('.slideshow-content > *:eq('+this.options.index +')');
                
                if (current.attr('alt')) {
                    label = current.attr('alt');
                } else if (current.attr('title')) {
                    label = current.attr('title');
                }else if (current.find('label:first').length>0) {
                            current.find('label:first').hide();
                    label = current.find('label:first').html();
                }
                
                ext.find('.slideshow-label').html(label);
            };

            this.play = function () {
                var _self = this;     
                this.playFlag = true;
                this.playId = setTimeout(function(ms){ _self._play() }, this.options.time);
                ext.find('a.play').addClass('stop');
            };

            this._play = function () {  
                var _self = this;     
                this.next();
                if (this.playFlag) {
                    if (this.options.index == (this.length-1) && !this.options.loop) { this.stop();return false; }
                    this.playId = setTimeout(function(ms){ _self._play() }, this.options.time);
                }    
            };

            this.next = function () {
                if (this.options.index == (this.length-1)) {
                    i = 0;
                } else {
                    i = this.options.index + 1;
                }            
                this.goSlide(i);
            };

            this.init = function (index) {
            
                for (var i = 0, loopCnt = this.inited.length; i < loopCnt; i++) {
                    if (this.inited[i] === index) {
                        return true;
                    }
                }
                
                this.inited.push(index);
                
                slide = ext.find('.slideshow-content > *:eq('+index+')');
                
                var _self = this; 

                if (slide.get(0).tagName == 'A') {
                    var href   = slide.attr('href');
                    
                    var title  = slide.attr('title');
                        title  = title.replace(/\"/i,'\'');
                        
                    var domain = document.domain;
                        domain = domain.replace(/\./i,"\.");
                    
                    var reimage = new RegExp("\.(png|gif|jpg|jpeg|svg)$", "i");
                    var relocal = new RegExp("^((https?:\/\/"+domain+")|(?!http:\/\/))", "i");
                    
                    
                    if (this.options.imgajax && reimage.test(href)) {
                        slide.replaceWith('<img src="'+href+'" alt="'+title+'"/>');                        
                    } else if (this.options.linkajax && relocal.test(href)) {
                        $.get(href, function(data){
                            slide.replaceWith('<div><label>'+title+'</label>'+data+'</div>');
                        });
                    } else { // nothing else
//                            slide.wrap('<p></p>');
                    }
                    
                    slide = ext.find('.slideshow-content > *:eq('+index+')');
                    
                    this._build(slide);
                }

                if (this.options.playclick)
                $(slide).click(function(){
                    if (_self.playFlag) {
                        _self.stop();
                    } else {
                        _self.play();
                    }
                    return false;
                });
            };

            this.goSlide = function (n) {
                
                if (this.options.index == n) return;
                
                this.init(n);
                
                var next = ext.find('.slideshow-content > *:eq('+n+')');
                var prev = ext.find('.slideshow-content > *:eq('+this.options.index+')');
                
                prev.css({zIndex:0});
                next.css({zIndex:1, top: 0, left: 0, opacity: 1, width: this.options.width, height: this.options.height});
                
                this.options.index = n;
                
                if (this.options.effect == 'random' ) {
                    var r = Math.random();
                          r = Math.floor(r*12);
                } else {
                      r = -1;
                }
                // effect between slides
                switch (true) {
                    case (this.options.effect == 'fade' || r == 10):
                    default:
                        prev.css({zIndex:0, opacity: 1});
                        next.css({zIndex:1, opacity: 0});
                        
                        prevAni = {opacity: 0};
                        break;
                }
                
                var _self = this;
                
                prev.animate(prevAni,this.options.effecttime);
                
                // play next slide animation, hide prev slide, update label, update counter
                next.show().animate({top: 0, left: 0,opacity: 1, width: this.options.width, height: this.options.height}, this.options.effecttime, function () { prev.hide(); _self.label(); _self.counter(); });
            };

            this.counter = function () {
                if (this.options.controls.counter)
                    ext.find('.slideshow-panel span.counter').html((this.options.index+1) + ' / ' + this.length);
                
            };
    		
    		this.options = $.extend({}, defaults, settings);
    		
    		if (typeof(settings) != 'undefined') {
        		if (typeof(settings.controls) != 'undefined')
        		   this.options.controls = $.extend({}, defaults.controls,  settings.controls);
    		}

            this.build();
            
            //Show slideshow
            ext.show();
            
            //Check play option
            if (this.options.play) {
                this.play();
            }
                
            return ext;
		});
		
		return this;
    }
})(jQuery);