/****************************************************************************
* 																			*
* HW Javascript Lightbox Module												*
* -----------------------------												*
* 																			*
* Author:			Leonard Martin (leonard.martin@heathwallace.com)		*
* Version:			0.0.2													*
* Updated:			19 May 2008												*
* 																			*
* **************************************************************************/

/*
--- LIGHTBOX FUNCTIONS ---
Requires:	Core, Ajax
Optional:	Animate
CSS:		css/lightbox.css
Other:		images/mask.png
--------------------------
Opens external content into a page overlay
*/
HW.LightBox = {
	contentToShow:null,
	cls:null,
	// set alpha level of the mask layer
	maskAlpha:30,
	// set colour of mask layer
	maskColour:'#000000',
	// set content of close button
	// if set as null then no close button will appear and the overlay can be removed by clicking anywhere outside the overlay window
	closeButton:'<img src="../../_images/btn-online-demo-close.gif"/>',
	// HTML code of popup window
	// Note: ids on wrapper element and content area are required and should be as set below
	popupHTML:'<div class="jvsLightBoxPopup" id="jvsLightBoxPopup"><div class="jvsLightBoxPopupInner"><div class="jvsLightBoxPopupContentArea" id="jvsLightBoxPopupContentArea"></div></div></div>',
	popupId:'jvsLightBoxPopup',
	contentId:'jvsLightBoxPopupContentArea',
	// give the option to set a callback function to call once lightbox content is loaded
	callback:function(){return;},
	/*
	* init(c)
	* set up the event handlers on links
	* c:		The classname on links which should open in an overlay
	* Returns:	Nothing
	*/
	init:function(c) {
		if(c) {
			/*HW.detachEvent(document.body,'click', dcsDownload);
			HW.detachEvent(document.body,'click', dcsOffsite);
			HW.detachEvent(document.body,'click', dcsAnchor);
			HW.detachEvent(document.body,'mousedown', dcsRightClick);*/
			
			this.cls = c;
			// find the link with the right class
			var links = $$(this.cls,document.body,null);
			for(var i=0,j=links.length;i<j;i++) {
				var obj = this;
				// set click handlers
				HW.attachEvent(links[i],'click', function(e){
					HW.preventDefault(e);
					e=e||window.event;
					trg = e.srcElement||e.target;
					obj.openLightBox(trg.href);	
				});
			}
		}
	},
	/*
	* displayContent()
	* if the popup overlay and mask do not exist, create them
	* Returns:	Nothing
	*/
	displayContent:function() {
		if(!this.mask) {this.createMask();}
		if(!this.popup) {this.createPopup();}
		if(this.mask && this.popup) {
			this.popup.contentArea.innerHTML = '';
			this.popup.contentArea.appendChild(this.contentToShow);
			this.showMask();
		}
	},
	/*
	* createMask()
	* creates the mask overlay
	* Returns:	Nothing
	*/
	createMask:function() {
		// if we're using IE then add an iframe to layer over select boxes
		if(HW.isIE) {
			this.ieFixIframe = HW.createNode('iframe',document.body);
			this.ieFixIframe.className = 'jvsLightBoxMask';
			HW.setStyle(this.ieFixIframe,{display:'none'});
			this.ieFixIframe.frameBorder = 0;
			HW.setFade(this.ieFixIframe,0);
		}
		this.mask = HW.createNode('div',document.body);
		this.mask.className = 'jvsLightBoxMask';
		HW.setStyle(this.mask,{display:'none'});
		// if the user is using Mac Firefox then we need to use a png for the mask
		if(HW.isMacFF) {
			HW.addClass(this.mask,'jvsLightBoxMaskMacFF');
			this.maskAlpha = 100;
		}
		else {
			var c = this.maskColour;
			HW.setStyle(this.mask,{background:c});
			HW.setFade(this.mask,this.maskAlpha);
		}
		var obj = this;
		// hide the overlay when the user clicks outside the popup
		HW.attachEvent(this.mask,'click',function(){obj.hidePopup();});
	},
	/*
	* createPopup()
	* creates the popup window
	* Returns:	Nothing
	*/
	createPopup:function() {
		// create an empty div...
		var div = HW.createNode('div',document.body);
		// ... and set its contents
		div.innerHTML = this.popupHTML;
		// set popup and content elements
		this.popup = $(this.popupId);
		this.popup.contentArea = $(this.contentId);
		if(!this.popup || !this.popup.contentArea) {HW.error('Elements with correct ids not found.');}
		HW.setStyle(this.popup,{display:'none'});
		// if the close button is set then create it
		if(this.closeButton !== null) {
			var obj = this;
			this.popup.closeButton = HW.createNode('a',this.popup);
			this.popup.closeButton.href = '#';
			this.popup.closeButton.innerHTML = this.closeButton;
			this.popup.closeButton.className = 'jvsLightBoxClose';
			HW.attachEvent(this.popup.closeButton,'click',function(e) {obj.hidePopup();HW.preventDefault(e);});
		}
	},
	/*
	* showMask()
	* displays the mask layer
	* Returns:	Nothing
	*/
	showMask:function() {
		this.setMaskSize();
		// fade in if we can
		if(HW.Animate) {
			HW.setFade(this.mask,0);
			HW.setStyle(this.mask,{display:''});
			var obj = this;
			HW.Animate.fade(this.mask,this.maskAlpha,200,function(){obj.showPopup();});
		}
		else {
			HW.setStyle(this.mask,{display:''});
			this.showPopup();
		}
	},
	/*
	* showPopup()
	* displays the popup window
	* Returns:	Nothing
	*/
	showPopup:function() {
		var obj = this;
		// fade in if we can
		if(HW.Animate) {
			HW.setFade(this.popup,0);
			HW.setStyle(this.popup,{display:''});
			this.setPopupSize();
			HW.Animate.fade(this.popup,100,500,function(){obj.callback();});
		}
		else {
			HW.setStyle(this.popup,{display:''});
			this.setPopupSize();
			this.callback();
		}
	},
	/*
	* hidePopup()
	* hides the popup window and mask layer
	* Returns:	Nothing
	*/
	hidePopup:function() {
		var s = {display:'none'};
		HW.setStyle(this.popup,s);
		HW.setStyle(this.mask,s);
		if(this.ieFixIframe) {
			HW.setStyle(this.ieFixIframe,s);
		}
		var flashmovie = $('flashmovietour');
		if(flashmovie && HW.isIE) flashmovie.StopPlay();
		this.popup.contentArea.removeChild(this.contentToShow);
	},

	/*
	* setMaskSize()
	* set the size of the mask layer to fill the window
	* Returns:	Nothing
	*/
	setMaskSize:function() {
		var dims = this.getDocSize();
		this.mask.style.height = dims[1]+'px';
		if(this.ieFixIframe) {
			this.ieFixIframe.style.height = dims[1]+'px';
			this.ieFixIframe.style.display = '';
		}
	},
	/*
	* setPopupSize()
	* set the size of the popup window and centre on screen
	* Returns:	Nothing
	*/

	setPopupSize:function() {
		var dims = this.getWinSize();
		var scrY = window.scrollY||document.body.scrollTop;
		var _left = Math.max((dims[0]-this.popup.offsetWidth)/2,0)+'px';
		var _top = Math.max((dims[1]-this.popup.offsetHeight)/2+scrY,0)+'px';
		HW.setStyle(this.popup,{left:_left,top:_top});
	},
	/*
	* getDocSize()
	* gets the size of the document, if the document is shorter than the window, returns window height
	* Returns:	Array of dimensions
	*/
	getDocSize:function() {
		var dims = this.getWinSize();
		var w = dims[0];
		var h = dims[1];
		w = Math.max(w,document.body.offsetWidth);
		w = Math.max(w,document.documentElement.offsetWidth);
		h = Math.max(h,document.body.offsetHeight);
		h = Math.max(h,document.documentElement.offsetHeight);
		h = Math.max(h,document.documentElement.scrollHeight);
		return [w,h];
	},
	/*
	* getWinSize()
	* gets the size of the window
	* Returns:	Array of dimensions
	*/
	getWinSize:function() {
		var w = 0;
		var h = 0;
		if(window.innerWidth) {
			w = window.innerWidth;
			h = window.innerHeight;
		}
		else if(document.documentElement.clientWidth) {
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		else if(document.body.clientWidth) {
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
		return [w,h];
	},
	/*
	* openLightBox(href)
	* loads a lightbox with content from the spcified url
	* href:		String - URL of the content to load, with hash reference if required
	* Returns:	Nothing
	*/
	openLightBox:function(href) {
		var obj = this;
		this.contentToShow = document.createElement('div');
		var url = href.split('#');
		// create an Ajax request which calls back to parseResponse
		new HW.Ajax(url[0],function(r) {obj.parseResponse(r,href);});
		
	},
	/*
	* parseResponse(response,href)
	* parse the content of the AJAX response to load correct content
	* response:	Ajax.Response Object - response object from Ajax request
	* href:		String - URL of the content to load, with hash reference if required
	* Returns:	Nothing
	*/
	parseResponse:function(response,href) {
		// if the requested content is an image tehn create an img tag
		if(response.contentType.substr(0,5) == 'image') {
			var obj = this;
			var img = HW.createNode('img',this.contentToShow);
			HW.attachEvent(img,'load',function(){obj.displayContent();});
			img.src = href;
		}
		// otherwise try to load as text
		else {
			try {
				// if the link requested has a hash value then pick out the right node
				if(href.split('#')[1] !== null) {
					var idToLoad = href.split('#')[1];
					// first check the id doesn't exist in the current page, if it does then temporarily rename
					if($(idToLoad)) {
						$(idToLoad).id += '_tmpID';
					}
				}
				// create a placeholder for the imported content
				var div = HW.createNode('div',document.body);
				// find the body element
				var reg = new RegExp("<body[ a-zA-Z0-9=;:\-_\"]*>([\\w\\W]+)</body>");
				try{div.innerHTML = reg.exec(response.text)[1];}
				catch(e) {
					HW.error('Unable to load content: Content has no &lt;body&gt; tag.');
				}
				HW.setStyle(div,{display:'none'});
				var c;
				if(idToLoad) {
					// get the node with id matching our hash value
					c = $(href.split('#')[1]);
				}
				// if we have founbd a particular element, use it, else use the whole page
				var content = c?c.innerHTML:div.innerHTML;
				// remove placeholder
				document.body.removeChild(div);
				// reset the elements we changed id of earlier
				if($(idToLoad+'_tmpID')) {
					$(idToLoad+'_tmpID').id = idToLoad;
				}
				this.contentToShow.innerHTML = content;
				// display
				this.displayContent();
			} catch(e) {
				// if the link points at something weird, throw an error
				HW.error('Unsupported content-type: '+response.contentType);
			}
		}
	}
};
// set up the lightbox
HW.onload(function(){HW.LightBox.init('lightbox');});

/*
--- END LIGHTBOX FUNCTIONS ---
*/
