/* $Id$ */


var skiline_debug = true;

function debugMessage(message)
{
	if (skiline_debug)
	{
		alert(message);
	}
}


function debugLog(message)
{
    var logContainer = jQuery('#debug_log');
    logContainer.html(logContainer.html() + message + "<br/>"); 
}

jQuery.fn.extend({
	innerTooltip : function (target) {
		
		this.bind('mouseenter', function() {			
			jQuery(target).text(jQuery(this).attr('title'));
		});
		this.bind('mouseleave', function() {
			  jQuery(target).text('');
		});
	
}});

jQuery.fn.extend({
	setDisabled : function(flag) {
		
		if (flag)
			this.disable();
		else
			this.enable();
	},
	disable : function() {
		
		var bgLeftId  = this.attr('id') + "_bg_left";
		var bgRightId = this.attr('id') + "_bg_right";
		
		this.find(".button_left").addClass('disabled');		
		this.find(".button_right").addClass('disabled');
			
	    return this.attr('disabled', true).addClass('disabled');

	},
	enable : function() {
		var bgLeftId  = this.attr('id') + "_bg_left";
		var bgRightId = this.attr('id') + "_bg_right";
		
		this.find(".button_left").removeClass('disabled');
		this.find(".button_right").removeClass('disabled');
		
	    return this.removeClass('disabled').attr('disabled', false);

	} 
});

/**
 * This function is used to toggle the css classname of a HTML element. It is used to 
 * blink the number of unread mails, new threads etc, if the value has changed since
 * the last repaint.
 *  
 * @param elementId    the ID of the html element
 * @param blinkCount   the number of repetitions (if -1: repeat infenitely)
 * @param interval     the interval in milliseconds between the css changes
 * @param styleClass1  the first css class (the default value)
 * @param styleClass2  the second css class
 * @param index        for the first call pass 0 as the value
 * @return -
 */
function switchCssClassnames(elementId,blinkCount,interval,styleClass1, styleClass2, index)
{
	var element = jQuery(elementId);
	
	if (blinkCount > 0 && index==blinkCount * 2)
	{
	    element.className = styleClass1;	
	}
	else
	{
   	   if ((index % 2) == 0)
       {
		  element.className = styleClass1;
	   }
	   else
	   {
		  element.className = styleClass2;
	   }
   	   
   	   var functionCall = "switchCssClassnames('" + elementId + "'," + blinkCount + "," + interval + ",'" + styleClass1 +
   	       "','" + styleClass2 + "'," + (index + 1) + ")";
   	   window.setTimeout(functionCall, interval);
	}
}

function openNewPopupWindow(href,title,w,h,scroll)
{
   LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
   TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
   settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',noresize';
   window.open(href,title,settings);
}


// scroll to an element (thanks to http://radio.javaranch.com/pascarello/2005/01/09/1105293729000.html)
function scrollToElementBottom(element)
{
	element = $(element);
	
	// now get the y position of the element
    var selectedPosY = element.offsetHeight + 20;
    while(element != null)
    {
	    selectedPosY += element.offsetTop;
	    element = element.offsetParent;
	}
    
    // now check, if the element is already visible at the bottom
    if (selectedPosY > window.pageYOffset + window.innerHeight)
    {
    	window.scrollTo(window.pageXOffset, selectedPosY - window.innerHeight);
    }
}

function escapeJSFClientId(id) 
{
   return "#" + id.replace(/:/g,"\\:");
}
 
/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var UrlUTF8 = {

   // public method for url encoding
   encode : function (string) {
       return escape(this._utf8_encode(string));
   },

   // public method for url decoding
   decode : function (string) {
       return this._utf8_decode(unescape(string));
   },

   // private method for UTF-8 encoding
   _utf8_encode : function (string) {
       string = string.replace(/\r\n/g,"\n");
       var utftext = "";

       for (var n = 0; n < string.length; n++) {

           var c = string.charCodeAt(n);

           if (c < 128) {
               utftext += String.fromCharCode(c);
           }
           else if((c > 127) && (c < 2048)) {
               utftext += String.fromCharCode((c >> 6) | 192);
               utftext += String.fromCharCode((c & 63) | 128);
           }
           else {
               utftext += String.fromCharCode((c >> 12) | 224);
               utftext += String.fromCharCode(((c >> 6) & 63) | 128);
               utftext += String.fromCharCode((c & 63) | 128);
           }

       }

       return utftext;
   },

   // private method for UTF-8 decoding
   _utf8_decode : function (utftext) {
       var string = "";
       var i = 0;
       var c = c1 = c2 = 0;

       while ( i < utftext.length ) {

           c = utftext.charCodeAt(i);

           if (c < 128) {
               string += String.fromCharCode(c);
               i++;
           }
           else if((c > 191) && (c < 224)) {
               c2 = utftext.charCodeAt(i+1);
               string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
               i += 2;
           }
           else {
               c2 = utftext.charCodeAt(i+1);
               c3 = utftext.charCodeAt(i+2);
               string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
               i += 3;
           }

       }

       return string;
   }
}

