
// ------------------------------------------------------------------------
// Calendar Widget
// ------------------------------------------------------------------------

// ------------------------------------------------------------------------
function attachCalendar(cal, inputID) {
	cal = new dhtmlxCalendarObject (inputID, true, {
		isWinHeader: true,
		headerButtons: 'XT',
		headerText: '',
		onClick:function(){
			return true;}
		});

	cal.setDateFormat('%Y-%m-%d');
}

// ------------------------------------------------------------------------
// Auto-Fill Widget Functions
// ------------------------------------------------------------------------

var afw_minInput = 1;
var afw_optionDiv_id = 'afw_options';
var afw_currentInput = false;
var afw_currentOption = false;
var afw_firstOption = false;

// Hide list when clicking anywhere in the document
document.documentElement.onclick = afw_autoHideOptions;

//---------------------------------------------------------------------------
function afw_showOptions (inputObj, url, e)
{
    // Enter / Tab
	if(e.keyCode==13 || e.keyCode==9) {
	    afw_hideOptions();
	    return;
	}

	// Up / Down Arrow / Esc / Shift
	if(e.keyCode==38 || e.keyCode==40 || e.keyCode==27 || e.keyCode==16) {
	    return;
	}

    afw_optionDiv=document.getElementById(afw_optionDiv_id);

	if(!afw_optionDiv) {

		obj = document.createElement('DIV');
		obj.id = afw_optionDiv_id;
		obj.className = 'afw_optionDiv';
		document.body.appendChild(obj);
        afw_optionDiv=document.getElementById(afw_optionDiv_id);
        if (!afw_optionDiv) alert('Error: cannot create optionDIV');

		var allInputs = document.getElementsByTagName('INPUT');
		for (var i=0; i < allInputs.length; i++){
			if(!allInputs[i].onkeyup) allInputs[i].onfocus = afw_hideOptions;
		}

		var allSelects = document.getElementsByTagName('SELECT');
		for (var i=0; i < allSelects.length; i++){
			allSelects[i].onfocus = afw_hideOptions;
		}

		// Handle keyboard navigation
		var oldonkeydown = document.body.onkeydown;
		if(typeof oldonkeydown!='function'){
			document.body.onkeydown=afw_keyNavigation;
		}else{
			document.body.onkeydown=function(){
				oldonkeydown();
			    afw_keyNavigation();
			}
		}
	}

	if(inputObj.value.length < afw_minInput){
		afw_hideOptions();
		return;
	}

    afw_optionDiv.innerHTML='';
	afw_optionDiv.style.display='block'

    var afw_offsetX = -1;
    var afw_offsetY = 2;

	afw_optionDiv.style.top  = (dom__getRealTop(inputObj) + inputObj.offsetHeight + afw_offsetY) + 'px';
	afw_optionDiv.style.left = (dom__getRealLeft(inputObj) + afw_offsetX) + 'px';

    afw_currentInput = inputObj;
    afw_currentOption = false;


    url=url+'&letters='+inputObj.value.replace(" ","+");
    ajax_load_url(url, afw_optionDiv_id, false, 'afw_fillOptions(\''+inputObj.id+'\',responseText);');

}

//---------------------------------------------------------------------------
function afw_hideOptions()
{
    var obj=document.getElementById(afw_optionDiv_id);
	if(obj)obj.style.display='none';
}

//---------------------------------------------------------------------------
function afw_chooseOption(e, optionObj)
{
	if(!optionObj) optionObj=this;

	// Need to take innerText and not innerHTML to handle special characters correctly
	// innerHTML is not supported in FF: we need to use textContent instead
    afw_currentInput.value = optionObj.innerText;
    if (optionObj.innerText == undefined) afw_currentInput.value = optionObj.textContent;

	// If a corresponding "key" field exists, we set its value to the option key value
	var s=afw_currentInput.id;
	var key_id=s.replace(/_display/i,'');
	var keyObj=document.getElementById(key_id);
	if (keyObj) {
	    keyObj.value = optionObj.id;
	}
	// If a corresponding "selected" field exists, we set its value to the option value
	var sel_id=key_id+'_selected';
	var selObj=document.getElementById(sel_id);
	if (selObj) selObj.value = afw_currentInput.value;

	afw_hideOptions();
}

