/**
 * opens a popup window in the center of the screen
 * @param (string)url 		- url to open in popup
 * @param (string)title		- title of the window
 * @param (int)width		- width of the window
 * @param (int)height		- height of the window
 * @param (boolean)scrollbas	- show scroolbars  (0|1)
 * @param (boolean)status	- show status (0|1)
 **/

function openPopup(url,naslov,width,height,scrollbar,status) {
	var m, h;
	var LeftPosition=(screen.width)?(screen.width-width)/2:100;
	var TopPosition=(screen.height)?(screen.height-height)/2:100;
	m =  window.open(url,"popupWin","toolbar=no,width=" + width + ",height=" + height + ",top=" + TopPosition + ",left=" + LeftPosition + ",location=no,directories=no,status="+ status +",menubar=no,resizable=yes,scrollbars="+status+",target=_blank");
 	m.focus();
}

function addToFavorites(url,title) { 
	
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true; }
}

function changeArrowImage(imageId){

	var img 	= document.getElementById(imageId);
	
	if(img == null) return;
	var srcStr	= img.src;
	var lok 	= srcStr.lastIndexOf("/");
	
	if(srcStr.substring(lok+1)=='arrow_up.gif'){
		img.src='pic/arrow_down.gif';
	} else {
		img.src='pic/arrow_up.gif';
	}
}



function change_child(childName,id) {
	
	childField = document.getElementById(childName);
	childField.selectedIndex=0;
	
	var i= 1;
	for(var x in znamke[id]) {
		childField.options[i]=new Option(znamke[id][x], x);
		i++;
	}
	childField.length=i;
}


function changeAction(formName,actionFieldName,newAction){
	form = document.getElementById(formName);
	actionField = document.getElementById(actionFieldName);
	actionField.value = newAction;
	form.submit();
	
}

function setOldAction(){
	form = document.getElementById(formName);
	actionField = document.getElementById(actionFieldName);
	actionField.value = newAction;
}

function addAction(formName,actionFieldName,newAction){
	form = document.getElementById(formName);
	actionField = document.getElementById(actionFieldName);
	actionField.value = newAction;
	form.submit();
	
}


function addDeleteFileName(fieldName,fileName){
	actionField = document.getElementById(fieldName);
	actionField.value = fileName;
}


function calcHeight(elem_id){
	a = parent.document.getElementById(elem_id);
	alert(a);
	if (a){
		var the_height= top.document.body.scrollHeight;//find the height of the internal page
		a.style.height=the_height + 15;//change the height of the iframe
		//a.style.width='100%';
		alert("height:"+the_height);
	}
}

function calcHeightTop(frame_name) {
	a= parent.document.getElementById(frame_name);
	if (a){
		the_height= a.contentWindow.document.body.scrollHeight;
		a.style.height= the_height + 15;
		//a.style.width='100%';
	}
}

function loadFrames(leftURL, titleURL, listURL, list_editURL){
	l= top.window.left;
	t= top.window.title;
	ls= top.window.list;
	ls_edit= top.window.list_edit;

	if (leftURL=='null'){ // skrije frame
		l.style.display= 'none';
	}else if (leftURL!=''){ // ce ni nic ga ne zamenja, drugace gre na podan naslov
		l.document.write('');
		l.location.href = leftURL;
	}

	if (titleURL=='null'){
		t.style.display= 'none';
	}else if (titleURL!=''){
		t.document.write('');
		t.location.href= titleURL;
	}

	if (listURL=='null'){
		ls.style.display = 'none';
	}else if (listURL!=''){
		ls.document.write('');
		ls.location.href= listURL;
	}

	if (list_editURL=='null'){
		//ls_edit.style.display= 'none';
		top.window.document.getElementById('list_edit_tr').style.display= 'none';
		top.window.document.getElementById('list_separator_tr').style.display= 'none';
		top.window.document.getElementById('list_td').style.height= '100%';
	}else if (list_editURL!=''){
		ls_edit.document.write('');
		top.window.document.getElementById('list_edit_tr').style.display= '';
		top.window.document.getElementById('list_separator_tr').style.display= '';
		top.window.document.getElementById('list_td').style.height= '40%';
		ls_edit.location.href= list_editURL;
	}
}

