

src=$('script[src*="common.js"]').first().attr('src');
window.SITEROOT=src.match(/(.*)\/js\/(.*)\.js/)[1]+'/';

var ALT=0,CTRL=0,SHIFT=0;

function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

var loadjslastfn=0;
function loadjs(fn){
	if(loadjslastfn!=fn){
		loadjslastfn=fn;
		if(document.getElementById('dynamic_script')){
			document.body.removeChild(document.getElementById('dynamic_script'));
		};
		ds=document.createElement('script');
		ds.type='text/javascript';
		ds.id='dynamic_script';
		document.body.appendChild(ds);
		document.getElementById('dynamic_script').src=fn;		
	}
}

function json_decode(json){var o=eval('('+json+')');return o;};

function fillselect(element,options,selected){
	$(element).empty();
	element=$(element).first();
	html='';
	for(i in options){
		html+='<option value="'+i+'" '+((i==selected)?'SELECTED="1"':'')+'>'+options[i]+"</option>";
	};
	$(element).html(html);
	return;
		
}

function fillformAjax(url,element){
	if(!element)return;
	$.getJSON(url,{name:$(element).attr('name'),value:$(element).attr('value')},function(resp){
		for(i in resp){
			console_log(i+':'+resp[i]);
			
			$(':input[name='+i+']').attr('value',resp[i]);
		}
	});
}

/**/
function ajaxsubmit(form,onready){
 //if(!form)return;
 form_action=$(form).attr('action');
 var fields={};
 $(':input',form).each(function(){
	name=$(this).attr('name');
	value=$(this).attr('value');
	if(name)fields[name]=value;	 
 });
 console_log(fields);
 console_log('onready');
 console_log(onready);
 var fready=null;
 if(onready)fready=onready;
 $.post(form_action,fields,function(d){
	if(fready)fready(d);
 });
 return false;
}/**/

function html_entity_decode(s) {
	var t=document.createElement('textarea');
	t.innerHTML = s;
	var v = t.value;
	return v;
}

function include(destination) {
	var e=window.document.createElement('script');
	e.setAttribute('src',destination);
	window.document.body.appendChild(e);
}

function console_log(o){
	try{
		console.log(o);
	}
	catch(err){		
	}
}

function microtime () {
    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10); 
    return (Math.round((now - s) * 1000) / 1000)+s;
}

function submitwithform(input){
	frm=document.createElement('form');
	frm.action=document.location.toString().split('?')[0];
	console_log(frm.action);
	$(input).after(frm);
	$(frm).append(input);
	routeparam=(document.location+'').split('?');
	if(routeparam[1]){
		routeparam=routeparam[1].split('&');
		for(i in routeparam){
			f=routeparam[i].split('=');
			if(f[1] && (f[0]!=input.name)){
				var h=document.createElement('input');
				h.type='hidden';
				h.name=f[0];
				h.value=decodeURIComponent(f[1].replace(/\+/g, '%20'));
				$(frm).append(h);
			}
		}
	};
	frm.submit();		
};

function parseGETbyname(name){
	rx=new RegExp('[&|?]'+this.name+'=([a-zA-Z0-9%]*)[&?]');
	loc=document.location+'';
	match=(loc).match(rx);
	if(match)return match[1];
	return 0;
}

function openAjaxWindow(purl,ptitle,poncompleted){
	var oncompleted=0;var url=purl;	
	if(url.indexOf('?'))url+='&noframe=1';else url+='?noframe=1';	
	if(poncompleted)oncompleted=poncompleted;var div=document.createElement('div');
	div.id=S4();div.className='ajaxwindow';$(document.body).append(div);
	div.innerHTML='<img src="/pic/static/loading.gif" />'
	/**/
	$('#'+div.id).dialog({width:parseInt(window.width)-150,position:[0,30],title:ptitle});
	var API={
		reload:function(){
			$.get(url,{},function(data){
				iframeid=S4();
				data+='<iframe src="" id="'+iframeid+'" name="'+iframeid+'" style="display:none;"  ></iframe>';
				div.innerHTML=data;
				$('form',div).bind('submit',function(){
					this.target=iframeid;
					this.submit();
					poncompleted();
					$(div).dialog('close');
				});
				var iframeloadcount=0;
				$('#'+iframeid,div).bind('load',function(){
						iframeloadcount++;					
						if(iframeloadcount>1)poncompleted();
				});
				INITHTMLCOMPONENTS();
			});			
		}	
	};
	API.reload();	
}