//---------------------------------------------------------------------------
function afw_fillOptions(inputID, options)
{
    // options = list of {key###value} separated by "|"

    afw_optionDiv=document.getElementById(afw_optionDiv_id);
    afw_optionDiv.innerHTML='';

    inputObj=document.getElementById(inputID);

	var option = options.split('|');
	var is_firstOption=true;
	afw_firstOption = false;

	for (var i = 0; i < option.length - 1; i++){

	    var item=option[i];
        var elem=item.split('###');

        var className='afw_option';
        // Select first option by default

        // Create DIV for option item
		var div = document.createElement('DIV');
		div.id = elem[0];
        div.className = className;
		div.innerHTML = elem[1];
		div.onclick = afw_chooseOption;
		div.onmouseover = function(){ afw_rollOver(this, false) }
        if (is_firstOption) {
            afw_firstOption=div;
            // Automatically select first option
            afw_rollOver(afw_firstOption,false);
        }
		afw_optionDiv.appendChild(div);
        is_firstOption=false;
    }
}

//---------------------------------------------------------------------------
function afw_validate(obj) {

    // Actual value is always in key field (ID)
    // Auto-fill (free value): only key field (ID)
    // Picker (forced value) : visible display field (ID_display) + hidden key (ID) + hidden current selection (ID_selected)

    var id=obj.id;

	var key_id=String(id).replace(/_display/i,'');
	var sel_id=key_id+'_selected';

    var valObj=document.getElementById(id);
    var keyObj=document.getElementById(key_id);
    var selObj=document.getElementById(sel_id);

	// Clear hidden key/selected field if displayed field is cleared
	if (valObj.value=='') {
	    if(keyObj) keyObj.value='';
	    if(selObj) selObj.value='';
	}
	// Ensure that displayed field contains always the selected value (the user could clear part of it or enter an invalid value)
	else if (selObj) {
		if (valObj.value!=selObj.value) valObj.value=selObj.value;
	}
}

//---------------------------------------------------------------------------
function afw_rollOver(option, KeyboardInput)
{
    // Reset style for current option if necessary
    if(afw_currentOption) afw_currentOption.className='afw_option';
    // Set current option to rollOver option
	option.className='afw_optionSelected';
	afw_currentOption = option;

	// Handle scrolling from keyboard
	if(KeyboardInput){
        afw_optionDiv=document.getElementById(afw_optionDiv_id);

		if(afw_currentOption.offsetTop > afw_optionDiv.offsetHeight){
			afw_optionDiv.scrollTop = afw_currentOption.offsetTop - afw_optionDiv.offsetHeight + afw_currentOption.offsetHeight + 2 ;
		}
		if(afw_currentOption.offsetTop < afw_optionDiv.scrollTop)
		{
			afw_optionDiv.scrollTop = 0;
		}
	}
}

//---------------------------------------------------------------------------
function afw_keyNavigation(e)
{
	if(document.all) e = event;

	if(!afw_optionDiv)return;
	// Do nothing if option widget is not visible
	if(afw_optionDiv.style.display=='none')return;

	// Up arrow
	if(e.keyCode==38){
		if (!afw_currentOption) return;
		if (afw_currentOption && !afw_currentOption.previousSibling) return;
		afw_rollOver(afw_currentOption.previousSibling, true);
	}
    // Down arrow
	if(e.keyCode==40){
		if(!afw_currentOption){
			afw_rollOver(afw_firstOption, true);
		}else{
			if(!afw_currentOption.nextSibling) return;
			afw_rollOver(afw_currentOption.nextSibling, true);
		}
	}
    // Enter key or tab key
	if(e.keyCode==13 || e.keyCode==9){
		if (afw_currentOption) afw_chooseOption(false, afw_currentOption);

        // Prevent the Enter key from triggering a form submit and stay in the input field
		if(e.keyCode==13) return false;
	}
    // Escape key
	if(e.keyCode==27){
		afw_hideOptions();
	}
    return true;
}

//---------------------------------------------------------------------------
function afw_autoHideOptions(e)
{
	if(document.all) e = event;

	if (e.target) source = e.target;
	else if (e.srcElement) source = e.srcElement;

	if (source.nodeType == 3) { // for Safari bug
        source = source.parentNode;
	}
	if(source.tagName.toLowerCase()!='input' && source.tagName.toLowerCase()!='textarea') {
	    afw_hideOptions();
	}

}
//---------------------------------------------------------------------------