var __currentDiv	= 'infoLayer';

function toogleDiv(layerId){
	
	toggle_view(__currentDiv,false);
	toggle_view(layerId,true);
	__currentDiv	= layerId;
	
}

function toggle_view(item_id, visible){
	var el = document.getElementById(item_id);
	if (el){
		if (!visible){
			el.style.display= 'none';
		}else{
			el.style.display= '';
		}
	}
}

var prev_elem;
function change_style(elem_id, prev_style, new_style){
	a= document.getElementById(elem_id);
	if (a && a!=prev_elem){
		a.className= new_style;
	}
	if (prev_elem && prev_elem!=a){
		prev_elem.className= prev_style;
	}
	prev_elem= a;
}

function changeStyle(iFrameName,elem_id, prev_style, new_style){
	iframe = parent.document.getElementById(iFrameName);
	//alert(iframe.src);
	a = iframe.document.getElementById(elem_id);
	if (a && a!=prev_elem){
		a.className= new_style;
	}
	if (prev_elem && prev_elem!=a){
		prev_elem.className= prev_style;
	}
	prev_elem= a;
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}		
/**
Parameters functions
**/

function openNewParametersWindow(selectField){
	if(selectField == null){
		alert('Entity select field not defined !');
		return;
	}
	if(selectField.selectedIndex ==0) {
		alert("Izberite parameter !!!");
		return;
	}
	var entity	= selectField.options[selectField.selectedIndex];
	var winUrl	= __entityUrls[selectField.selectedIndex];
	var paramWin	= window.open(winUrl,'paramsWin','width=750,height=650,menubars=0,scrollbars=1,location=0,statusbar=0,resizable=1');
	paramWin.focus();
}


var __archiveWin		= null;
var __archiveWinTrigger	= null;
function showPersonArchiveWindow(image,url){
	
	if(url =='') return;
	
	if(__archiveWin == null){
		__archiveWin	= document.getElementById('personArchiveWindow');
	}
	if(__archiveWinTrigger != null){
		__archiveWinTrigger.src ='pic/button_preview.gif';
	}
	if((__archiveWin.style.visibility=='visible') && (__archiveWinTrigger.id == image.id)){
		__archiveWin.style.visibility='hidden';
		
		return;
	}
	
	__archiveWinTrigger = image;
	__archiveWinTrigger.src ='pic/button_preview_selected.gif';
	
	if(__archiveWin == null){
		alert("Napaka pri prikazu arhivskega okna !");
		return;
	}
	__archiveWin.style.top			= (findPosY(image)+23)+"px";
	__archiveWin.style.left			= "0 px";
	__archiveWin.style.visibility	= 'visible';

	var ajaxObj						= 	__ajaxCollection.get('personArchiveTable');
	var origUrl 					= ajaxObj.getUrl();
	var tmpUrl						= ajaxObj.getUrl();
	tmpUrl							+=url;
	ajaxObj.setUrl(tmpUrl);
	//window.open(tmpUrl,'asdf','');
	ajaxObj.clearAll();
	ajaxObj.build();
	ajaxObj.setUrl(origUrl);
}


function tableButton_selectPerson(actionId){
	var action	= __ajaxCollection.get(actionId);
	
	if(action == null){
		alert('No action defined!!!');
		return;
	}
	
	//alert(action.getSource()+":"+action.getSelectedValue());
	var params	= new HashMap();
	params.put("value",action.getSelectedValue());
	__ajaxMessenger.send(action.getSource(),"",params);
	
}

