// This is a heavily modified version of the jqFancyTransitions script created by Ivan Lazarevic, credits go to him.
// see more info for the original script at http://www.workshop.rs/projects/jqfancytransitions

// Changes from the original script
// - performs a single transition on one IMG element, instead of working on a list of images
// - moved all variables to private section instead of public
// - has a callback function when the transition completes
// - added a random effect

(function($) {

    $.fn.CurtainsTransition = function(settings, onCompleteFunc) {
        var opts = new Array;
        var level = new Array;
        var img = new Array;
        var titles = new Array;
        var order = new Array;
        var imgInc = new Array;
        var inc = new Array;
        var stripInt = new Array;
        var imgInt = new Array;
        var imgWidth = 0;
        var imgHeight = 0;

        // default values
        var config = {
            //width: 640, // width of panel
            //height: 360, // height of panel
            strips: 20, // number of strips
            delay: 0, // delay between images in ms
            stripDelay: 50, // delay beetwen strips in ms
            titleOpacity: 0.7, // opacity of title
            titleSpeed: 1000, // speed of title appereance in ms
            position: 'curtain', // top, bottom, alternate, curtain
            direction: 'fountainAlternate', // left, right, alternate, random, fountain, fountainAlternate
            effect: '' // curtain, zipper, wave		
        };

        if (settings) $.extend(config, settings);

        init = function(el) {
            opts[el.id] = config;
            img[el.id] = new Array(); // images array
            titles[el.id] = new Array(); // titles array
            order[el.id] = new Array(); // strips order array
            imgInc[el.id] = 0;
            inc[el.id] = 0;

            //set up bars
            params = opts[el.id];

            if (params.effect == 'zipper') { params.direction = 'alternate'; params.position = 'alternate'; }
            if (params.effect == 'wave') { params.direction = 'alternate'; params.position = 'top'; }
            if (params.effect == 'curtain') { params.direction = 'alternate'; params.position = 'curtain'; }
            if (params.effect == 'random') {
                //choose random direction and position
                var pos = Math.floor(Math.random() * 4);

                switch (pos) {
                    case 0:
                        params.position = 'top';
                        break;
                    case 1:
                        params.position = 'bottom';
                        break;
                    case 2:
                        params.position = 'alternate';
                        break;
                    case 3:
                        params.position = 'curtain';
                        break;
                }

                var dir = Math.floor(Math.random() * 6);
                switch (dir) {
                    case 0:
                        params.direction = 'left';
                        break;
                    case 1:
                        params.direction = 'right';
                        break;
                    case 2:
                        params.direction = 'alternate';
                        break;
                    case 3:
                        params.direction = 'random';
                        break;
                    case 4:
                        params.direction = 'fountain';
                        break;
                    case 5:
                        params.direction = 'fountainAlternate';
                        break;
                }
            }


            // create images and titles arrays
            img[el.id][0] = $(el).attr('src');
            imgWidth = $(el).attr('width');
            imgHeight = $(el).attr('height');
            $(el).hide();

            // width of strips
            stripWidth = parseInt(imgWidth / params.strips);
            gap = imgWidth - stripWidth * params.strips; // number of pixels
            stripLeft = 0;

            $("#" + el.id).replaceWith('<div id="' + el.id + '" style="position: relative; top: 0px; left: 0px;"></div>');
            $("#" + el.id).css({ 'width': imgWidth, 'height': imgHeight });
            odd = 1;
            // creating bars
            // and set their position
            for (j = 1; j < params.strips + 1; j++) {

                if (gap > 0) {
                    tstripWidth = stripWidth + 1;
                    gap--;
                } else {
                    tstripWidth = stripWidth;
                }

                $('#' + el.id).append("<div class='ft-" + el.id + "' id='ft-" + el.id + j + "' style='width:" + tstripWidth + "px; height:" + params.height + "px; float: left; position: absolute;'></div>");

                // positioning bars
                $("#ft-" + el.id + j).css({
                    'background-position': -stripLeft + 'px top',
                    'left': stripLeft
                });

                stripLeft += tstripWidth;

                if (params.position == 'bottom')
                    $("#ft-" + el.id + j).css('bottom', 0);

                if (j % 2 == 0 && params.position == 'alternate')
                    $("#ft-" + el.id + j).css('bottom', 0);

                // bars order
                // fountain
                if (params.direction == 'fountain' || params.direction == 'fountainAlternate') {
                    order[el.id][j - 1] = parseInt(params.strips / 2) - (parseInt(j / 2) * odd);
                    order[el.id][params.strips - 1] = params.strips; // fix for odd number of bars
                    odd *= -1;
                } else {
                    // linear
                    order[el.id][j - 1] = j;
                }

            }

            $('.ft-' + el.id).mouseover(function() {
                opts[el.id].pause = true;
            });

            $('.ft-' + el.id).mouseout(function() {
                opts[el.id].pause = false;
            });

            //clearTimeout(imgInt[el.id]);	
            imgInt[el.id] = setTimeout(function() { transition(el) }, params.delay + params.stripDelay * params.strips);



        }

        // transition
        function transition(el) {

            if (opts[el.id].pause == true) return;

            stripInt[el.id] = setInterval(function() { strips(order[el.id][inc[el.id]], el) }, opts[el.id].stripDelay);

            //$('#'+el.id).css({ 'background-image': 'url('+img[el.id][0]+')' });

            inc[el.id] = 0;

            if (opts[el.id].direction == 'random')
                fisherYates(order[el.id]);

            if ((opts[el.id].direction == 'right' && order[el.id][0] == 1)
				|| opts[el.id].direction == 'alternate'
				|| opts[el.id].direction == 'fountainAlternate')
                order[el.id].reverse();
        };


        // strips animations
        function strips(itemId, el) {

            temp = opts[el.id].strips;
            if (inc[el.id] == temp) {
                clearInterval(stripInt[el.id]);

                //delay by 1 sec
                if (typeof onCompleteFunc == 'function') {
                    setTimeout(function() { onCompleteFunc.call(this); }, 1000);
                }

                return;
            }

            if (opts[el.id].position == 'curtain') {
                currWidth = $('#ft-' + el.id + itemId).width();
                $('#ft-' + el.id + itemId).css({ width: 0, height: imgHeight, opacity: 0, 'background-image': 'url(' + img[el.id][0] + ')' });
                $('#ft-' + el.id + itemId).animate({ width: currWidth, opacity: 1 }, 1000);
            } else {
                $('#ft-' + el.id + itemId).css({ height: 0, opacity: 0, 'background-image': 'url(' + img[el.id][0] + ')' });
                $('#ft-' + el.id + itemId).animate({ height: imgHeight, opacity: 1 }, 1000);
            }

            inc[el.id]++;

        };

        // shuffle array function
        function fisherYates(arr) {
            var i = arr.length;
            if (i == 0) return false;
            while (--i) {
                var j = Math.floor(Math.random() * (i + 1));
                var tempi = arr[i];
                var tempj = arr[j];
                arr[i] = tempj;
                arr[j] = tempi;
            }
        }

        this.each(
			function() { init(this); }
		);

        // allow jQuery chaining 
        return this;


    };



})(jQuery);
