if(!window.timeline)
    var timeline = {};
	
timeline.Base = {
    cnt       : 0,
    build     : function(options)
    {
        
        options = $.extend({
             height   :   false,
			 shortcut :   [37,39],
             id       :   false,
             scroll   :   false,
             history  :   true,
             draggable:   true,
             sidebars :   true,
			 easeTime :   750
              }, options);
        return this.each(
            function(nr)
            {
                //contatore statico di istanze
                timeline.Base.cnt++;

                this.timeline = {};
                this.timeline.options = options || {};
                    
                timeline.Base.gui(this, options);         
                timeline.Base.init(this);
                timeline.Base.count(this);
                timeline.Base.start(this);
                timeline.Base.nav(this);
                timeline.Base.bindings(this);
                timeline.Base.defaults(this);     
            }
        );
        
    },
    gui     :   function(el, options){
        el.id = el.timeline.options.id || el.id || 'yslider-' + timeline.Base.cnt;//id
        var html = '<div class="yslider-wrap"><div class="yslider-viewer"><div class="yslider-container">';
        var jPanels = $(".panelwrapper", el);
		
		jPanels.css({display:"block"});
        
		$(el).empty();
        $(el)
        .append(html);
        $('.yslider-container', el).append(jPanels);
        jPanels.wrap('<div class="yslider-panel">');

		$(el).append("<div id='timeslider' class='ui-slider'><div class='slider-handle'></div></div>");
		$(el).append("<b class='c ctl'>.</b><b class='c ctr'>.</b><b class='c cbr'>.</b><b class='c cbl'>.</b>");

        if(!el.timeline.options.sidebars)
            $(".yslider-wrap", el).width($(".yslider-wrap", el).width() - 100);
    },
    count   :   function(el){
		
        var jContainer = $("div.yslider-container",el);
        el.timeline.pw = 0;
		el.timeline.positions = [];
		
		jContainer.find(".panelwrapper").each(function(i){
			el.timeline.positions[i] = el.timeline.pw;
			el.timeline.pw += $(this).width();

		});
		el.timeline.pc = jContainer.find("div.yslider-panel").size();//panel
        el.timeline.vw = el.timeline.pw// * el.timeline.pc;//viewer
		el.timeline.nw = el.timeline.pw;//el.timeline.pc * 2 ?
        jContainer.css("width" , el.timeline.vw);
		
		el.timeline.smv = el.timeline.pw - jContainer.find(".panelwrapper:last").width();//panel
		var maxValue = "-" + el.timeline.smv;


		$('#timeslider').slider({
				handle: '.slider_handle',
				min: 0,
				max: maxValue,
				slide: function(e, ui) {
					$('.yslider-container').css({left: Math.round(ui.value)});
				}
			});
		
    },
    init    :   function(el){
        if(el.timeline.options.width){
            $(el).css("width", el.timeline.options.width + 100);
            $('.yslider-panel,.yslider-viewer', el).css("width", el.timeline.options.width);
        }
        if(el.timeline.options.height)
            $('.yslider-viewer', el).css("height", el.timeline.options.height);
        if(el.timeline.options.scroll)    
            $('.yslider-viewer', el).css({"overflow-y":"auto"});
        if(el.timeline.options.draggable){

		$('.yslider-viewer', el).mousemove(
			function(){
				var containerLeftPosPx = $('.yslider-container', el).css("left");
				var containerLeftPos =  Math.round(containerLeftPosPx.substring(0,containerLeftPosPx.length-2));
				var containerStart = el.timeline.positions[0];
				var containerEnd = - el.timeline.positions[el.timeline.positions.length - 1]

				if(containerLeftPos > containerStart ){
					$("div.yslider-container")
					.stop()
					.animate({ left: containerStart} ,250,el.timeline.options.easeFunc);
				}
				if(containerLeftPos < containerEnd ){
					$("div.yslider-container",el)
					.stop()
					.animate({ left: containerEnd} ,250,el.timeline.options.easeFunc);
				}
			}															 
		);
			
            $('.yslider-container', el).draggable({axis : "x"}).hover(
				function(){
                    $(this).css("cursor","move");
				},
                function(){
                    $(this).css("cursor","");
                }
            );            
        }
    },
    start  :   function(el){
        // Specify the current panel.
        // If the loaded URL has a hash (cross-linking), we're going to use that hash to give the slider 
        // a specific starting position...

		timelinePopBox(); // popups initialized
		
		if (timeline.Base.current(el)) {
            el.timeline.current   = parseInt(location.hash.slice(1)) || 1;
            el.timeline.cnt = - (el.timeline.pw*(el.timeline.current - 1));

			var leftPos = - el.timeline.positions[el.timeline.current-1]+'px';
			$(el).find("div.yslider-container").css({ "left": leftPos });
        // Otherwise, we'll just set the current panel to 1...
        } else { 
            el.timeline.current = 1;
        };
    },
    nav    :   function(el){
        var jViewer = $("div.yslider-viewer",el);

        if(el.timeline.options.sidebars){
            jViewer.after('<div class="yslider-navl"><a href="#">Left</a></div>');
            jViewer.after('<div class="yslider-navr"><a href="#">Right</a></div>');
        }
        jViewer.before('<div class="yslider-nav"><ul><\/ul></div>');
        
        var jNav = $("div.yslider-nav ul",el);
        $("div.yslider-panel",el)
        .each(function(n) {
            var lp = $("div.panelwrapper",this).attr("name") || (n+1);
            if(el.timeline.options.history){
                $('<li><a href="#' + (n + 1) + '">' + lp + '</a></li>')
                .appendTo(jNav); 
            }else{
                $('<li><a href="#">' + lp + '</a></li>')
                .appendTo(jNav)
                .click(function(){
                   return false;    
                });
            }
        });
    },
    bindings : function(el){
                
        // Tab nav
        $("div.yslider-nav a",el).each(function(z) {
            $(this).bind("click", function() {
                $(this)
                .addClass("current").parent().parent().find("a").not($(this))
                .removeClass("current"); // wow!
                //:) yes wow
                var cnt = - ( el.timeline.pw * z);
                el.timeline.current = z + 1;
                
                if(el.lazy)
                   timeline.Lazy.lazyload(el, (el.timeline.current - 1), el.timeline.pc);
                
				var leftPosPx = - el.timeline.positions[el.timeline.current-1]+'px';

			  $("div.yslider-container",el).queue(function () {
				$(this).animate({ left: leftPosPx} ,el.timeline.options.easeTime,el.timeline.options.easeFunc);
				$(this).dequeue();


			var leftPos = - el.timeline.positions[el.timeline.current-1];				
				$('#timeslider').slider("moveTo", leftPos + 1); 					

			  });


				
				
            });
        });
        // Left nav
        if(el.timeline.options.sidebars)
        $("div.yslider-navl a",el).click(function(){
            if (el.timeline.current == 1) {
                var cnt = - (el.timeline.pw * (el.timeline.pc - 1));
                el.timeline.current = el.timeline.pc;
                $(this).parent().parent().find("div.yslider-nav a.current")
                .removeClass("current").parent().parent().find("li:last a")
                .addClass("current");
            } else {
                el.timeline.current -= 1;
                var cnt = - (el.timeline.pw * (el.timeline.current - 1));
                $(this).parent().parent().find("div.yslider-nav a.current")
                .removeClass("current").parent().prev().find("a")
                .addClass("current");
            };
            if(el.lazy)
                timeline.Lazy.lazyload(el, (el.timeline.current - 1), el.timeline.pc);
                
			var leftPos = - el.timeline.positions[el.timeline.current-1]+'px';


            $(this).parent().parent().find("div.yslider-container")
			.stop()
            .animate({ left: leftPos } ,el.timeline.options.easeTime,el.timeline.options.easeFunc);
                    
            // Change the URL hash (cross-linking)...
            if(el.timeline.options.history)
                location.hash = el.timeline.current;
            return false;
        });
        
        // Right nav
        if(el.timeline.options.sidebars)
        $("div.yslider-navr a",el).click(function(){
            if (el.timeline.current == el.timeline.pc) {
                var cnt = 0;
                el.timeline.current = 1;
                $(this).parent().parent().find("div.yslider-nav a.current")
                .removeClass("current").parent().parent().find("a:eq(0)")
                .addClass("current");
            } else {
                var cnt = - (el.timeline.pw * el.timeline.current);
                el.timeline.current += 1;
                $(this).parent().parent().find("div.yslider-nav a.current")
                .removeClass("current").parent().next().find("a")
                .addClass("current");
            };
            
            if(el.lazy)
                timeline.Lazy.lazyload(el, (el.timeline.current - 1), el.timeline.pc);
            
			
			var leftPos = - el.timeline.positions[el.timeline.current-1]+'px';
			$(this).parent().parent().find("div.yslider-container")
			.stop()
            .animate({ left: leftPos } ,el.timeline.options.easeTime,el.timeline.options.easeFunc);
                    
            // Change the URL hash (cross-linking)...
            if(el.timeline.options.history)
                location.hash = el.timeline.current;
            return false;
        });
        //keycode
        var sc = el.timeline.options.shortcut;
        if(sc && sc[0] && sc[1]){
            $(document).keydown(function(e){
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                //settabili - se non è nascosto muovi
                if(!($(el).css("display") === "none")){
                    if(keycode == sc[0]){ // display previous image
                       $("div.yslider-navl a",el).trigger("click", el);
                    } else if(keycode == sc[1]){ // display next image
                       $("div.yslider-navr a",el).trigger("click", el);
                    }  
                }
            });
        }
       $('.load_modeltip').cluetip({
			cluetipClass: 'jtip', 
			activation: 'click', 
			width: 350,  
			sticky: true,
			titleAttribute:'null',
			closeText:        '<img src="/js/fancybox/fancy_closebox.png" alt="close" />',
			closePosition: 'title',
			dropShadowSteps:  2,
			leftOffset: 10
		});     
    },
    defaults    :   function(el){
        // Specify which tab is initially set to "current". 
        // Depends on if the loaded URL had a hash or not (cross-linking).
        if (timeline.Base.current(el)) {
            $("div.yslider-nav a:eq(" + (location.hash.slice(1) - 1) + ")",el)
            .addClass("current");
        } else {
            //if(timeline.Base.init_current(el))//ok inizializzo 1. ma se non ho un'altra location
               //location.hash = 1;
               
            $("div.yslider-nav a:eq(0)",el).addClass("current");
        }
    
    },
    current     :   function(el){
        return el.timeline.options.history && 
               location.hash && 
               parseInt(location.hash.slice(1)) <= el.timeline.pc;   			   
    }
};  
$.fn.timeline = timeline.Base.build;

