var SickTools = Class.create ({
	
	initialize: function() {
		this.inputFileId = 0;
	},
	
	// metoda ustawiajaca Event na obiekcie 'funcExe'
	// odpalany tylko z poziomu metody sm.getSessionStatus();
	// potrzebne po to by odswiezac zawartosc obiektow ktorych content zalezy od statusu sesji
	setFunctionHandler: function(funcToCall) {
		Event.observe($('funcExe'), 'sick:exe', funcToCall);
	},
	
	unsetFunctionHandler: function(funcToCall) {
		Event.stopObserving($('funcExe'), 'sick:exe', funcToCall);
	},
		
	sickLogout: function() 
	{
		$('logout').fire('sick:click');
	},
	
	reloadInterface: function()
	{
		im.onClick('reload');
		//alert('reload!');
	},
	
	adminOverlay: function(todo)
	{
		var array = $$('.admin');//$(cm.contentID).select('.admin');
		
		switch (todo)
		{
		case 'show':
			array.each(function(element){ element.show(); });
			$('navEditUsers').show();
			break;
		case 'hide':
			array.each(function(element){ element.hide(); });
			$('navEditUsers').hide();
			break;
		default:
			array.each(function(element){
			if(!element.visible()) 	{ element.show(); $('navEditUsers').show(); }
			else 					{ element.hide(); $('navEditUsers').hide();	}
			});
			break;
		}
	},
	
	delBlobRecord: function($id, $name) {
		if (confirm('Are You sure, You want to delete image: '+$name)) {
			new Ajax.Request('php/FormProcessor.php', {
				method: 'post',
				parameters: { action:'delOneBlobRecord', recID:$id, table:''},
				
				onCreate: function() {
					$('editFormStatus').update(mm.getStatusMsg('loader'));
				},
				
				onSuccess: function(transport) {
					$('editFormStatus').update('');
					ajaxResponse = transport.responseText;
				},
				
				onComplete: function() {
					if (ajaxResponse = 'True') {
						$($name+$id).remove();
						tools.reloadInterface();
					}
				}
			});
		}
		else {}
	},
	
	modBlobRecord: function($id, $name) {
		$newDesc = prompt('Please enter new description for image: '+$name);
		if ($newDesc != '' && $newDesc != null) {
			new Ajax.Request('php/FormProcessor.php', {
				method: 'post',
				parameters: { action:'modBlobRecord', recID:$id, table:'', newDesc:$newDesc},
				
				onCreate: function() {
					$('editFormStatus').update(mm.getStatusMsg('loader'));
				},
				
				onSuccess: function(transport) {
					$('editFormStatus').update('');
					ajaxResponse = transport.responseText;
				},
				
				onComplete: function() {
					if (ajaxResponse = 'True') {
						$('desc'+$name+$id).update('Desc.: '+$newDesc);
						tools.reloadInterface();
					}
				}
			});
		}
	},
	
	createFileInput: function() {
		$('editForm').setAttribute('userfiles','true');
	
		var newId = ++this.inputFileId;
		var trueInputId = 'trueInput' + newId;
		var fakeInputId = 'fakeInput' + newId;
		
		var removeLink = document.createElement('a');
			removeLink.href = 'javascript:tools.removeFileInput(\''+trueInputId+'\');';
			removeLink.className = 'small';
			removeLink.innerHTML = 'remove file';
		
		var showDescLink = document.createElement('a');
			showDescLink.setAttribute('onclick', 'javascript:$(\'descContainer'+trueInputId+'\').toggle()');
			showDescLink.className = 'small';
			showDescLink.innerHTML = 'add or remove description';
		
		var adviceContainer = document.createElement('div');
			adviceContainer.id = 'advice-'+trueInputId+'-container';
		
		var fieldDesc = document.createElement('div');
			fieldDesc.className = 'fieldDesc';
		
		var splitter = document.createElement('span');
			splitter.innerHTML = ' | ';
		
		var filedDescLink = fieldDesc.cloneNode(true);
			filedDescLink.appendChild(removeLink);
			filedDescLink.appendChild(splitter);
			filedDescLink.appendChild(showDescLink);
			
			adviceContainer.appendChild(filedDescLink);
			adviceContainer.appendChild(document.createElement('br'));
		
		var fieldDescDesc = fieldDesc.cloneNode(true);
			fieldDescDesc.id = 'descfield'+trueInputId;
			fieldDescDesc.innerHTML = 'Add description to a file, if required.';
		
		var inputWrapper = document.createElement('div');	
			inputWrapper.className = 'inputWrapper';
		
		var descInput = document.createElement('textarea');
			descInput.name = 'desc'+trueInputId;
			descInput.value = '';
			descInput.id = 'desc'+trueInputId;
			descInput.className = 'normalTextAreaFileDesc';
//		var descInput = document.createElement('input');
//			descInput.type = 'text';
//			descInput.name = 'desc'+trueInputId;
//			descInput.value = '';
//			descInput.id = 'desc'+trueInputId;
//			descInput.className = 'normalText';
		var descContainer = document.createElement('div');
			descContainer.style.display = 'none';
			descContainer.id = 'descContainer'+trueInputId;
			descContainer.appendChild(descInput);
			descContainer.appendChild(fieldDescDesc);
		
		var trueFileInput = document.createElement('input');
			trueFileInput.type = 'file';
			trueFileInput.size = '35';
			trueFileInput.name = 'userfiles[]';
			trueFileInput.className = 'trueFileInput hidden required';
			trueFileInput.id = trueInputId;
		
		var fakeFileInput = document.createElement('div');
			fakeFileInput.className = 'fakeFileInput';
			fakeFileInput.id = fakeInputId;
			fakeFileInput.appendChild(document.createElement('input')).className = 'normalFile';
			fakeFileInput.appendChild(document.createElement('br'))
			fakeFileInput.appendChild(adviceContainer);
		
		inputWrapper.appendChild(trueFileInput.cloneNode(true));
		inputWrapper.appendChild(fakeFileInput.cloneNode(true));
		
		var clone = inputWrapper.appendChild(inputWrapper.cloneNode(true));
		var fileBox = $('fileBox')
			fileBox.appendChild(descContainer);
			fileBox.appendChild(clone);
			
		Event.observe(trueInputId,'mouseout',function(event){
			$(fakeInputId).down(0).value = this.value;
			
			/*
			propozycja dzialania:
			1. uzywamy iframe, do odpalenia procedury w phpie, ktora rozpocznie upload
			2. submit na formularzu do plikow jest wolany z procedury submit calego dokumentu po dodaniu rekordu (mamy juz id do linkow)
			3. JS w locie musi sprawdzac zawartosc input file by ocenic czy pliki moga byc dodane (???)
			4. po zakonczeniu php uploadujacy pliki, wypluwa JSa, ktory zamyka procedure dodawania rekordu (zwija forma i uwalnia close window)
			5. jesli polecialy bledy, robimy del na dodanym rekordzie, zwracamy blad i uwalniamy forma
			*/
		});
	},
	
	removeFileInput: function(inputId) {
		$('desc'+inputId).remove();
		$('descfield'+inputId).remove();
		$(inputId).up(0).remove();
		
//		if ($$('div.inputWrapper').inspect() == "[]")
//			$('editForm').setAttribute('userfiles','false');
	},
	
	fromArrToStr: function(array) {
		var tmpStr;
		
		array.each(function(s,index){
			if (index!='0')
				tmpStr+=index+' '+s;
			else
				tmpStr+=s+'<br/>';
			
			tmpStr+=' ';
			});
		
		return tmpStr;
	},
	
	wyswigControl: function(newStatus) {
		if ($('editForm')) {
			switch(newStatus)
			{
				case 'turnOn':
					if($('editForm').select('textarea')) {
						$('editForm').select('.wyswig').each(function(element){
							tinyMCE.execCommand('mceAddControl', false, element.identify());
						}); 
					}	
					break;
				case 'turnOff':
					if($('editForm').select('textarea')) {
						$('editForm').select('.wyswig').each(function(element){
							tinyMCE.execCommand('mceRemoveControl', false, element.identify());
						}); 
					}
					break;
			}
		}
	},
	
	getPageSize: function() {

	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 if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
		xScroll = document.documentElement.scrollWidth;
		yScroll = document.documentElement.scrollHeight;
	} else { // Explorer Mac...would also work in 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;
	}

});