//some basic site-initalizing functions----------------------------------------

function INITHTMLCOMPONENTS(){
	$('tr[href],td[href],tr[onclick]').unbind('mouseover.hover').bind('mouseover.hover',function(){$(this).addClass('hover');}).unbind('mouseleave.hover').bind('mouseleave.hover',function(){$(this).removeClass('hover');}).unbind('click.hover').bind('click.hover',function(){u=$(this).attr('href');if(u)document.location.assign(u);});
	$('.datepicker').datepicker({
		onSelect:function(){
			console_log(this);
			$(this).trigger('change.watermark').trigger(document.all?'keyup':'keydown');
		},
		onChangeMonthYear:function(){
			year=$('.ui-datepicker-year').attr('value');
			month=($('.ui-datepicker-month').attr('value')*1)+1;
			if(month<10)month='0'+month;
			this.value=year+'-'+month+'-'+this.value.substr(8,3);
		},
		showAnim:''
	});
	
	$('.submitonenter').each(function(){
		var input=this;
		v=parseGETbyname(this.name);
		if(v)this.value=decodeURI(v);		
		$(input).keypress(function(e){
			if(e.keyCode==13){
				submitwithform(input);	
			};			
		});		
	});	
	$('.submitonchange').each(function(){	
		var input=this;
		v=parseGETbyname(this.name);
		if(v)this.value=decodeURI(v);		
		$(input).bind('change',function(e){
			submitwithform(input);				
		});		
	});	
	
	$(':input').each(function(){
		if(!$(this).attr('value') && $(this).attr('title'))$(this).Watermark($(this).attr('title'));
	});	
	if($('textarea[wysiwyg=1]').length){	
		_print=0;
		$('textarea').tinymce({
			script_url : SITEROOT+'js/tinymce/jscripts/tiny_mce/tiny_mce.js',
			theme : "advanced",
			elements : 'absurls', /**/
			theme : "advanced",
			plugins : 'advlink,advimage',
			style_width:'100%',
			width:'100%',
			height:'500px',
			relative_urls : false,			
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
			// Theme options
			theme_advanced_buttons1 : "save|,bold,italic,underline,strikethrough,codetag,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,preview",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,fullscreen",
			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,|,forecolor,backcolor",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			theme_advanced_resize_horizontal : false,

			
			content_css : ((_print)?"/css/print_v0.php":SITEROOT+"editor.css"),			
			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js"
		});			
	};	
	
	function formatSettingName(name){
		arr=name.split(':');
		if(arr.length==2){
			if(arr[0][0]!='{')return '{'+
									  arr[0].substr(0,8)+'-'+
									  arr[0].substr(8,4)+'-'+
									  arr[0].substr(12,4)+'-'+
									  arr[0].substr(16,4)+'-'+
									  arr[0].substr(20)+									
									  '}:'+arr[1];		
		};		
		return name;		
	}
	
	
	//column swapping!-------------------------------------------
	$('.columnhead').each(function(){
		if($('span.columnhead_drag',this).length){
			return;
		};
		var div=document.createElement('span');div.innerHTML=$(this).html();
		$(div).attr('name',$(this).attr('name'));div.className='columnhead_drag';
		$(this).empty().append(div);
		$(div).draggable({
			axis:'x',distance:60,connectToSortable:'.columnhead',start:function(){$('*').css('cursor','move');},
			stop:function(event,ui){
				tableid=$(div).parents('table').first().attr('id');if(!tableid)return;
				tableid=formatSettingName(tableid+':fields');
				tr=$(div).parents('tr').first();cols=$('.columnhead_drag',tr);poss=[];
				coords=[];for(i=0;i<cols.length;i++){ix=Math.round($(cols[i]).offset().left)*1;
				while(coords[ix])ix++;coords[ix]=$(cols[i]).attr('name');poss[poss.length]=ix;};
				data={};j=0;poss.sort(function(a,b){return a-b;});for(i in poss){data[j++]=coords[poss[i]];poss[i]=null;};
				$.post('/common.php/usersettings/'+tableid+'/change.html',data,function(r){document.location.assign(document.location);});				
			}
		});
	});
	
	//column resize!----------------------------------------------
	$('.columnheadresizer').each(function(){
		var div=this;
		$(div).draggable({
			axis:'x',distance:3,connectToSortable:'.columnhead',start:function(){$('*').css('cursor','col-resize');},
			stop:function(event,ui){
				tableid=$(div).parents('table').first().attr('id');if(!tableid)return;tableid=formatSettingName(tableid+':colwidth');
				tr=$(div).parents('tr').first();trleft=$(tr).offset().left;resizers=$('.columnheadresizer:visible',tr);var coords=[];max=0;				
				for(i=0;i<resizers.length;i++){name=$(resizers[i]).attr('name');val=Math.round($(resizers[i]).offset().left-trleft);coords[name]=val;if(val>max)max=val;};								
				data=[];for(i in coords)data[coords[i]]=i;coords={};prev=0;
				for(i in data){var name=data[i];coords[name]=Math.round(((i-prev)/max)*100);prev=i;};				
				$.post('/common.php/usersettings/'+tableid+'/change.html',coords,function(r){document.location.assign(document.location);});			
			}
		});
	});
	
	$('a[href^="mailto:"]').each(function(){
		e=$(this).attr('href').substr(7);
		e2=e.split("").reverse().join("");
		if($(this).html()==e)$(this).html(e2);
		$(this).attr('href','mailto:'+e2);
		
	});
	
	//if(htmlselectinit)htmlselectinit();
}

