// MOVEMENT FUNCTIONS

function requiem_action() { // (n)move = array(startpoint, endpoint, acceleration)
	this.element='';
	this.cycle = 0;
	this.cycles = 10;
	this.fps = 40;//ms
	
	this.xmove='';
	this.ymove='';
	this.wmove='';
	this.hmove='';
	this.hmove='';
	this.amove='';
	
	this.callback = '';
	
	this.obj;
	this.coords = new Array();
	this.timer;
	this.id = requiemInstances.length;
	requiemInstances[this.id] = this;
	
	
	this.go = function(o,x,y,w,h,a){
		if(!undef(o)){if(o!=''){this.element = o;}}
		if(!undef(x)){if(is_array(x)){this.xmove=x;}}
		if(!undef(y)){if(is_array(y)){this.ymove=y;}}
		if(!undef(w)){if(is_array(w)){this.wmove=w;}}
		if(!undef(h)){if(is_array(h)){this.hmove=h;}}
		if(!undef(a)){if(is_array(a)){this.amove=a;}}
		
		this.obj = objektas(this.element);
		var xa = fix_coordinates(this.xmove, this.obj, 'x');
		var ya = fix_coordinates(this.ymove, this.obj, 'y');
		var wa = fix_coordinates(this.wmove, this.obj, 'w');
		var ha = fix_coordinates(this.hmove, this.obj, 'h');
		var aa = fix_coordinates(this.amove, this.obj, 'a');
		
		if(this.xmove!=''){setProperty(this.obj, 'x', xa[0]);}
		if(this.ymove!=''){setProperty(this.obj, 'y', ya[0]);}
		if(this.amove!=''){setProperty(this.obj, 'a', aa[0]);}
		if(this.wmove!=''){setProperty(this.obj, 'w', wa[0]);}
		if(this.hmove!=''){setProperty(this.obj, 'h', ha[0]);}
		
		this.coords['x']=xa;
		this.coords['y']=ya;
		this.coords['w']=wa;
		this.coords['h']=ha;
		this.coords['a']=aa;
		
		this.move();
	}
	
	this.move = function(){
		clearTimeout(this.timer);
		
		for(i in this.coords){
			if(this.coords[i][0]!=this.coords[i][1]){
				var acc = acceleration(this.coords[i][0], this.coords[i][1], this.coords[i][2], this.cycle, this.cycles);
				var newc = this.coords[i][3] + acc;
				this.coords[i][3] = newc;
			
				setProperty(this.obj,i,round(newc,0));
				
				if(this.cycle >= this.cycles){setProperty(this.obj, i, this.coords[i][1]);}
			}
		}
		
		this.cycle++;
		if(this.cycle < this.cycles){
			this.timer = setTimeout('requiemInstances['+this.id+'].move()',this.fps);
		}
		else {
			if(this.callback!=''){eval(this.callback);}
		}
	}
}
	
function acceleration(x1, x2, a, n, cycles) {
	if(a==0){dx = acceleration0(x1, x2, n, cycles);}
	else {dx = acceleration1(x1, x2, a, n, cycles);}
	return dx;
}

function acceleration0(x1, x2, n, cycles) {
	var out = (x2-x1) / cycles;
	return out;
}

function acceleration1(x1, x2, a, n, cycles) {
	n = n+1;
	var o = (cycles+1) / 2;
	var v = (x2-x1) / cycles;
	
	var out = v + ((o-n)*v*a) / (100*o);
	
	return out;
}


function fix_coordinates(s, obj, tipas){
	var out = new Array();
	if(is_array(s)) {
		var pos = koordinates(obj);
		
		if(typeof(s[0])=='number'){out[0] = s[0];}
		else {out[0] = getProperty(obj, tipas);}
		
		if(typeof(s[1])=='number'){out[1] = s[1];}
		else {out[1] = getProperty(obj, tipas);}
		
		if(typeof(s[2])=='number'){out[2] = s[2];}
		else {out[2] = 0;}
	}
	else {
		var pos = getProperty(obj, tipas);
		out[0] = pos;
		out[1] = pos;
		out[2] = 0;
	}
	out[3] = out[0];
	return out;
}


function round(val, dec) {
	dec = parseInt(dec);
	var d = Math.pow(10,dec)
	return Math.round(val*d)/d;
}

var requiemInstances = new Array();
	
	

// PROPERTY FUNCTIONS