var ImagePreloader = Class.create({

	initialize: function(images) {
		
		this.aImages = new Array;
		
		for ( var i = 0; i < images.length; i++ )
			this.preload(images[i], i);
			
		
	},
	
	preload: function(image, i) {
		
		this.aImages[i] = new Image();
		this.aImages[i].src = imgDir+image;
	}
});

var SessionManager = Class.create ({
	
	initialize: function() {
		this.sessionStatus = '';
		this.sessionNavigateID = '';
		this.sessionContentID = '';
		this.sessionStartPage = '';
		this.sessionMaxOnPage = '';
		this.sessionOrderBy = '';
		
		this.session = false;
	},
		
	getSession: function() {
		return sm.session;
	},
	
	// metoda obslugujaca zagadnienia zwiazane ze statusem uzytkownika przegladajacego tresc strony
	// wykorzystujemy ja wszedzie tam gdzie zmieniamy status uzytkownika i jednoczesnie chcemy odswiezyc 
	// zawartosc czesci serwisu przy uzyciu metody typu: set....Container
	// sposob jej wykorzystania jest nastepujacy:
	// 1. najpierw nalezy ustawic obsloge zdarzenia odpalanego po pobraniu statusu sesji
	// 		ufem.setFunctionHandler('setUserFormContainer');
	// 2. nastepnie wywolac sama metode
	//		sm.getSessionStatus();
	// mtoda wysyla zapytanie do PHPa i w odpowiedz dostaje jedna z trzech wartosci: user, admin, null
	// nastepnie odpala zdarzenie ustawione na obiekcie 'funcExe'
	getSessionStatus: function() {
		new Ajax.Request('php/SessionProcessor.php', {
			method: 'post',
			parameters: { },
			
			onSuccess: function(transport) {
				tmp = (transport.responseText).evalJSON(true);
					sm.session = true;
				// sessionStatus
					sm.sessionStatus = tmp.status;
				// interface	
					sm.sessionNavigateID = tmp.navID;
					sm.sessionContentID = tmp.conID;
					sm.sessionStartPage = tmp.startPage;
					sm.sessionMaxOnPage = tmp.maxOnPage;
					sm.sessionOrderBy = tmp.orderBy;
			},
			
			onComplete: function() {
				$('funcExe').fire('sick:exe');
				
				//im = new InterfaceManager();
				
				if (sm.sessionStatus == 'admin')
					tools.adminOverlay();
			}
		});
	}
});

function toggleEditor(id) {
	if (!tinyMCE.get(id))
		tinyMCE.execCommand('mceAddControl', false, id);
	else
		tinyMCE.execCommand('mceRemoveControl', false, id);
}

function isSet(variable) {
      return (typeof(variable) != 'undefined');
}

function contains(word,phrase) {
	if (word.match(phrase) != 'null')
		return true
	else
		return false
}

function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
		}

	return vars;
}

function returnTransport(response) {return response}