(function($){
    $.fn.PortfolioSlide = function(options) {
        var dataarray;
        var position=0;
        var btnNaprej=null,btnNazaj=null,btnZapri=null;
        var animation=false;
        var mode=0;
        var thumbPositioning=new Array();
        var loadingIcon=null;
        var animations={
            "anim": [

            {
                "height": "0%",
                "opacity": "30"
            },

            {
                "width": "0%",
                "opacity": "100"
            },

            {
                "opacity": "0"
            },

            {
                "height": "0%",
                "width": "0%"
            }
            ]
        };
        var defaults = {
            pid:null,
            datasource: "",
            table:"",
            action:"",
            animation:'random',
            slices:5,
            animSpeed:1200,
            timeBetwenSlides:5000,
            /*thumb*/
            keyboardNav:true,
            showInfoBig:true,
            showInfoContainer:"#footer",
            lan:"slo",
            loadingIcon:'images/spinner.gif',
            container:'pHolder',
            containerCSS:'pHolder',
            left_padding:250
        };
        var private_vars={
            dataarray:null,
            numAll:null,
            parentObj:null,
            loadingIcon:null,
            containerObj:null
        }

        var options = $.extend(defaults, options);
        function init(data){
            private_vars.dataarray=data["images"];
            
            if( $(options.showInfoContainer).length>0){
                $(options.showInfoContainer).hide();
            }
            private_vars.numAll=private_vars.dataarray.length;

            imloading(true,private_vars.parentObj);
           
            $.imgpreload(private_vars.dataarray[position].src,function()
            {
                imloading(false,private_vars.parentObj);
                show(position);
                if(options.showInfoBig){
                    if(private_vars.dataarray[position].title.length>0){
                        $(options.showInfoContainer).show();
                        $("#portfolio_title").show();
                        $("#portfolio_title").html(private_vars.dataarray[position].title);
                    }else{
                        $(options.showInfoContainer).hide();
                        $("#portfolio_title").hide();
                    }

                }
            //animateImage();
            });

        }
       
        
        function showObject(object,show){
            if(object && show==true){
                object.show();
            }else if(object && show==false){
                object.hide();
            }
        }


        function animateImage(){
            private_vars.containerObj.css("visibility", "visible");
            private_vars.containerObj.fadeIn(1000);

        }
        //Keyboard Navigation

        if(options.keyboardNav){
            $(document).keydown(function(event){

                if(mode==1){
                    //Left
                    if(event.keyCode == '37' && btnNazaj.is(":visible")){
                        if(!animation){
                            animation=true;
                            var prevp=Number(position)-1;
                            imloading(true,private_vars.containerObj);
                            $.imgpreload(private_vars.dataarray[prevp].src,function()
                            {
                                imloading(false,private_vars.containerObj);
                                animateSlider(false);
                            });
                        }
                    }
                    //Right
                    if(event.keyCode == '39' && btnNaprej.is(":visible")){
                        if(!animation){
                            animation=true;
                            var nextp=Number(position)+1;
                            imloading(true,private_vars.containerObj);
                            $.imgpreload(private_vars.dataarray[nextp].src,function()
                            {
                                imloading(false,private_vars.containerObj);
                                animateSlider(true);
                            });
                        }
                    }
                    if(event.keyCode == '27' && btnZapri.is(":visible")){
                        hideBigPresentation();

                    }
                }else{
                    //Left
                    if(event.keyCode == '37' && btnNazaj.is(":visible")){
                        if(!animation){
                            position_thumb--;
                            showThumbs();
                        }
                    }
                    //Right
                    if(event.keyCode == '39' && btnNaprej.is(":visible")){
                        if(!animation){
                            position_thumb++;
                            //alert(position_thumb);
                            showThumbs();
                        }
                    }
                }

            });
        }
        $(document).focus();
        function hideBigPresentation(){
            if(!animation){
                showBackground(false);
                btnZapri.unbind();
                btnNazaj.unbind();
                btnNaprej.unbind();
                showObject(btnNazaj,false);
                showObject(btnNaprej,false);
                showObject(btnZapri,false);
                mode=0;
                private_vars.containerObj.fadeOut(100,function(){
                    // thumbPositioning
                    var arg_num=null;
                    var arg_k=0;
                    // alert(thumbPositioning.length);
                    for(var j=0;j<thumbPositioning.length;j++){
                        arg_k+=thumbPositioning[j].num;
                        if((arg_k>(position)) && arg_num==null){
                            arg_num=j;
                        }
                    }
                    // alert(arg_num);
                    position_thumb=arg_num;
                    if(mode==0){
                        $(options.showInfoContainer).hide();
                    }
                    showThumbs();
                });

            }
        }
        function imloading(show,containerObj){
            if(private_vars.loadingIcon){
                if(show){
                    private_vars.loadingIcon.show();
                    loadingIcon.position({
                        "my": "center",
                        "at": "center",
                        "of": private_vars.containerObj
                    });
                }else{
                    private_vars.loadingIcon.hide();
                }
            }
        }

        function show(id){
           
            private_vars.containerObj.empty();
            private_vars.containerObj.css('background-image','url("'+ private_vars.dataarray[id].src +'")');
            private_vars.containerObj.css('width',private_vars.dataarray[id].width +'px');
            private_vars.containerObj.css('height',private_vars.dataarray[id].height +'px');
            animateImage();
            createSlices();
        }
       
        function animateSlider(next){
            animation=true;
            var newposition;
            if(next==true && (position < private_vars.numAll-1)){
                newposition=Number(position)+1;
            }else{
                newposition=Number(0);
            }
           
            position=newposition;

            private_vars.containerObj.css('background-image','url("'+ private_vars.dataarray[newposition].src +'")');
           
            var j=0;
            var timeBuff = 0;
            // $('.slice', private_vars.containerObj)._reverse();
            var slicesa = $('.slice', private_vars.containerObj);
            if(newposition%2==0)var slicesa = $('.slice', private_vars.containerObj)._reverse();
            var animid=Math.floor(Math.random()*animations.anim.length);
            slicesa.each(function(){
                var slice=$(this);
                if(j == options.slices-1){
                    setTimeout(function(){
                        slice.animate(
                            animations.anim[animid], options.animSpeed, '', function(){
                                $('.slice').remove();
                                createSlices();
                                animation=false;

                            });
                    }, (100 + timeBuff));
                } else {
                    setTimeout(function(){
                        slice.animate(animations.anim[animid], options.animSpeed);
                    }, (100 + timeBuff));
                }
                timeBuff += 50;
                j++;
            });
            if(options.showInfoBig){
                if(private_vars.dataarray[position].title.length>0){
                    $(options.showInfoContainer).show();
                    $("#portfolio_title").show();
                    $("#portfolio_title").html(private_vars.dataarray[position].title);
                }else{
                    $(options.showInfoContainer).hide();
                    $("#portfolio_title").hide();
                }

            }
        }
        function createSlices(){
            for(var i = 0; i < options.slices; i++){
                var sliceWidth = Math.round(private_vars.containerObj.width()/options.slices);
                if(i == options.slices-1){
                    private_vars.containerObj.append(
                        $('<div class="slice"></div>').css({
                            left:(options.left_padding+(sliceWidth*i))+'px',
                            width:(private_vars.containerObj.width()-(sliceWidth*i))+'px'
                        })
                        );
                } else {
                    private_vars.containerObj.append(
                        $('<div class="slice"></div>').css({
                            left:options.left_padding+(sliceWidth*i)+'px',
                            width:sliceWidth+'px'
                        })
                        );
                }
            }
            var j=0;
            $('.slice', private_vars.containerObj).each(function(){

                var sliceWidth = Math.round(private_vars.containerObj.width()/options.slices);
                var offset=((sliceWidth + (j * sliceWidth)) - sliceWidth);
                //alert(offset);
                $(this).css({
                    height:private_vars.dataarray[position].height,
                    opacity:'1.0',
                    background: 'url("'+ private_vars.dataarray[position].src +'") no-repeat -'+ offset +'px 0%'
                });

                j++;
            });

            setTimeout ( function(){
                animateSlider(true);
            }, options.timeBetwenSlides );

        }
        return this.each(function() {
            /*loadingIcon=$("<div id='loading' class='loading' />").appendTo("body");
            $("<img alt='loading...' title='loading...' />").attr("src", options.loadingIcon).appendTo(loadingIcon);
            loadingIcon.hide();*/
            private_vars.containerObj = $("<div id='"+options.container+"' class='"+options.containerCSS+"' />").appendTo($(this));
            private_vars.containerObj.fadeOut(100);
            private_vars.containerObj.css("visibility", "hidden");
            private_vars.containerObj.css("cursor", "pointer");
            $("#portfolio_title").css("cursor", "pointer");
            $(options.showInfoContainer).css("cursor", "pointer");
            $("#portfolio_title").css("z-index", "53");
            private_vars.containerObj.click(function(){
                window.location = "?module=21&id="+private_vars.dataarray[position].id;
            });
            $("#portfolio_title,"+options.showInfoContainer).click(function(){
                window.location = "?module=21&id="+private_vars.dataarray[position].id;
            });
            
            private_vars.parentObj=$(this);
            $.ajax({
                url: options.datasource,
                type: "POST",
                cache:false,
                dataType:"json",
                data: (
                {
                    table:options.table,
                    pid:options.pid,
                    action:options.action,
                    lan:options.lan
                }),
                async: false,
                success: function(data) {
                   
                    setTimeout(function() {
                        init(data);
                    }, 100);
                },
                error:function(request,error) {
                    alert(request.responseText);
                }
            });
        });


    };
    $.fn._reverse = [].reverse;
})(jQuery);
