/*
 * gallery.js
 * (c) 2010 BISNIS Online
 * based on an idea by Andre Bieleman of BISNIS Online
 * developed by Mathijs Futselaar of BISNIS Online
 *
 */

/*
 * Define gallery settings 
 *
 */
var galleryTitle = 'Vlaggen.nl';
var galleryTitleColor = '#84C012';
/*
 *
 */


Array.prototype.find = function (element){for (var keys in this){if (this[keys] == element){return keys;break;}}return -1;};
function strpos (haystack, needle, offset) {var i = (haystack+'').indexOf(needle, (offset ? offset : 0)); return i === -1 ? false : i;}
window.debug=(function(){var c=this,e=Array.prototype.slice,b=c.console,i={},f,g,j=9,d=["error","warn","info","debug","log"],m="assert clear count dir dirxml group groupEnd profile profileEnd time timeEnd trace".split(" "),k=m.length,a=[];while(--k>=0){(function(n){i[n]=function(){j!==0&&b&&b[n]&&b[n].apply(b,arguments)}})(m[k])}k=d.length;while(--k>=0){(function(n,o){i[o]=function(){var q=e.call(arguments),p=[o].concat(q);a.push(p);h(p);if(!b||!l(n)){return}b.firebug?b[o].apply(c,q):b[o]?b[o](q):b.log(q)}})(k,d[k])}function h(n){if(f&&(g||!b||!b.log)){f.apply(c,n)}}i.setLevel=function(n){j=typeof n==="number"?n:9};function l(n){return j>0?j>n:d.length+j<=n}i.setCallback=function(){var o=e.call(arguments),n=a.length,p=n;f=o.shift()||null;g=typeof o[0]==="boolean"?o.shift():false;p-=typeof o[0]==="number"?o.shift():n;while(p<n){h(a[p++])}};return i})();
var cbSplit;if (!cbSplit) {cbSplit = function (str, separator, limit) {if (Object.prototype.toString.call(separator) !== "[object RegExp]") {return cbSplit._nativeSplit.call(str, separator, limit);}var output = [], lastLastIndex = 0,flags = (separator.ignoreCase ? "i" : "") +(separator.multiline  ? "m" : "") + (separator.sticky     ? "y" : ""),  separator = RegExp(separator.source, flags + "g"), separator2, match, lastIndex, lastLength;str = str + "";  if (!cbSplit._compliantExecNpcg) { separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); } if (limit === undefined || +limit < 0) {limit = Infinity;} else {limit = Math.floor(+limit);if (!limit) {return [];}}while (match = separator.exec(str)) {lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) {output.push(str.slice(lastLastIndex, match.index));if (!cbSplit._compliantExecNpcg && match.length > 1) {match[0].replace(separator2, function () {for (var i = 1; i < arguments.length - 2; i++) {if (arguments[i] === undefined) {match[i] = undefined;}}});}if (match.length > 1 && match.index < str.length) {Array.prototype.push.apply(output, match.slice(1));}lastLength = match[0].length;lastLastIndex = lastIndex;if (output.length >= limit) {break;}}if (separator.lastIndex === match.index) {separator.lastIndex++;}}if (lastLastIndex === str.length) {if (lastLength || !separator.test("")) {output.push("");}} else {output.push(str.slice(lastLastIndex));}return output.length > limit ? output.slice(0, limit) : output;};cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined;cbSplit._nativeSplit = String.prototype.split;}String.prototype.split = function (separator, limit) {return cbSplit(this, separator, limit);};

var aImages = new Array();
var sizePattern = /_(\d+)_(\d+)\.jpg$/;
var rTest = new RegExp(sizePattern);

function galleryStop() {
	window.removeEvents('keydown');
	$('galleryImage').destroy();
	$('controlBar').destroy();
	galleryLightBoxActive = false;
}

function galleryApplyStyles() {
	if ($('galleryImage').get('src').test(rTest)) {
		var imgDetails = $('galleryImage').get('src').split(rTest);
		$('galleryImage').setStyles({
			'width': imgDetails[1]+'px',
			'height': imgDetails[2]+'px'
		});
	}
	$('galleryImage').setStyles({
		'border': '4px solid #ccc',
		'backgroundColor': '#fff'
	});
}

function getGalleryPos() {
	return parseInt(aImages.find($('galleryImage').get('src')));
}

function doWhileLoading(a,g) {
	if (g.complete) {
		a.destroy();
		g.inject($(document.body));
	} else setTimeout('doWhileLoading(a,g)',100);
};


function galleryNav(direction) {
	var pos = getGalleryPos()+direction;
	if (pos < 0) pos = aImages.length-1;
	if (pos > aImages.length-1) pos = 0;

	var xx = $('galleryImage');
	var galleryImage = new Element('img',{'id': 'galleryImage', src: aImages[pos]});

	xx.destroy();
	galleryImage.inject($(document.body));

	$('controlBarNavTxt').innerHTML = parseInt(getGalleryPos()+1)+' / '+aImages.length;	
	galleryApplyStyles();	
	showUponFog('galleryImage');
}

