$(function(){
	$.extend($.fn.disableTextSelect = function() {
		return this.each(function(){
			if($.browser.mozilla){//Firefox
				$(this).css('MozUserSelect','none');
			}else if($.browser.msie){//IE
				$(this).bind('selectstart',function(){return false;});
			}else{//Opera, etc.
				$(this).mousedown(function(){return false;});
			}
		});
	});
});

$(function(){
	$.extend($.fn.totalWidth = function() {
		var _tW = this.width();
		if(parseInt(this.css('margin-left'))) _tW += parseInt(this.css('margin-left'));
		if(parseInt(this.css('margin-right'))) _tW += parseInt(this.css('margin-right'));
		if(parseInt(this.css('padding-left'))) _tW += parseInt(this.css('padding-left'));
		if(parseInt(this.css('padding-right'))) _tW += parseInt(this.css('padding-right'));
		if(parseInt(this.css('borderLeftWidth'))) _tW += parseInt(this.css('borderLeftWidth'));
		if(parseInt(this.css('borderRightWidth'))) _tW += parseInt(this.css('borderRightWidth'));
		if(_tW) 
			return _tW;
		else
			return this.width();
	});
});
$(function(){
	$.extend($.fn.totalHeight = function() {
		var _tH = this.height();
		if(parseInt(this.css('margin-top'))) _tH += parseInt(this.css('margin-top'));
		if(parseInt(this.css('margin-bottom'))) _tH += parseInt(this.css('margin-bottom'));
		if(parseInt(this.css('padding-top'))) _tH += parseInt(this.css('padding-top'));
		if(parseInt(this.css('padding-bottom'))) _tH += parseInt(this.css('padding-bottom'));
		if(parseInt(this.css('borderTopWidth'))) _tH += parseInt(this.css('borderTopWidth'));
		if(parseInt(this.css('borderBottomWidth'))) _tH += parseInt(this.css('borderBottomWidth'));
		if(_tH)
			return _tH;
		else
			return this.height();
	});
});

function dumpVar(_var, printFunctions, printObjects) {
	if(!printFunctions)
		printFunctions = false;
	var str = "<pre>";
	for(x in _var) {
		if(typeof _var[x] == "function" && !printFunctions)
			str += x+": function - \n";
		else if(typeof _var[x] == "object" && !printObjects)
			str += x+": object - \n";
		else
			str += x+": "+typeof _var[x]+" -> "+_var[x]+"\n";
	}
	$(document.body).append(str+"</pre>");
}