// ------------------------------------------------------------------------
// Drag Object
// ------------------------------------------------------------------------

var dragobject={
  z: 0, 
  x0: 0, y0: 0, 
  offsetx : null, offsety : null, 
  targetobj : null, targetID : null
}

//---------------------------------------------------------------------------
function drag_start(e, obj){

    var ev = window.event ? window.event : e;
    
    dragobject.targetobj = obj;
    dragobject.targetID = obj.id;
    
    document.onmousemove = drag_move;
    document.onmouseup   = function(){
     	dragobject.targetobj = null; 
     	document.onmousemove = null;
     }
    
    dragobject.offsetx = parseInt(dom__getRealLeft(obj));
    dragobject.offsety = parseInt(dom__getRealTop(obj));

    if (isNaN(dragobject.offsetx)) {dragobject.offsetx = 0}
    if (isNaN(dragobject.offsety)) {dragobject.offsety = 0}
    
    dragobject.x0 = ev.clientX;
    dragobject.y0 = ev.clientY;
    
    // Cancel out any text selections
    document.body.focus();
    
    // Prevent text selection in IE
    document.onselectstart = function () { return false; };
    // Prevent IE from trying to drag an image
    obj.ondragstart = function() { return false; };
    // Prevent text selection (except IE)
    return false;
}

//---------------------------------------------------------------------------
function drag_move(e){
  
     var ev = window.event ? window.event : e;
     
     if (dragobject.targetobj != null) {
      dragobject.targetobj.style.left = dragobject.offsetx + ev.clientX - dragobject.x0 + "px";
      dragobject.targetobj.style.top  = dragobject.offsety + ev.clientY - dragobject.y0 + "px";
      return false;
    }
}

// ------------------------------------------------------------------------
// APP Functions
// ------------------------------------------------------------------------

//---------------------------------------------------------------------------
function app_popup_show(modal) {
	dom_show('app-popup');
	if (modal) dom_show('app-click-catcher');
}

//---------------------------------------------------------------------------
function app_popup_hide() {
	dom_hide('app-popup');
	dom_hide('app-click-catcher');
}

//---------------------------------------------------------------------------
function app_popup_show_url(url, easyClose, modal) {
	app_popup_set_title('');
    dom_set_html('app-popup-content', '<div style="height:50%; padding-top:20%;"><center><img src="../themes/ajax_load_studio.gif"></img></center></div>');
	dom_load_url('app-popup-content', url);
	app_popup_show(modal);
	if (easyClose) {
 	    document.getElementById('app-popup').onclick=app_popup_hide;
	} else {
 	    document.getElementById('app-popup').onclick=function(){return true;};
	}
}

//---------------------------------------------------------------------------
function app_popup_set_title(title) {
	dom_set_html('app-popup-title', title);
}

//---------------------------------------------------------------------------
function app_notify(html, autoHide, className) {
	obj=document.getElementById('app-dialog');
	if (!obj) {
	   document.write(html);
	   return true;
	}
	app_dialog_show();
    obj.className=className;
	obj.onclick=app_dialog_hide;

	if (autoHide) {
	   setTimeout("app_dialog_hide()", 2000);
	} else {
	   html=html+'<input type="button" value="OK" onclick="app_dialog_hide();">';
	}
	dom_set_html('app-dialog', html);
}

//---------------------------------------------------------------------------
function app_dialog_show_url(url, modal) {
    document.getElementById('app-dialog').onclick=function(){return true;};
	dom_load_url('app-dialog', url);
	dom_show('app-dialog');
	if (modal) dom_show('app-click-catcher');
}

//---------------------------------------------------------------------------
function app_dialog_show(html, modal) {
    document.getElementById('app-dialog').onclick=function(){return true;};
 	if (html) dom_set_html('app-dialog', html);
	dom_show('app-dialog');
	if (modal) dom_show('app-click-catcher');
}

//---------------------------------------------------------------------------
function app_dialog_hide() {
	dom_hide('app-dialog');
	dom_hide('app-click-catcher');
    document.getElementById('app-dialog').className=false;
}

//---------------------------------------------------------------------------
function app_dialog(html) {
	app_dialog_show(html, false);
}

//---------------------------------------------------------------------------
function app_dialog_modal(html) {
	app_dialog_show(html, true);
}


// ------------------------------------------------------------------------
// DOM Functions
// ------------------------------------------------------------------------