function tableButton_viewPersonArchive(actionId){
	var action	= __ajaxCollection.get(actionId);
	
	if(action == null){
		alert('No action defined!!!');
		return;
	}
	
	alert("view person archive !!!");
	
	
}

function addToParamsTableFromChildWin(entity,pKey,textLeft, textRight,url,closeCurrentWin){
	var targetTable = window.opener.document.getElementById('ajaxParametersTable');
	if(targetTable == null){
		alert("Params table not found !");
		return;
	}
	
	var wasAdded = addRowToParamsTable(url,entity,pKey,textLeft,textRight,false);
	
	if(url && wasAdded){
		url+="&entity="+entity+"&entityPk="+pKey;
		//window.open(url,'testWin','');
		ajaxRequest(null,url,null,null);
	}
	
	if(wasAdded) alert("Podatki dodani k parametrom !");
	if(closeCurrentWin){
		if(wasAdded) if(confirm("Želite zapreti okno ?"))	self.close();
	}
}

function addToParamsTableFromTimeWin(formId,entity,textLeft,url,closeCurrentWin){
	var form		= document.getElementById(formId);
	var targetTable = window.opener.document.getElementById('ajaxParametersTable');
	if(targetTable == null){
		alert("Params table not found !");
		return;
	}
	
	if(
		(form.elements['time_date_from'].value == "") 
		&& (form.elements['time_date_to'].value == "")
		){
		alert("Vpišite časovni okvir !");
		return;	
	}
	
	var pKey=form.elements['time_zone'].options[form.elements['time_zone'].selectedIndex].value+"_"
		+form.elements['time_zone_text'].value+"_"
		+form.elements['time_date_from'].value+"_"
		+form.elements['time_time_from'].value+"_"
		+form.elements['time_date_to'].value+"_"
		+form.elements['time_time_to'].value;
		
	//alert(pKey);
	var text= form.elements['time_zone_text'].value;
	text+=" [ ";
	if(form.elements['time_date_from'].value != ''){
		text+= form.elements['time_date_from'].value;
		if(form.elements['time_time_from'].value){
			text+=" "+form.elements['time_time_from'].value;
		}
	}
	if(form.elements['time_date_to'].value != ''){
		if(form.elements['time_date_from'].value != ''){
			text +=" - ";
		}
	
		text+= form.elements['time_date_to'].value;
		if(form.elements['time_time_to'].value){
			text+=" "+form.elements['time_time_to'].value;
		}
	}
	text+="]";
	var wasAdded = addRowToParamsTable(url,entity,pKey,textLeft,text,false);
	
	var paramsStr	= "";
	
	
	if(wasAdded) {
		alert("Podatki dodani k parametrom !");
		form.submit();
	}
	if(closeCurrentWin){
		if(wasAdded) if(confirm("Želite zapreti okno ?"))	self.close();
	}
	
}



function addRowToParamsTable(url,entity,keyValue, leftColumnData,rightColumnData,sameWindow){
	var table = null;
	if(sameWindow){
		table = document.getElementById('ajaxParametersTable');
	} else {
		table = window.opener.document.getElementById('ajaxParametersTable');
	}
	if(table == null){
		alert("Params table not found !");
		return;
	}
	var rowId				= "row_"+entity+"_"+keyValue;
	if(rowExistInTable(table,rowId)) {
		alert("Vrstica s temi podatki obstaja ! ["+rowId+"]");
		return false;
	}
	
	var row 			= table.insertRow(-1);
	row.id				= rowId;
	
	var column			= row.insertCell(-1);
	column.className	= "oddRow";
	column.align		= 'center';
	column.innerHTML	= '<img src="pic/button_delete.gif" alt="Odstrani parameter" border="0" onclick="if(confirm(\'Ali želite odstraniti parameter ?\')) removeTableRowWithReq(\''+table.id+'\',\''+row.id+'\',\''+url+'\',\''+entity+'\',\''+keyValue+'\');" style="cursor:pointer;" />';
	
	var column			= row.insertCell(-1);
	column.className	= "oddRow";
	column.innerHTML	= leftColumnData;
	
	var column			= row.insertCell(-1);
	column.className	= "evenRow";
	column.innerHTML	= rightColumnData;
	
	var column			= row.insertCell(-1);
	column.className	= "evenRow";
	column.innerHTML	= '<input type="hidden" name="entity[]" value="'+entity+'" /><input type="hidden" name="entityPKey[]" value="'+keyValue+'" /><img src="pic/button_source.gif" alt="Pogled detaljno" onclick="javascript:openParamDetails(\'index.php?SYS_TASK=fbExtModule&MODULE=moduleDocuments&MODULE_TASK=show_entity_details\',\''+entity+'\',\''+keyValue+'\');"  border="0" style="cursor:pointer;" />';
	
	return true;
}

