// -----------------------------------------------------------------------------------
//
//  jsir v1.0
//  by Jeffrey Sambells <jeff@wecreate.com>
//  Copyright (c) 2006 Jeffrey Sambells (http://jeffreysambels.com)
//
//  For more information visit:
//  http://jeffreysambells.com/openprojects/JavaScript/jsir/
//
//  Licensed under the Creative Commons Attribution 2.5 License
//  http://creativecommons.org/licenses/by/2.5/
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
//  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.//
//
// -----------------------------------------------------------------------------------

(function(){

var jsir = {
	version: 1,
	loaded:false,
	root:null,
	engine:null,
	classNameReplaced:'jsirReplaced',
	load: function() {
		//setup the properties...
		//this script has already loaded or lese it woulnd't be running
		//so we'll get the root path from the script.src
		var arrScripts = document.getElementsByTagName("script");
		var path = false;
		var altEngine = false;
		for(var i=0; i<arrScripts.length; i++){
			oScript = arrScripts[i];
			if(oScript.src && oScript.src.match(/jsir\.js(\?.*)?$/)) {
				path = oScript.src.replace(/jsir\.js(\?.*)?$/,'');
				altEngine = oScript.src.match(/\?.*engine=(.*)/);
				break;
			}
		}
		if(!path) throw("jsir could not determine where it is loaded.");
		jsir.root = path;
		jsir.engine = ( altEngine ? altEngine : '.php?l=' );
	},

	replace: function(strTagName,strClassName) {
		//check for W3CDOM compliance
		if(!(document.getElementsByTagName && document.createElement)) return false;

		//load the object if it's not already loaded
		//effectivly simulates window.onload without specifying window.onload
		if(!jsir.loaded) jsir.load();

		if(typeof strTagName == 'object') {
			//was probably called using addEvent(window,'load',jsir.replace); so use the defaults
			strTagName = '*';
			strClassName = '';
		}

		try {
			//check the className to search for
			strClassName = (strClassName ? strClassName : 'jsirReplace');

			//check the tag name to search for
			//TODO: allow an array of tag names?
			strTagName = (strTagName ? strTagName.toUpperCase() : '*' );
			var arrElements = document.getElementsByTagName(strTagName);
			strClassName = strClassName.replace(/\-/g, "\\-");

			//use a Regex so that we catch the full string not a substring.
			var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");


			var oElm;
			for(var i=0; i<arrElements.length; i++){
				oElm = arrElements[i];
				if(!oElm.className) continue;

				//Does the class name match?
				if(oRegExp.test(oElm.className) && !oElm.className.match('jsirReplaced')){
					//create the URL for the image based on the location of this script adn the defined engine
					var strSrc = jsir.root
						+ 'generator/'
						+ oElm.nodeName.toLowerCase()
						+ jsir.engine
						+ escape(oElm.innerHTML)
						+ '&className='
						+ escape(oElm.className);
					//do the actualy assignment in an alternate method to maintain proper scope.
					jsir.assignImage(oElm,strSrc,strClassName);
				}
			}
		} catch(e) {
			JSLog.write(e);
		}
	},

	assignImage: function(oElm,strSrc) {
		/*
		Load an Image() object to pre-determin the width and height of the image.

		Properties
		    * border - The width of the border around the image in pixels.
		    * complete - A boolean value which identifies whether an image is completely loaded yet.
		    * height - The read only height of the image in pixels.
		    * hspace - The read only amount of horizontal space to the left and right sides of the image.
		    * lowsrc - The read or write string giving the URL of an alternate image for low resolution screen display.
		    * name - The assigned name of the image.
		    * prototype - Used for adding user-specified properties to the image.
		    * src - The URL of the image to be displayed. It is a read/write string.
		    * vspace - The read only vertical space above and below the image.
		    * width - The read only width of the image in pixels.

		Events
		    * onAbort
		    * onError
		    * onLoad
		*/

		var oImage = new Image();
		oImage.onload = function(event) {
			//create a container div to hold the current contents of the oElm
			var oContainer = document.createElement('DIV');

			//hide it as we won;t want to see it
			oContainer.style.visibility = 'hidden';

			//Move all the children from oElm to oContainer
			for( var i = 0; i < oElm.childNodes.length; i++ ) {
				//because we're not using clone, this is actually moving the
				//node from oElm to oContainer so we need not remove it from oElm
				oContainer.appendChild(oElm.childNodes[i]);
			}

			//append oContainer to oElm so it's still there is CSS is disabled
			oElm.appendChild(oContainer);

			//make sure oElm a block element so width and height apply.
			//oElm.style.display = '-moz-inline-box';
			//oElm.style.display = 'inline-block';
			oElm.style.visibility = 'visible';
			oElm.style.overflow = 'hidden';

			//oElm.style.border = '1px solid red';

			//set the height based on the loaded image
			//TODO: add the padding...
			//TRICKY: I was using this.height which worked fine in IE and FF but
			//in safari 'this' refers to the window object, not the image so use oImage instead
			//thought: maybe alternativly use the event's target?
			oElm.style.height = oImage.height + 'px';
			oElm.style.width = oImage.width + 'px';
			//( this.height + parseInt(oElm.style.paddingTop,10) + parseInt(oElm.style.paddingBottom,10) )

			oElm.className += ' ' + jsir.classNameReplaced;

			if(oElm.filters) {
				//Set the background in IE to accomodate IE PNG stuff
				//This could cause problem for clikability on object in oELm, but since we hide
				//the content anyways, it won't matter.
				//(need to add a flag to check if the image is a PNG somehow?)
				oElm.style.backgroundColor = 'transparent';
				oElm.style.backgroundImage = 'url(/blank.gif)';
				oElm.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + strSrc + "',sizingMethod='scale')";
			} else {
				//set the background for all other browsers
				//(assumes all other support transparent PNG files)
				oElm.style.background='transparent url(' + strSrc + ') no-repeat';
			}
		}
		oImage.onerror = function() {
			//do nothing since there was no image loaded.
			if(JSLog) JSLog.write('Error: ' + this.src);
		}
		oImage.onabort = function() {
			//do nothing since there was no image loaded.
			if(JSLog) JSLog.write('Aborted: ' + this.src);
		}

		//assign the src (it will then load it and trigger the above events)
		oImage.src = strSrc;
	}
}

window['jsir'] = jsir;

})();