function getProperty(obj, savybe) {
	obj = objektas(obj);
	if(savybe=='x'){var temp = koordinates(obj); return temp[0];}
	else if(savybe=='y'){var temp = koordinates(obj); return temp[1];}
	else if(savybe=='w'){var temp = findDim(obj); return temp[0];}
	else if(savybe=='h'){var temp = findDim(obj); return temp[1];}
	
	else if(savybe=='a') {
		if(obj.style.opacity){var temp = (obj.style.opacity)*100; if(temp==''){temp=100;} return temp;}
		else {return 100;}
	}
	
	else if(savybe=='sx') {var temp = getPageScroll(); return temp[0];}
	else if(savybe=='sy') {var temp = getPageScroll(); return temp[1];}
	
	else if(savybe=='px') {var temp = getPageSize(); return temp[0];} 
	else if(savybe=='py') {var temp = getPageSize(); return temp[1];} 
	else if(savybe=='wx') {var temp = getPageSize(); return temp[2];} 
	else if(savybe=='wy') {var temp = getPageSize(); return temp[3];} 
}

function setProperty(obj, savybe, value) {
	obj = objektas(obj);
	if(savybe=='x'){obj.style.left = value;}
	else if(savybe=='y'){obj.style.top = value;}
	else if(savybe=='w'){obj.style.width = value;}
	else if(savybe=='h'){obj.style.height = value;}
	else if(savybe=='a'){
		obj.style.opacity = value/100;
		obj.style.filter = 'alpha(opacity='+value+')';
	}
}

function copyProperty(source,target,property){
	setProperty(target,property,getProperty(source,property));
}


function mousePos(e) {
	var out = new Array();
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		out[0] = e.pageX;
		out[1] = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		var scr = getPageScroll();
		out[0] = e.clientX + scr[0];
		out[1] = e.clientY + scr[1];
	}
	return out;
}




// PAGALBINES FUNKCIJOS
function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}


function showFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "visible";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "visible";
	}
}

function hideFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "hidden";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "hidden";
	}

}

function clearFileInputField(tagId) {
    ge(tagId).innerHTML = ge(tagId).innerHTML;
}



function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
}



function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		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
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			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 = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


function koordinates(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}

	return [curleft,curtop];
}

function findDim(obj) {
	return [obj.offsetWidth,obj.offsetHeight];
}


function scrollpage(y2, a, ciklu){
	var y1 = getProperty('','sy');
	scrollpage_ft(y1, y2, a, ciklu, 0);
}

function scrollpage_ft(y1, y2, a, ciklu, n) {
	if(undef(n)){n=0;}
	n++;
	var dy = acceleration(y1,y2,a,n,ciklu);
	dy = Math.round(dy);
	window.scrollBy(0,dy);
	
	if(n<ciklu){setTimeout('scrollpage_ft('+y1+','+y2+','+a+','+ciklu+','+n+')',40);}
}


// HTML FUNKCIJOS
function addRow(table_id, row_nr, row_id, cols) {
	var tbl = ge(table_id);
	if(row_nr == 'last'){row_nr = countRows(table_id);}
	var row = tbl.insertRow(row_nr);
	if(!undef(row_id)){row.id = row_id;}
	if(is_array(cols)){
		for(var i=0; i<cols.length; i++){
			var cell = row.insertCell(i);
			cell.innerHTML = cols[i];
		}
	}
}

function countRows(table_id){
	return document.getElementById(table_id).getElementsByTagName("TR").length;
}

function insert_before(elem,dest){
	elem = objektas(elem); dest = objektas(dest);
	dest.parentNode.insertBefore(elem,dest);
}

function remove(obj){
	obj = objektas(obj);
	obj.parentNode.removeChild(obj);
}

function createhidden(target,name,id,value) {
	currentElement = document.createElement("input");
	currentElement.setAttribute("type", "hidden");
	currentElement.setAttribute("name", name);
	currentElement.setAttribute("id", id);
	currentElement.setAttribute("value", value);
	document.getElementById(target).appendChild(currentElement);
}

function html(elem,value,append){
	obj = objektas(elem);
	if(typeof(obj)!='object') {obj = ge(elem);}
	if(undef(append)){append = false;}
	
	if(!undef(obj)){
		if(append){obj.innerHTML+= value;}
		else{obj.innerHTML = value;}
	}
}

function setcss(elem,css){
	elem = objektas(elem);
	elem.className+= ' '+css;
}
function delcss(elem,css){
	elem = objektas(elem);
	elem.className = elem.className.replace(css,'');
}


// PAPILDOMOS FUNKCIJOS
function nalpha(elem,alpha){
	alpha = Math.round(alpha);
	var el = ge(elem);
	if(el.style.opacity){el.style.opacity=alpha/100;}
	if(el.filters){el.filters.alpha.opacity=alpha;}
}

function ge(elem) {
	return document.getElementById(elem);
}

function gv(elem) {
	var obj = objektas(elem);
	if(exists(obj)){return obj.value;}
	else {return '';}
}

function sv(elem,val) {
	if(undef(val)){val = '';}
	return document.getElementById(elem).value = val;
}

function objektas(elem){
	obj = elem;
	if(typeof(elem)!='object') {obj = ge(elem);}
	return obj;
}

