/*
*       ADDITIONAL FUNCTIONS       
*/
function fitImage(e, width)
{
	var img = new Image();
	img.src = e.src;

	//alert(img);
	//alert(img.width);
	
	if (img.width > width)
		e.width = width;
	else
		e.width = img.width;
}


Element.realWidth = function(e)
{
	if (e.offsetWidth)
		return e.offsetWidth;
	else
		return e.style.offsetWidth;
}

Element.realHeight = function(e)
{
	return Element.getHeight(e);
}

/*
*  Use this function insted of body.innerHTML += ....
*  This function doesn't redraws already rendered part of document
*/
function appendToBody(html)
{
	var div = document.createElement('div');
	div.innerHTML = html;
	var elements = div.childNodes;
	var body = getBody();
	
	for (i = 0; i < elements.length; i++)
	{
		body.appendChild(elements.item(i));
	}
}


Element.center = function(element)
{
	
}





/*
*  path = 'div:0/span:1'
*  means second span in the first div in the 'where' element
*  it's possible to use word 'last' instead of index of element's index 
*/
function getElementByPath(path, where)
{
	var pathArr =  path.split('/');
	var current = where;
	for (var i = 0; i < pathArr.length; i++)
	{
		var tmp = pathArr[i].match(/^([^\[]+)\[([^\]]+)\]$/);
		var tag = tmp[1];
		var index = tmp[2];
		
		var elements = current.getElementsByTagName(tag);
		if (index == 'last') 
			index = elements.length - 1;
		else
			index = parseInt(index);
			
		current = elements.item(index);	
	}
	
	return current;
}




/*
*       GLOBAL VARIABLES       
*/
var fileBrowsers = new Array();
var uploadsBrowsers = new Array();
var uploaders = new Array();
var screenLocker = new ScreenLocker();
var loadingPopup = new LoadingPopup(5000);
var screenLockerId = 1;















/*
*       FILE BROWSER CLASS      
*
*
*	forid: id of input (type=hidden) which contains filelist
*	ulId: id of <ul> which contains filelist
*	pageid: comma separated list of page ids file belongs to
*	filetype: file format (Images|*.jpg\;*.jpeg\;*.gif\;*.png)
*	type1, type2: additional variables which help to categorize files
*/
function FileBrowser(forId, ulId, pageId, fileTypes, type1, type2)
{
	this.forId = forId;
	this.pageId = pageId;
	this.fileTypes = fileTypes;
	this.type1 = type1;
	this.type2 = type2;
	this.ulId = ulId;
	this.loading = false;
	
	this.oldHref = '';
	
	fileBrowsers[this.forId] = this;
	
	this.generateHtmlList();
	
	
}


FileBrowser.prototype.getUL = function()
{
	return $(this.ulId);
}


FileBrowser.prototype.setText = function(text)
{
	var ul = this.getUL();
	ul.innerHTML = '<li style="border-bottom: 0px; padding: 15px 0px 15px 5px">'+text+'</li>';
}


FileBrowser.prototype.getFilesArray = function()
{
	var str = $(this.forId).value;
	var arr = eval(str);
	if (!arr)
		arr = new Array();
	
	
		
	return arr;
	
}

FileBrowser.prototype.setFilesArray = function(arr)
{
	var str = arr.toJSONString();
	$(this.forId).value = str;
}

FileBrowser.prototype.generateHtmlList = function()
{
	var arr = this.getFilesArray();
	if (arr.length == 0)
		this.setText('please <a href="javascript:fileBrowsers[\''+this.forId+'\'].addFiles();">add</a> some files');
	else
	{
		var code = '';
		n = arr.length;
		for (var i = 0; i < n; i++)
		{
			code += '<li id=""'+this.forId+'_li_'+i;
			if (i == n-1) 
				code += ' style="border-bottom: 0px;" ';
			code += '>';
			code += this.generateHtmlListItem(i, arr[i], n);
			code += '</li>';
		}
				
		this.getUL().innerHTML = code;
	}
}


