var $E = YAHOO.util.Event;
//var $A = YAHOO.util.Assert;
/*
	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 loadingImage = '/attributes/display_images/loading.gif';		
var closeButton = '';		

var LIGHTBOX_PADDING_HEIGHT = 145; // Total vertical space in the lightbox above and below the image
var LIGHTBOX_IMAGE_WIDTH = 500; // Pad image frame to this width
var LIGHTBOX_IMAGE_HEIGHT = 500; // Pad image frame to this height

var browser=navigator.appName;
// -----------------------------------------------------------------------------------

//
//	Extending built-in Array object
//	- array.removeDuplicates()
//	- array.empty()
//
Array.prototype.removeDuplicates = function () {
    for(i = 0; i < this.length; i++){
        for(j = this.length-1; j>i; j--){        
            if(this[i][0] == this[j][0]){
                this.splice(j,1);
            }
        }
    }
}

// -----------------------------------------------------------------------------------

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

// -----------------------------------------------------------------------------------




//
// 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;
}


//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//

function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){ hideLightbox(); }
}


//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }
	

//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
// opts = a hash of options.
// Only supported option is showGalleryLinks: true/false; whether to show gallery paging.
//    (Requires the presence of a 'gallery' object - see gallery.js)
//
function showLightbox(objLink, opts)
{
	if (opts == null) {
		opts = {}
	}
	
	// prep objects
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objDownload = document.getElementById('lightboxDownload');
	var objImage = document.getElementById('lightboxImage');
	var objLoadingImage = document.getElementById('loadingImage');
	var objLightboxDetails = document.getElementById('lightboxDetails');
	var objGalleryPreview = document.getElementById('gallery_preview');

	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// center loadingImage if it exists
	if (objLoadingImage) {
		objLoadingImage.style.top = Math.max(
			arrayPageScroll[1] + ((arrayPageSize[3] - LIGHTBOX_PADDING_HEIGHT - LIGHTBOX_IMAGE_HEIGHT) / 2), 0
		) + 'px';
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - LIGHTBOX_IMAGE_WIDTH) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}

	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';
	if (opts.showGalleryLinks) {
		// darken background when gallery is active
		$D.addClass(objOverlay, 'gallery_overlay');
	} else {
		$D.removeClass(objOverlay, 'gallery_overlay');
	}

	// hide scrollbars on elements with the hide_scrollbar_on_lightbox class
	var scrollables = $D.getElementsByClassName('hide_scrollbar_on_lightbox')
	for (var i = 0; i < scrollables.length; i++) {
		var elem = scrollables[i];
		elem.style.overflowX = 'hidden';
		elem.style.overflowY = 'hidden';
	}

	// preload image
	imgPreload = new Image();

	imgPreload.onload=function(){
		objImage.src = objLink.href;

		// adjust top margin of image to centre it vertically within image frame
		//objImage.style.marginTop = Math.max(0, (LIGHTBOX_IMAGE_HEIGHT - imgPreload.height) / 2) + 'px';
		
		//Get img inside lightbox link
		objThumbImage = objLink.getElementsByTagName('img')[0];
		
		//Get caption text
		objCaptionText = "";
		
		if(opts=="solo"){
			if(objLink.nextSibling.innerHTML != undefined){
						objCaptionText = objLink.nextSibling.innerHTML;
			}
		}else{
			objCaptionText = objGalleryPreview.getElementsByTagName('p','.caption')[0].innerHTML;
		}
		var printText="Print this photo";
		if($D.hasClass($('wrapper'),"arabic")){
			printText="\u0637\u0628\u0639 \u0627\u0644\u0635\u0648\u0631\u0629";
		}else if($D.hasClass($('wrapper'),"spanish")){
			printText="Imprimir la foto";
		}else if($D.hasClass($('wrapper'),"portugese")){
			printText="Imprimir esta foto";
		}else if($D.hasClass($('wrapper'),"french")){
			printText="Imprimer la photo";
		}else if($D.hasClass($('wrapper'),"russian")){
				printText="Печать фотографии";
		}else if($D.hasClass($('wrapper'),"chinese")){
				printText="打印照片";
		}
		
		objCaptionText+='<br />'+'<a href="'+ objLink.href +'" class="bullet" onclick="printme(\''+ objLink.href +'\');return false;" onkeypress="printme(\''+objLink.href +'\');return false;">'+printText+'</a>';
		// center lightbox and make sure that the top and left values are not negative
		// and the image placed outside the viewport
		//var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - LIGHTBOX_PADDING_HEIGHT - LIGHTBOX_IMAGE_HEIGHT) / 2);
		var lightboxTop = 20;
		var lightboxLeft = ((arrayPageSize[0] - 20 - LIGHTBOX_IMAGE_WIDTH) / 2);
		
		objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";

		objLightboxDetails.style.width = LIGHTBOX_IMAGE_WIDTH + 'px';
		if(objLink.getAttribute('title')){
			objCaption.style.display = 'block';
			//objCaption.style.width = LIGHTBOX_IMAGE_WIDTH + 'px';
			//objCaption.innerHTML = '<strong>'+objLink.getAttribute('title')+'</strong>'+'<br />'+objCaptionText;
			objCaption.innerHTML = objCaptionText;
			//var objDownloadHighResLB = objCaption.getElementsByTagName('a','bullet')[0];
			//objDownloadHighResLB.onclick = function(){window.open(this.href);return false;}
			//objDownloadHighResLB.onkeypress = function(){window.open(this.href);return false;}
		} else {
			objCaption.style.display = 'none';
		}
		if(objThumbImage.getAttribute('title')){
			//objCaption.innerHTML += '<div id="lightboxCopyright">' +objThumbImage.getAttribute('title') +'</div>';
		}
		/*-----------------------------------------*/
		/*- change 09.07.09 - Note David 19.05.09 -*/
		/*-----------------------------------------*/
		if(objLink.getAttribute('href')){
			objDownload.style.display = 'block';
			//objCaption.style.width = LIGHTBOX_IMAGE_WIDTH + 'px';
			//if (objThumbImage.getAttribute('longdesc') != ''){
			//	objDownload.innerHTML = '<a href="'+ objThumbImage.getAttribute('longdesc')+'" class="bullet">'+downloadText+'</a><br /><a href="'+ objImage.src +'" class="bullet">'+printText+'</a>';
			//}else{
			//	objDownload.innerHTML = browser+'<br />'+'<a href="'+ objImage.src +'" class="bullet" onclick="printme(\''+ objImage.src +'\');return false;" onkeypress="printme(\''+ objImage.src +'\');return false;">'+printText+'</a>';
			//}
		}else{
			objDownload.style.display = 'none';
		}
		
		//-hidden on 09.07.09 - if(objLink.getAttribute('href')){
		//-hidden on 09.07.09 -	objDownload.style.display = 'block';
			//objCaption.style.width = LIGHTBOX_IMAGE_WIDTH + 'px';
			//hide by val 10-04-08: objDownload.innerHTML = '<a href="'+ objThumbImage.getAttribute('longdesc')+'" class="bullet">'+downloadText+'</a><br /><a href="'+ objImage.src +'"  onclick="window.print(); return false;" class="bullet">'+printText+'</a>';
		//-hidden on 09.07.09 -	if(objThumbImage.getAttribute('longdesc')){objDownload.innerHTML = '<a href="'+ objThumbImage.getAttribute('longdesc')+'" class="bullet">'+downloadText+'</a><br />';}
		//-hidden on 09.07.09 -	objDownload.innerHTML+='<a href="'+ objImage.src +'" onclick="printme('+"'"+objImage.src+"'"+');return false;" class="bullet">'+printText+'</a>';
			
		//-hidden on 09.07.09 -} else {
		//-hidden on 09.07.09 -	objDownload.style.display = 'none';
		//-hidden on 09.07.09 -}
		/*---------------------*/
		/*end change - 09.07.09*/
		/*---------------------*/
		
		/* Gallery paging */
		if (opts.showGalleryLinks) {
			$('lightbox_gallery_pager').style.display = 'block';
			document.getElementById('lightbox_current_index').innerHTML = (gallery.currentIndex + 1);
			document.getElementById('lightbox_image_count').innerHTML = (gallery.imageList.length);
			if (gallery.currentIndex == 0) {
				$D.addClass($('lightbox_previous'), 'disabled');
				$('lightbox_previous').onclick = null;
			} else {
				$D.removeClass($('lightbox_previous'), 'disabled');
				$('lightbox_previous').onclick = function() {
					gallery.showImage(gallery.currentIndex - 1);
					showLightbox($('lightbox_link'), opts);
				};
			}
	
			if (gallery.currentIndex == gallery.imageList.length - 1) {
				$D.addClass($('lightbox_next'), 'disabled');
				$('lightbox_next').onclick = null;
			} else {
				$D.removeClass($('lightbox_next'), 'disabled');
				$('lightbox_next').onclick = function() {
					gallery.showImage(gallery.currentIndex + 1);
					showLightbox($('lightbox_link'), opts);
				};
			}
		} else {
			/* no gallery paging */
			$('lightbox_gallery_pager').style.display = 'none';
		}
		
		// 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){
			pause(250);
		} 

		if (objLoadingImage) {	objLoadingImage.style.display = 'none'; }

		// Hide select boxes as they will 'peek' through the image in IE
		selects = document.getElementsByTagName("select");
        for (i = 0; i != selects.length; i++) {
                selects[i].style.visibility = "hidden";
        }

	
		objLightbox.style.display = 'block';

		// After image is loaded, update the overlay height as the new image might have
		// increased the overall page height.
		arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');
		
		// Check for 'x' keypress
		listenKey();
	
		return false;
	}

	imgPreload.src = objLink.href;
	
}
/* val additionnal fcts */
function makepage(src){
  return "<html>\n" +
    "<head>\n" +
    "<title>Temporary Printing Window</title>\n" +
    "</head>\n" +
    "<body>\n" +
    "<img src='" + src + "'/>\n" +
    "</body>\n" +
    "</html>\n";
}