function hide(elem) {
	obj = objektas(elem);
	obj.style.display = 'none';
}

function show(elem,mode) {
	if(undef(mode)){mode = '';}
	obj = objektas(elem);
	obj.style.display = mode;
}

function toggle(elem,mode){
	if(undef(mode)){mode = '';}
	if(is_hidden(elem)){show(elem,mode);}
	else {hide(elem);}
}

function is_hidden(elem){
	obj = objektas(elem);
	if(obj.style.display=='none'){return true;} else {return false;};
}


function is_array(input){    
	return typeof(input)=='object'&&(input instanceof Array);
}

function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) {return false;}
	else {return true;}
}

function enter(event) {
	if(key(event)==13){return true;}
	return false;
}

function key(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	return keycode;
}

function undef(kint) {
	if(kint==null) {return true;}
	if(typeof(kint)=="undefined"){return true;}
	return false;
}

function exists(obj) {
	obj = objektas(obj);
	if(obj!=null){return true;}
	return false;
}

function basename(path) {
    return path.replace( /.*\//, "" );
}

function dirname(path) {
    return path.match( /.*\// );
}

function nl2br(text){
	text = escape(text);
	return unescape(text.replace(/%0D%0A/g,'<br>'));
}

function r2r(l1,l2) {
	objektas(l2).value = objektas(l1).value;
}

function html2html(l1,l2) {
	objektas(l2).innerHTML = objektas(l1).innerHTML;
}

function skaicius(val) {
	val = val.replace(',','.');
	var sk = parseFloat(val);
	if(isNaN(sk)){sk = 0;}
	return sk;
}
function skaicius_lt(val) {
	val = val+'';
	val = val.replace('.',',');
	return val;
}

function find(tekstas, fragm) {
	tekstas = tekstas.toLowerCase(); 
	fragm = fragm.toLowerCase(); 
	if(fragm==''){return true;}
	if(tekstas.indexOf(fragm)==-1){return false;}
	else {return true;}
}

function unhtmlspecialchars(str) {
	var out = str;
	out = out.replace(/&amp;/g,'&');
	out = out.replace(/&gt;/g,'>');
	out = out.replace(/&lt;/g,'<');
	out = out.replace(/&quot;/g,'"');
	return out;
}

function timestamp(){
	var laikas = new Date();
	return laikas.getTime();
}

function getElementsByClassName(searchClass,node,tag) {
        var classElements = new Array();
        if ( node == null )
                node = document;
        if ( tag == null )
                tag = '*';
        var els = node.getElementsByTagName(tag);
        var elsLen = els.length;
        var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
        for (i = 0, j = 0; i < elsLen; i++) {
                if ( pattern.test(els[i].className) ) {
                        classElements[j] = els[i];
                        j++;
                }
        }
        return classElements;
}


function strip_tags (str, allowed_tags) {
	var key = '', allowed = false;
	var matches = []; var allowed_array = [];
	var allowed_tag = '';
	var i = 0;
	var k = '';
	var html = ''; 
	var replacer = function(search, replace, str) {return str.split(search).join(replace);};
	// Build allowes tags associative array
	if(allowed_tags) {allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);}
	str += '';

	// Match tags
	matches = str.match(/(<\/?[\S][^>]*>)/gi);
	// Go through all HTML tags
	for (key in matches) {
	if (isNaN(key)) {continue;}
		// Save HTML tag
		html = matches[key].toString();
		allowed = false;
 
		// Go through all allowed tags
		for (k in allowed_array) {
		    allowed_tag = allowed_array[k];
		    i = -1;
		    if(i!=0) {i=html.toLowerCase().indexOf('<'+allowed_tag+'>');} if(i!=0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
		    if(i!=0) {i =html.toLowerCase().indexOf('</'+allowed_tag);}
		    if(i==0) {allowed = true; break;}
		}
		if (!allowed) {str = replacer(html, "", str);}
	}
	return str;
}



// COOKIE FUNKCIJOS
function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) {c_end=document.cookie.length;}
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}





// AJAX FUNKCIJOS
var http = createRequestObject();
var ajaxText = '';


function ajax_siusti(keys, vals, target, callback, test) { 
	if(undef(target)){target = 'ajax.php';}
	if(undef(callback)){callback = '';}
	if(undef(test)){test = false;}
	
	var suburl = parametrai(keys, vals);
	http.open('get', target+suburl); 
	http.onreadystatechange = function(){handleResponse(callback,test);}; 
	http.send(null);
}

function rezultatai(callback){
	//var ev = ajaxText.replace(/=/g, ':');
	var ev = ajaxText;
	if(callback!=''){
		var func = callback+'("'+ev+'");';
		eval(func);
	}
}