//---------------------------------------------------------------------------
function dom_insert_html(id, html) {
   	document.getElementById(id).innerHTML = document.getElementById(id).innerHTML + html;
}
//---------------------------------------------------------------------------
function dom_set_html(id, html) {
    document.getElementById(id).innerHTML = html;
}
//---------------------------------------------------------------------------
function dom_set_tag_html(tag, html) {
    document.getElementByTagName(tag).innerHTML = html;
}
//---------------------------------------------------------------------------
function dom_get_html(id) {
    return document.getElementById(id).innerHTML;
}
//---------------------------------------------------------------------------
function dom_load_url(id, url, showWaitImage) {
    ajax_load_url(url, id, showWaitImage);
}
//---------------------------------------------------------------------------
function dom_set_img(id, src, height, width) {
    document.getElementById(id).src = src;
    if (height > 0) document.getElementById(id).height = height;
    if (width > 0) document.getElementById(id).width = width;
}
//---------------------------------------------------------------------------
function dom_toggle_visibility(id)
{
	var obj=document.getElementById(id);
	obj.style.display=((obj.style.display=='none') ? '' : 'none');
}
//---------------------------------------------------------------------------
function dom_show(id)
{
	var obj=document.getElementById(id);
	obj.style.display='';
}
//---------------------------------------------------------------------------
function dom_hide(id)
{
	var obj=document.getElementById(id);
	obj.style.display='none';
}

//---------------------------------------------------------------------------
function dom_trigger_onclick(id)
{
	var obj=document.getElementById(id);
	obj.onclick();
}
//---------------------------------------------------------------------------
function dom_stop_event(e) {
   if (e.stopPropagation) {
     e.stopPropagation();
   } else {
     e.cancelBubble = true;
   }
}

//---------------------------------------------------------------------------
function dom_trigger_child_scripts_in_obj(obj) {
    var i=0;
    if (obj.hasChildNodes()) {
      for (i=0; i<obj.childNodes.length; i++) {
           if (obj.childNodes[i].tagName == "SCRIPT") {
             eval(obj.childNodes[i].innerHTML);
           } else {
              // Trigger scripts within a child
              dom_trigger_child_scripts_in_obj(obj.childNodes[i]);
           }
      }
    }
}

//---------------------------------------------------------------------------
function dom_trigger_child_scripts(id) {
    var obj=document.getElementById(id);
    dom_trigger_child_scripts_in_obj(obj);
}


//-------------------------------------------------------------
function dom_get_mouse_coord(e, refID, returnX) {

	var posx = 0;
	var posy = 0;

	if (!e) var e = window.event;

	if (e.pageX || e.pageY)
	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		posx = e.clientX + document.body.scrollLeft;
		posy = e.clientY + document.body.scrollTop;
	}

	// posx and posy contain the mouse position relative to the document

	c = document.getElementById(refID);

	LeftX = dom__getRealLeft(c);
	TopY  = dom__getRealTop(c);

	x = (posx - LeftX);
	y = (posy - TopY);

	if (returnX == true) return x.toFixed(0);
	if (returnX == false) return y.toFixed(0);
}

//-------------------------------------------------------------
function dom__getRealLeft(obj) {

     if (arguments.length==0) obj = this;

     xPos = obj.offsetLeft - obj.scrollLeft;
     tempObj = obj.offsetParent;

     while (tempObj != null) {
         xPos += tempObj.offsetLeft - tempObj.scrollLeft;
         tempObj = tempObj.offsetParent;
     }
     return xPos;
 }

//-------------------------------------------------------------
function dom__getRealTop(obj) {

     if (arguments.length==0) obj = this;

     yPos = obj.offsetTop - obj.scrollTop;
     tempObj = obj.offsetParent;

     while (tempObj != null) {
         yPos += tempObj.offsetTop - tempObj.scrollTop;
         tempObj = tempObj.offsetParent;
     }
     return yPos;
 }

