/*
	Lightbox JS: Fullsize Image Overlays 
	by Lokesh Dhakar - http://www.huddletogether.com

	For more information on this script, visit:
	http://huddletogether.com/projects/lightbox/

	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
	(basically, do anything you want, just leave my name and link)
	
	Table of Contents
	-----------------
	Configuration
	
	Functions
	- getPageScroll()
	- getPageSize()
	- pause()
	- getKey()
	- listenKey()
	- showLightbox()
	- hideLightbox()
	- initLightbox()
	- addLoadEvent()
	
	Function Calls
	- addLoadEvent(initLightbox)

*/
//
// Configuration
//

// If you would like to use a custom loading image or close button reference them in the next two lines.
var lightbox = {};

//Change CSS setting in element property.
var CSSClass = {};

var loadingImage = 'loading.gif';		
var closeButton = 'close.gif';
var debug = false;
var lightboxUseTinymce = false;
lightbox.OrgiX = null;
lightbox.OrigY = null;
var overlay;
var lightboxbody;
var lightboxtitle;
var lightboxform;
var lightboxad;

		
// *********************************** Coding by James.
lightbox.backToOrigXY = function()
{
	lightboxbody.style.left = lightbox.OrigX + 'px';
	lightboxbody.style.top = lightbox.OrigY + 'px';
};

lightbox.getOrigXY = function()
{

	var lightboxX = lightboxbody.style.left;
	var lightboxY = lightboxbody.style.top;
	if(isNaN(lightboxX))
	{
    	var i = lightboxX.length;
   		var j = lightboxX.indexOf('px');
   	
    	lightbox.OrigX = lightboxX.slice(0, j - i);
		if(debug)alert(lightboxX);
	}
	lightbox.OrigX = parseInt(lightbox.OrigX);
	if(isNaN(lightboxY))
	{
    	var i = lightboxY.length;
   		var j = lightboxY.indexOf('px');
   	
   		lightbox.OrigY = lightboxY.slice(0, j - i);
		if(debug)alert(lightboxY);
	}
	lightbox.OrigY = parseInt(lightbox.OrigY);

};

// classname can have query value like  name=value&name1=value1&name2=value2 
lightbox.reset = function(conf)
{
	var params;
	
	if (typeof(conf.theme) == 'undefined' || conf.theme == ""){
		conf.theme = 'lightbox';
	}
	CSSClass.remove($('lightbox'));
	CSSClass.add($('lightbox'),conf.theme);
	if (typeof(conf.width) == 'string')	lightboxbody.style.width = conf.width;
	if (typeof(conf.height) == 'string') lightboxbody.style.height = conf.height;
	
	//if (typeof(conf.title) == 'string'){
		//lightboxtitle.innerHTML = conf.title;
		
	//}else{
		//lightboxtitle.innerHTML = 'NULL';
	//}
};

lightbox.setPosition = function()
{
	var arrayPageSize = getPageSize();
	// [0]pageWidth  [1]pageHeight  [2]windowWidth  [3]windowHeight
	var arrayPageScroll = getPageScroll();
	// [0]xScrollLength  [1]yScrollLength

	//Reset the overlay's windth and height to fit document size.
	overlay.style.width = arrayPageSize[0] + 'px';
	overlay.style.height = arrayPageSize[1] + 'px';
	
	var x = CSSClass.getDigit(lightboxbody.style.width);
	if(x <=0) x = lightboxbody.clientWidth;
	if(x > arrayPageSize[2])
	{
		lightboxbody.style.left = '0px';
	}
	else
	{
		lightboxbody.style.left = (((arrayPageSize[2] - x) / 2)) + 'px';
	}
	//if(Actions.OrigX)Actions.OrigX = CSSClass.getDigit(lightbox.style.left);
	
	var y = CSSClass.getDigit(lightboxbody.style.height);
	if(y <= 0) y = lightboxbody.clientHeight;
	if(y > arrayPageSize[3])
	{
		lightboxbody.style.top = '0px';
	}
	else
	{
		lightboxbody.style.top = (((arrayPageSize[3] - y) / 2) + arrayPageScroll[1]) + 'px';
	}
	//if(Actions.OrigY)Actions.OrigY = CSSClass.getDigit(lightbox.style.top);
};