function JsPhGallery(elem,_options) {

	this.name = "JsPhGallery on "+elem.id;

	this.settings = { 
		HI_RES_DIR: "HI/",
		SLIDE_INTERVAL: 10,
		SLIDE_FOR: 1,
		SPEED: false,
		PH_WIDTH: false,
		PH_HEIGHT: false
	};

	this._elems = new Array();
	this._links = new Array();
	_THIS = this;
	var n = -1;
	$(elem).children("ul").children("li").each( function () { 
		_THIS._elems[++n] = $(this).children("img");
		_THIS._links[n] = $(this).children("a");
		_THIS._links[n][0].nIdx = _THIS._elems[n][0].nIdx = n;
		$(this).remove();
	});
	$(elem).children("ul").remove();
	for(x in this._elems) {
		$(elem).append(this._elems[x]);
	}

	this.slider = $(elem).addClass("slidegallery-slider");
	this._container = $('<div class="slidegallery-container"></div>').appendTo($(elem).parent());
	this._screen = $('<div class="slidegallery-scr" align="center"></div>').appendTo(this._container);
	this._screenImg = $('<img class="slidegallery-scr-img" src="" alt="" title="" width="0" height="0" />').appendTo(this._screen);
	this._screenTxt = $('<div class="slidegallery-scr-txt" align="center"></div>').appendTo(this._screen);
	this._cntrl_sx = $('<div class="slidegallery-cntrl-sx"></div>').appendTo(this._container);
	this._sl_container = $('<div class="slidegallery-sl-container"></div>').appendTo(this._container);
	this.slider.appendTo(this._sl_container);
	this._cntrl_dx = $('<div class="slidegallery-cntrl-dx"></div>').appendTo(this._container);

	if(this.settings.PH_WIDTH)
		this._container.css('width', this.settings.PH_WIDTH);
	else
		this._container.css('width', this._container.parent().width());
	if(this.settings.PH_HEIGHT)
		this._container.css('height', this.settings.PH_HEIGHT);
	else
		this._container.css('height', this._container.parent().height());
	
	this._loadStatusDiv = $('<div class="slidegallery-loading hidden"></div>').appendTo(this._screen);
	
	this.selected = null;
	this.interval = null;
	this.slider.css('margin-left','0px');
	this.startFrom = parseInt(this.slider.css('margin-left'));
	this.totWidth = 0;
	this.endAt = 0;
	
	this.thinner = 100;
	this.higher = 50;
	
	this.getSpeed = function (spd) {
		switch(spd)	{
			case 'slow':
				this.settings.SLIDE_INTERVAL = 5;
				this.settings.SLIDE_FOR = 2;
				break;
			case 'fast':
				this.settings.SLIDE_INTERVAL = 3;
				this.settings.SLIDE_FOR = 3;
				break;
			case 'faster':
				this.settings.SLIDE_INTERVAL = 5;
				this.settings.SLIDE_FOR = 4;
				break;
			default:
				this.settings.SLIDE_INTERVAL = 1;
				this.settings.SLIDE_FOR = 2;
				break;
		}
	}
	
	this.getNewSrc = function (oldSrc) {
		_filename = oldSrc.match(new RegExp('[a-zA-Z0-9_.-]*\.?[a-zA-Z]{3}$'));
		return this.settings.HI_RES_DIR+"/"+_filename;
	}
	
	this.showElemOnClick = function (img) { this.showElem(img); }
	
	this.getAvailableH = function () { return this._screen.height() - this._screenTxt.totalHeight(); }
	this.getAvailableW = function () { return this._screen.width(); }
	
	this.stopSlide = function () {
		clearInterval(this.interval);
		this.interval = null;
	}

	this.loadingDivShow = function () { this._loadStatusDiv.removeClass('hidden'); }
	this.loadingDivHide = function () { this._loadStatusDiv.addClass('hidden'); }

	this.slideDx = function () {
		_THIS_OBJ = this; //mantieni referenza all'oggetto corrente per funzioni di callback
		if( parseInt(this.slider.css('margin-left')) > this.endAt )
			this.slider.css('margin-left',parseInt(this.slider.css('margin-left'))-this.settings.SLIDE_FOR);
		if(!this.interval) this.interval = setInterval( function () { _THIS_OBJ.slideDx(); } ,this.settings.SLIDE_INTERVAL);
	}
	
	this.slideSx = function () {
		_THIS_OBJ = this; //mantieni referenza all'oggetto corrente per funzioni di callback
		if( parseInt(this.slider.css('margin-left')) < this.startFrom )
			this.slider.css('margin-left',parseInt(this.slider.css('margin-left'))+this.settings.SLIDE_FOR);
		if(!this.interval) this.interval = setInterval( function () { _THIS_OBJ.slideSx(); } ,this.settings.SLIDE_INTERVAL);
	}
	
	this.slideAllDx = function () {
		this.stopSlide();
		this.slider.css('margin-left',this.endAt);
	}
	
	this.slideAllSx = function () {
		this.stopSlide();
		this.slider.css('margin-left',this.startFrom);
	}
	

	this.showElem = function (_toShow) {
		if(!_toShow.src) _toShow = _toShow[0]; //converto oggetto jQuery in oggetto htmlImageElement
		if(!_toShow.complete)
			setTimeout(function () { _This_Ph_Gallery.showElem(_toShow); }, 50);
		this.loadingDivShow();
		_This_Ph_Gallery = this;
		var _newImg = new Image();
		_newImg.onload = function () {
			_This_Ph_Gallery._screenImg.remove();
			var avW = _This_Ph_Gallery.getAvailableW();
			var avH = _This_Ph_Gallery.getAvailableH();
			var _prop = _newImg.width/_newImg.height;
			if(_newImg.width > avW) {
				_newImg.width = avW;
				_newImg.height = avW/_prop;
			}
			if(_newImg.height > avH) {
				_newImg.height = avH;
				_newImg.width = avH*_prop;
			}
			_This_Ph_Gallery._screenTxt.remove();
			_This_Ph_Gallery._screenImg = $(_newImg).appendTo(_This_Ph_Gallery._screen);
			_This_Ph_Gallery._screenTxt.appendTo(_This_Ph_Gallery._screen);
			_This_Ph_Gallery._screenTxt.html("Vai al sito: ");
			_This_Ph_Gallery._screenTxt.append(_This_Ph_Gallery._links[_toShow.nIdx]);
			//_This_Ph_Gallery._screenTxt.appendTo(_This_Ph_Gallery._screen);
			_This_Ph_Gallery.loadingDivHide();
		}
		var newSrc = this.getNewSrc(_toShow.src);
		_newImg.src = newSrc;
		_newImg.alt = _toShow.alt;

		if(this.selected) this.selected.removeClass('slidegallery-selected');
		this.selected = $(_toShow).addClass('slidegallery-selected');
	}
	
	this.showHelp = function () {
		$('<div class=="slidegallery-help-div" title="Photogallery Help!"><p>Passare con il mouse sopra le icone delle frecce in basso per far scorrere le immagini.</p><p>Fare click sulle immagini in formato ridotto per visualizzarle ingrandite.</p><p>In caso di ritardo prolungato della fase di caricamento della foto fare click nuovamente sulla foto selezionata.</p></div>').dialog();
	}
	
	//inizializzazione
	for(x in _options) { this.settings[x] = _options[x]; }
	
	this.helpLink = $(".slidegallery-help");
	if(this.helpLink) this.helpLink.click(this.showHelp);
	
	if(this.settings.SPEED) this.getSpeed(this.settings.SPEED);

	for(var x=0; x<this._elems.length; ++x) {
		var _This_Ph_Gallery = this;
		var galleryElem = $(this._elems[x]);
		galleryElem.click( function () { _This_Ph_Gallery.showElemOnClick(this); } );
		galleryElem.wrap('<div class="slidegallery-img-wrapper" align="center"></div>');
		this.totWidth += galleryElem.parent().totalWidth();
		if(galleryElem.parent().totalWidth() < this.thinner) this.thinner = galleryElem.parent().totalWidth();
		if(galleryElem.parent().totalHeight() > this.higher) this.higher = galleryElem.parent().totalHeight();
	}
	
	this.slider.css('width',this.totWidth).css('height',this.higher).css('overflow',"hidden");
	this._container.width(parseInt(this._container.css('width')));
	this._sl_container.css('width',parseInt(this._container.css('width'))-this._cntrl_sx.totalWidth()-this._cntrl_dx.totalWidth());
	this._sl_container.css('height',this.slider.totalHeight());
	this._screen.css('height',this._container.totalHeight()-this._sl_container.totalHeight());
	if(!this.selected) $(this._elems[0]).addClass('slidegallery-selected');

	this.endAt = parseInt(this._sl_container.totalWidth())-parseInt(this.slider.totalWidth());

	var _THIS_OBJ = this;

	$(this._cntrl_sx).mouseenter( function () { _THIS_OBJ.slideSx(); } ).
					  mouseleave( function () { _THIS_OBJ.stopSlide(); } ).
					  click( function () { _THIS_OBJ.slideAllSx(); } );
	$(this._cntrl_dx).mouseenter( function () { _THIS_OBJ.slideDx(); } ).
					  mouseleave( function () { _THIS_OBJ.stopSlide(); } ).
					  click( function () { _THIS_OBJ.slideAllDx(); } );
	
	this.slider.disableTextSelect();
	if(!parseInt(this.slider.css('margin-left'))) this.slider.css('margin-left',0);
	for(x in this._elems) {
		__elem = $(this._elems[x]);
		if( __elem.hasClass("slidegallery-selected") ) {
			this.selected = __elem;
			this.showElem(__elem);
		}
	}
};
