var galleryInitialised = false;
gallery.prototype.buildCatList = _galleryBuildCatList;
gallery.prototype.categories = new Array;
gallery.prototype.copyList = _galleryCopyList;
gallery.prototype.currentPage = 0;
gallery.prototype.folderId = 0;
gallery.prototype.imageClick = _galleryImageClick;
gallery.prototype.images = new Array;
gallery.prototype.imageSpace = 8;
gallery.prototype.serverId = 0
gallery.prototype.showImages = _galleryShowImages;
gallery.prototype.main = null;
gallery.prototype.pageSize = 10;
gallery.prototype.selectedIndex = 0;
gallery.prototype.setImage = _gallerySetImage;
function gallery(id, folderId, windowColor, hilightColor, serverId) {
	// Preload stuff here:
	this.id = id;
	this.windowColor = windowColor;
	this.hilightColor = hilightColor;
	this.folderId = folderId;
	this.serverId = serverId;
	this.main = document.getElementById(id);
	this.main.container = this;
	this.display = document.getElementById(id + "_viewWindow");
	this.selCategory = document.getElementById(id + "_selectCategory");
	this.selCategory.tabIndex = 1;
	this.inpSearch = document.getElementById(id + "_inputSearchText");
	this.inpSearch.tabIndex = 2;
	this.inpSearch.container = this;
	this.inpSearch.onkeypress = searchKey;
	this.btnSearch = document.getElementById(id + "_searchButton");
	this.btnSearch.tabIndex = 3;
	this.btnSearch.container = this;
	this.btnSearch.onclick = searchImages;
	this.btnClear = document.getElementById(id + "_clearButton");
	this.btnClear.tabIndex = 4;
	this.btnClear.container = this;
	this.btnClear.onclick = searchClear;
	this.btnClear.disabled = true;
	this.imageContainer = document.getElementById(id + "_selectWindow");
	this.data = makeRequestSync('Gallery.axd?func=1&folderId=' + folderId + '&serverId=' + serverId + '&IFrame=False','');
	re = /<!\[CDATA\[((?:\n|.)*?)\%\|\|\%\]\]>/igm;
	this.dataItems = new Array();
	var values = re.exec(this.data);
	if(values!=null) {
		this.dataItems = values[1].split('%||%');
	}
	this.imageList = new Array();
	var count = 0;
	count = this.dataItems.length;
	for (var i=0; i<count; i++) {
		this.imageList[i] = new imageListItem(this.dataItems[i]);
	}
	var oItem = document.createElement("div");
	document.getElementById(id + "_infoWindow").appendChild(oItem);
	this.info = oItem;
	this.imageList.sort(imageSorter);
	this.buildCatList();
	this.pageSize = parseInt((this.imageContainer.clientWidth-8)/108,10);
	this.imageSpace = (this.imageContainer.clientWidth - (100 * this.pageSize)) / (this.pageSize + 1);
	var oItem = document.createElement("img");
	oItem.style.cssText = 'position: absolute; top: 0px; left: 0px; width: ' + this.display.clientWidth + 'px; height: ' + this.display.clientHeight + 'px; display: none; Border:0px;';
	this.display.appendChild(oItem);
	this.mainImage = oItem;
	var oItem = document.createElement("div");
	oItem.id = this.id + "_MainCover";
	oItem.style.cssText = 'overflow: hidden; display: table; _position: relative; top: 0px; left: 0px; width: ' + this.display.clientWidth + 'px; height: ' + this.display.clientHeight + 'px; text-align: center; background-color: #' + this.windowColor;
	oItem.innerHTML = '<div style=\'_position: relative; _top: 50%;display: table-cell; vertical-align: middle;\'><div style=\'_height: 30px;_margin-top:-15px;\'>Loading...<br>Please wait.</div></div>';
	this.display.appendChild(oItem);
	this.mainHide = oItem;
	this.copyList();
	this.showImages();
}
function _galleryBuildCatList() {
	for (var i=0; i<this.imageList.length; i++) {
		var cat = this.imageList[i].category;
		var cats = cat.split(',');
		for (var j=0; j<cats.length; j++) {
			var pos = searchArray(this.categories, cats[j]);
			if( pos<0) {
				pos = (pos*-1) - 1;
				this.categories.splice(pos, 0, cats[j]);
			}
		}
	}
	// Populate the category selection list
	var oOption = document.createElement("option");
	this.selCategory.options.length = 0;
	this.selCategory.options.add(oOption);
	oOption.innerHTML = 'All categories'
	for (var i=0; i<this.categories.length; i++) {
		var oOption = document.createElement("option");
		this.selCategory.options.add(oOption);
		oOption.innerHTML = this.categories[i];
	}
}
function _galleryCopyList() {
	this.selectedList = new Array;
	for (var i=0; i<this.imageList.length; i++) {
		this.selectedList[i] = this.imageList[i];
	}
}
function _galleryImageClick() {
	var cont = this.container;
	if(cont.selectedIndex != this.index) {
		cont.images[cont.selectedIndex].style.borderColor = '#' + cont.windowColor;
		document.getElementById(cont.id + '_Cover_' + cont.selectedIndex).style.borderColor = '#' + cont.windowColor;
		cont.selectedIndex = this.index;
		cont.images[cont.selectedIndex].style.borderColor = '#' + cont.hilightColor;
		document.getElementById(cont.id + '_Cover_' + cont.selectedIndex).style.borderColor = '#' + cont.hilightColor;
		cont.setImage();
		if (document.all) {
			var windowLeft = cont.imageContainer.parentElement.parentElement.scrollLeft;
			var windowRight = cont.imageContainer.parentElement.parentElement.clientWidth + windowLeft;
			var itemLeft = parseInt(this.style.left, 10) - 2;
			var itemRight = itemLeft + this.clientWidth + 4;
			
			if(windowLeft > itemLeft) {
				cont.imageContainer.parentElement.parentElement.scrollLeft = itemLeft;
			} else if (windowRight < itemRight) {
				cont.imageContainer.parentElement.parentElement.scrollLeft = itemLeft - (cont.imageContainer.parentElement.parentElement.clientWidth - (this.clientWidth + 4));
			}
		}
	}
}
function _galleryShowImages() {
	var left = this.imageSpace
	this.imageContainer.innerHTML = '';
	if (this.selectedIndex >= this.selectedList.length) {
		if(this.selectedList.length>0) {
			this.selectedIndex = this.selectedList.length - 1;
		} else {
			this.selectedIndex = 0;
		}
	}
	for (var i=0; i<this.selectedList.length; i++) {
		var oItem = document.createElement("img");
		oItem.id =  this.id + '_Image_' + i;
		oItem.style.cssText=('position: absolute; top: 18px; left: ' + parseInt(left,10) + 'px; width: 98px; height: 78px; display: none;Border:1px solid #' + this.windowColor + ';');
		if (i==this.selectedIndex) {
			oItem.style.borderColor = '#' + this.hilightColor;
		}
		oItem.alt = 'Click on this image to view a larger version\nImage title: ' + this.selectedList[i].title;
		oItem.index=i;
		oItem.tabIndex = (2 * i) + 5;
		oItem.container = this;
		oItem.onfocus = new Function('if(document.createEvent) {myEvt=document.createEvent(\'MouseEvents\');myEvt.initMouseEvent(\'click\',1,1,document.defaultView,1,0,0,0,0,0,0,0,0,0,document.getElementById(\'' + oItem.id + '\'));document.getElementById(\'' + oItem.id + '\').dispatchEvent(myEvt);} else {document.getElementById(\'' + oItem.id + '\').click()}');
		oItem.item = this.selectedList[i];
		oItem.onclick = this.imageClick;
		if (document.images) {
			var oDiv = document.createElement("div");
			oDiv.id =  this.id + '_Cover_' + i;
			oDiv.style.cssText = 'overflow: hidden; display: table; position: absolute; top: 18px; left: ' + parseInt(left,10) + 'px; width: 98px; height: 78px; text-align: center; background-color: #' + this.windowColor + '; Border:1px solid #' + this.windowColor + ';';
			if (i==this.selectedIndex) {
				oDiv.style.borderColor = '#' + this.hilightColor;
			}
			oDiv.index=i;
			oDiv.tabIndex = (2 * i) + 6;	
			oDiv.container = this;
			oDiv.onfocus = new Function('if(document.createEvent) {myEvt=document.createEvent(\'MouseEvents\');myEvt.initMouseEvent(\'click\',1,1,document.defaultView,1,0,0,0,0,0,0,0,0,0,document.getElementById(\'' + oDiv.id + '\'));document.getElementById(\'' + oDiv.id + '\').dispatchEvent(myEvt);} else {document.getElementById(\'' + oDiv.id + '\').click()}');
			oDiv.onclick = this.imageClick;
			oDiv.innerHTML = '<div style=\'_position: relative; _top: 50%;display: table-cell; vertical-align: middle;\'><div style=\'_height: 30px; _margin-top:-15px;\'>Loading...<br>Please wait.</div></div>';
			this.imageContainer.appendChild(oDiv);
			var oImage = new Image;
			oItem.image = oImage;
			oImage.imageCont = oItem;
			oImage.imageHide = oDiv;
			oImage.onload = imageLoaded;
			oImage.src = 'Gallery.axd?func=101&path=' + this.selectedList[i].path + '&width=100&height=80&backColor=' + this.windowColor;
			oImage.timeout = setTimeout('notFound(\'' + this.id + '_Cover_' + i + '\')', 5000);
		} else {
			oItem.src = 'Gallery.axd?func=101&path=' + this.selectedList[i].path + '&width=100&height=80&backColor=' + this.windowColor;
		}	
		this.imageContainer.appendChild(oItem);
		if (i==this.selectedIndex) {
			oItem.focus;
		}
		left = left + this.imageSpace + 100;
		this.images[i] = oItem;
	}
	var oItem = document.createElement("span");
	oItem.style.cssText=('position: absolute; overflow: hidden; top: 16px; left: ' + parseInt(left-this.imageSpace,10) + 'px; width: ' + this.imageSpace + 'px; height: 78px; display: block;');
	this.imageContainer.appendChild(oItem);
	this.setImage();
}
function _gallerySetImage() {
	this.mainImage.style.display = 'none';
	this.mainHide.style.cssText = 'overflow: hidden; display: table; _position: relative; top: 0px; left: 0px; width: ' + this.display.clientWidth + 'px; height: ' + this.display.clientHeight + 'px; text-align: center; background-color: #' + this.windowColor;
	if (this.selectedList.length == 0) {
		this.mainHide.innerHTML = '<div style=\'_position: relative; _top: 50%;display: table-cell; vertical-align: middle;\'><div style=\'_height: 30px;_margin-top:-15px;\'>No images were found.</div></div>';
		return false;
	} else {
		this.mainHide.innerHTML = '<div style=\'_position: relative; _top: 50%;display: table-cell; vertical-align: middle;\'><div style=\'_height: 30px;_margin-top:-15px;\'>Loading...<br>Please wait.</div></div>';
	}
	var item = this.currentPage * this.pageSize + this.selectedIndex;
	if(item>=this.selectedList.length) {
		this.images[this.selectedIndex].style.borderColor = "#c0c0c0";
		this.selectedIndex = (this.selectedList.length - 1) % this.pageSize;
		this.images[this.selectedIndex].style.borderColor = "blue";
		item = this.currentPage * this.pageSize + this.selectedIndex;
	}
	this.info.innerHTML = '<div id=\''+this.id+'_title\' style=\'padding-bottom: 4px;\'><b>Title: </b> ' + 
							  this.selectedList[item].title  + '</div>' + 
							  '<div id=\''+this.id+'_filesize\' style=\'padding-bottom: 4px;\'><b>File size: </b>' + 
							  this.selectedList[item].size  + '</div>' +
							  '<div id=\''+this.id+'_size\' style=\'padding-bottom: 4px;\'><b>Size: </b>' + 
							  this.selectedList[item].dimensions  + '</div>';
	if (this.selectedList[item].alt!='') {
		this.info.innerHTML += '<div id=\''+this.id+'_alttext\' style=\'padding-bottom: 4px;\'><b>Alt text: </b>' + 
							  this.selectedList[item].alt + '</div>'
	}
	if (this.selectedList[item].description!='') {
		this.info.innerHTML += '<div id=\''+this.id+'_description\' style=\'padding-bottom: 4px;\'><b>Description: </b>' + 
							   this.selectedList[item].description + '</div>'
	}
	if (this.selectedList[item].path!='') {
		this.info.innerHTML +=  '<div id=\''+this.id+'_downloadlink\' style=\'padding-bottom: 4px;\'><a href="' + this.selectedList[item].path + '" target=\'_blank\'>Download</a></div>';
	}
	
	if (document.images) {
		var oImage = new Image;
		this.currentImage = oImage;
		oImage.imageCont = this.mainImage;
		oImage.imageHide = this.mainHide;
		oImage.onload = imageLoaded;
		if (this.selectedList[item].alt!='') {
			oImage.alt = this.selectedList[item].alt;
		}
		oImage.src = 'Gallery.axd?func=101&path=' + this.selectedList[item].path + '&width=' + this.display.clientWidth + '&height=' + this.display.clientHeight + '&backColor=' + this.windowColor;
		oImage.timeout = setTimeout('notFound(\'' + this.mainHide.id + '\')', 5000);
	} else {
		this.mainImage.src = 'Gallery.axd?func=101&path=' + this.selectedList[item].path + '&width=' + this.display.clientWidth + '&height=' + this.display.clientHeight + '&backColor=' + this.windowColor;
	}
}
function getEvent(evt) {
	if (!evt) {
		return event;
	}
	return evt;
}
function getReqObj() {
	var lObj = new Object(false);
    if (window.XMLHttpRequest) {
        lObj = new XMLHttpRequest();
        if (lObj.overrideMimeType) {
            lObj.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject)  {
		try {
			lObj = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				lObj = new ActiveXObject("Microsoft.XMLHTTP");		
			} catch (e) {
				throw('');
			}
		}					
	}
    return lObj;
}
function imageListItem(data) {
	var re = /(\w*?)=(.*?)(?:\%\|\%|$)/gim;
	var concat = '';
	while ((arr = re.exec(data)) != null) {
		eval('this.' + arr[1] + '=\'' + arr[2] + '\''); 
		concat += arr[2] + ' ';
	}
	this.concat = concat;
}
function makeRequestSync(url, data) {
	var lReq = getReqObj();
	var path = location.href;
	path = path.substring(0, path.lastIndexOf('/')+1);
	url = path + url;
    if (!lReq) {
        alert('An XMLHTTP instance could not be created.');
    } else {
        lReq.open('POST', url, false);
		lReq.send(data);
		if (lReq.readyState == 4) {
			if (lReq.status == 200) {
				return lReq.responseText;
			} else {
				return 'There was a problem with the request.';
			}
		}
	}        
}
function notFound(id) {
	document.getElementById(id).childNodes[0].childNodes[0].innerHTML = 'The image could not be loaded.';
}
function searchArray(arr, val) {
	var ret = -1;
	for (aLoop=0; aLoop<arr.length; aLoop++) {
		if(arr[aLoop]<val) {
			ret = (aLoop + 2) * -1;
		}
		if(arr[aLoop]==val) {
			return aLoop;
		}
	}
	return ret;
}
function searchKey(evt) {
	evt = getEvent(evt);
	if (evt.keyCode == 13||evt.keyCode == 10) {
		this.container.btnSearch.click();
		return false;
	}
}
function searchImages() {
	var cont = this.container;	
	cont.copyList();
	if (cont.selCategory.selectedIndex>0) {
		for (i=cont.selectedList.length-1; i>=0; i--) {	
			var re = new RegExp('(^|,)' + cont.selCategory.options[cont.selCategory.selectedIndex].innerHTML + '($|,)','mig');
			if (!re.test(cont.selectedList[i].category)) {
				cont.selectedList.splice(i, 1);
			}
		}
	}
	if (cont.inpSearch.value!='') {
		try {
			for (i=cont.selectedList.length-1; i>=0; i--) {	
				var re = new RegExp(cont.inpSearch.value,'mig');
				if (!re.test(cont.selectedList[i].concat)) {
					cont.selectedList.splice(i, 1);
				}
			}
		} catch(e) {
		}
	}
	cont.showImages();	
	cont.btnClear.disabled = false;
	return false;	
}
function searchClear() {
	var cont = this.container;
	cont.selCategory.selectedIndex=0;
	cont.inpSearch.value='';
	cont.copyList();
	cont.showImages();
	cont.btnClear.disabled = true;
	return false;
}
function imageSorter(a, b) {
	if (a.title.toLowerCase()<b.title.toLowerCase()) {
		return -1;
	} else  {
		if (b.title.toLowerCase()<a.title.toLowerCase()) {
			return 1;
		} else {
			return 0;
		}
	}
}
function imageLoaded() {
	this.imageHide.style.display = "none";
	window.clearTimeout(this.timeout);
	this.imageCont.src = this.src;
	this.imageCont.style.display = "block";	
}