﻿/*
* FoundryShow - A jquery extension to make a scroll bar with snapping and go-to highlights.
*
* Copyright (c) 2011 Matthew Drake (w) The Foundry Agency
*
* Licensed under the MIT license:
*   http://www.opensource.org/licenses/mit-license.php
*
*
*/
if (!window.isNumber)
    window.isNumber = function (n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    };

if (!window.$functions)
    window.$functions = function (args) {
        var funcs = [];
        for (var i in args) {
            if ($.isFunction(args[i]))
                funcs.push(args[i]);
        }
        return funcs;
    };

if (!window.$numbers)
    window.$numbers = function (args) {
        var nums = [];
        for (var i in args) {
            if (isNumber(args[i]))
                nums.push(args[i]);
        }
        return nums;
    };

if (!window.$strings)
    window.$strings = function (args) {

        var strs = [];
        for (var i in args) {
            if (typeof (args[i]) == 'string' && !isNumber(args[i]))
                strs.push(args[i]);
        }
        return strs;
    };

(function ($) {

    var defaults = {
        viewer: false,
        //content is, by default, all conveyor children
        content: false,
        controls: {
            index: false,
            play: false,
            pause: false,
            next: false,
            prev: false,
            playpause:false
        },
        layout:{
            width:"fixed",
            height:"fixed"
        },
        logicalkeys: true,
        events: {
            snap: function () { },
            next: function () { },
            prev: function () { },
            pass: function () { },
            play: function () { },
            onmoveto: function () { },
            slide: function () { },
            pause: function () { },
            _pass: function (e, ui, item) {

                //this._clearSnap.call(this,e,ui,item);
                this.events.pass.call(item, e, ui);
            }
        },
        slice: 1,
        repeat: true,
        animate: {
            cycle: 100,
            scroll:350,
            reverse: false,
            pause: false,
            orientation: "horizontal",
            offset: 0,
            autoplay:false
        },
        index: 0,
        
        snapSpeed: 20,
        //left, center, right
        focusPoint: "center",
        //left, center, right
        restPoint: "left",
        
        
        _input: {
            keyboard:true,
            touch:true
        },
        _paused:false,
        shows:null,
        _len: 0

        
        

    };

    var data = function (self, $data) {
        if (!self)
            self = window;
        if ($data)
            return $(self).data("foundryShow", $data);

        var $d = $(self).data("foundryShow");
        if ($d)
            return $d;
        $d = $.extend(true, {}, defaults);
        return data(self, $d);
    };

    var methods = {
        base: function (opt) {
            if(!$(this).get(0))
                return false;

            $(this).each(function(){
            var root = this;
            /*
            * 
            * Extend defaults and create new options object
            */
            var funcs = $functions(arguments);
            var nums = $numbers(arguments);
            var strs = $strings(arguments);

            var args={};

            
            
            var options = $.extend(true, {}, defaults, opt);

            var shows = options.shows || ($(this).hasClass("fn-foundry-show-canvas")?$(this):false) ||$(this).find(".fn-foundry-show-canvas");
            options.shows = $(shows);
            
            data(this,options);
            $(this).foundryShow("refresh");
            var nav = options.nav;
            
            nav.prev = options.controls.prev || $(this).find(".fn-foundry-show-prev");nav.prev=$(nav.prev);
            nav.next = options.controls.next || $(this).find(".fn-foundry-show-next");nav.next=$(nav.next);
            $(nav).each(function(){$(this).data("foundryShow.base",root);});


            if(options.logicalkeys){
					$(this).hover(function(){
						$(this).focus();
                        $(this).toggleClass("focus",true);
						$(window).bind('keyup',this, function(e) {
							
							
							switch(Number(e.which)){
								case 37:
									$(e.data).foundryShow("prev");
									break;
								case 39:
                                case 13:
                                
									$(e.data).foundryShow("next");
									break;
							
							}
							
						});
						
						
					},function(){
						$(this).blur();
                        $(this).toggleClass("focus",false);
						$(window).unbind('keyup');
						
					});
					
				}
                

            $(nav.index).click(function(){
                var i = $(this).attr("rel");
                $(root).foundryShow("moveto",i);

            });

            $(nav.next).click(function(){               
                $(root).foundryShow("next");
            });
            $(nav.prev).click(function(){               
                $(root).foundryShow("prev");
            });
            
            if(options.animate.autoplay){
                setInterval(function(){
                    if(!$(root).foundryShow("paused"))
                    $(root).foundryShow("next");
                    
                },options.animate.cycle*1000);
                /*$(root).enterFrame("interval",options.animate.cycle,function(){
                    //$(this).foundryShow("next");
                    console.log("next");
                });*/
                $(root).hover(function(){
                    $(root).foundryShow("pause",true);
                },function(){
                    $(root).foundryShow("pause",false);
                });
            }

            data(this,options);
            return this;
            });
        },
        refresh:function(){
            var options = data(this);
            var root = this;
            
            var len=0;
            options.shows.each(function(j){
                var orientation = $.isArray(options.animate.orientation)?options.animate.orientation[j]:options.animate.orientation;
                orientation=orientation||options.animate.orientation[0];

                var canvas=this;
                

                
                
                $(this).find(".slide-default").remove();
                
                if(!$(this).find(".fn-foundry-show-conveyor").get(0))
                    $(this).wrapInner("<div class='fn-foundry-show-conveyor'></div>");
                   
                
                var canvasData={width:0,height:0,maxwidth:0,maxheight:0};

                var slides = $(this).find(".fn-foundry-show-slide");


                slides.each(function(){
                    $(this).data("foundryShow.pos",{x:canvasData.width,y:canvasData.height});

                    var tag = $(this).get(0).nodeName.toLowerCase();
                    if(tag=="a"){
                        var href = $(this).attr("href");
                        
                        if(!href||href=="javascript:void(0);"){
                        
                            $(this).toggleClass("nolink",true);
                        }
                    }

                    if(!$(this).width()&&$(this).find("img").get(0))
                        $(this).find("img").load(function(){$(root).foundryShow("refresh");});

                    
                    
                    $(this).data("foundryShow.canvas",canvas);

                    canvasData.maxwidth=Math.max($(this).width(),canvasData.maxwidth);
                    canvasData.maxheight=Math.max($(this).height(),canvasData.maxheight);
                    
                    switch(orientation){
                        case "horizontal":
                            canvasData.width+=$(this).width();                        
                            canvasData.height=0;
                        break;

                        case "vertical":
                            canvasData.height+=$(this).height();
                            
                            canvasData.width=0;
                        break;
                        case "stacked":
                        default:
                            canvasData.width=0;
                            canvasData.height=0;
                        break;
                        
                        
                    }

                });

                switch(orientation){
                        case "horizontal":                     
                            canvasData.height=canvasData.maxheight;
                        break;

                        case "vertical":                            
                            canvasData.width=canvasData.maxwidth;
                        break;
                        case "stacked":
                        default:
                            canvasData.width=canvasData.maxwidth;;
                            canvasData.height=canvasData.maxheight;
                        break;
                        
                        
                    }

                $(this).data("foundryShow.slides",slides);
                
                if(!len)
                    len=$(slides).size();
                if(len!=$(slides).size()){
                    console.log("Error: the sizes between shows must match. Len:"+len+" Size:"+$(slides).size());
                    
                    return false;
                }
               
                switch(orientation){
                    case "horizontal":
                        var w = "";
                        if(options.layout.width=="fixed"){
                            w = canvasData.maxwidth*(1+len);
                            slides.each(function(i){
                                var pos = $(this).data("foundryShow.pos");
                                $(this).data("foundryShow.pos",{x:canvasData.maxwidth*i,y:pos.y});

                                
                                var sw = $(this).width();
                                var sh = $(this).height();
                                var pad = Math.max(0,Math.round((canvasData.maxwidth-sw)/2));
                                var hpad = Math.max(0,Math.round((canvasData.maxheight-sh)/2));
                                $(this).css({"padding-left":pad+"px","padding-right":pad+"px",
                                "padding-top":hpad+"px","padding-bottom":hpad+"px"});

                            });
                        }else{
                            w = canvasData.width;
                        }
                        $(this).children(".fn-foundry-show-conveyor").width(w);
                        $(this).children(".fn-foundry-show-conveyor").height(canvasData.maxheight);
                    break;
                    case "vertical":
                        var h = "";
                        if(options.layout.height=="fixed"){
                            h = canvasData.maxheight*(1+len);
                            slides.each(function(i){
                                var pos = $(this).data("foundryShow.pos");
                                $(this).data("foundryShow.pos",{y:canvasData.maxheight*i,x:pos.x});
                                
                                var sw = $(this).width();
                                var sh = $(this).height();
                                var pad = Math.max(0,Math.round((canvasData.maxwidth-sw)/2));
                                var hpad = Math.max(0,Math.round((canvasData.maxheight-sh)));
                                $(this).css({"padding-left":pad+"px","padding-right":pad+"px",
                                "padding-top":"0px","padding-bottom":hpad+"px"});
                            });
                        }else{
                            h = canvasData.height;
                        }
                        
                        $(this).children(".fn-foundry-show-conveyor").height(h);
                        $(this).children(".fn-foundry-show-conveyor").width(canvasData.maxwidth);
                        
                    break;
                    case "stacked":
                    default:
                        $(this).children(".fn-foundry-show-conveyor").height(canvasData.maxheight);
                        $(this).children(".fn-foundry-show-conveyor").width(canvasData.maxwidth);
                    break;
                }
                $(this).height(canvasData.maxheight);
                $(this).width(canvasData.maxwidth);
                $(this).data("foundyShow.canvasData",canvasData);
            });
            if(len==0){
                console.log("Error: no slide canvas");
                return false;
            }
                
            var nav={};
            nav.index = options.controls.index || $(this).find(".fn-foundry-show-index");            
            nav.index=$(nav.index).toggleClass("fn-foundry-show-index",true);

            var par;
            if(nav.index.size()>0&&nav.index.size()!=len){
                
                var base = nav.index.get(0);

                par = $(nav.index).parent();
                par.remove(".fn-foundry-show-index");
                for(var i =0;i<len;i++){
                    $(base).clone().appendTo(par).attr("rel",i);
                }
                $(base).remove();
            };
            
            nav.index = $(par).find(".fn-foundry-show-index");
            options.nav=nav;
            data(this,options);
            $(this).foundryShow("moveto",0);
            
            $(this).toggleClass("fn-slideshow-widget",false);
        },
        index: function () {
            
        },
        len: function () {
           return $(data(this).shows.get(0)).find(".fn-foundry-show-slide").size(); 
        },
        enable: function () {
            
        },
        paused: function () {
            var d = data(this);
            return d._paused;
            
        },
        pause: function (dopause) {
            
            var d = data(this);
            d._paused=dopause;
            data(this,d);
        },

        disable: function () {
            
        },

        reset: function () {
            //pass
        },
        moveto: function (i) {
           
            var d = data(this);
            d.index=i;

            d.events.onmoveto.call(this,i,d);

            $(d.nav.index).filter(":gt("+i+"),:lt("+i+")").toggleClass("active",false);
            $(d.nav.index).filter(".fn-foundry-show-index:eq("+i+")").toggleClass("active",true);
            
            $(d.shows).each(function(j){
            
                var showData = $(this).data("foundryShow.canvasData");
                var pos = $(this).find(".fn-foundry-show-slide:eq("+d.index+")").data("foundryShow.pos");
                $(this).find(".fn-foundry-show-slide");

                var orientation = $.isArray(d.animate.orientation)?d.animate.orientation[j]:d.animate.orientation;
                orientation=orientation||d.animate.orientation[0];
                
                
                
                
                switch(orientation){
                    case "horizontal":
                        
                        $(this).children(".fn-foundry-show-conveyor").tween(d.animate.scroll/$.enterFrame("frameRate"),Number($(this).children(".fn-foundry-show-conveyor").css("left").replace("px","")),-pos.x,"inOutQuad",function(e,t){
                        
                            $(this).css("left",t.tpos+"px");
                        });
                        break;
                    case "vertical":
                        
                         $(this).children(".fn-foundry-show-conveyor").tween(d.animate.scroll/$.enterFrame("frameRate"),Number($(this).children(".fn-foundry-show-conveyor").css("top").replace("px","")),-pos.y,"inOutQuad",function(e,t){
                        
                            $(this).css("top",t.tpos+"px");
                        });
                        break;
                    case "stacked":
                    default:
                        $(this).find(".fn-foundry-show-slide:gt("+i+"),.fn-foundry-show-slide:lt("+i+")").fadeOut();
                        $(this).find(".fn-foundry-show-slide:eq("+i+")").fadeIn();
                        break;
                }
                
            });
            data(this,d);

        },
        next: function () {
           var d = data(this);
           d.index++;
           if(d.index>=$(this).foundryShow("len")){
                d.index=0;
           }
           $(this).foundryShow("moveto",d.index);

        },
        prev: function () {
           
           var d = data(this);
           d.index--;
           if(d.index<0){
                d.index=$(this).foundryShow('len')-1;
           }
           $(this).foundryShow("moveto",d.index);

        },
        play: function (options) {
           
        },
        stop: function (options) {
           
        },
        movetoAndStop: function (options, i) {
            
        }
    };


    $.fn.extend(
{
    foundryShow: function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.base.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.foundryShow');
        }
    }
});

    $.extend(
	{
	    foundryShow: function (method) {
	        //return $("window").foundryShow(method);		
	    }
	});


})(jQuery);
