// Functions for standard use
// Copyright OLC Systems s.r.o.
// version phpcore 27.8.2009

function externallinks(){
     var c=document.getElementById('content');
     if(c)
     {
         var ls=c.getElementsByTagName('a');
         for(var i=0;i<ls.length;i++){
        	 var atributerel;
         	 atributerel = ls[i].getAttribute('rel');
         	 if (atributerel==null) {
         	 	continue;
         	 }
         	 
         	 inNewWindow = atributerel.substr(0,8).toLowerCase()=="external";
             if(inNewWindow){      
               ls[i].onclick=function(){
                  openw(this.rel,this.href);
                  return false;
               }
             }             
         }
     }
  }
  
 function openw(atributerel,wlocation){
   // Separate resolution and type
  	var height="", width="", type="", windowoptions="";
  	
  	output = atributerel.split("_");  	
  	width = output[1];
  	height = output[2];
  	type   = output[3];
  	
	if (type != undefined && type > 0 ) {
		if ((Number(height)==0) || (Number(width)==0)) {
		window.alert("Invalid height or width of window. Please check external parameter");
		type = 0;
		}
	}
	
  	switch (type) {
  		case '1': // with toolbar resizable
        	params="location=yes,menubar=no,toolbar=yes,scrollbars=yes,resizable=yes,width="+width+",height="+height
  			break;
  		case '2': // onlyborder no resizable
       		params="location=no,menubar=no,toolbar=no,scrollbars=no,resizable=no,width="+width+",height="+height
    		break;
  		case '3': // onlyadress resizable
    		params="location=yes,menubar=no,toolbar=no,scrollbars=yes,resizable=yes,width="+width+",height="+height
  			break;
		default:
  			params="location=yes,menubar=no,toolbar=yes,scrollbars=yes,resizable=yes,width=1000,height=768"     			
  			break;
  	}  	

  	window.open(wlocation,"_blank",params)
 }
  
 window.onload=function(){
   if(!document.getElementById && !document.createTextNode){return;}
 externallinks();
 }
 
 function click_checkbox_multi(object, formname, checkboxString){
  var uid=object.name.split("_");
  var checkbox_name;

  if (uid[0]=="ctl") {
	  // Support phpCore 2.0	  
	  checkbox_name="ctl_"+uid[1]+checkboxString+formname;	  
  } else {
	  // backward compatibility
	  checkbox_name=uid[0]+checkboxString+formname;
  }
  var x=document.getElementsByName(checkbox_name)[0];
  x.checked=true;
  if (JsCore.isFancyForm()) {
      FancyForm.update(x.parentNode);
      //FancyForm.chks.each(FancyForm.update);
      object.focus();
  }
 }

function click_checkbox(object, formname){
	click_checkbox_multi(object, formname, "_editedcheck_");
}

function click_insert_checkbox(object, formname){
	click_checkbox_multi(object, formname, "_insertcheck_");
}

// multiselect between checkbox disabled
// Jan Novak
function select_id(formname, checkboxObject){
   var lInputs=document.forms[formname].elements;
   var lInputsCount=document.forms[formname].elements.length;
   for(var Cyklus=0;lInputsCount>Cyklus; Cyklus++){
     if(lInputs[Cyklus].type=="checkbox" && lInputs[Cyklus].name.indexOf("edited")>0){
       lInputs[Cyklus].checked=false;
     }
   }
   checkboxObject.checked="true";
}

function inverse_checkboxes(formName, checkboxName, checkboxFunction) {
	//parameters:
	//formName - where script search for checkboxes, it must be unique name of form
	//checkboxName - part of name of checkboxes. To these checkboxes will be changed property checked
    var isFancyForm = JsCore.isFancyForm();
    
    var lInputs=document.forms[formName].elements;
    var lInputsCount=document.forms[formName].elements.length;
    for(var Cycle=0;lInputsCount>Cycle; Cycle++){
      if(lInputs[Cycle].type=="checkbox" && lInputs[Cycle].name.indexOf(checkboxName)>0){
        if(lInputs[Cycle].checked){
           lInputs[Cycle].checked=false;
        }else{
           lInputs[Cycle].checked=true;
        }
        if (isFancyForm) {
            FancyForm.update(lInputs[Cycle].parentNode);
        }
        if (checkboxFunction!=undefined) {
        	eval("result="+checkboxFunction+"(lInputs[Cycle]);");
        }
      }
    }


 }