FileBrowser.prototype.generateHtmlListItem = function(i, filename, n)
{
	var parts = filename.match(/^.*?([^\/]+)\.([^.]+)$/);
	if (!parts[1] || !parts[2])
		return 'error';
	
	var ulWidth = Element.realWidth(this.getUL());
	var imgWidth = ulWidth - 50;
			
	var name = parts[1];
	var ext = parts[2];	
	var code  = '';
	
	switch (ext.toLowerCase())
	{
		case 'jpg':
		case 'jpeg':
		case 'gif':
		case 'png':
			code += '<a title="delete" style="display: inline; float: right; clear: right; padding-right: 3px;" href="javascript:fileBrowsers[\''+this.forId+'\'].removeFile('+i+');"><img style="margin: 0; border: 0; display: inline;" src="/images/icon_delete2.gif" /></a>';	
			if (i > 0)   code += '<a title="move up" style="display: inline; float: right; clear: right; padding-right: 3px;" href="javascript:fileBrowsers[\''+this.forId+'\'].moveUp('+i+');"><img style="margin: 0; border: 0; display: inline;" src="/images/icon_up.gif" /></a>';
			if (i < n-1) code += '<a title="move down" style="display: inline; float: right; clear: right; padding-right: 3px;" href="javascript:fileBrowsers[\''+this.forId+'\'].moveDown('+i+');"><img style="margin: 0; border: 0; display: inline;" src="/images/icon_down.gif" /></a>';
			code += '<a href="'+filename+'" target="_blank"><img style="border: 0; margin: 0;" src="'+filename+'" onload="fitImage(this, '+imgWidth+');" /></a>';
			break;
			
		default:
			code += '<a title="delete" style="display: inline; float: right;" href="javascript:fileBrowsers[\''+this.forId+'\'].removeFile('+i+');"><img style="margin: 0; border: 0; display: inline;" src="/images/icon_delete2.gif" /></a>';	
			if (i > 0)   code += '<a title="move up" style="display: inline; float: right; padding-right: 3px;" href="javascript:fileBrowsers[\''+this.forId+'\'].moveUp('+i+');"><img style="margin: 0; border: 0; display: inline;" src="/images/icon_up.gif" /></a>';
			if (i < n-1) code += '<a title="move down" style="display: inline; float: right; padding-right: 3px;" href="javascript:fileBrowsers[\''+this.forId+'\'].moveDown('+i+');"><img style="margin: 0; border: 0; display: inline;" src="/images/icon_down.gif" /></a>';
			code += '<div style="width: '+imgWidth+'px; overflow: hidden;"><a style="display: inline;" href="'+filename+'" target="_blank">' + name+'.'+ext + '</a></div>';
	}
	
	return code;
}

FileBrowser.prototype.removeFile = function(i)
{
	var arr = this.getFilesArray();
	arr.splice(i, 1);
	this.setFilesArray(arr);
	this.generateHtmlList();
}

FileBrowser.prototype.moveUp = function(i)
{
	var arr = this.getFilesArray();
	var tmp = arr[i-1];
	arr[i-1] = arr[i];
	arr[i] = tmp;
	
	this.setFilesArray(arr);
	this.generateHtmlList();
}

FileBrowser.prototype.moveDown = function(i)
{
	var arr = this.getFilesArray();
	var tmp = arr[i+1];
	arr[i+1] = arr[i];
	arr[i] = tmp;
	
	this.setFilesArray(arr);
	this.generateHtmlList();	
}


FileBrowser.prototype.addFiles = function()
{
	new UploadsBrowser(this.forId, this.pageId, this.fileTypes, this.type1, this.type2);
}


















/*
*       UPLOADS BROWSER CLASS       
*
*
*	forid: id of input (type=hidden) which contains filelist
*	pageid: comma separated list of page ids file belongs to
*	filetype: file format (Images|*.jpg\;*.jpeg\;*.gif\;*.png)
*	type1, type2: additional variables which help to categorize files
*/
function UploadsBrowser(forId, pageId, fileTypes, type1, type2)
{
	this.forId = forId;
	this.pageId = pageId;
	this.fileTypes = fileTypes;
	this.type1 = type1;
	this.type2 = type2;
	this.containerId = this.forId + '_ub_container';
	this.ulId = this.forId + '_ub_ul';
	this.statusDivId = this.forId + '_ub_status';
	
	this.selectedIndex = -1;
	
	this.zIndex = 400;
	
	
	
	uploadsBrowsers[forId] = this;
	this.createContainer();
	this.loadFileList();
	screenLocker.lock(this.zIndex - 1);
}

UploadsBrowser.prototype.createContainer = function()
{
	var code = '';
	code += '<div class="uploads_browser_container" id="'+this.containerId+'" style="display: none; z-index: '+this.zIndex+';">';
	code += '<a style="float: left; font-weight: bold;" title="add file to the page" href="javascript:uploadsBrowsers[\''+this.forId+'\'].add();">add</a>';
	code += '<a title="view file" href="javascript:uploadsBrowsers[\''+this.forId+'\'].setStatus(\'<b>Please select file</b>\', \'red\');">view</a> | ';
	code += '<a title="remove file from this list" href="javascript:uploadsBrowsers[\''+this.forId+'\'].remove();">delete</a> | ';	
	code += '<a title="upload files" href="javascript:uploadsBrowsers[\''+this.forId+'\'].upload();">upload</a> |';
	code += '<a title="close this window" href="javascript:uploadsBrowsers[\''+this.forId+'\'].close();">close</a>';
	code += '<ul id="'+this.ulId+'">';
	code += '</ul>';
	code += '<div class="status" id="'+this.statusDivId+'">Ready</div>';
	code += '</div>';
	appendToBody(code);
}


