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


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.thumbsheetGenImageSiteGrinderCSS =
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 cssInitialized=false;
	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 changeimageonhover = "false";
	var checkLoadTimerID = null;
	var thumb = new Object();
	var hoverPath = getOption("hover_img");
	var	normalPath = getOption("norm_img");
	var	currentPath = getOption("current_img");
	this.sheetPreviouslySelected = false;
	var numThumbs = docent.getExhibitCount();
	var align = 'center';
	var marginH = 0;
	var marginV = 0;
	if(sheetMode!='exhibit') {numThumbs = docent.getNumViews();}
	var thumbsTotalWidth = 0;
	
	
	this.select = function (thumbnum) {
		// called whenever a new image is selected to sync
		// could be called becuase a thumb (including this one) is clicked
		// or for any other reason the docent wants, like next/prev buttons.
		
		// don't do anything if already synced 
		
		
		// If not synced then hilite apropriate thumb if necessary
		// and dehilite others if necessary
		var curThumb=0;
		if(sheetMode=='exhibit') { curThumb = docent.getCurrentExhibit(); }
		else { v = docent.getCurrentView(); }
		docent.sgconsole("thubsheet select called with " + thumbnum + ' curthumb: '+curThumb);
		if (thumbnum != curThumb || !that.sheetPreviouslySelected) {
			sheetPreviouslySelected = true;
			$ml('#' + sheetDivID + ' a').css('background-image', 'url(' + normalPath + ')');
			$ml('#' + sheetDivID + ' a').unbind('mouseenter');
			$ml('#' + sheetDivID + ' a').unbind('mouseleave');
			$ml('#' + sheetDivID + ' a').bind('mouseenter', function(){
				$ml(this).css('background-image', 'url(' + hoverPath + ')');
			})
			$ml('#' + sheetDivID + ' a').bind('mouseleave', function(){
				$ml(this).css('background-image', 'url(' + normalPath + ')');
			})
			
			$ml('#' + sheetDivID + ' a:eq(' + thumbnum + ')').css('background-image', 'url(' + currentPath + ')');
			$ml('#' + sheetDivID + ' a:eq(' + thumbnum + ')').css('cursor', 'default');
			$ml('#' + sheetDivID + ' a:eq(' + thumbnum + ')').unbind('mouseenter');
			$ml('#' + sheetDivID + ' a:eq(' + thumbnum + ')').unbind('mouseleave');
		}
		//initSheet();
	}
	
	function mouseEnter(element) {
		
	}
	function mouseLeave(element) {
		
	}
	
	function getAThumb(thumbnum, bkgdURL) {
		var tdiv = "";
		
		// Thumb div
		//tdiv += '<div class="'+ thumbDivID + '">';
		var curThumb=0;
		var humanizedNum = thumbnum+1;
		
			tdiv += '<a '
			tdiv += 'href="#" onclick="';
			tdiv += docent.getName() + '.selectThumb(' + thumbnum + ',\''+sheetMode+'\',true);return false;"';
			tdiv += '></a>';
		// Thumb anchor
		
		// Close thumb div
//		tdiv += '</div>';
		
		docent.sgconsole ("Adding thumb div: " + tdiv);
		return tdiv;
	}
	
	
	function init() {
		docent.sgconsole("SG Generic Image Thumbsheet: Init", this);
		if(getOption("type")!="thumbsheetGenImageSiteGrinderCSS") { docent.sgconsole("Type mismatch between thumbsheet javascript(thumbsheetGenImageSiteGrinderCSS) and data ("+getOption("type")+")"); return;}
		if(getOption("version") > 1.0) { docent.sgconole("Thumbsheet javascript version older than data version!"); return;}
		processXML();
		preload();
	}
	
	function preload() {
		docent.sgconsole("preloading gen images");
		thumb.hover = new Object();
		thumb.hover.image = new Image();
		thumb.hover.image.src = hoverPath;
		
		thumb.normal = new Object();
		thumb.normal.image = new Image();
		thumb.normal.image.src = normalPath;
		
		thumb.current = new Object();
		thumb.current.image = new Image();
		thumb.current.image.src = currentPath;
		
		checkLoad();
	}
	
	function checkLoad() {
		//docent.sgconsole("checkload");
		if(thumb.current.image.width != 0 &&
		thumb.normal.image.width != 0 &&
		thumb.hover.image.width != 0) {
			initSheet();
		}
		else {
			checkLoadTimerID = setTimeout(checkLoad,10);
		}
	}
	
	 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();
		sheetWidth = getOption("sheetwidth");
		sheetHeight = getOption("sheetheight");
		thumbWidth = getOption("thumbwidth");
		thumbHeight = getOption("thumbheight");
		sheetDivID = getOption("sheetdivname");
		thumbDivID = getOption("thumbdivname");
		linkClass = getOption("linkclassname");
		changeimageonhover = getOption("changeimageonhover");
		
		hoverPath = docent.url2CssUrl(getOption("hover_img")); docent.sgconsole(hoverPath);
		normalPath = docent.url2CssUrl(getOption("norm_img"));docent.sgconsole(normalPath);
		currentPath = docent.url2CssUrl(getOption("current_img"));docent.sgconsole(currentPath);

		align=getOption('alignment');
		marginH=getOption('hspacing');
		marginV=getOption('vspacing');
		
