/**
 *    Copyright (c) 2009-2010, As Is Software, dba Media Lab Inc.
 *    http://www.medialab.com
 */

/*
 * 	Notes:
 * 	1. Nice HTML thumbsheet here: http://plt-scheme.org/screenshots/
 */

var com;
if(!com) { com = {}; } else if(typeof(com) != "object") { throw new Error("can't initialize...com is not an object."); }
if(!com.medialab) { com.medialab = {}; } else if(typeof(com.medialab) != "object") { throw new Error("can't initialize...com.medialab is not an object."); }
if(!com.medialab.sg) { com.medialab.sg = {}; }
if (!com.medialab.sg.gallery1) { com.medialab.sg.gallery1 = {};}


com.medialab.sg.gallery1.thumbsheetSiteGrinderCSS =
function (thumbSheetXMLIn, modeIn, docentIn) { 
	var that=this;
	var debug = false;
	var sgalert = function(msg) { if (debug) {
		alert(msg);
	} };
	var docent= docentIn;

	//alert(docentIn);
	var xml = thumbSheetXMLIn;
	var clickAction = "picturebox";
	var hoverAction = "none";
	var thumbWidth = 0;
	var thumbHeight = 0;
	var sheetWidth = 0;
	var sheetHeight = 0;
	var sheetMode = modeIn;
	var sheetDivID = "not set yet";
	var thumbDivID = "not set yet";
	var linkClass = "not set yet";
	var d = new Date(); // for constructing a unique name
	var previewStyleName = "imagePreview" + d.getTime();
	
	var cssInitialized=false;
	
	this.select = function (thumbnum) {		
		$ml('#' + sheetDivID + ' .it').removeClass('it');
		$ml('#' + sheetDivID + ' a:eq('+ thumbnum +')').addClass('it');
	}
	
	function getAThumb(thumbnum, bkgdURL) {
		var tdiv = "";
		var curThumb=0;
		if(sheetMode=='exhibit') { curThumb = docent.getCurrentExhibit(); }
		else { curThumb = docent.getCurrentView(); }
		var className = "notit";
		if(curThumb==thumbnum) { className='it'; }
		
		// Thumb div
		tdiv += '<a href="#" class="'+ className + '" ';
		tdiv += 'style="background-image:url('+ bkgdURL + '); background-position: 50% 50%; background-repeat: no-repeat;" ';
		if (hoverAction == 'floatingpreview') {
			var previewUrl = "";
			if (sheetMode == 'exhibit') {
				previewUrl = docent.num2url(thumbnum, 0);
			}
			else {
				previewUrl = docent.num2url(docent.getCurrentExhibit(), thumbnum);
			}
			tdiv += ' rel="' + previewUrl + '" ';
		}
		tdiv += ' ></a>';		
		
		docent.sgconsole ("Adding thumb div: " + tdiv);
		return tdiv;
	}
	
	
	function init() {
		sgalert("SG Standard Thumbsheet: Init", this);
		if(getOption("type")!="sitegrindercss") { alert("Type mismatch between thumbsheet javascript and data!"); return;}
		if(getOption("version") > 1.0) { alert("Thumbsheet javascript version older than data version!"); return;}
		processXML();
		initSheet();
	}
	
	 function processXML () {
		sgalert("SG Standard Thumbsheet: processXML", this);
		/*
		 * we'll need to know:
		 * 
		 * 		- thumb div name prefix
		 * 		- options (scroll? change on hover?)
		 * 
		 *     1. count the thumbs (to figure out how to go page to page
		 */
		numExhibits = docent.getExhibitCount();
		sgalert("ne:"+numExhibits);
		sheetWidth = getOption('sheetwidth');
		sheetHeight = getOption('sheetHeight');
		thumbWidth = getOption("thumbwidth");
		thumbHeight = getOption("thumbheight");
		sheetDivID = getOption("sheetdivname");
		thumbDivID = getOption("thumbdivname");
		linkClass = getOption("linkclassname");
		hoverAction = getOption("hoveraction");
		clickAction = getOption("clickaction");

		return;
	}
		
	this.updateSheet = function() {
		docent.sgconsole(sheetMode + " : updateSheet");
		initSheet();
	}
	
	this.getAThumbIterator = function(n,data,url){
		data.containerText += getAThumb(n,url);
	}
	
	
	function jqClick(e) {
		var thumbNum = $ml(this).parent().children().index(this);
		docent.sgconsole('css '+ sheetMode +' thumb '+ thumbNum + ' clicked with return(false)');
		switch (clickAction) {
			case 'picturebox':
				docent.selectThumb(thumbNum,sheetMode,true);
				break;
			case 'bigbox':
				docent.selectThumb(thumbNum,sheetMode,true);
				docent.openBigbox(sheetMode);
				break;
			default:
				docent.sgconsole('css thumbs passed unknwn click action '+ clickAction);
				break;
		}
		return(false);
	}
	
	function jqHover(e) {
		var thumbNum = $ml(this).parent().children().index(this);
		docent.sgconsole('css '+ sheetMode +' thumb '+ thumbNum +' mouseover');
		switch (hoverAction) {
			case 'picturebox':
				docent.selectThumb(thumbNum,sheetMode,true);
				break;
			default:
				docent.sgconsole('css thumbs passed unknwn hover action '+ clickAction);
				break;
		}
	}

// New version of initsheet using docent iterator

	function initSheet () { 
		initSheetCSS();
		var data = new Object();
		data.containerText = "";
		// Create thumbs
		if (sheetMode == "exhibit") {
			docent.iterateExhibitThumbImageUrls(that.getAThumbIterator, data);
		}
		else {
			docent.iterateViewThumbImageUrls(that.getAThumbIterator, data, null);	// null means use current exhibit	
		}
		data.containerText += '<div class="divider"></div>';
		data.containerText += '<div style="clear:left"></div>';
		var targetDiv = $ml("#"+sheetDivID);
		$ml("div#"+sheetDivID).css("height","");  // get rid of height so we can grow (IS THIS RIGHT? div#?)
		targetDiv.html(data.containerText);
		
		if(clickAction && clickAction!='none') {
			docent.sgconsole('binding click to ' + clickAction);
			$ml("#" + sheetDivID + ' > a').bind('click',jqClick);
		}
		
		if(hoverAction && hoverAction!='none') {
			if (hoverAction == 'floatingpreview') {
				$ml('#' + sheetDivID + ' a').imgPreview({
					srcAttr: 'rel',
					containerID: previewStyleName,
					onShow: function(link){
						$ml('img', this).stop().css({
							opacity: 0
						});
					},
					onLoad: function(){
						// Animate image
						$ml(this).animate({
							opacity: 1
						}, 300);
					}
				});
			}
			else {
				docent.sgconsole('binding mouseover to ' + hoverAction);
				$ml("#" + sheetDivID + ' > a').bind('mouseover', jqHover);
			}
		}
		$ml('#'+sheetDivID + ' a').css('outline','none');
	}


	
	
	function getOption(opt) {
		var w = docent.getThumbSheetOption(sheetMode,opt);
		//var w = $ml('option[varname='+opt+']', options).attr("value");
		return w;
	}
	function initSheetCSS() {
		if(!cssInitialized) {
			var ruleObj = {};

			ruleObj["#"+sheetDivID+" a"]=[getAnchorNormalStyle() ];
			ruleObj["#"+sheetDivID+" a:hover"]=[getAnchorHoverStyle()];
			ruleObj["#"+sheetDivID+" a.it"]=[getAnchorCurrentPageStyle()];
			
			ruleObj["#"+previewStyleName] = ['z-index:1000;'];  // used for floating preview option
			$ml.cssRule(ruleObj);
			cssInitialized = true;
		}		
	}
	
	function getAnchorNormalStyle() {
	    var s='';
		s+='outline:none;';
		s+='border: '+ getBorderOptions('normal');
		s+='background:'+ getColorOption('normalbackgroundcolor') +';';
		s+=' display:block; float:left;';
		s+='margin: '+Math.round(getOption('vspacing')/2)+'px '+Math.round(getOption('hspacing')/2)+'px '+Math.round(getOption('vspacing')/2)+'px '+Math.round(getOption('hspacing')/2)+'px;'

		width = getOption('thumbwidth') + 2* getOption('hinset');
		height = getOption('thumbheight') + 2* getOption('vinset');
		s+=' width: '+ width +'px; height: '+ height +'px;';
		docent.sgconsole(s);
		return s;
	}
	function getAnchorHoverStyle() {
	    var s='';
		s+='outline:none;';
		s+='border: '+ getBorderOptions('hover');
		s+='background:'+ getColorOption('hoverbackgroundcolor') +';';
		docent.sgconsole(s);
		return s;
	}
	
	function getAnchorCurrentPageStyle() {
	    var s='';
		s+='outline:none;';
		s+='border: '+ getBorderOptions('current');
		s+='background:'+ getColorOption('currentbackgroundcolor') +';';
		s+=' display:block; float:left;';
		s+='margin: '+Math.round(getOption('vspacing')/2)+'px '+Math.round(getOption('hspacing')/2)+'px '+Math.round(getOption('vspacing')/2)+'px '+Math.round(getOption('hspacing')/2)+'px;'
		
		width = getOption('thumbwidth') + 2* getOption('hinset');
		height = getOption('thumbheight') + 2* getOption('vinset');
		s+=' width: '+ width +'px; height: '+ height +'px;';
		docent.sgconsole(s);
		return s;
	}
	 
	function getPXOption(optName) {
		var pxOpt = getOption(optName);
		if (pxOpt==undefined) { docent.sgconsole("no image thumb: px option not found!"); return "10px"; }
		else if (typeof(s)=='string' && pxOpt.substring(pxOpt.length-2)=='px') { return pxOpt; }
		else if (isNaN(pxOpt)) { docent.sgconsole("no image thumb: px option not a number!"); return "10px";}
		else { return pxOpt + 'px'; }
	}
	
    function getBorderOptions(borderType){
		var borderWidth = getOption('borderwidth');
		if (borderWidth == 0) {
			return 'none;';
		}
		else 
			return borderWidth + 'px ' + 'solid ' + getColorOption(borderType + 'bordercolor') + ';';
	}

	
    function getColorOption(optName) {
		var hexColor = getOption(optName);
		if (hexColor != undefined) {
			if (hexColor.substring(0, 1) == '#') {
				return hexColor;
			} // already css style for some reason
			else 
				if (hexColor.substring(0, 2) == '0x') {
					return '#' + hexColor.substring(2);
				}
				else 
					if (!isNaN('0x' + hexColor)) {
						return '#' + hexColor;
					}
		}
		return null;
	}
		
		
	init();
}