UploadsBrowser.prototype.loadFileList = function()
{
	loadingPopup.show('Loading...');
	
	
	var options = 
	{
		asynchronous: true, 
		onSuccess: this.processFileList.bind(this),
		onFailure: this.ajaxError.bind(this)	
	};
	
	var url = '/upload.processor.php?action=get_files&page_id='+this.pageId+'&type1='+this.type1+'&type2='+this.type2;
	new Ajax.Request(url, options);	
}

UploadsBrowser.prototype.getUL = function()
{
	return $(this.ulId);
}

UploadsBrowser.prototype.getContainer = function()
{
	return $(this.containerId);
}

UploadsBrowser.prototype.show = function()
{
	Element.show(this.getContainer());
}

UploadsBrowser.prototype.hide = function()
{
	Element.hide(this.getContainer());
}

UploadsBrowser.prototype.setText = function(text)
{
	var ul = this.getUL();
	ul.innerHTML = '<li style="border-bottom: 0px; padding: 15px 0px 15px 5px">'+text+'</li>';
}


UploadsBrowser.prototype.processFileList = function(req)
{
	var files = eval(req.responseText);
	this.files = files;
		
	if (files.length == 0)
	{
		this.setText('please <a href="javascript:uploadsBrowsers[\''+this.forId+'\'].upload();">upload</a> some files');
	}
	else
	{
		var ul = this.getUL();
				
		code = '';
		var n = files.length;
		for (var i = 0; i < n; i++)
		{
			code += '<li onclick="javascript:uploadsBrowsers[\''+this.forId+'\'].select('+i+');"';
			if (i == n-1) 
				code += ' style="border-bottom: 0px;" ';
			code += '>';
			code += '<div style="border: solid 1px white; padding: 1px; cursor: pointer;">';
			code += this.generateHtmlListItem(files[i]);
			code += '</div>';
			code += '</li>';		
		}
		
		ul.innerHTML = code;
	}

	this.clearSelection();
	this.setStatus('Ready', 'black');		
	this.show();
	
	
	loadingPopup.hide();
}

UploadsBrowser.prototype.generateHtmlListItem = function(file)
{
	var parts = file.filename.match(/^.*?([^\/]+)\.([^.]+)$/);
	if (!parts[1] || !parts[2])
		return 'error';
	
	
	var name = parts[1];
	var ext = parts[2];	
	var code  = '';
	
	switch (ext.toLowerCase())
	{
		case 'jpg':
		case 'jpeg':
		case 'gif':
		case 'png':
			code += '<img style="border: 0; margin: 0;" src="'+file.filename+'" onload="fitImage(this, 200);" />';
			break;
			
		default:
			code += '<div  style="width: 200px; overflow: hidden; margin: 0px; padding: 0px;">' + name+'.'+ext + '</div>';
	}
	
	return code;		
}

UploadsBrowser.prototype.select = function(i)
{
	this.clearSelection();	
	
	this.selectedIndex = i;
	var lis = this.getUL().getElementsByTagName('li');
	var div = lis.item(this.selectedIndex).getElementsByTagName('div').item(0);
	div.style.border = 'solid 1px red';
	
	var viewLink = this.getContainer().getElementsByTagName('a').item(1);
	viewLink.href = this.files[i].filename;
	viewLink.target = '_blank';
	
	this.setStatus(this.files[this.selectedIndex].filename + ' selected', 'green');
}


UploadsBrowser.prototype.close = function()
{
	Element.remove(this.getContainer());
	screenLocker.unlock();	
}

UploadsBrowser.prototype.setStatus = function(message, color)
{
	var statusDiv = $(this.statusDivId);
		
	statusDiv.style.color = color;
	statusDiv.innerHTML = message;
}

UploadsBrowser.prototype.getFilesArray = FileBrowser.prototype.getFilesArray;
UploadsBrowser.prototype.setFilesArray = FileBrowser.prototype.setFilesArray;