function timelinePopBox() {
	$('.sword').each(function () {
		var distance = 10;
		var time = 150;
	
		var beingShown = false;
		var shown = false;
		var trigger = $('.trigger', this);
		var infoContent = $('.popContent', this);
		infoContent.wrap("<div class='popBox'>");
			
		var info = $('.popBox', this).css('opacity', 0);
		info.prepend("<div class='popClose'></div>");

		$(trigger).bind("click", function(e) {
				
				if (beingShown || shown) {
					// don't trigger the animation again
					return;
				} else {																					
				
				beingShown = true;


				width = $("#timelinea").width();
				height = $("#timelinea").height();
				
				boxheight = info.height();
				boxwidth = info.width();		

				// Change position to get different pop
				info.css({
						top: ((height - boxheight )/ 2) ,
						position: 'absolute',
						left: ((width - boxwidth ) / 2),
						display: 'block'
					}).animate({
						top: '-=' + distance + 'px',
						opacity: 1
					}, time, 'swing', function() {
						beingShown = false;
						shown = true;
					}).makeAbsolute("#timelinea");;
				}							
		
				e.stopPropagation(); // Stops the following click function from being executed

				$(".popClose").one("click", function(f) {
						info.animate({
							top: '-=' + distance + 'px',
							opacity: 0
						}, time, 'swing', function () {
							shown = false;
							info.css('display', 'none');
						});
				});
				
				return false;
   		 });
	});

}

$.fn.makeAbsolute = function(rebase) {    
	return this.each(function() {
		var el = $(this);        
		var pos = el.position();        
		
		el.css({ position: "absolute", marginLeft: 0, marginTop: 0, top: pos.top, left: pos.left });        
		
		if (rebase)
			el.remove().appendTo("#timelinea");    
	});
}