//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
lightbox.show = function(objLink)
{
	var css = objLink.getAttribute('css');
	var url = objLink.getAttribute('href');
	// prep objects
	var  conf = objLink.getAttribute('conf').evalJSON();
	// center loadingImage if it exists
	var objLoadingImage = document.getElementById('loadingImage');
	if (objLoadingImage) 
	{
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}
		// A small pause between the image loading and displaying is required with IE,
		// this prevents the previous image displaying for a short burst causing flicker.
	if (navigator.appVersion.indexOf("MSIE")!=-1)
	{
		Actions.pause(250);
	} 
	overlay.style.display = 'block';

	if(conf)
	{
		lightbox.reset(conf);
	}
	lightbox.setPosition();
	lightbox.getOrigXY();
	if(url)
	{
		//res = new Ajax.Updater({success: 'lightboxform',failure: 'lightboxform'}, url, {asynchronous:true, evalScripts: true});
		new Ajax.Request(url, {method : 'post', asynchronous : true, evalScripts : true, 
			onComplete: function(transport) {
			var response = 	transport.responseText;
			var receiver = $('lightboxform');
			receiver.update(response);
			// set height of Overlay to take up whole page and show

			 //objLightbox.style.display = 'block';
		
			lightboxbody.style.visibility = 'visible';
	
			lightboxtitle.style.display = 'block';

			lightboxform.style.display = 'block';

			lightboxad.style.display = 'block';

			objLoadingImage.style.display = 'none';
			}, onLoading : function(){}});
	}
};

//
// hideLightbox()
//
lightbox.hide = function()
{
	// hide lightbox and overlay
	overlay.style.display = 'none';
	lightboxbody.style.visibility= 'hidden';
		if (lightboxUseTinymce){
	document.getElementById('lightboxform').innerHTML = '';

	if (typeof(tinyMCE) != 'undefined'){	
		objIFrame = document.getElementsByTagName('iframe');
		for (var i=0; i < objIFrame.length; i++) {
			if (objIFrame[i].id.indexOf('mce_editor') != -1){
				tinyMCE.removeMCEControl(objIFrame[i].id);
			}
		}
		tinyMCE.idCounter = 0;

	}	
	}
	};

lightbox.check = function(e)
{
	if(typeof e != "string")
	{
		return false;
	}
	var divs = ['overlay', 'lightbox', 'lightboxtitle', 'lightboxform', 'lightboxad'];
	for(var i in divs)
	{
		if(e == divs[i])
		{
			return true;
		}
	}
	return false;
};

CSSClass.getDigit = function(v)
{
	var k;
	if(isNaN(v))
	{
	   	var i = v.length;
    	var j = v.indexOf('px');
    	
	   	k = v.slice(0, j - i);
		k = parseInt(k);
		//if(debug)alert(lightboxX);
	}
	if(!k)
	{
		return 0;
	}
	else
	{
		return k;
	}
};

CSSClass.is = function(e, c)
{
	var classes = e.className;
	//alert("c=" + c + "\n classes =" + classes);
	if(classes == "")
	{
		return false;
	}
	if(classes == c)
	{
		return true;
	}
	else
	{
		CSSClass.remove(e, classes);
		return false;
	}
	
	//Otherwise, use a regular expression to search for c as a word by itself
	// \b in a regular expression requires a mtch at a word boundary.
	// return e.className.search("\\b" + c + "\b") != 1;
};

CSSClass.add = function(e, c)
{
	if(typeof e == "string")e = document.getElementById(e);
	//if(CSSClass.is(e, c))return;
	if(e.className)c = " " + c;
	e.className += c;
	var validate;
};

CSSClass.remove = function(e, c)
{
	if(typeof e == "string")
	{
		e = document.getElementById(e);
		// Search the className for all occurrences of c and replace with "".
		// \s* matches any number of whitespace characters.
		// "g" makes the regular expression match any number of occurrences
		e.className = e.className.replace(new RegExp("\\b" + c + "\\b\\s*", "g"), "");
	}
	else
	{
		e.className = e.className.replace(new RegExp("\\b" + c + "\\b\\s*", "g"), "");
	}
};
// ***************************************End of coding
//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll()
{
	var yScroll;

	if (self.pageYOffset) 
	{
		yScroll = self.pageYOffset;
	} 
	else if (document.documentElement && document.documentElement.scrollTop)
	{	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} 
	else if (document.body) 
	{// all other Explorers
		yScroll = document.body.scrollTop;
	}
	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize()
{	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) 
	{	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} 
	else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} 
	else 
	{ // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) 
	{	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} 
	else if (document.documentElement && document.documentElement.clientHeight) 
	{ // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) 
	{ // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight)
	{
		pageHeight = windowHeight;
	} 
	else 
	{ 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth)
	{	
		pageWidth = windowWidth;
	} 
	else 
	{
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

lightbox.parse = function()
{
	if (!document.getElementsByTagName)
	{ 
		return; 
	}
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];

		if ((anchor.getAttribute("migulu") == "lightbox"))
		{
			anchor.onclick = function () {lightbox.show(this); return false;}
		}
	}
}

lightbox.reinit = function()
{
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];

		if ((anchor.getAttribute("migulu") == "lightbox"))
		{
			anchor.onclick = function () {lightbox.show(this); return false;}
		}
	}

}