//		sheetWidth = $ml('#'+sheetDivID).width(); //("sheetwidth");
//		sheetHeight = $ml('#'+sheetDivID).height();

		return;
	}
		
	this.updateSheet = function() {
		initSheet();
	}
	
	this.getAThumbIterator = function(n,data,url){
		data.containerText += getAThumb(n,url);
	}
	
	this.calcWidth = function() {
		var myWidth = thumb.normal.image.width * numThumbs;
		myWidth += marginH*numThumbs;
		if (myWidth > sheetWidth) { myWidth = sheetWidth; }
		return myWidth;
	}

// New version of initsheet using docent iterator

	function initSheet () { 
		initSheetCSS();
		var data = new Object();
		thumbsTotalWidth = that.calcWidth();
		docent.sgconsole('total thumbs width = ' + thumbsTotalWidth);
		data.containerText = "";
	    var alignString = "";
		if(align=='right') { alignString = 'margin-left:auto;'; }
		else if(align=='center') { alignString = 'margin-left:auto;margin-right:auto;'; }
		data.containerText += "<div style="+alignString+"width:"+thumbsTotalWidth+"px;'>";
		// 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>"
		data.containerText += '<div style="clear:left"></div>';
		$ml("div#"+sheetDivID).css("height","");  // get rid of height for growing
		$ml("#"+sheetDivID).html(data.containerText);
		var curThumb=0;
		if(sheetMode=='exhibit') { curThumb = docent.getCurrentExhibit(); }
		else { curThumb = docent.getCurrentView(); }
		that.select(curThumb);
		if(typeof doResize == 'function') { doResize(null,null); }
		$ml('#'+sheetDivID + ' a').css('outline','none');

	}

	function initSheetCSS() {
		if(!cssInitialized) {
			var ruleObj = {};
//			var aAndStrong ="border: 1px solid #CCDBE4; display:block; float:left; margin: 5px 5px 5px 5px; padding: 10px 30px; text-align:center; text-decoration:none;";
			ruleObj["#"+sheetDivID+" a"]=[getAnchorNormalStyle() ];
		//	ruleObj["#"+sheetDivID+" a:hover"]=[getAnchorHoverStyle()];
			
		//	ruleObj["#"+sheetDivID+" strong"]=[getCurrentPageStyle()];
			
			$ml.cssRule(ruleObj);
			cssInitialized = true;
		}		
	}
	
	function getAnchorNormalStyle() {
	    var s='';
		s+='display:block;float:left;';
		s+='margin:'+marginV+'px 0 0 '+marginH+'px;';
		s+='padding:0;';
		s+='width:'+ thumb.normal.image.width +'px;height:'+ thumb.normal.image.height +'px;';
		s+="background-position:50% 50%;background-repeat:no-repeat;";
//		s+="background-image:'url("+normalPath+")';background-position:50% 50%;background-repeat:no-repeat;";
		docent.sgconsole(s);
		return s;
	}
	function getAnchorHoverStyle() {
	    var s='';
		s+='background-image:'+ 'url('+hoverPath+');';
		docent.sgconsole(s);
		return s;
	}
	function getCurrentPageStyle() {
	    var s='';
		s+='background-image:'+ 'url('+currentPath+');';
		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;
	}
	
	function getOption(opt) {
		var w = docent.getThumbSheetOption(sheetMode,opt);
		//var w = $ml('option[varname='+opt+']', options).attr("value");
		return w;
	}
		
		
	init();
}
