/*
 * 
 * jbgallery 1.0
 * @requires jQuery v1.3.2
 * 
 * Copyright (c) 2009 Massimiliano Balestrieri
 * Examples and docs at: http://maxb.net/blog/
 * Licensed GPL licenses:
 * http://www.gnu.org/licenses/gpl.html
 *
 * Inspired by http://www.ringvemedia.com/introduction
 */

//jQuery.noConflict();

;(function($){


jBGallery = {};

jBGallery.Init = function(options, data){
	if(typeof options == "string"){
		if(jBGallery.Api.enabled(this) || options === 'enable' || options === 'destroy')
			return jBGallery.Api[options](this, data);
	}else{
		return this.each(function(nr){
			new jBGallery.Core(this, options, nr);
		});
	}	
};

jBGallery.Api = {
	enabled : function(el){
		return $(el).data("enabled");
	},
	current : function(el){
		return $(el).data("current");
	},
	go : function(el, nr){
		return $(el).trigger("go", [nr]);
	},
	left : function(el){
		return $(el).trigger("left");
	},
	right : function(el){
		return $(el).trigger("right");
	},
	play : function(el, interval){
		return $(el).trigger("play", [interval]);
	},
	stop : function(el){
		return $(el).trigger("stop");
	},
	disable : function(el){
		return $(el).trigger("disable");
	},
	enable : function(el){
		return $(el).trigger("enable");
	},
	destroy : function(el){
		return $(el).trigger("destroy");
	}
}; 



jBGallery.Core = function(el, options, nr){
	var _metadata = {};
	if($.metadata)
		_metadata = $(el).metadata();
	
	var _options = $.extend({
        style       : "zoom",//centered, zoom    
		slideshow   : false,
		interval    : 4000,
		fade_time	: 400,
		fade		: true,
		menu 	    : 'simple', //false, numbers, simple
        shortcuts   : [37,39],
		after       : function(ev){},
		before	    : function(){},
        load        : function(ev){},
        close		: function(){},
        popup       : false,
        labels      : {},
        log         : function(){}//_log//
	},_metadata,options);

	if(!_options.fade)
		_options.fade_time = 0;

    var that = el;
    var _id = nr;

    $("html, body").addClass("jbg");
    $("#jbgallery-css").removeAttr("disabled");
    
    
    //nascondo l'ul - x ie
    $(that).find("ul").hide();
    
	var _imgs = $.map($(that).find("ul > li > a"), function(a, i){
		//fix numbers
        if(_options.menu == "numbers")
            $(a).text((i+1));
            
        return {href : a.href, title: a.title};
	});
    
	var _current_url = _imgs[0].href;//(_current - 1)//$(that).find("a").eq(0).attr("href");
    var _current_title = _imgs[0].title;//(_current - 1)//$(that).find("a").eq(0).attr("href");

	$(that).prepend('<div id="jbg"><table cellpadding="0" cellspacing="0"><tr><td><img class="'+_options.style+'" id="jbgallery_target" alt="'+_current_title+'" src="'+_current_url+'" /></td></tr></table></div>');
	
    var _target = $("#jbgallery_target", that);
    
    //centered
    if(_options.style == "centered"){
        $("#jbg").css({"top":"auto", height : "100%"});
        $("#jbg").height("100%");
    }
    
    jBGallery.OnLoadImage(that, _options, _target);
    
    if(_imgs.length > 1)
        new jBGallery.Engine(that, _options, _target,_id, _imgs);
    
    
    function _log(arg){
        if(window.console)
            console.log(arg);
        else
            alert(arg);
    }
    
};

//NEW
jBGallery.slideshow = false;
jBGallery.interval = false;
jBGallery.timeout = false;

jBGallery.OnLoadImage = function(that, _options, _target){
    
    var _is_webkit = navigator.userAgent.toLowerCase().search(/webkit/) != -1;
    var _is_ie6 = 1;//navigator.userAgent.toLowerCase().search(/msie/) != -1;
	_target.bind("load",function(ev){
        _options.log("jBGallery.OnLoadImage : load");
        _onload(ev);
        _options.load(ev);
        _options.after(ev);
		
		//TEST
		if(jBGallery.slideshow){
			clearTimeout(jBGallery.timeout);
			jBGallery.timeout = setTimeout(function(){
				$(that).trigger("right", [jBGallery.interval]);
			}, jBGallery.interval);
		}
    });
    
    if(_is_webkit || _is_ie6 || _options.style == "centered"){
        jBGallery.Fix(that, _options, _target, _is_ie6, _options.style == "centered");
    }
    
    function _onload(ev){
        _options.log("ev: _onload");
        $("#jbg-loading").hide();
        _appear(ev);
    }
    
    function _appear(ev){      
    	_options.log("ev: _appear");
        _target.fadeIn(_options.fade_time);
    }
    
    
};


jBGallery.Fix = function(that, _options, _target, _is_ie6, _centered){
    
    var _resize_timer = null;
    var _el = _target.get(0);
    
    $(window).bind('resize', function(ev) {
        if (_resize_timer) clearTimeout(_resize_timer);
        _resize_timer = setTimeout(function(){
            _options.log("resize: _fix_dimensions");
                _fix(ev);
        }, 100);
    });
    
    _target.bind('load',function(ev){
        _fix(ev);
    });
    
    
    function _fix(ev){
    
        if(_centered)
        
            _fix_bigimage(ev);
        else if(_is_ie6){
            _target.height("auto").width("auto");
            setTimeout(_fix_dimensions,10);
        }else{
            _fix_dimensions(ev);
        }
    }
    
    function _fix_bigimage(ev){
        _options.log("jBGallery.Fix: load/fix_bigimage");
        $(_target).width("auto").height("auto");
        var _dim = _get_dimensions();
        if(_dim.h > _dim.bh || _dim.w > _dim.bw){
            if(_dim.p <=  1){//immagine alta -> larghezza
                $(_target).width(_dim.bw);                        
            }else if(_dim.p > 1){//immagine larga -> altezza
                $(_target).height(_dim.bh);    
            }      
        }
    }
    
    function _fix_dimensions(ev){
        _options.log("jBGallery.Fix: load/fix_dimensions");
		//TODO
        if($("#jbgallery-css").size() == 0){
            alert("load css");
            return;
        }
        var _dim = _get_dimensions();
        if(_is_ie6){        
            if(_dim.h < _dim.bh)
                    $(_target).height(_dim.bh);
        }else{//webkit
                if(_dim.h < _dim.bh)
                    $(_target).height(_dim.bh);
                    
        }
        
    }

    function _get_dimensions(){
        var bw = $("body").width();
        var bh = $("body").height();
        var pm = bw / bh;
        var p = _el.width / _el.height;
        return {bw : bw, bh : bh, pm : pm, p : p, h : _el.height, w : _el.width};
    }
};



jBGallery.Data = function(that, key, val){
    if(typeof val !== 'undefined'){
        $(that).data(key,val);
        return val;
    }else{
        return $(that).data(key);
    } 
};

jBGallery.Css = function(href){
	$(document.getElementsByTagName("head")[0]).append('<link rel="stylesheet" type="text/css" id="jbgallery-css" media="screen" href="'+href+'" />');
};

$.fn.jbgallery = jBGallery.Init;
$.fn.jbgcss = jBGallery.Css;

})(jQuery);