UploadsBrowser.prototype.add = function()
{
	if (this.selectedIndex == -1)
	{
		this.setStatus('<b>Please select file</b>', 'red');
	}
	
	var input = $(this.forId);
	var arr = this.getFilesArray();
	arr.push(this.files[this.selectedIndex].filename);
	this.setFilesArray(arr);
	
	fileBrowsers[this.forId].generateHtmlList();
	this.setStatus(this.files[this.selectedIndex].filename + ' added', 'green');
	
	
}

UploadsBrowser.prototype.remove = function()
{
	if (this.selectedIndex == -1)
	{
		this.setStatus('<b>Please select file</b>', 'red');
	}
	
	
	loadingPopup.show('Loading...');
	
	var options = 
	{
		asynchronous: true, 
		onSuccess: this.processFileList.bind(this),
		onFailure: this.ajaxError.bind(this)	
	};
	
	var url = '/upload.processor.php?action=delete&file_id='+this.files[this.selectedIndex].file_id+'&page_id='+this.pageId+'&type1='+this.type1+'&type2='+this.type2;
	new Ajax.Request(url, options);	
}


UploadsBrowser.prototype.clearSelection = function()
{
	var lis = this.getUL().getElementsByTagName('li'); 
	for (var i = 0; i < lis.length; i++)
	{
		var div = lis.item(i).getElementsByTagName('div').item(0);
		if (div)
			div.style.border = 'solid 1px white';
	}
	

	selectedIndex = -1;
	
	
	var viewLink = this.getContainer().getElementsByTagName('a').item(1);
	viewLink.href = 'javascript:uploadsBrowsers[\''+this.forId+'\'].setStatus(\'<b>Please select file</b>\', \'red\');';
	viewLink.target = '_self';
}

UploadsBrowser.prototype.upload = function()
{
	new FileUploader(this);
}

UploadsBrowser.prototype.ajaxError = function(req)
{
	alert('Error!');
	loadingPopup.hide();
	screenLocker.unlock();
}



/*
*       FILE UPLOADER CLASS       
*/

function FileUploader(uploadsBrowser)
{
	this.pageId = uploadsBrowser.pageId;
	this.fileTypes = uploadsBrowser.fileTypes;
	this.type1 = uploadsBrowser.type1;
	this.type2 = uploadsBrowser.type2;
	this.ulId = uploadsBrowser.ulId;
	this.uploadsBrowser = uploadsBrowser;
	this.containerId = this.ulId + '_uploader';
	this.closeLinkId = this.ulId + '_close';
	
	this.working = false;
	this.zIndex = 410;
	
	
	
	uploaders[this.ulId] = this;
	this.show();	
	screenLocker.lock(this.zIndex - 1);
}


FileUploader.prototype.show = function()
{
	code = '';
	code += '<div class="uploader" id="'+this.containerId+'">';
	
	code += '<div class="hdr">';
	code += '<a id="'+this.closeLinkId+'" href="javascript:uploaders[\''+this.ulId+'\'].close();">close</a>';
	code += '</div>';
	
	code += '<div>';
	code += '<iframe style="border: 0px; padding: 0px; margin: 0px;" frameborder="0" src="/uploader.php?page_id='+this.pageId+'&type1='+this.type1+'&type2='+this.type2+'&file_types='+this.fileTypes+'&close_link_id='+this.closeLinkId+'" width="400" height="330"></iframe>';
	code += '</div>';
	
	code += '</div>';
	
	appendToBody(code);
}

FileUploader.prototype.close = function()
{
	if (this.working)
	{
		alert("Cannot close window...\nfile transfer in progress");
		return;
	}
	
	screenLocker.unlock();
	Element.remove($(this.containerId));
	this.uploadsBrowser.loadFileList();
}




/*
*       SCREEN LOCKER CLASS       
*/
function ScreenLocker()
{
	this.id = 'locker_'+screenLockerId;
	this.indexArr = new Array();
	
	screenLockerId++;
}








ScreenLocker.prototype.create = function(zIndex)
{
	var body = getBody();
	
	
	appendToBody('<div id="'+this.id+'" style="position: absolute; display: none;"></div>');
		
	
	
	locker = $(this.id);
	locker.style.left = '0px';
	locker.style.top = '0px';
	locker.style.width = '100%';
	locker.style.height = Element.realHeight($('theBodyContainer'))+'px';
	locker.style.background = 'white';
	Element.setOpacity(locker, 0.8);
	
	this.setZIndex(zIndex);
	Element.show(locker);
}


ScreenLocker.prototype.setZIndex = function(zIndex)
{
	$(this.id).style.zIndex = zIndex;
}

ScreenLocker.prototype.isLocked = function()
{
	if ($(this.id))
		return true;
	else
		return false;
}