function printme(src){
	var browser=navigator.appName;
	var pw = window.open("","PrintPhoto","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,top=50px,left=50px,width=500px,height=500px,resizable=no");
	pw.document.write('<html><head><title>Print Photo</title></head><body><img src="' + src + '" /></body></html>');
	pw.document.close();
	pw.print();
	pw.close();
}
/* end val additionnal fcts */



//
// hideLightbox()
//
function hideLightbox()
{
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');

	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';

	// make select boxes visible
	selects = document.getElementsByTagName("select");
    for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}

	// re-show scrollbars on elements with the hide_scrollbar_on_lightbox class
	var scrollables = $D.getElementsByClassName('hide_scrollbar_on_lightbox')
	for (var i = 0; i < scrollables.length; i++) {
		var elem = scrollables[i];
		elem.style.overflowX = elem.oldOverflowX;
		elem.style.overflowY = elem.oldOverflowY;
	}

	// disable keypress listener
	document.onkeypress = '';
}




//
// 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.
//
function initLightbox(){	
	//language textual options
	if($D.hasClass($('wrapper'),"arabic")){
		downloadText="Download image";
		printText="\u0637\u0628\u0639 \u0627\u0644\u0635\u0648\u0631\u0629";
		photoText="\u0627\u0644\u0635\u0648\u0631";
		ofText="\u0645\u0646";
		closeText="\u0625\u063A\u0644\u0642";
	}else if($D.hasClass($('wrapper'),"french")){
		downloadText="T&eacute;l&eacute;charger l'image";
		printText="Imprimer cette photo";
		photoText="Photo";
		ofText="sur";
		closeText="FERMER";
	}else if($D.hasClass($('wrapper'),"spanish")){
		downloadText="Download image";
		printText="Imprimir la foto";
		photoText="Foto";
		ofText="de";
		closeText="CERRAR";
	}else if($D.hasClass($('wrapper'),"portugese")){
		downloadText="Download image";
		printText="Imprimir esta foto";
		photoText="Foto";
		ofText="of";
		closeText="FECHAR";
	}else if($D.hasClass($('wrapper'),"russian")){
		downloadText="Download image";
		printText="Imprimir esta foto";
		photoText="Foto";
		ofText="of";
		closeText="Закрыть";
	}else if($D.hasClass($('wrapper'),"chinese")){
		downloadText="Download image";
		printText="打印照片";
		photoText="Foto";
		ofText="of";
		closeText="关闭窗口";
	}else{ //english
		downloadText="Download image";
		printText="Print this photo";
		photoText="Photo";
		ofText="of";
		closeText="CLOSE";// [x]
	}
	
	
	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];
		var relAttribute = String(anchor.getAttribute('rel'));
		
		if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
			anchor.onclick = function () {showLightbox(this,"solo"); return false;}
		}
	}

	// the rest of this code inserts html at the top of the page that looks like this:
	//
	// <div id="overlay">
	//		<a href="#" onclick="hideLightbox(); return false;"><img id="loadingImage" /></a>
	//	</div>
	// <div id="lightbox">
	//		<a href="#" onclick="hideLightbox(); return false;" title="Click anywhere to close image">
	//			<img id="closeButton" />		
	//			<img id="lightboxImage" />
	//		</a>
	//		<div id="lightboxDetails">
	//			<div class="scrollernav"></div>
	//			<div id="lightboxCaption"></div>
	//			<div id="keyboardMsg"></div>
	//		</div>
	// </div>
	
	var objBody = document.getElementsByTagName("body").item(0);
	
	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, 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 () {hideLightbox(); return false;}
		objOverlay.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
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'fixed';
	objLightbox.style.zIndex = '100';	
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	
	//create title
	//var galleryTitle=document.getElementsByTagName('h1');
	//if(galleryTitle[0]){/*hidden from test -&& galleryTitle[0].className == 'lightbox'-*/
	//	var objTitle=document.createElement("div");
	//	objTitle.id="lightboxTitle";
	//	objTitle.appendChild(document.createTextNode(galleryTitle[0].innerHTML));
	//	objLightbox.appendChild(objTitle);
	//}
	
	// create link
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	objLink.setAttribute('accesskey','x');
	objLink.setAttribute('title','Click, or press \'X\' to close');
	objLink.onclick = function () {hideLightbox(); return false;}
	objLightbox.appendChild(objLink);

	// 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.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objLink.appendChild(objCloseButton);

		return false;
	}

	imgPreloadCloseButton.src = closeButton;
	
			
	
	// create image
	var objImageFrame = document.createElement("div");
	objImageFrame.setAttribute('id','lightboxImageFrame');
	var objImage = document.createElement("img");
	objImage.setAttribute('id','lightboxImage');
	objImageFrame.appendChild(objImage);
	objLink.appendChild(objImageFrame);
	
	// create details div, a container for the caption and keyboard message
	var objLightboxDetails = document.createElement("div");
	objLightboxDetails.setAttribute('id','lightboxDetails');
	objLightbox.appendChild(objLightboxDetails);

	
	var lightboxpagination = document.createElement('div');
	lightboxpagination.className = "gallerypager";
	lightboxpagination.style.display = 'none';
	lightboxpagination.id = 'lightbox_gallery_pager';
	
	lightboxpagination.innerHTML = photoText + ' ' + '<span id="lightbox_current_index"></span>&nbsp;' + ofText + '&nbsp;<span id="lightbox_image_count"></span><div class="scrollernav"><a class="lightboxprevious" id="lightbox_previous">Previous photo</a><a class="lightboxnext" id="lightbox_next">Next photo</a></div>';
		
	// append elements
	objLightboxDetails.appendChild(lightboxpagination);

	// create caption
	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objCaption.style.display = 'none';
	objLightboxDetails.appendChild(objCaption);

	// create caption
	var objDownload = document.createElement("div");
	objDownload.setAttribute('id','lightboxDownload');
	objLightboxDetails.appendChild(objDownload);

	// create keyboard message
	var objKeyboardMsg = document.createElement("div");
	objKeyboardMsg.setAttribute('id','keyboardMsg');
	objKeyboardMsg.innerHTML = '<a href="#" accesskey="x" onclick="hideLightbox(); return false;" title="Click, or press \'X\' to close">'+closeText+' <span class="close">x</span></a>';
	objLightboxDetails.appendChild(objKeyboardMsg);

	// note down initial 'overflow' settings on .hide_scrollbar_on_lightbox elements, so we can
	// restore scrollbars afterwards
	var scrollables = $D.getElementsByClassName('hide_scrollbar_on_lightbox')
	for (var i = 0; i < scrollables.length; i++) {
		var elem = scrollables[i];
		elem.oldOverflowX = elem.style.overflowX;
		elem.oldOverflowY = elem.style.overflowY;
	}
}




$E.onDOMReady(initLightbox); // run initLightbox onLoad

