/****************************************************************************
* 																			
* HW Javascript Lightbox Module												
* -----------------------------												
* 																			
* Author: Ivor Ng (ivor.ng@heathwallace.com)		
* Version:	0.1.3													
* Updated:	8 September 2009										
* 																			
* **************************************************************************/

/*
--- LIGHTBOX FUNCTIONS ---
Requires:	Core, Ajax
Optional:	Animate
CSS:		_css/lightbox.css
Other:		_images/lightbox/mask.png
--------------------------
Opens external content into a page overlay
*/

HW.LightBox = {
	contentToShow:null,
	cls:null,
	// set alpha level of the mask layer
	maskAlpha:85,
	// set colour of mask layer
	//maskColour:'#000000 url(../images/octoImage05.gif) center no-repeat',
	maskColour:'#000000 center no-repeat',
	// 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="/web09_include/_images/lightbox/octoButton01.gif" alt="Close" />',
	closeButton:'Close',
	// preloader
	preloader:'Loading...',
	// 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>',

	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) {
			this.cls = c;
			
			// covert HTML brackets to JS brackets
			var cob = this.closeButton.indexOf("&lt;");
			var ceb = this.closeButton.indexOf("&gt;");
			if( cob > -1 && ceb > -1 ) {
				this.closeButton = '<' + this.closeButton.substring(cob+4,ceb) + '>';
			}
			
			var pob = this.preloader.indexOf("&lt;");
			var peb = this.preloader.indexOf("&gt;");
			if( pob > -1 && peb > -1 ) {
				this.preloader = '<' + this.preloader.substring(pob+4,peb) + '>';
			}
			
			// 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;
					/* added in version 0.1.2
					 * if the target is not an anchor, that is an image with an anchor,
					 * update the target as the parent anchor.
					 */
					if(trg.tagName != 'A') {
						trg = trg.parentNode;	
					}
					obj.openLightBox(trg.href);
				});
			}
		}
	},
	/*
	* displayContent()
	* if the popup overlay and mask do not exist, create them
	* Returns:	Nothing
	*/
	displayContent:function() {
		
		/* added in Version 0.1.2:
		*	 print the lightbox content
		*/
		var pl = $$('jvsPrint',this.popup.contentArea,'a');
		var plc = $$('jvsPrintContent',this.popup.contentArea,'div');

		if(pl.length === 1 && plc.length === 1){
			HW.attachEvent(pl[0],'click',function(e){
				HW.preventDefault(e);
				// create a new window to print only part of the content
				// concept and code taken from: http://siligic.blogspot.com/2009/03/print-part-of-webpage-using-javascript_27.html
				var pwin = window.open('','pwin','width=100,height=100,top=0,left=0');
				pwin.document.open();
				pwin.document.write(plc[0].innerHTML);
				pwin.print();
				pwin.document.close();
				pwin.close();
			});
		}
		// 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);});
		}
		HW.setStyle(this.popup.contentArea,{visibility:'hidden'});
		HW.setStyle(this.popup.contentArea,{display:''});
		this.setPopupSize();
		HW.setStyle(this.popup.contentArea,{visibility:'visible'});
	},
	/*
	* 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'});
		
	},
	/*
	* 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(type) {
		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);
		}
		this.contentToShow.innerHTML = '';
	},
	/*
	* 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';
		// for IE5.5		
		this.mask.style.width = dims[0]+'px';	
		// end for IE5.5
		if(this.ieFixIframe) {
			this.ieFixIframe.style.height = dims[1]+'px';
			// for IE5.5		
			this.mask.style.width = dims[0]+'px';
		// end for IE5.5			
			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||document.documentElement.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';
		if (this.popup.offsetHeight > this.getWinSize()[1]){
			_top = _top+(this.popup.offsetHeight - this.getWinSize()[1])/2+20; /* if popup's height larger than window's height, align top with 20px padding */
			this.setMaskSize();
		}
		
		_top = (scrY+15) +'px'  ;
		
		// set left margin of the popup window
		//	_left = '300';
		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);
		// for IE5.5
		if(document.body.scrollWidth) { w = Math.max(w,document.body.scrollWidth); }
		if(document.body.scrollHeight) { h = Math.max(h,document.body.scrollHeight); }		
		// end for IE5.5		
		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');
		//this.contentToShow.innerHTML = '<img src="/web09_include/_images/lightbox/preloader.gif" alt="Loading..." />';
		this.contentToShow.innerHTML = this.preloader;
		var url = href.split('#');
		
		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();
		}
		// 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;
			HW.setStyle(this.popup.contentArea,{display:'none'});
			this.contentToShow.innerHTML = '';
			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[^>]*>([\\w\\W]+)</body>");
				try{div.innerHTML = reg.exec(response.text)[1];}
				catch(e) {
					HW.error('Unable to load content: Content has no <body> 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 ---
*/

