/**
 * @name jQuery 360* Panorama Viewer
 * @description Viewer for 360 panoramic images
 * @author Webarto.com
 * @copyright 2011
 */
 
(function($){
$.fn.panorama = function(options){

    var t;                          
    var self = this;
    // defaults
    var conf = {
        "step":     1,
        "speed":    10,
        "direction":    "right",
        "margin":   0,
        "auto": false,
        "navi": false
    };
    if(options){$.extend(conf, options);}
    if(!conf.image || !conf.width || !conf.height) return;

    $(self).css("background", "url(" + conf.image + ") repeat-x top left");
    $(self).css("height", conf.height);

    if(!conf.viewport){
        conf.viewport = conf.width;
        self.css("width", conf.width);
    }
    self.css("width", conf.viewport);

    if(conf.navi == true){
        $(self).append('<div><a href="#" rel="start">Start</a> <a href="#" rel="stop">Stop</a> <a href="#" rel="left">&lt;&lt;</a> <a href="#" rel="right">&gt;&gt;</a></div>');
        var navi = self.find("div:first");
        navi.css("margin-top", conf.height - navi.height());
    }
    
    if(conf.auto == true) start();


    $(this).dblclick(function(){
        stop();
    });

    $("a[rel=left]").mousehold(function(){
        stop();
        conf.direction = "left";
        pano();
    });
    $("a[rel=right]").mousehold(function(){
        stop();
        conf.direction = "right";
        pano();
    });

    $("a[rel=start]").click(function(){
        start();
    });
    $("a[rel=stop]").click(function(){
        stop();
    });

    function pano(){
        var step = conf.step;        
        if(conf.direction == "left") step = -step;
        conf.margin = conf.margin - step;
        if(conf.margin < -conf.width || conf.margin > conf.width) conf.margin = 0;
        $(self).css("background-position", conf.margin + "px 0");
    }
    
    function start(){
        clearInterval(t);
        t = setInterval(function(){pano()}, conf.speed);
        conf.auto = true;
    }
    function stop(){
        clearInterval(t);
        conf.auto = false;
    }
    
}
})(jQuery);

$.fn.mousehold = function(timeout, f) {
	if (timeout && typeof timeout == 'function') {
		f = timeout;
		timeout = 1;
	}
	if (f && typeof f == 'function') {
		var timer = 0;
		var fireStep = 0;
		return this.each(function(e) {
			jQuery(this).mouseover(function() {
				fireStep = 1;
				var ctr = 0;
				var t = this;
				timer = setInterval(function() {
					ctr++;
					f.call(t, ctr);
					fireStep = 2;
				}, timeout);
			})

			clearMousehold = function() {
				clearInterval(timer);
				if (fireStep == 1) f.call(this, 1);
				fireStep = 0;
			}
			
			jQuery(this).mouseout(clearMousehold);
			jQuery(this).mouseleave(clearMousehold);
		})
	}
}