/* form utils */

function submitGetFormSearch(form) {
	
	var url = jQuery(form + " .hiddenGetUrl").attr("href");			
	var queryString = jQuery(form + " .queryString input").attr("value");	
	url = url.replace(/query_string/,UrlUTF8.encode(queryString));		
	window.location.href = url;	
	return false;
}

function getEvent(event)
{
   if(!event)
   {
      return window.event;
   }
   else
   {
      return event;
   }
}


function getKeyCodeFromEvent(event)
{
   event = getEvent(event);

   if(event.keyCode)
   {
      return event.keyCode;
   }
   else if(event.which)
   {
      return event.which;
   }
   else
   {
      return 0;
   }
}

function getCharCodeFromEvent(event)
{
   event = getEvent(event);

   var charCode;

   if(event.charCode == 0)
   {
      return -1;
      // 0 and space seems to be the same in javascript => we use -1 to indicate, that we have no key
   }

   if(event.charCode)
   {
      charCode = event.charCode;
   }
   else
   {
      charCode = getKeyCodeFromEvent(event);
   }

   return String.fromCharCode(charCode);
}


/**
 * This function checks, if the user pressed a valid key for an unsigned integer input field.
 * An unsigned integer input field is allowed to contain digits only.
 */
function unsignedIntegerFieldKeyPressed(event)
{
   charCode = getCharCodeFromEvent(event);

   if(charCode == ' ')
   {
      return false;
   }
   if(charCode == -1)
   {
      return true;
   }
   return (charCode >= '0' && charCode <= '9');
}


/**
 * This function checks, if the user pressed a valid key for a date input field.
 * An unsigned date input field is allowed to contain digits and dots only.
 */
function dateFieldKeyPressed(event)
{
   charCode = getCharCodeFromEvent(event);

   if(charCode == ' ')
   {
      return false;
   }
   if(charCode == -1)
   {
      return true;
   }
   return (charCode >= '0' && charCode <= '9') || charCode=='.';
}



var smartTextFieldHideLabelOnFocus = false;


