// FlashZoom.js
// Started 29-Nov-2007 by Jacek
// Based on code from http://developer.mozilla.org/en/AJAX/Getting_Started

//-----------------------------------------------

// !!!!!!! YOU MAY WANT TO MODIFY THESE: !!!!!!!

// This should point to a path on your web server where swfobject.js, zoomer.swf and config.xml are
// If all files (calling html, swfobject.js, zoomer.swf, config.xml and this file) are in the same folder, you may set it to empty string
var flashZoomPath = "/merchandizer/zoom_flash/"; // Note: empty string does not work in Firefox on Mac

// Location of MediaRich server (mgen), it may be URL (http://somehost/mgen) or just /mgen if on the same server
var mediaRichLocation = "/mgen";

//-----------------------------------------------

var includeFile = flashZoomPath + "swfobject.js";
document.write('<script type="text/javascript" language="javascript" src="' + includeFile + '"></script>'); 

FlashZoom = function(stageWidthHeight, hMargins, vMargins, loadingMsg)
{
	this.hMargins = hMargins; if (!this.hMargins) this.hMargins = 0;
	this.vMargins = vMargins; if (!this.vMargins) this.vMargins = this.hMargins;
	this.verifyMargins();
	if (!stageWidthHeight) // if not specified, we will use current window size
		stageWidthHeight = this.maxContentHeight(); // need vMargins before we can call this
	this.stageWidth = parseInt(stageWidthHeight); // Flash stage width
	this.stageHeight = this.stageWidth;           // Flash stage height
	///alert("stageWidthHeight: " + stageWidthHeight);
	this.loadingMsg = loadingMsg; if (!this.loadingMsg) this.loadingMsg = "<center>Loading...<br>If it times out, wait a moment and reload the page.<br><br><font size=-2>Got Flash?</font></center>";	// message to display while we are loading
	
	this.picPath = "";
	this.picWidth = 0;
	this.picHeight = 0;
	this.lastStageWidth = 0;
	this.lastStageHeight = 0;
	this.picAspectRatio = 1.0; // width / height
	this.firstLoadDone = false;
	this.skipResizeSmallerThan = 10;
	this.skipFirstResize = 0;
	if (navigator.userAgent.indexOf('Firefox') >= 0) // Firefox call onResize, when we sizeWindowToContents, we will skip that
		this.skipFirstResize = 1;
	else if (navigator.userAgent.indexOf('MSIE') >= 0) // IE calls it twice
		this.skipFirstResize = 2;
	///alert("this.skipFirstResize = " + this.skipFirstResize);
	this.clipStageToPicSize = true;
	
	var divID = "flashZoom"; // ID of the div element SWFObject will fill (string)
	document.write("<div id=\"" + divID + "\">" + this.loadingMsg + "<\/div>");
	this.divElement = document.getElementById(divID);
	this.divElement.innerHTML = this.loadingMsg;
};