ScreenLocker.prototype.lock = function(zIndex)
{
	if (this.isLocked())
		this.setZIndex(zIndex);
	else
		this.create(zIndex);
		
	this.indexArr.push(zIndex);
}

ScreenLocker.prototype.unlock = function()
{
	this.indexArr.pop();
	if (this.indexArr.length == 0)
	{
		this.unlockAll();
		return;
	}
	
	this.setZIndex(this.indexArr.last());
	
}



ScreenLocker.prototype.unlockAll = function()
{
	var body = getBody();
	
	this.indexArr = new Array();
	Element.remove($(this.id));
}



/*
*         FCKEDITOR POPUP
*/


function FckPopup(forId)
{
	this.forId = forId;
	this.id = this.forId + '_div';
	this.editorId = this.forId + '_editor';
	
	this.zIndex = 400;
	
	fckPopups[this.forId] = this;
	
	
	this.create();
	this.show();
}

FckPopup.prototype.classId = 0;
var fckPopups = new Array();

FckPopup.prototype.create = function()
{
	var code = '';
	code += '<div id="'+this.id+'" style="visibility: hidden; position: absolute; left: 120px; top: 200px;">';
	code += '<form>';
	code += '<textarea id="'+this.editorId+'" name="'+this.editorId+'" style="width: 100%; height: 100%">' +$(this.forId).value+ '</textarea>';
	code += '<br /><br />';
	code += '<input style="width: 100px;" type="button" value="OK" onclick="fckPopups[\''+this.forId+'\'].submit();"> '
	code += '<input style="width: 100px;" type="button" value="Cancel" onclick="fckPopups[\''+this.forId+'\'].close();">'
	code += '</form>';
	code += '</div>';

	appendToBody(code);
	
	this.fck = new FCKeditor(this.editorId);
	this.fck.BasePath = "/FCKeditor/";
	this.fck.Config['CustomConfigurationsPath'] = '/FCKeditor/myConfig.js';
	this.fck.Width = 640;
	this.fck.Height = 480;
	this.fck.ReplaceTextarea();
}

FckPopup.prototype.show = function()
{
	var div = $(this.id);
	
	div.style.padding = '5px';
	div.style.textAlign = 'right';
	div.style.background = 'white';
	div.style.border = 'solid 1px black';
	div.style.zIndex = this.zIndex;
	
	
	
	loadingPopup.show('Loading...');
	
	//this.onEditorLoad();
}

FckPopup.prototype.close = function()
{
	Element.remove($(this.id));
	screenLocker.unlock();	
}


FckPopup.prototype.submit = function()
{
	var editor = FCKeditorAPI.GetInstance(this.editorId);
	var value = editor.GetXHTML(true);
	
	$(this.forId).value = value;
	$(this.forId+'_container').innerHTML = value;
	this.close();

}


FckPopup.prototype.onEditorLoad = function()
{
	screenLocker.lock(this.zIndex - 1);
	
	var div = $(this.id);
	div.style.visibility = 'visible';
	
	var editor = FCKeditorAPI.GetInstance(this.editorId);
	editor.Focus();
	
	loadingPopup.hide();
}



function popupFck(forId)
{
	new FckPopup(forId);
}


function FCKeditor_OnComplete(editorInstance)
{
	var edName = editorInstance.Name;
	var tmp = edName.match(/(.+)_editor$/);
	
	if (!tmp)
		return;
		
	fckPopups[tmp[1]].onEditorLoad();
		
}







/*
*           LOADING POPUP CLASS
*/

function LoadingPopup(zIndex)
{
	this.id = 'loading_'+LoadingPopup.prototype.classId;
	this.zIndex = 500;
	LoadingPopup.prototype.lockerId++;
}

LoadingPopup.prototype.classId = 1;

LoadingPopup.prototype.show = function(text)
{
	var body = getBody();
	appendToBody('<div id="'+this.id+'" style="z-index: '+this.zIndex+'; position: absolute; display: none;"><div style="float: right;">'+text+'</div></div>');		
	
	var divContainer = $(this.id);
	var divInner = divContainer.firstChild;
	
	divContainer.style.left = '0px';
	divContainer.style.top = '0px';
	divContainer.style.width = '100%';
	divContainer.style.height = Element.realHeight($('theBodyContainer'))+'px';
	
	
	divInner.style.padding = '3px 10px 4px 15px';
	divInner.style.color = 'white';
	divInner.style.background = '#8B0000';
	divInner.style.fontWeight = 'bold';
	divInner.style.position = 'static';
	divInner.style.width = 'auto';
	divInner.style.height = 'auto';
	
	Element.show(divContainer);
}

LoadingPopup.prototype.hide = function()
{
	Element.hide($(this.id));
}