// parameter inputType defines the characters, which will be accepted. It supports
// the following values:
//
//   integer:  only digits will be accepted
//   date:     only digits and dots will be accepted
//   in all other cases: all characters will be accepted
function SmartTextField(id, deleteIconId, inputType, autoSkip, smartTextFieldHideLabelOnFocus)
{
    var field = document.getElementById(id);
    
    var deleteIcon = document.getElementById(deleteIconId);
    var debug = true;

    jQuery(escapeJSFClientId(id)).updnWatermark();
    
    var validateFunction = null;
    
    if (inputType=="integer")    	
    {
    	validateFunction = unsignedIntegerFieldKeyPressed;
    }
    else if (inputType=="date")
    {
    	validateFunction = dateFieldKeyPressed;
    }
    
    if (debug)
    {
       if (!field)
       {
    	  alert("field '" + id + '" not found');
       }    
    
       if (deleteIconId && !deleteIcon)
       {
    	  alert("deleteIcon '" + deleteIconId + '" not found');
       }
    }
    
	if (field)
	{
		
		field.deleteIcon = deleteIcon;
		field.validateFunction = validateFunction;
		field.autoSkip = autoSkip;
		field.oldValue = field.value;
		
		field.onFieldEmpty = function()
		{			
			jQuery(escapeJSFClientId(id)).updnWatermark();
			if (deleteIcon)
			{
			   this.deleteIcon.className = "delete_icon invisible";
			   this.deleteIcon.onclick = null;
			}
		}
		field.onFieldNotEmpty = function() 
		{			
		    jQuery(escapeJSFClientId(id)).updnWatermark();
			if (deleteIcon)
			{
			   this.deleteIcon.className = "delete_icon";
			   this.deleteIcon.onclick = this.deleteIcon.onclickFunction;
			}
		}
		
		if (deleteIcon)
		{
    	   deleteIcon.textField = field; 	       
		   deleteIcon.onclickFunction = function(event)
		   { 
			  this.textField.value = "";
			  this.className = "delete_icon invisible" ;			  
			  this.textField.onFieldEmpty();
			  this.textField.focus();
		   }		
		   deleteIcon.onclick = deleteIcon.onclickFunction;
		}
		
		if (field.value=="")
		{
			field.onFieldEmpty();
		}
		else
		{
			field.onFieldNotEmpty();
		}
						
		field.onkeypress = function(event)
		{
			if (this.isCharacterKey(event))
			{
				if (this.validateFunction && !this.validateFunction(event))
				{
					return false;
				}
			}
			this.checkEmpty();
			this.oldValue = this.value;
		}
		
		field.onkeyup = function(event)
		{
			this.checkEmpty();
			
			if (this.autoSkip && this.oldValue!=this.value)
			{
				this.oldValue = this.value;
				
				// if a character key was pressed at the end of the field => skip to the autoSkip field
				if (this.value.length==this.maxLength)
				{
					document.getElementById(this.autoSkip).focus();
				}
			}
		}
		
		field.onchange = function(event)
		{
			this.checkEmpty();
		}
		
		field.checkEmpty = function()
		{
			if (this.value=="")
			{
				this.onFieldEmpty();
			}
			else
			{
				this.onFieldNotEmpty();
			}
		}
		
		jQuery(document).ready(function() {
		    jQuery.timer(200, function() {
		        field.checkEmpty();
		    })
		});
		
		field.isCharacterKey = function(event)
		{
	        if (!event)
	        {
	        	event = window.event;
	        }
			
			var keyCode = event.keyCode;
			
			switch(keyCode)
			{
			case 27: /* escape */
			case 37: /* cursor left */
			case 39: /* cursor right */
			case 38: /* cursor up */
			case 40: /* cursor down */
			case 33: /* page up */
			case 34: /* page down */
			case 16: /* shift */
			case 17: /* ctrl */
			case 18: /* alt */
			case 20: /* capslock */
			case 35: /* end of line */
			case 36: /* begin of line */
			case 224: /* cmd on a mac */
			case 9: /* tab */
			case 8: /* backspace */
			case 46: /* delete */
			case 13: /* enter */
				return false;
			}
			return true;
		}		
	}
}



/* -------------------------------------------------------------------------- */

function SmartSelectBox(id)
{
    var field = document.getElementById(id);
	
	if (field)
	{
	    jQuery(field).change(function() {
	        if (jQuery(this).attr("selectedIndex")==0)
	        {
	            jQuery(this).removeClass("selected");
	            jQuery(this).addClass("noselection");
	        }
	        else
	        {
                jQuery(this).addClass("selected");
                jQuery(this).removeClass("noselection");
	        }
	    });
	    
        if (jQuery(field).attr("selectedIndex")==0)
        {
            jQuery(field).removeClass("selected");
            jQuery(field).addClass("noselection");
        }
        else
        {
            jQuery(field).addClass("selected");
            jQuery(field).removeClass("noselection");
        }
	    
	    /*
		field.checkSelectedIndex = function()
		{
			if (this.selectedIndex==0)
			{
				this.className = "select noselection";
			}
			else
			{
				this.className = "select selected";
			}
		}
		
		field.setSelectedIndex = function(index)
		{
			this.selectedIndex = index;
			this.checkSelectedIndex();
		}
		
		
		jQuery(field).change(function() {
		    
		});
		
		field.onchange = function(event)
		{
			this.checkSelectedIndex();
		}
		
		
		field.checkSelectedIndex();
		*/
	}
	else
	{
		alert("selectbox with id " + id + " not found");
	}
}


