/**************************************************************************************

this is used in conjunction with MooTools (1.2+) and Squeezebox (digitarald.de)
use: automatically runs a gallery with squeezebox behaviors

each gallery item <a href>:
- must have class="squeezegallery"
- optional "title" tag for item caption
- must be set with a rel="" tag, with these vars (all required):

	g: gallery tag name
		(used to distinguish one group from another if more than one gallery on a page, should be the same for all items in a group)
	type: jpg/gif/png/mp3/video/flv/youtube
	width: px
	height: px

tag format example:
<a class="squeezegallery" title="Caption Text For This Item" href="/path/to/image.jpg" rel="g:my_group_name,type:jpg,width:400,height:500"><img src="/path/to/thumbnail" etc="" /></a>

**************************************************************************************/

function sg_nav(d,n) {
	var num = parseInt(n.getParent().id);
	if (num != NaN && num > -1) {
		if (d == "next") {
			idnum = (num + 1 > (sg_tags[n.retrieve("gt")] - 1) ? 0 : num + 1);
		} else {
			idnum = (num - 1 < 0 ? (sg_tags[n.retrieve("gt")] - 1) : num - 1);
		}
		var nextobj = $(idnum + n.retrieve("gt"));
		sg(nextobj);
	}
}

function sg(obj) {
	obj = $(obj);
	if ($(obj.id + "cont")) { $(obj.id + "cont").dispose(); }

	cur_sg_element = parseInt(obj.id);
	var config = new Array();
	var opt;
	var options = obj.rel.split(",");
	var textlines = 1; // increments for every p, througout the function... set =1 for init, give some room
	var textlineheight = 14;
	var maxwidth = window.getSize().x - 80;
	var maxheight = window.getSize().y - 80;

	options.each(function(o) {
		opt = o.split(":");
		config[opt[0]] = opt[1];
	});
		
	config["width"] = parseInt(config["width"]);
	config["height"] = parseInt(config["height"]);

	var viewerwidth = config['width'] + 40;
	var viewerheight_est = config['height'] + (textlineheight * 3); // estiamtion used for establishing convert ratio

	var ratiow = (viewerwidth > maxwidth ? (maxwidth/viewerwidth) : 1);
	var ratioh = (viewerheight_est > maxheight ? (maxheight/viewerheight_est) : 1);
	var ratio = (ratiow < ratioh ? ratiow : ratioh);
	
	if (ratio < 1) {
		config["width"] = Math.floor(config["width"] * ratio);
		config["height"] = Math.floor(config["height"] * ratio);
		viewerwidth = Math.floor(viewerwidth * ratio);
	}
	
	// set up object that we're viewing:
	var objContainer = new Element("div", {
		'width' : config['width'],
		'height' : config['height'],
		'styles' : { 'marginBottom' : '2px' }
	});
	
	switch (config['type'].toLowerCase()) {
		case "jpg":
		case "gif":
		case "png":
		case "photo":
			var m_el = new Element("img", {
				'width' : config['width'],
				'height' : config['height'],
				'src' : obj.href,
				'border' : '0'
			});
			break;

		case "mp3":
			var m_el = new Element('p', { 'text' : 'this is audio, src: '+obj.href });
			break;

		case "flv": // flv
		case "video": // flv
			var m_el = new Element('p', { 'text' : 'this is video, src: '+obj.href });
			break;

		case "youtube": // flv
			var m_el = new Element('p', { 'text' : 'youtube reference, src: '+obj.href });
			break;
	}
	
	objContainer.grab(m_el);


	// set up element for squeezebox
	var mainContainer = new Element("div", {
		'id' : obj.id + "cont",
		'class' : 'sg_container'
	});
	mainContainer.addClass('hidden');

	// ie doesn't like setStyles().... meh
	//mainContainer.setStyles({ 'width':config['width']+'px', 'height': viewerheight+'px', 'overflow' : 'hidden' });
	mainContainer.setStyle("width",config['width']);
	mainContainer.setStyle("height",viewerheight);
	mainContainer.setStyle("overflow","hidden");
		
	mainContainer.grab(objContainer);
	
	var h = new Element("input", {
		'type' : 'button',
		'value' : '<< Prev',
		'class' : 'cotu_button_sm',
		'events' : { 'click' : function(e) { new Event(e).stop(); sg_nav('prev',this); } },
		'styles' : { 'float' : 'left', 'fontSize' : '9px', 'paddingTop' : '2px' }
	});
	h.store("gt",obj.retrieve("gt"));
	mainContainer.grab(h);

	var h = new Element("input", {
		'type' : 'button',
		'value' : 'Next >>',
		'class' : 'cotu_button_sm',
		'events' : { 'click' : function(e) { new Event(e).stop(); sg_nav('next',this); } },
		'styles' : { 'float' : 'right', 'fontSize' : '9px', 'paddingTop' : '2px' }
		
	});
	h.store("gt",obj.retrieve("gt"));
	mainContainer.grab(h);

	textlines++;
	
	if (obj.title != "") {
		p = new Element("p", { 'id' : obj.id+'cap', 'html' : obj.title });
		mainContainer.grab(p);
		textlines++;
	}
	
	config.each(function(v,k) {
		if (v != "width" && v != "height" && v != "type") {
			p = new Element("p", { 'html' : '<strong>'+v+':</strong> ' + k });
			mainContainer.grab(p);
			textlines++;
		}
	});

	// set real viewer height based on config height, plus actual number of text lines (p) added * textlineheight
	var viewerheight = config['height'] + (textlines * textlineheight);

	/*
	MAY HAVE TO DO CALCULATION HERE THAT WILL CHECK viewheight AGAINST viewheight_est
	AND IF IT'S BEYOND WINDOW HEIGHT, THEN READJUST SOMEHOW.
	*/
	
	$$("body").grab(mainContainer);
	
	var str = " w:"+config['width']+", h:"+config['height'];
	str += ", vw:"+viewerwidth+", vh:"+viewerheight;
	str += ", tl * tlh: "+textlines+" * "+textlineheight+", rh:"+viewerheight;
	str += ", mxw:"+maxwidth+", mxh:"+maxheight;
	
	$$(obj.id + "cont p").setStyle('width',viewerwidth - 40);

	SqueezeBox.fromElement($(obj.id + "cont"), {
		size: {x: config['width'] + 10, y: viewerheight },
		handler: 'adopt' // we set a handler to disable handler/parser detection
	});
	
	//mainContainer.removeClass('hidden');
	// need delay because sometimes browsers will show the mainContent el before SB grabs it
	var tim = setTimeout(function() { $(obj.id + "cont").removeClass('hidden'); } , 500);
	
}

var sg_count = 0;
var cur_sg_element = 0;
var cur_sg_tag = "";
var sg_tags = new Array();

window.addEvent('domready', function() {

	if (Browser.Engine.trident) {
		SqueezeBox.assign($$('a.squeezegallery'));
	} else {
		$$("a.squeezegallery").each(function(a) {
			var options = a.rel.split(",");
			options.each(function(o) {
				opt = o.split(":");
				if (opt[0] == "g") {
					if (cur_sg_tag == "" || cur_sg_tag != opt[1]) {
						if (cur_sg_tag != "") { sg_tags[cur_sg_tag] = sg_count; }
						cur_sg_tag = opt[1];
						sg_count = 0;
					}
					a.id = sg_count + opt[1];
					a.store("gt",opt[1]);
				}
			});
			
			a.addEvent('click', function(e) {
				new Event(e).stop();
				sg(this);
			});
			sg_count++;
		});
		// this catches the last tag count
		sg_tags[cur_sg_tag] = sg_count;
	}
	
	
});