function rowExistInTable(table,rowId){
	for(var i = 0; i < table.rows.length;i++){
		var row = table.rows[i];
		if(row.id == rowId) return true;
	}
	return false;
}

function removeTableRowWithReq(tableId,rowId,url,entity,entityPk){
	var table 	= document.getElementById(tableId);
	if(table == null){
		alert("Table not found !");
		return;
	}
	
	var row 	= document.getElementById(rowId);
	if(row	== null){
		alert("Row not found !");
		return;
	}
	
	for(var i = 0; i < table.rows.length;i++){
		var row = table.rows[i];
		if(row.id == rowId) {
			table.deleteRow(i);
			break;
		}
	}
	if(url){
		url+="&entityDelete=1&entity="+entity+"&entityPk="+entityPk;
		///window.open(url,'testWin','');
		ajaxRequest(null,url,null,null);
		//window.open(origUrl,'testWin','');
		//ajaxRequest(null,origUrl,null,null);
		openParamDetails("empty.php?i=0","","");
	}
}


function removeTableRow(tableId,rowId){
	var table 	= document.getElementById(tableId);
	if(table == null){
		alert("Table not found !");
		return;
	}
	
	var row 	= document.getElementById(rowId);
	if(row	== null){
		alert("Row not found !");
		return;
	}
	
	for(var i = 0; i < table.rows.length;i++){
		var row = table.rows[i];
		if(row.id == rowId) {
			table.deleteRow(i);
			break;
		}
	}
	
}

function openParamDetails(url,entity,keyValue){
	var frame = document.getElementById('detailsFrame'); 
	if(frame == null) {
		alert("Details frame does not exist !");
		return;
	}
	var newUrl	= url;
	if(entity != ""){
		newUrl	+= "&entity="+entity;
	}
	if(keyValue != ""){
		newUrl	+= "&entityPk="+keyValue;
	}
	//window.open(newUrl,'','');
	frame.src	= newUrl;
}


function addLocation(fieldId,targetName){
	var field	= document.getElementById(fieldId);
	if(field == null) {
		alert("Field ["+fieldId+"] not found! ");
		return;
	}
	var fieldLocationText		= document.getElementById('locationText');
	var fieldTargetLocation		= document.getElementById('targetLocation');
	var fieldTargetLocationId	= document.getElementById('targetLocationId');
	if(field.selectedIndex >0){
		var o = field.options[field.selectedIndex];
		fieldTargetLocationId.value 	= o.value;
		fieldTargetLocation.value 		= targetName;
		fieldLocationText.value 		= o.text;
	}
}


function changeFormActionAndSubmit(formId,actionFieldName,newAction){

	var form 	= document.getElementById(formId);
	
	if(form == null) return;
	var oldAction 	= form.elements[actionFieldName].value;
	form.elements[actionFieldName].value	= newAction;
	form.submit();
	form.elements[actionFieldName].value	= oldAction;
	

}