function parametrai(keys, vals){
	var out='';
	var params = '?';
	
	for(var i=0; i<keys.length; i++) {
		params+= keys[i]+'='+utf8_ajax(vals[i])+'&';
	}
	
	var laikas = new Date();
	params+= 'rand='+laikas.getTime();
	
	return params;
}

function parse_get(str, mod) {
	if(undef(mod)){mod = '=';}
	var out = new Array();
	var rezs = new Array();
	var blocks = new Array();
	blocks = str.split('&');
	if(blocks.length==0){blocks[0] = str;}
	
	for(var i=0; i<blocks.length; i++) {
		rezs = new Array();
		rezs = blocks[i].split('=');
		out[rezs[0]] = rezs[1];
	}
	return out;
}




function handleResponse(callback,test) { 
	if(undef(test)){test = false;}
	if(http.readyState == 4){
		var response = http.responseText; 
		if(response) { 
			if(test){alert(response);}
			ajaxText = response;
			rezultatai(callback);
		}
	}
}
	
function createRequestObject() { 
	var req; 
	try {
		req=new XMLHttpRequest();  // Firefox, Opera 8.0+, Safari  
	}
	catch (e) {
		try {
			req=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer  
		}
		catch (e){
			try {
				req=new ActiveXObject("Microsoft.XMLHTTP");	  
			}
			catch (e) {
				return false;	  
			}	
		}  
	}
	return req; 
}


function ajax_decode(str){
	str = unescape(str);
	str = unhtmlspecialchars(str);
	return str;
}

function utf8_ajax(formVar) {
	var result = encodeURIComponent(formVar);
	result = result.replace(/%20/g,"+");
	for ( var p = result.indexOf("%u"); p != -1; p = result.indexOf("%u")  ) {
		var code = result.substr(p,6);
		var rep = '%' + code.substr(2,2) + '%' + code.substr(4,2);
		result = result.replace(code,rep);
	}
	var p = -1;
	for ( p = result.indexOf("%",p+1); p != -1; p = result.indexOf("%",p+1)  ) {
		var code = result.substr(p,3);
		var rep = code.toUpperCase();
		result = result.replace(code,rep);
	}
	return result;
}


function utf8_encode(string) {   
    string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");   
  
    var utftext = "";   
    var start, end;   
    var stringl = 0;   
  
    start = end = 0;   
    stringl = string.length;   
    for (var n = 0; n < stringl; n++) {   
        var c1 = string.charCodeAt(n);   
        var enc = null;   
  
        if (c1 < 128) {   
            end++;   
        } else if((c1 > 127) && (c1 < 2048)) {   
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);   
        } else {   
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);   
        }   
        if (enc != null) {   
            if (end > start) {   
                utftext += string.substring(start, end);   
            }   
            utftext += enc;   
            start = end = n+1;   
        }   
    }   
  
    if (end > start) {   
        utftext += string.substring(start, string.length);   
    }   
  
    return utftext;   
}



// PAPILDOMOS FUNKCIJOS
function getFlashMovieObject(movieName){
	if (window.document[movieName]) {return window.document[movieName];}
	if (navigator.appName.indexOf("Microsoft Internet")==-1){
		if (document.embeds && document.embeds[movieName])
		return document.embeds[movieName]; 
	}
	else {return document.getElementById(movieName);}
}

function setFlashvar(movie, variable, val){
	getFlashMovieObject(movie).SetVariable(variable, val);
}



function emotion(text,oid) {  
    var obj = ge(oid);
    if(document.selection) {  
        obj.focus();  
        var orig = obj.value.replace(/\r\n/g, "\n");  
        var range = document.selection.createRange();  
 
        if(range.parentElement() != obj) {  
            return false;  
        }  
 
        range.text = text;  
          
        var actual = tmp = obj.value.replace(/\r\n/g, "\n");  
 
        for(var diff = 0; diff < orig.length; diff++) {  
            if(orig.charAt(diff) != actual.charAt(diff)) break;  
        }  
 
        for(var index = 0, start = 0;   
            tmp.match(text)   
                && (tmp = tmp.replace(text, ""))   
                && index <= diff;   
            index = start + text.length  
        ) {  
            start = actual.indexOf(text, index);  
        }  
    } else if(obj.selectionStart) {  
        var start = obj.selectionStart;  
        var end   = obj.selectionEnd;  
 
        obj.value = obj.value.substr(0, start)   
            + text   
            + obj.value.substr(end, obj.value.length);  
    }  
      
    if(start != null) {  
        setCaretTo(obj, start + text.length);  
    } else {  
        obj.value += text;  
    }  
}  
 
function setCaretTo(obj, pos) {  
    if(obj.createTextRange) {  
        var range = obj.createTextRange();  
        range.move('character', pos);  
        range.select();  
    } else if(obj.selectionStart) {  
        obj.focus();  
        obj.setSelectionRange(pos, pos);  
    }  
} 

