/**
 *    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.pictureboxAmenKFlash = function(pictureboxXMLIn, docentIn){

	////
	////		"PRIVATE" Variables
	////
	
	var that = this;  		// store for when object scope isn't available
	var debug = false;  	// use to turn on or off debug alerts
	var docent = docentIn;  // Actual docent object
	docent.sgconsole("Constructing sg flash picturebox");
	var xml = pictureboxXMLIn;
	
	var timerID = 0;		  // used for async waiting for Flash movie to load
	var intervalTicks = 1000; // frequency of checking.  Shorten this for final build.
	
	//
	// var flashName:
	//
	// Flash embed object name/id for swfobject to set.
	// It is then used to get the browser object reference.
	// (Why isn't that just returned from swfobject.embedSWF()?  I have no idea.)
	// It is initialized in initPictureBox() to be "flashmovie" + a unique ID. 
	//
	
	var flashName = "not set yet";			

	//
	// Below options will come from xml.  See processXML()
	//
	
	var myWidth = 0;
	var myHeight = 0;
	var flashFileName = "not set yet";		// Actual file path of Flash movie for swfobject
	var flashBrowserRef = "not set yet";	// cached reference to Flash browser object to use for function calling
	var myDivID = "not set yet";
	var myClickAction = "not set yet";
	var myHoverAction = "not set yet";
	var rightClickBlock = false;
	var curImageUrl = "not set yet";
	
	// not sure if these will be needed here or just in the Flash movie
	//autoAdvance
	//autoadvancedelayms
	//autoadvancedtransitiontimems
	
	// sgalert()
	// Conditional wrapper for debug alerts
	// This was in docent but for some reason I decided each routine needed it's own/
	// 
	// docent.sgconsole() is less obtrusive, but only works in Firefox
	//
	var sgalert = function(msg){
		if (debug) {
			alert(msg);
		}
	};
	
	
	////
	////		"PRIVATE" functions
	////
	
	
	//
	// getPictureboxQuery()
	//
	// Returns jQuery string for getting the picturebox div element.
	// If HTML structure changes just chage this.
	// 
	
	function getPictureboxQuery() {
		// sample : '#divname img'
		return '#'+myDivID+' img';
	}
	
	//
	// getUrlFromNum
	//
	// Given zero-based exhibit and view ordinals returns the picturebox image URL
	// This might be better moved to the docent.
	//
	
	function getUrlFromNum(exhibitNum, viewNum){
		return $ml('exhibits exhibit:eq('+ exhibitNum +') views view:eq('+ viewNum +') picturebox url',xml).text();
	}
	
	//
	// waitForFlashLoad
	//
	// Use some docent utility routines to check if Flash movie is loaded
	//
	
 	function waitForFlashLoad () {
		
		if (docent.flashMovieIsLoaded(docent.getFlashMovie(flashName))) {
			clearInterval(timerID);
			that.flashLoaded();
		}
		else { docent.sgconsole("Flash not loaded yet!"); }
	}

	//
	// initPictureBox
	//
	// Create the picturebox element and inject it into the DOM
	//

	function initPictureBox() {
		
		
		// Set up Flash container uing swfobject()
		var flashvars = {};
		
		var params = {};
		params.allowScriptAccess = "always";
		params.scaleMode = "noScale";
		params.wmode = "transparent";
		
		var d = new Date(); // for constructing a unique name
		flashName = "flashmovie" + d.getTime();
		docent.sgconsole("naming picturebox move " + flashName);
		
		// add internal div for flash embed to replace
		//var innerDivID = myDivID + "flash";
		$ml('#'+myDivID).html('<div id="'+flashName+'"><p></p></div>');

		var attributes = {};
		attributes.id = flashName;
//		attributes.id = myDivID;
		attributes.NAME=flashName;
		docent.sgconsole("Calling swfobject with " + flashFileName + " " + flashName);
//		swfobject.embedSWF(flashFileName, myDivID, myWidth, myHeight, "9.0.0", false, flashvars, params, attributes);
		swfobject.embedSWF(flashFileName, flashName, myWidth, myHeight, "9.0.0", false, flashvars, params, attributes);
		
		// Set up timer to intialize Flash movie once it loads
		timerID = setInterval ( waitForFlashLoad, intervalTicks );// hey
	}
	
	//
	// myClick
	//
	// Click event handler.  Probably not used by Flash.  (Can embeds have javascript click events?)
	//

	function myClick(e) { 
		//return docent.pictureboxClick(myClickAction,e);
	}
	
	// init()
	//
	// Check environment to make sure everything we need is available
	//    If something isn't right give a useful error
	//    If everything is good hand off to processXML() and initPictureBox()
	//
	function init() {
		sgalert("SG Flash Picturebox: Init", this);
		
		if(xml==undefined || xml==null) { docent.sgconsole("Picturebox got bad xml!!")};
		
		if(!window.swfobject) { docent.sgconsole("Error - Missing javascript: swfobject")};
		//if(!window.jQuery) { docent.sgconsole("Error - Missing javascript: jquery")};
		
		if(getOption("type")!="sitegrinderflashAmenK") { docent.sgconsole("Type mismatch between picturebox (sitegrinderflashAmenK) javascript and data ("+getOption("type")+")!"); return;}
		if(getOption("version") > 1.0) { docent.sgconsole("Picturebox javascript version older than data version!"); return;}
		
		processXML();
		if (numExhibits > 0) {
			initPictureBox();
		}
	}
	
	// processXML
	//
	// Slurp all options and other useful stuff out of the xml so we don't have
	// to parse every time we want something
	//
	function processXML () {
		sgalert("SG Flash Picturebox: processXML", this);
		
		numExhibits = docent.getExhibitCount();
		
		flashFileName = getOption("filename");
		myDivID = getOption("divname");
		myWidth = $ml('#'+myDivID).width(); //getOption("width");
		myHeight = $ml('#'+myDivID).height();
		myClickAction = getOption("clickaction");
		myHoverAction = getOption("hoveraction");
	
		return;
	}
	
	// getOption
	//	
	// Get a picturebox option from the XML.
	// If xml format changes just change this.
	//
	function getOption(opt) {
		var w = $ml('options > picturebox > option[varname='+opt+']', xml).attr("value");
		if(w==null || w=="" || w==undefined) { docent.sgconsole("Picturebox option '" + opt + "'not found in XML!!"); }
		return w;
	}

	
	
	////
	////		"PUBLIC" methods
	////
	
	
	// getRightClickBlock()
	//
	// Accessor to determine if we are blocking right click to save.
	// Not relevant to Flash pbox, so always returns false
	//
	
	this.getRightClickBlock = function () { return false; }
	
	// displayByUrl()
	//
	// Tell pbox to display a certain URL, provided as a string
	//	
	
	this.displayByUrl = function(imageUrl) { flashBrowserRef.displayFromURL(imageUrl); 	}
	
	// displayByNum()
	//
	// Tell pbox to display an image by finding it in the XML
	// using Zero-Based exhibit and view ordinals.
	//	
	
	this.displayByNum = function(exhibitNum, viewNum) {
		var dispUrl = getUrlFromNum(exhibitNum,viewNum);
		docent.sgconsole("displayByNum: " + exhibitNum  + " " + dispUrl);
		flashBrowserRef.displayByNum(exhibitNum, viewNum);
//		flashBrowserRef.displayByUrl(dispUrl);
	}
	
	function prepareAmenKXML() {
		var xs = "<images>";
		$ml('exhibit', xml).each(function(n){
			//sgalert($ml('views > view > thumbnail > url',this).length);
			//sgalert($ml('views > view > thumbnail > url',this).eq(0).text());
			var newThumb = $ml('views > view > picturebox > url', this).eq(0).text();
			xs+="<img>";
			xs+=newThumb;
			xs+="</img>";
		});
		xs+="</images>";
		return xs;
	}		
	
	// flashLoaded()
	//
	// Called when Flash movie is finally loaded to
	// finish setting it up.  Should probably be private,
	// but not sure if timer could call it if it were.
	//	
	
	this.flashLoaded = function () {
		flashBrowserRef = docent.getFlashMovie(flashName);
		docent.sgconsole("Flashpbox : found movie " + flashName + " " + flashBrowserRef);
//		flashBrowserRef.initWithXML(prepareAmenKXML(), docent.getName(), flashName, docent.getCurrentExhibit(), docent.getCurrentView());
		flashBrowserRef.initWithXML($ml(xml).toXML(), docent.getName(), flashName, docent.getCurrentExhibit(), docent.getCurrentView());
		
		// not used yet...there for load delay problems if any crop up
		docent.pictureboxReady();
	}
	
	// Start the whole house of cards going!
	init();
}