//-------------------------------------------------------------
function form_get_post_param(id) {

  var PostStr='';
  var i=0;
  var formSubmitElementName=false;

  obj=document.getElementById(id);

  for (i=0; i<obj.elements.length; i++) {

     // In order to be able to know which submit object has been clicked, a hidden field should be defined
     // in the form to hold its name and the onClick event must be used to set is value. This field should be
     // defined in the form before any submit object.
     // If the field is not defined, the submit element name will not be posted.
     if (obj.elements[i].name == 'formSubmitElementName') formSubmitElementName=obj.elements[i].value;

	 var value = encodeURIComponent(obj.elements[i].value);

     if (obj.elements[i].tagName == "INPUT") {

        if (obj.elements[i].type == "checkbox") {
           if (obj.elements[i].checked) {
              PostStr += obj.elements[i].name + "=" + value + "&";
           } else {
              PostStr += obj.elements[i].name + "=&";
           }

        } else if (obj.elements[i].type == "radio") {
           if (obj.elements[i].checked) {
              PostStr += obj.elements[i].name + "=" + value + "&";
           }

        } else if (obj.elements[i].type == "submit") {
            // If formSubmitElementName is defined (should be set on the submit object's onClick event),
            // we POST only the submit element which trigger the form submit (this is the normal behaviour
            // for a form).
            if (formSubmitElementName == obj.elements[i].name) {
                PostStr += obj.elements[i].name + "=" + value + "&";
            }
        } else {
            PostStr += obj.elements[i].name + "=" + value + "&";
        }

     } else if (obj.elements[i].tagName == "SELECT") {
        var sel = obj.elements[i];
        var sel_count = 0;
        if ((sel.options.length>0) && (sel.selectedIndex>=0)) {
            var selected = new Array();
            PostStr += sel.name + "=";
            for (var j = 0; j < sel.options.length; j++) {
                if (sel.options[j].selected) {
                    sel_count += 1;
                    if (sel_count > 1) PostStr += ',';
                    PostStr += sel.options[j].value;
                }
            }
            PostStr += "&";
        }

     } else if (obj.elements[i].tagName == "TEXTAREA") {
           PostStr += obj.elements[i].name + "=" + value + "&";
     } else {
     }

  }
  return PostStr;
}

// ------------------------------------------------------------------------
// AJAX Functions
// ------------------------------------------------------------------------

var xhr=false;
var xhr_post_script=false;
var xhr_target=false;

//---------------------------------------------------------------------------
function ajax_get_request_object() {

	xhr=false;
	xhr_post_script=false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		xhr = new XMLHttpRequest();
		if (xhr.overrideMimeType) {
			xhr.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!xhr) {
		msg('Cannot create an XMLHTTP instance');
		return false;
	}
	xhr.onreadystatechange = ajax_handle_response;
	return xhr;
}

//---------------------------------------------------------------------------
function ajax_post_form(id, method, url, target, showWaitImage) {

    parameters=form_get_post_param(id);
    if (!method) method='POST';
    if(method.toLowerCase() == 'get') url = url+"?"+parameters;

    xhr_target=target;
    xhr=ajax_get_request_object();
	xhr.open(method, url, true); // asynchronous
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", parameters.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.send(parameters);
    if (showWaitImage) {
        dom_set_html(target, '<center><img src="../themes/ajax_load_studio.gif"></img></center>');
    }
}

//---------------------------------------------------------------------------
function ajax_load_url(url, target, showWaitImage, postScript) {
    xhr_target=target;
    xhr=ajax_get_request_object();
    if (postScript) xhr_post_script=postScript;
	xhr.open('GET', url, true); // asynchronous
    xhr.setRequestHeader("Content-type", "text/html");
	xhr.send(null);
    if (showWaitImage) {
        dom_set_html(target, '<center><img src="../themes/ajax_load_studio.gif"></img></center>');
    }
}

//---------------------------------------------------------------------------
function ajax_handle_response() {

    if(xhr.readyState == 4){
    	if (xhr.status == 200) {

    		var responseText = xhr.responseText;
    		var DOMdocument  = xhr.responseXML;

    		// Execute post script if defined
    		if (xhr_post_script) {
    		  eval(xhr_post_script);

    		// Set HTML content otherwise
    		} else {
        		if (document.getElementById(xhr_target)) {

                    dom_set_html(xhr_target, responseText);

                    // All scripts within the response have to be executed explicitely
                    // as they are not executed when setting the innerHMTL
                    dom_trigger_child_scripts(xhr_target);
                } else {
                    alert('Destination does not exists');
                }
    		}
    	} else {
    		if (xhr.status != 0) {
    		   alert('There was a problem with the request ('+xhr.status+')');
    		}
    	}
    }
}

//---------------------------------------------------------------------------