FlashZoom.prototype = 
{
	toString : function()
	{
		return "FlashZoom object (" + this.picPath + ")";
	},
	
	createHttpRequest : function()
	{
		var httpRequest = null;
		if (window.XMLHttpRequest)	// Mozilla, Safari, ...
		{
			httpRequest = new XMLHttpRequest();
		} 
		else if (window.ActiveXObject)	// IE
		{
			try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
			try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP");	} catch (e) {} }
		}
		///if (!httpRequest) alert('Cannot create HTTP request');
		return httpRequest;
	},
	
	verifyMargins : function() // Firefox has these weird minimum margins
	{
		if ((navigator.userAgent.indexOf('Firefox') >= 0) && (navigator.userAgent.indexOf('Macintosh') >= 0) &&
			window.toolbar.visible)
		{
			if (this.hMargins < 2 * 86) // minimum right is 1, but we prefer symetry
				this.hMargins = 2 * 86;
			if (this.vMargins < 2 * 9)
				this.vMargins = 2 * 9;
		}
		else if (navigator.userAgent.indexOf('MSIE') >= 0)
		{
			if (this.hMargins < 2 * 21) // minimum right is 1, but we prefer symetry
				this.hMargins = 2 * 21;
			if (this.vMargins < 2 * 27)
				this.vMargins = 2 * 27;
		}
		else
		{
			if (this.hMargins < 2 * 9) // minimum right is 1, but we prefer symetry
				this.hMargins = 2 * 9;
			if (this.vMargins < 2 * 9)
				this.vMargins = 2 * 9;
		}
	},
	
	sizeWindowToContents : function()
	{
		this.verifyMargins(); ///alert("hMargins-vMargins: " + this.hMargins + "-" + this.vMargins);
		///alert(navigator.userAgent);
		if (navigator.userAgent.indexOf('Firefox') >= 0)
		{
			if (window.toolbar.visible) // in FF, when toolbar is visible, window.innerWidth is bigger than outerWidth (and there is strangly big left margin)
			{
				///alert("outer-innerWidth, outer-innerHeight: " + window.outerWidth + "-" + window.innerWidth + ", " + window.outerHeight + "-" + window.innerHeight);
				var windowWidth = this.stageWidth + this.hMargins;
				var windowHeight = this.stageHeight + this.vMargins + (window.outerHeight - window.innerHeight);
				window.resizeTo(windowWidth, windowHeight);
			}
			else
			{
				window.sizeToContent(); // unfortunately, only FF can do this, and unfortunately only when toolbar is hidden
			}
		}
		else if (navigator.userAgent.indexOf('MSIE') > 0) // IE doesn't have window.innerWidth, outerWidth
		{
			var windowWidth = this.stageWidth + this.hMargins + 10;
			var windowHeight = this.stageHeight + this.vMargins + 152; // in IE7 (it was 70 in IE6)
			window.resizeTo(windowWidth, windowHeight);
		}
		else // Safari, ...
		{
			var windowWidth = this.stageWidth + this.hMargins + (window.outerWidth - window.innerWidth);
			var windowHeight = this.stageHeight + this.vMargins + (window.outerHeight - window.innerHeight);
			window.resizeTo(windowWidth, windowHeight);
		}
	},
			
	maxContentWidth : function()
	{
		if (typeof(window.innerWidth) == 'number') // Non-IE
			return window.innerWidth - this.hMargins;
		else if (document.documentElement && document.documentElement.clientWidth) // IE 6+ in 'standards compliant mode'
			return document.documentElement.clientWidth - this.hMargins;
		else if (document.body && document.body.clientWidth) // IE 4 compatible
			return document.body.clientWidth - this.hMargins;
		return 1440 - 16 - this.hMargins; // 1440x900 is the smallest screen we support
	},
	
	maxContentHeight : function()
	{
		if (typeof(window.innerHeight) == 'number') // Non-IE
			return window.innerHeight - this.vMargins;
		else if (document.documentElement && document.documentElement.clientHeight) // IE 6+ in 'standards compliant mode'
			return document.documentElement.clientHeight - this.vMargins;
		else if (document.body && document.body.clientHeight) // IE 4 compatible, IE7
			return document.body.clientHeight - this.vMargins;
		return 900 - 135 - this.vMargins; // 1440x900 is the smallest screen we support
	},
	
	checkStageSize : function()
	{
		if (this.clipStageToPicSize)
		{
			///alert("stage: " + this.stageWidth + "-" + this.stageHeight + ", pic: " + this.picWidth + "-" + this.picHeight);
			if (this.stageWidth > this.picWidth)
				this.stageWidth = this.picWidth
			if (this.stageHeight > this.picHeight)
				this.stageHeight = this.picHeight
		}
	},
	
	writeFlashIntoDiv : function()
	{
		if (this.picWidth != this.picHeight && this.stageWidth == this.stageHeight)
		{
			if (this.picWidth < this.picHeight)
				this.stageWidth = Math.round((this.stageWidth - 2) * this.picAspectRatio) + 2; // zoomer.swf content is 2 pixels less than the stage
			else
				this.stageHeight = Math.round((this.stageHeight - 2) / this.picAspectRatio) + 2;
			this.checkStageSize();
			if ((Math.abs(this.stageWidth - this.lastStageWidth) < this.skipResizeSmallerThan) && (Math.abs(this.stageHeight - this.lastStageHeight) < this.skipResizeSmallerThan))
				return;
			this.lastStageWidth = this.stageWidth;
			this.lastStageHeight = this.stageHeight;
		}
		else
		{
			this.checkStageSize();
		}
		this.divElement.style.width = this.stageWidth;
		this.divElement.style.height = this.stageHeight;
		this.divElement.innerHTML = this.loadingMsg;
		
		var so = new SWFObject(flashZoomPath + "zoomer.swf?configPath=" + flashZoomPath + "config.xml"
			+ "&picPath=" + this.picPath
			+ "&originalWidth=" + this.picWidth + "&originalHeight=" + this.picHeight
			+ "&contentWidth=" + (this.stageWidth-2).toString() + "&contentHeight=" + (this.stageHeight-2).toString(), // we have to provide these, since in IE, Stage.width and height are garbage
			"zoom", this.stageWidth.toString(), this.stageHeight.toString(), "6.0", "#ffffff", "high");
		so.write(this.divElement);
	},
	
	resizeWindow : function()
	{
		if (this.skipFirstResize)
		{
			--this.skipFirstResize;
			return;
		}
		///alert("in resizeWindow");
		this.verifyMargins();
		var maxWidth = this.maxContentWidth();
		var maxHeight = this.maxContentHeight();
		var windowAspectRatio = maxWidth / maxHeight;
		var stageWidthHeight;
		if (this.picAspectRatio > 1)
			stageWidthHeight = this.picAspectRatio > windowAspectRatio ? maxWidth : Math.floor(maxWidth * this.picAspectRatio/windowAspectRatio);
		else
			stageWidthHeight = this.picAspectRatio < windowAspectRatio ? maxHeight : Math.floor(maxHeight * windowAspectRatio/this.picAspectRatio);
		if (stageWidthHeight <= 0) { alert("stageWidthHeight is " + stageWidthHeight); return; }

		this.stageWidth = stageWidthHeight;
		this.stageHeight = stageWidthHeight;
		this.writeFlashIntoDiv();
	},

	loadFlash : function()
	{
		this.writeFlashIntoDiv();
		if (!this.firstLoadDone)
		{
			this.sizeWindowToContents();
			window.fz = this;
			window.onresize = function() { this.fz.resizeWindow.call(this.fz); } // we set it here, so it doesn't get called until we are done loading and adjusting (sizing) to contents
			this.firstLoadDone = true;
		}
	},
	
	stdCreateImageResponseHandler : function(responseText) // MR will create the image and return its path and size as text
	{
		var response = responseText.split(","); if (response.length != 3) { alert("Bad response to MediaRich request\n" + responseText); return; }
		this.picPath = mediaRichLocation + "/" + response[0];
		this.picWidth = parseInt(response[1]);
		this.picHeight = parseInt(response[2]);
		this.picAspectRatio = this.picWidth / this.picHeight;
		this.loadFlash.call(this);
	},
	
	stdGetImageSizeResponseHandler : function(responseText)
	{
		var response = responseText.split(","); if (response.length != 2) { alert("Bad response to MediaRich request\n" + responseText); return; }
		this.picWidth = parseInt(response[0]);
		this.picHeight = parseInt(response[1]);
		this.picAspectRatio = this.picWidth / this.picHeight;
		this.loadFlash.call(this);
	},
	
	handleHttpResponse : function(httpRequest)
	{
		///alert("handleHttpResponse, readyState = " + httpRequest.readyState);
		try
		{
			if (httpRequest.readyState != 4) { return; }
			if (httpRequest.status != 200) { alert("httpRequest.status: " + httpRequest.status); return; }
			httpRequest.responseHandler.call(httpRequest.obj, httpRequest.responseText);
		}
		catch(e)
		{
			alert("Error handling HTTP response: " + e.description);
		}
	},
	
	SendHttpRequest : function(mrl, responseHandler, obj)
	{
		///alert("SendHttpRequest");
		var httpRequest = this.createHttpRequest(); if (!httpRequest) { alert("Could not create httpRequest"); return; }
		httpRequest.fz = this;
		httpRequest.obj = obj;
		httpRequest.responseHandler = responseHandler;
		httpRequest.onreadystatechange = function() { this.fz.handleHttpResponse(httpRequest) };
		httpRequest.open('GET', mrl, true);
		httpRequest.send('');
	},
	
	DontResize : function() // call this before Load/CreateAndLoad to prevent auto-sizing and resizing-with-window
	{
		this.firstLoadDone = true;
	},
	
	CreateAndLoad : function(createImageMrl, responseHandler, obj) // CreateAndLoad and Load are mutually exclusive
	{
		if (responseHandler && obj)
			this.SendHttpRequest(createImageMrl, responseHandler, obj);
		else
			this.SendHttpRequest(createImageMrl, this.stdCreateImageResponseHandler, this);
	},
	
	Load : function(mrImagePath) // CreateAndLoad and Load are mutually exclusive
	{
		this.picPath = mediaRichLocation + "/" + mrImagePath;
		///alert("picWidth, picHeight = " + this.picWidth + ", " + this.picHeight);
		if (!this.picWidth || !this.picHeight)
		{
			var getImageSizeMrl = mediaRichLocation + "?gis=" + mrImagePath;
			this.SendHttpRequest(getImageSizeMrl, this.stdGetImageSizeResponseHandler, this);
		}
		else
		{
			this.loadFlash.call(this);
		}
	}
};

/***
function stdCreateImageResponseHandler(fz, responseText) // MR will create the image and return its path and size as text
{
	var response = responseText.split(","); if (response.length != 3) { alert("Bad response to MediaRich request\n" + responseText); return; }
	fz.picPath = mediaRichLocation + "/" + response[0];
	fz.picWidth = response[1];
	fz.picHeight = response[2];
	fz.picAspectRatio = fz.picWidth / fz.picHeight;
	fz.loadFlash.call(fz);
}

function stdGetImageSizeResponseHandler(fz, responseText)
{
	alert("this = " + this);
	var response = responseText.split(","); if (response.length != 2) { alert("Bad response to MediaRich request\n" + responseText); return; }
	fz.picWidth = response[0];
	fz.picHeight = response[1];
	fz.picAspectRatio = fz.picWidth / fz.picHeight;
	fz.loadFlash.call(fz);
}
***/