//function for hiddin and appearing search box in multiform
// Honza Novak & Jakub Ferenc
function collapse(element){
	document.getElementById(element).style.display="none";
}
	
function expand(element){
	document.getElementById(element).style.display="block"
}	
	
function searchBoxAction(element){
	if(document.getElementById(element).style.display=="none")
		expand(element)
	else
		collapse(element)
}

function hide_core_message(delay){
    var core_message=document.getElementById("core_message");
    var core_message2=document.getElementById("core_message2");
    if(core_message){
      core_message.style.visibility='visible';
      core_message2.style.visibility='visible';
      window.setTimeout("document.getElementById('core_message').style.visibility='hidden';document.getElementById('core_message2').style.visibility='hidden'", delay)
    }
  }
  
/**
 * Author: David Pokorny
 * Simple display and hide object 
 */ 
function visibilityHandling(hidden,divId) {
     rightMenuObject = document.getElementById(divId);     

     if (hidden==null) {
    	if (rightMenuObject.style.visibility=="hidden") {
    		rightMenuObject.style.visibility="visible";
    	} else {
    		rightMenuObject.style.visibility="hidden";
    	}
     } else {
	     if (hidden==true) {
	        rightMenuObject.style.visibility="hidden";
	     } else {
	        rightMenuObject.style.visibility="visible";
	     }
     }
}  

function setPreloaderInfo(elementId,htmlInfo) {
	objectElement = document.getElementById(elementId);
	objectElement.innerHTML=htmlInfo;
}

/**
 * 
 * @param string  textToTitle 
 * @param type 1- before, 2-end, 0-replace - default
 * @return
 */
function addToTitle(textToTitle,type) {
	if (type==undefined) {
		type = 0;  
	}
	switch (type) {
	case 0:
		document.title = textToTitle;
		break;
	case 1:
		document.title = textToTitle+" "+document.title;
		break;
	case 2:
		document.title = document.title +" "+textToTitle;
		break;
	}
}

/* Assign list function */
/* David Pokorny */
function refreshAssignList(indexphp,otherParameters,targetAjax, preloader, objectId) {
	setPreloaderToList(objectId,preloader);
	makeHttpRequest(indexphp,otherParameters+"&listaction=refresh",targetAjax,targetAjax);
}

function removeAssignList(indexphp,otherParameters,targetAjax,objectId) {
	selectXml = getSelectArray(objectId);
	makeHttpRequest(indexphp,otherParameters+"&selection="+selectXml+"&listaction=remove",targetAjax,targetAjax,true,false);
}

function addAssignList(indexphp,otherParameters,targetAjax,objectId) {
	selectXml = getSelectArray(objectId);
	/* httpServer, paramsString, requestName, elementId, targetdiv, async */	
	makeHttpRequest(indexphp,otherParameters+"&selection="+selectXml+"&listaction=assign",targetAjax,targetAjax,true,false);
}

function setPreloaderToList(elementId,preloaderText) {
	objectElement = document.getElementById(elementId);
	objectElement.length = 1;
	objectElement.options[0].text = preloaderText;
	objectElement.disabled = true;
}

function getSelectArray(objectId) {
	var objectElement, cycle, output; 
	objectElement = document.getElementById(objectId);
	output = '<?xml version="1.0" encoding="UTF-8"?><selection>';
	for (cycle=0; cycle<objectElement.length;cycle++) {
		if (objectElement.options[cycle].selected) {
			output = output +'<item>'+objectElement.options[cycle].value+'</item>';
		}		
	}
	output = output + '</selection>';
	return urlencode(output); 
}

/* source: http://www.phpbuilder.com/board/showthread.php?t=10318476 */
function urlencode(str) {
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
	}