function loading(state){
	$('#AJAX_LOADING').remove();if(state)$(document.body).prepend('<div id="AJAX_LOADING"></div>');
}

function processHashResponse_old(response){
	console_log(response);
	var xmlobject = (new DOMParser()).parseFromString(response, "text/xml");
	console_log(xmlobject);
	var root=xmlobject.childNodes[0];
	console_log(root);
	for(i=0;i<root.childNodes.length;i++){
		if(root.childNodes[i].tagName=='script'){
			console_log('script');
			$(document.body).append(root.childNodes[i]);
		}else{
			selector=root.childNodes[i].tagName;
			console_log('selector:' + selector);
			if(root.childNodes[i].attributes){
				for(j=0;j<root.childNodes[i].attributes.length;j++){
					if(!root.childNodes[i].attributes[j])continue;
					attr=root.childNodes[i].attributes[j];
					if(attr.name=='id' || attr.name=='class' || attr.name=='type' || attr.name=='name')
						selector+='['+attr.name+'='+attr.value+']';
				};
				$(selector+'').replaceWith((new XMLSerializer()).serializeToString(root.childNodes[i]));
			};
		}
	};
}

function processHashResponse(resp){
	div=document.createElement('div');
	div.innerHTML=resp;
	for(i=0;i<div.childNodes.length-1;i++){
		node=div.childNodes[i];
		if(node.tagName=='script')document.head.appendChild(node);
		else{
			selector=node.tagName;
			if(node.id)selector+='[id='+node.id+']';
			if(node.className)selector+='[class='+node.className+']';
			$(selector+'').html(node.innerHTML);			
		}
	}
	delete div;
	
}


function initHashChangeEvents(){
	/*
	$('form').submit(function(){	
		var d={};		
		$(':input',this).each(function(){d[this.name]=this.value;});
		url=$(this).attr('action');
		if(url.indexOf('?')!=-1)url+='&_hashchange_=1';else url+='?_hashchange_=1';	
		$.post(url,d,function(resp){
			processHashResponse(resp);		
			initHashChangeEvents();
		});		
		return false;
	});	
	$(window).bind('hashchange',function(){
		url=document.location.hash.substr(1);
		if(url.indexOf('?')!=-1)url+='&_hashchange_=1';else url+='?_hashchange_=1';						
		loading(1);
		$.get(url,function(response){
			processHashResponse(response);
			initHashChangeEvents();
			loading(0);				
		});		
	});/**/	
}