//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
lightbox.init = function()
{
	if(debug)alert("Initialization lightbox successfully...");
	if (!document.getElementsByTagName)
	{ 
		return; 
	}
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];

		if ((anchor.getAttribute("migulu") == "lightbox"))
		{
			anchor.onclick = function () {lightbox.show(this); return false;}
		}
	}

	var objBody = document.getElementsByTagName("body").item(0);
	
	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	overlay = document.createElement("div");
	overlay.setAttribute('id','overlay');
	// remarked by James objOverlay.onclick = function () {hideLightbox(); return false;}
	overlay.style.display = 'none';
	overlay.style.position = 'absolute';
	overlay.style.top = '0';
	overlay.style.left = '0';
	overlay.style.zIndex = '90';
 	overlay.style.width = '100%';
	overlay.style.height = '100%';
	objBody.insertBefore(overlay, objBody.firstChild);
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// preload and create loader image
	var imgPreloader = new Image();
	
	// if loader image found, create link to hide lightbox and create loadingimage
	imgPreloader.onload=function()
	{
		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {lightbox.hide(); return false;}
		overlay.appendChild(objLoadingImageLink);
		
		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);

		imgPreloader.onload = function(){};	//	clear onLoad, as IE will flip out w/animated gifs

		return false;
	}

	imgPreloader.src = loadingImage;

	// create lightbox div, same note about styles as above
	lightboxbody = document.createElement("div");
	lightboxbody.setAttribute('id','lightbox');
	//objLightbox.style.display = 'none';
	lightboxbody.style.visibility= 'hidden';
	lightboxbody.style.position = 'absolute';
	lightboxbody.style.zIndex = '100';	
	objBody.insertBefore(lightboxbody, overlay.nextSibling);
	if(debug)lightboxbody.innerHTML = "This is lightbox";   //for testing by James
	
	// create lightbox title
	lightboxtitle = document.createElement("div");
	lightboxtitle.setAttribute('id', 'lightboxtitle');
	lightboxtitle.display = 'none';
	lightboxbody.appendChild(lightboxtitle);
	if(debug)lightboxtitle.innerHTML = "This is lightboxTitle";  //for testing by James

	//********** create link and append to lightboxTitle
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	objLink.setAttribute('title','Click to close');
	objLink.onclick = function () {lightbox.hide(); return false;}

	// preload and create close button image
	var imgPreloadCloseButton = new Image();

	// if close button image found, 
	imgPreloadCloseButton.onload=function()
	{
		var objCloseButton = document.createElement("img");
		objCloseButton.src = closeButton;
		objCloseButton.setAttribute('id','closeButton');
		objCloseButton.setAttribute('border','0');
		//objCloseButton.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objLink.appendChild(objCloseButton);

		return false;
	}
	imgPreloadCloseButton.src = closeButton;
	lightboxtitle.appendChild(objLink);
	//************* end of create close button which in lightboxTitle
	
	//create form container for Allan use
	lightboxform = document.createElement("div");
	lightboxform.setAttribute('id', 'lightboxform');
	lightboxform.style.display = 'none';
	lightboxbody.appendChild(lightboxform);
	if(debug)lightboxform.innerHTML = "This is lightboxForm <br> <br> <br>";  //for testing by James
	
	// create lightbox advertisement area for AD.
	lightboxad = document.createElement("div");
	lightboxad.setAttribute('id','lightboxad');
	lightboxbody.appendChild(lightboxad);
	if(debug)lightboxad.innerHTML = "This is Ad..";  //for testing by James
};