function galleryShow(i) {
	if ($('galleryImage')) $('galleryImage').destroy();

	var galleryImage = new Element('img',{'id': 'galleryImage', 'src': i});
	galleryImage.inject($(document.body));

	galleryApplyStyles();
	galleryLightBoxActive = true;
	showUponFog('galleryImage');
	
	window.addEvent('keydown',function(e) {
		if (e.key == 'right') { e.stop(); galleryNav(1); }
		if (e.key == 'left')  { e.stop(); galleryNav(-1); }
		if (e.key == 'esc') closeFog();
		if (e.code == 35)  { e.stop(); galleryNav(-999); }
		if (e.code == 36)  { e.stop(); galleryNav(999); }
	});

	//alert('controlbar');

	var controlBar = new Element('div',{'id': 'controlBar'});
	controlBar.setStyles({
		'width': '100%',
		'height': '34px',
		'position': 'fixed',
		'top': '20px',
		'left': '0',
		'zIndex': '3',
		'backgroundColor': '#fff',
		'borderTop': '2px solid #555',
		'borderBottom': '2px solid #555'
	});

	//alert('controlbarTitle');
	
	var controlBarTitle = new Element('h1');
	controlBarTitle.setStyles({
		'margin': '7px 0 0 20px',
		'fontSize': '16px',
		'fontFamily': 'verdana',
		'fontWeight': 'bold',
		'color': galleryTitleColor,
		'position': 'absolute'
	});
	controlBarTitle.innerHTML = galleryTitle;

	//alert('controlbarClose');
	
	var controlBarClose = new Element('img',{'src':'/images/icons/delete.gif'});
	controlBarClose.setStyles({
		'position': 'absolute',
		'right': '20px',
		'top': '10px',
		'cursor': 'pointer'
	});

	if (document.attachEvent) {	//use native for IE6, otherwise it could crash
		controlBarClose.attachEvent('onclick',function(){closeFog();});
	} else {
		controlBarClose.addEvent('click',function(){closeFog();});
	}
	
	//alert('controlbarCenterpiece');
	
	var controlBarCenterpiece = new Element('div');
	controlBarCenterpiece.setStyles({
		'width': '200px',
		'marginLeft': '-100px',
		'marginTop': '3px',
		'left': '50%',
		'position': 'absolute',
		'textAlign': 'center'
	});
		
	
	//alert('controlbarBtnleft');
	var controlBarBtnLeft = new Element('img',{'src': '/images/icons/moveLeft.png'});
	controlBarBtnLeft.setStyles({
		'position': 'absolute',
		'left': 0,
		'cursor': 'pointer'
	});

	if (document.attachEvent) {	//use native for IE6, otherwise it could crash	
		controlBarBtnLeft.attachEvent('onclick',function(){galleryNav(-1)});
	} else {
		controlBarBtnLeft.addEvent('click',function(){galleryNav(-1)});
	}		

	
	//alert('controlbarBtnright');
	var controlBarBtnRight = new Element('img',{'src': '/images/icons/moveRight.png'});
	controlBarBtnRight.setStyles({
		'position': 'absolute',
		'right': 0,
		'cursor': 'pointer'
	});

	if (document.attachEvent) {	//use native for IE6, otherwise it could crash	
		controlBarBtnRight.attachEvent('onclick',function(){galleryNav(1)});	
	} else {
		controlBarBtnRight.addEvent('click',function(){galleryNav(1)});		
	}
	
	//alert('controlbarTxt');
	var controlBarTxt = new Element('span',{'id': 'controlBarNavTxt'});
	controlBarTxt.setStyles({
		'fontSize': '16px',
		'position': 'relative',
		'top': '3px'
	});
	
	controlBarTxt.innerHTML = parseInt(getGalleryPos()+1)+' / '+aImages.length;	

	var bcH_b = document.body.clientHeight;
	controlBar.inject($(document.body));
	controlBarTitle.inject(controlBar);
	controlBarCenterpiece.inject(controlBar);
	controlBarBtnLeft.inject(controlBarCenterpiece);
	controlBarTxt.inject(controlBarCenterpiece);
	controlBarBtnRight.inject(controlBarCenterpiece);
	controlBarClose.inject(controlBar);
	var bcH_a = document.body.clientHeight;

	//correct position IE6
	if (bcH_a > bcH_b) {
		var ctrlDiv = document.getElementById('controlBar');
		controlBar.style.position = 'absolute';
		var sXY = getScrollXY();
		var tmp = getViewPort();
		controlBar.style.top = (sXY[1] + 20) + 'px';
		controlBar.style.width = tmp[0] + 'px';
	}
	
}

window.addEvent('domready', function() {
	var vP = getViewPort();
	
	var x = 0;	
	$$('a').each(function(item, index) {
		if (item.get('rel') == 'lightbox[pimage]') {
			aImages[x] = item.get('href');
			/* resize */
			if ((strpos(aImages[x],'images.bisnis.nl') !== false)  && vP[1] < 765) {
				var imgDetails = aImages[x].split(rTest);
				var nWidth = parseInt(imgDetails[1] * 0.8);
				////alert(imgDetails);
				var nHeight = parseInt(imgDetails[2] * 0.8);
				aImages[x] = aImages[x].replace(rTest,'_'+nWidth+'_'+nHeight+'.jpg');
				item.set('href',aImages[x]);
			}
			x++;
			item.addEvent('click',function(e){
				e.stop();
				galleryShow($(this).get('href'));
			});
		}
	});
});;;