function CheckBoxTableColumn(headerCheckboxId, tableId, checkBoxesId, onNoSelection, onSelection)
{
	var headerCheckbox = document.getElementById(headerCheckboxId);
	var table = document.getElementById(tableId);
	
	if (!headerCheckbox)
	{
		alert("headerCheckbox not found: " + headerCheckboxId);
	}
	
	if (!table)
	{
		alert("table not found: " + tableId);
	}
	
	var inputs = table.getElementsByTagName("input");
	var checkboxes = new Array();

	// now search all inputs of type checkbox, where the id ends with
	// checkBoxesId
	for (var i=0; i < inputs.length; i++)
	{
		var input = inputs[i];
		if (input.type=='checkbox')
		{
			var id = input.id;
			
			if (id.lastIndexOf(checkBoxesId) == (id.length - checkBoxesId.length))
			{
				checkboxes.push(input);
			}
		}
	}
	
	headerCheckbox.tableCheckboxes = checkboxes;
	headerCheckbox.onNoSelection = onNoSelection;
	headerCheckbox.onSelection = onSelection;
	
	this.headerCheckbox = headerCheckbox;
	this.tableCheckboxes = checkboxes;
	this.onNoSelection = onNoSelection;
	this.onSelection = onSelection;
	
	this.showHideLink = function()
	{
		var found = false;
		var all = true;
		
		for (var i=0; i < this.checkBoxTableColumn.tableCheckboxes.length; i++)
		{
			if (this.checkBoxTableColumn.tableCheckboxes[i].checked)
			{
				found = true;
			}
			else
			{
				all = false;
			}
		}
		
		if (found)
		{
			// at least one checkbox is selected
			eval(this.checkBoxTableColumn.onSelection);

		}
		else
		{
			// no checkbox is selected => disabled the link
			eval(this.checkBoxTableColumn.onNoSelection);
		}
		
    	this.checkBoxTableColumn.headerCheckbox.checked = all;
	}
	
	// if any of the checkboxes is selected or deselected => check, if the link
	// must be disabled or enabled
	// if at least one checkbox is selected => enable otherwise disable
	for (var i=0; i < this.tableCheckboxes.length; i++)
	{
		this.tableCheckboxes[i].onclick  = this.showHideLink;
		this.tableCheckboxes[i].onchange = this.showHideLink;
		this.tableCheckboxes[i].checkBoxTableColumn = this;
	}
	

	// if the checkbox in the table header is clicked => set the checked state
	// of all
	// checkboxes in the table to the same value.
	headerCheckbox.onclick = function()
    {
		for (var i=0; i < this.tableCheckboxes.length; i++)
		{
			this.tableCheckboxes[i].checked = this.checked;
		}
	
		if (this.checked && this.tableCheckboxes.length > 0)
		{
			// at least one checkbox is selected
     		eval(this.onSelection);
		}
		else
		{
			// no checkbox is selected => disabled the link
			eval(this.onNoSelection);
		}
	}
}



function setFocus(id, delay)
{
	var element = document.getElementById(id);
	
	if (element)
	{
	   if (delay)
	   {
		   window.setTimeout("document.getElementById('" + id + "').focus()", delay);
	   }
	   else	   
	   {
		   element.focus();
	   }
	}
	else
	{
		alert('focus element "' + id + '" not found');
	}
}


// set the cursor within a textarea or text input field
// if delay is not empty, the caretposition will be set after the given delay
function setCaretPosition(elemId, caretPos, delay) 
{
	if (!delay)
	{
		_setCaretPosition_(elemId, caretPos);
	}
	else
	{
		var func = "_setCaretPosition_('" + elemId + "'," + caretPos + ")";
		window.setTimeout(func, delay);
	}
}


// set the cursor within a textarea or text input field
// thanks to
// http://blog.josh420.com/archives/2007/10/setting-cursor-position-in-a-textbox-or-textarea-with-javascript.aspx
function _setCaretPosition_(elemId, caretPos)
{
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}


function suppressEnter(event)
{
    var keyCode = getKeyCodeFromEvent(event);
    if (keyCode==13)
    {
        return false;
    }
    return true;
}


// submit the form, where the given element is a part of
function submitForm(formElement)
{
    var form = formElement;
    while (form && form.nodeName.toUpperCase()!='FORM')
    {
        form = form.parentNode;
    }
    if (form)
    {
        form.submit();
    }
}