$(document).ready(function(){
	initHashChangeEvents();
	$.datepicker.setDefaults({dateFormat:'yy.mm.dd.',changeMonth: true,changeYear: true, minDate: new Date(1920, 1, 1),yearRange: 'c-90:c+10'});
	INITHTMLCOMPONENTS();
	
	$(':input').each(function(){
		$(this).attr('changed',0);
		$(this).bind('change',function(){
			$(this).attr('changed',1);
		});
	});
	
	$('#ui-datepicker-div').hide();
	
	$(document).bind('keydown',function(e){
		switch(e.which){	
			case 16:{SHIFT=1;break;};
			case 17:{CTRL=1;break;};
			case 18:{ALT=1;break;};s
			case 83:{
				if(CTRL){
					f1=$('form').first();
					if(f1)$(f1).trigger('submit');
					return false;
				};				
			};
			case 87:{
				if(CTRL){
					closelink=$('.taskbar_item_active > .taskbar_close').first().attr('href');
					console_log(closelink);
					if(!closelink)return false;
					document.location.assign(closelink);				
					return false;
				}	
			}
			default:{		
			}
		};
	});	
	$(document).bind('keyup',function(e){
		switch(e.keyCode){case 16:{SHIFT=0;break;};case 17:{CTRL=0;break;};case 18:{ALT=0;break;};}
	})
});

function jquerydivvedtablefix(){
	var triggertimer=0;
	jquerydivvedtablefix.prototype.apply();
	//triggertimer=setInterval('jquerydivvedtablefix.prototype.apply()',1);
}

jquerydivvedtablefix.prototype.apply=function(){
	$('.table').each(function(){
		var widths=new Array();
		$(this).children('.table_row').each(function(){
			i=0;
			$(this).children('.table_cell').each(function(){
				if(!widths[i])widths[i]=0;
				if(widths[i]<$(this).width()){
						widths[i]=$(this).width();
				}
				i++;
			});
		});		
		$(this).children('.table_row').each(function(){
			i=0;
			$(this).children('.table_cell').each(function(){
				$(this).css('width',widths[i]+5);
				i++;
			});			
		});		
	});		
};


function showaftermeinrow(url,row){	
	$('#showaftermeinrow').remove();
	$('.myrowinfo').removeClass('myrowinfo');
	$(row).addClass('myrowinfo');
	var tr=document.createElement('tr');
	tr.id='showaftermeinrow';
	tr.height='100';
	var td=document.createElement('td');
	colspan=row.childNodes.length;
	console_log(colspan);
	td.colspan=colspan;
	var div=document.createElement('div');
	div.innerHTML='<center><img src="/pic/static/loading.gif" /></center>';
	div.style.height='200px';
	div.style.overflow='auto';
	div.className='inrowinfo';
	td.appendChild(div);
	tr.appendChild(td);
	$(row).after(tr);
	$(td).attr('colspan',colspan);	
	$.get(url,function(data){
		$(div).css('height',200);
		div.innerHTML=data;				
		$(div).resizable({helper:'inrowinfo_resize',handles:'s'});
	});	
}


function fetchonchange(psource,pdest,puri){
	var pubAPI={
		loaded:function(data){
			o='<option value="">-</option>';
			active=$(''+dest).attr('value');
			for(i=0;i<data.length;i++){
				id='';caption='';
				for(j in data[i])if(!id)id=data[i][j];else caption=data[i][j];
				o+="<option value='"+id+"' "+ ((id==active)?'SELECTED':'') +" >"+caption+"</option>";				
			}
			$(''+dest).html(o);
		},	
		sourcechanged:function(){			
			url=uri+this.value+'&cols=id,title';
			$.getJSON(url,0,pubAPI.loaded);
		}
	}
	var source=psource;
	var dest=pdest;
	var uri=puri;
	$(document).ready(function(){
		$(''+source).bind('change',pubAPI.sourcechanged);		
		$(''+source).trigger('change');
	});
};

function validateinputbyregexpattr(inputfield){
	return;
	s=unescape($(inputfield).attr('regexp'));
	s=s.substring(1,s.length-1);
	val=$(inputfield).val();
	if(!val.match(s)){
		//console_log('hibás,  regexp: '+s+'  value: '+val);
		$(inputfield).addClass('invalidvalue');
		$(inputfield).addClass('custominvalidvalue');
		$(inputfield).removeClass('validvalue');
	}else{
		//console_log('ok');
		$(inputfield).removeClass('custominvalidvalue');
		$(inputfield).removeClass('invalidvalue');
		$(inputfield).addClass('validvalue');
	}
	
	$(inputfield).bind('keyup:validator',function(){
		inputfield=this;
		$(inputfield).removeClass('custominvalidvalue');
		$(inputfield).removeClass('invalidvalue');
		$(inputfield).addClass('validvalue');
	});
}