/*used to move with popupWindow*/
function activateMover(divID) {
    var divTmp = divID + '_header';
    var divEl = document.getElementById(divTmp);
    if (divEl == undefined) {
        return;
    }
    
    divEl.onmousedown = function(e) {
        e = e || event;
        var thisObj = this;
        this.posX = parseInt(this.style.left + '0');
        this.posY = parseInt(this.style.top + '0');
        this.mouseX = e.clientX;
        this.mouseY = e.clientY;

        var containerObj = document.getElementById(divID);
        this.containerPosX = parseInt(containerObj.style.left + '0');
        this.containerPosY = parseInt(containerObj.style.top + '0');

        var debugDiv = document.getElementById(divID+'_debug');

        document.documentElement.onmousemove = function(e) {
            e = e || event;

            containerObj.style.left = (e.clientX - thisObj.mouseX + thisObj.containerPosX) + "px";
            containerObj.style.top = (e.clientY - thisObj.mouseY + thisObj.containerPosY) + "px";
            return false;
        };

        document.documentElement.onmouseup = function(e) {
            document.documentElement.onmousemove = null;
            document.documentElement.onmouseup = null;

            if (debugDiv != undefined) {
                debugDiv.innerHTML = "l: "+containerObj.style.left+" t: "+containerObj.style.top;
            }

            return false;
        };
    };
}

//var rowColor = ""; //do not remove!
/**
 * Set a color to all cells in a row
 *
 * @param cell HTMLElement td element
 * @param color String
 */
function setBgColorToRow(cell, color) {
    /*if (color == undefined) {
        color = rowColor;
    } else {
        rowColor = cell.style.background;
    }*/

    var row = cell.parentNode;
    for (i = 0; i < row.cells.length; i++) {
        cellTmp = row.cells[i];
        cellTmp.style.backgroundColor=color;
        cellTmp.style.cursor='pointer';
    }
}
/**
 * Unset a color in all cells in a row
 *
 * @param cell HTMLElement td element
 */
function unsetBgColorToRow(cell) {
    var row = cell.parentNode;
    for (i = 0; i < row.cells.length; i++) {
        cellTmp = row.cells[i];
        cellTmp.style.backgroundColor='';
        //cellTmp.style.cursor='auto';
    }
}

/**
 * class/namespace for basic javascript functions
 */
function JsCore() {}

/**
 * @var if bookmarks over Ajax, then actual bookmark is saved in this variable
 */
JsCore.bookmark;

/**
 * @var deafult preloader text set dynamically by server
 */
JsCore.preloaderText = '';

/**
 * check if FancyForm (uses Mootools) is used to create graphic checkboxes
 * @return boolean
 */
JsCore.isFancyForm = function() {
    if (typeof(FancyForm)=='object') {
        return true;
    } else {
        return false;
    }
}

/**
 * Convert checkboxes in left column in multiform to pictures if Mootools FancyForm available
 */
JsCore.convertNewCheckboxesIfFancyForm = function() {
    if (JsCore.isFancyForm()) {
        var chkboxesE = $$('input[name*=editedcheck]');
        var chkboxesI = $$('input[name*=insertcheck]');
        FancyForm.add(chkboxesE);
        FancyForm.add(chkboxesI);
    }
}

/**
 * Remove element with given id
 * @var elementID
 */
JsCore.removeElement = function(elementID)
{
    var child = $(elementID);
    child.parentNode.removeChild(child);
}

/**
 * @param url String
 * @param width int
 * @param height int
 * @param type int
 */
JsCore.openw = function(url,width,height,type){
    var params = "";

	if (type > 0) {
		if ((Number(height)==0) || (Number(width)==0)) {
		window.alert("Invalid height or width of window. Please check external parameter");
		type = 0;
		}
	}

  	switch (type) {
  		case 2: // onlyborder no resizable
       		params="location=no,menubar=no,toolbar=no,scrollbars=no,resizable=no,width="+width+",height="+height
    		break;
  		case 3: // onlyadress resizable
    		params="location=yes,menubar=no,toolbar=no,scrollbars=yes,resizable=yes,width="+width+",height="+height
  			break;
        case 1: // with toolbar resizable
		default:
  			params="location=yes,menubar=no,toolbar=yes,scrollbars=yes,resizable=yes,width="+width+",height="+height
  			break;
  	}
  	window.open(url,"_blank",params)
 }

/**
 * Strip curly brackets from given string
 * @param stringValue e.g. uid
 */
JsCore.stripCurlyBrackets = function(stringValue) {
    if (stringValue == undefined || (typeof(stringValue)!='string')) {
        return stringValue;
    }

    stringValue = stringValue.replace(/\{/g,"");
    stringValue = stringValue.replace(/\}/g,"");

    return stringValue;
}