function storeDocument(){
	
	var form 	= document.getElementById('documentForm');
	if(form ==null){
		alert("Form [documentForm] not found !");
		return;
	}
	
	if(form.elements['id_vrsta_informacije'].value == ''){
		alert("Vpišite vrsto informacije !");
		return;
	}
	
	if(form.elements['vsebina_kontakt'].value == ''){
		alert("Vpišite vsebino kontakta !");
		return;
	}
	
	var tematika		= form.elements['tematika[]'];
	var selectedCount	= 0;
	for(var i = 0; i < tematika.options.length; i++){
		if(tematika.options[i].selected){
			selectedCount++;
		}
	}
	
	if(selectedCount == 0){
		alert("Izberite tematiko !");
		return;
	}
	
	var oEditor = FCKeditorAPI.GetInstance('vsebina'); 
	if(oEditor.GetXHTML() == ''){
		alert("Vpišite vsebino dokumenta !");
		return;
	}
	
	
	form.submit();
}

function cancelDocument(actionFieldName){
	
	var form 	= document.getElementById('documentForm');
	if(form ==null){
		alert("Form [documentForm] not found !");
		return;
	}
	form.elements[actionFieldName].value = "cancel_document_edit";
	form.submit();
	
}


function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}



/**
	Ajax requests
**/

var __childTargetFieldId	= null;


function changeChildWithReq(sourceId,targetId,url){
	var target = document.getElementById(targetId);
	if(target == null){
		return;
	}
	var source	= document.getElementById(sourceId);
	if(source == null){
		return;
	}
	
	__childTargetFieldId	= targetId;
	var params	= getSourceParams(source);
	if(params.length){
		for(var i = 0; i < params.length; i++){
			url+='&'+source.id+'[]='+params[i];
		}
	}
	ajaxRequest(url);

}

function getSourceParams(source){
	if(source == null) return;
	//alert(source.type);
	var params	= new Array();
	if(source.type == "select-multiple"){
		//alert("asdf");
		for(var i = 0; i < source.options.length;i++){
			if(source.options[i].selected){
				params[params.length]	= source.options[i].value;
			}
		}
	} else 
	if(source.type == "select"){
		params[params.length]	= source.options[source.selectedIndex].value;
	}
	//alert(params);
	return params;
}

function fillTarget(data){
	if(data.length == 0) return;
	if(__childTargetFieldId == null) return;
	clearTargetField(__childTargetFieldId);
	var header	= data['header'];
	var elData	= data['data'];
	
	addToTargetElement(0, '...');
	for(var i = 0; i < elData.length; i++){
		var value	= 0;
		var text	= '';
		var row		= elData[i];
		for(var paramIdx = 0; paramIdx < header.length;paramIdx++){
		    if(paramIdx == 0){
				value = row.get(header[paramIdx]);
			} else {
				if(text != '') text+=',';
				text += row.get(header[paramIdx]);
			}
		}
		addToTargetElement(value, text);
	}
	
}

function addToTargetElement(value,text){
	var target = document.getElementById(__childTargetFieldId);
	if(target==null) return;
	
	if(target.type.indexOf('select') != -1 ){
		target.options[target.options.length] = new Option(text,value);
	}
	
}

function clearTargetField(fieldId){
	var target = document.getElementById(fieldId);
	if(target.type.indexOf('select') != -1 ){
		clearSelectField(fieldId);
	}
}

function clearSelectField(fieldId){
	var select = document.getElementById(fieldId);
	for(var i = (select.options.length-1); i >= 0;i--){
		select.options[i] = null;
	}
}

function showSubMenu(div){
	
	
	var obj=document.getElementById(div);

	var curTop = findPosY(obj.parentNode);
	var curLeft = findPosX(obj.parentNode);

	obj.style.top = curTop+16+"px";
	obj.style.left = curLeft+"px";
	obj.style.display="block";
}

function hideSubMenu(div){
	document.getElementById(div).style.display="none";

}