/**
 * Change position of div with divID
 * Document coordinates: var coordinates = document.getCoordinates(); //etc. check mootools function getCoordinates();
 * window.onresize = someFunctionName; if you need to reposition window on browser resize
 *
 * @param divID div id
 * @param left space left page border to left top corner of element
 * @param top space top page border to left top corner of element
 */
JsCore.setPopupWindowPosition = function(divID,left,top) {
    var containerObj = $(divID);

    if (containerObj == undefined || containerObj == null)
    {
        return;
    }
    containerObj.style.left = left + "px";
    containerObj.style.top = top + "px";
}

/**
 * Return selected options in combo as array or empty array
 * JsCore functions require Mootools
 *
 * @param comboID if of combo to be processed
 * @return array of selected options or empty array
 */
JsCore.getSelectedOptions = function(comboID)
{
    var options = new Array();
    var idx = 0;

    listObject = $(comboID);

    if (listObject == undefined)
    {
        return options;
    }
    for (cycle=0; cycle<listObject.length;cycle++) {
        if (listObject.options[cycle].selected) {
            options[idx] = listObject.options[cycle];
            idx = idx + 1;
        }
    }

    return options;
}

/**
 * Return checked checkboxes (only "control checkboxes" == first column) in a multiform
 * Require Mootools
 *
 * return array of checkboxes or null if nothing checked
 */
JsCore.getSelectedChckboxesInMultiform = function(formName, msgNothingChecked)
{
    var checked = new Array();
    var idx = 0;
    var chkboxes = $$('#' + formName + ' input[name*=editedcheck]');

    //no checkbox is checked
    if ( chkboxes.every(function(el) {return el.checked == false;}) ) {
        if (msgNothingChecked != undefined)
        {
            alert(msgNothingChecked);
        }

        return null;
    }

    //get checked checkboxes
    chkboxes.each(function(el) {
        if (el.checked == true) {
            checked[idx] = el;
            idx = idx + 1;
            /*var splitted = el.name.split('_');
            var id = splitted[1];
            $('id_blank').value = id;
            $('blank_identifier').value = $('ctl_'+id+'_identifier').value;*/
            return;
        }
    });

    return checked;
}

/**
 * Fire onchange event on element with given id
 * @param elementID String
 */
JsCore.fireOnChange = function(elementID)
{
    var el = $(elementID);

    if (el.hasAttribute)
    { // Firefox
        if(el.hasAttribute("onchange"))
        {
            el.onchange();
        }
    }
    else if (el.onchange)
    { // IE
        var newEvt = document.createEventObject();
        el.fireEvent("onchange", newEvt);
    }
}

/**
 * Used by selectWithButtonsClass
 */
function comboWithButtons() {}

/**
 *Select previous combo option
 */
comboWithButtons.selectPrevious = function(comboID)
{
    var combo = $(comboID);

    var index = combo.selectedIndex;
    if (index > 0)
    {
        combo.options[index].selected = false;
        combo.options[index - 1].selected = true;
    }

    JsCore.fireOnChange(comboID);
}

/**
 *Select next combo option
 */
comboWithButtons.selectNext = function(comboID)
{
    var combo = $(comboID);
    var index = combo.selectedIndex;

    if (index < combo.length - 1)
    {
        combo.options[index].selected = false;
        combo.options[index + 1].selected = true;
    }

    JsCore.fireOnChange(comboID);
}

/**
 * Update buttons (active/passive)
 */
comboWithButtons.update = function(comboID)
{
    var combo = $(comboID);
    var index = combo.selectedIndex;

    if (index == combo.length - 1)
    {
        $(comboID + '_nextActive').style.display = "none";
        $(comboID + '_nextEnd').style.display = "inline";
    }

    if (index < combo.length - 1)
    {
        $(comboID + '_nextActive').style.display = "inline";
    $(comboID + '_nextEnd').style.display = "none";
    }

    if (index == 0)
    {
        $(comboID + '_prevActive').style.display = "none";
        $(comboID + '_prevEnd').style.display = "inline";
    }

    if (index > 0)
    {
        $(comboID + '_prevActive').style.display = "inline";
        $(comboID + '_prevEnd').style.display = "none";
    }
}