/*
 * <copyright>
 *  Copyright (c) 2009 by IICM, Graz University of Technology, Austria
 * </copyright>
 *
 *  This software is the confidential information of IICM,
 *  Graz University of Technology, Austria. You shall not disclose such
 *  confidential information and shall use it only in accordance with
 *  the IICM.
 *
 *  IICM MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 *  SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 *  PURPOSE, OR NON-INFRINGEMENT. IICM SHALL NOT BE LIABLE FOR ANY DAMAGES
 *  SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
 *  THIS SOFTWARE OR ITS DERIVATIVES.
 *
 */
 

/* Checks KeyEvent on <ENTER> and returns true on success */
function checkKeyOnEnter(keyEvent)
{
	var keycode;
	if (window.event) { 
		keycode = window.event.keyCode; 
	}
	else 
		if (keyEvent) { 
			keycode = keyEvent.which; 
	}
	else return false;

	if (keycode == 13) { 
		return true; 
	}
	else {
   		return false;
	}
}


/* Returns the current Cursorposition of a Text- or Input-Field with id='idObj' */
/* on error -1 is returned */
function getCursorPositon(idObj) {
	var cursorPos = -1;
	if (!document.getElementById || idObj=='' ) { return cursorPos; }
	var field=document.getElementById(idObj);
	if (document.selection) { // IE support
		field.focus ();
		var selection = document.selection.createRange ();
		selection.moveStart ('character', -field.value.length);
		cursorPos = selection.text.length;
	}	
	else {	// Other browsers
		if (field.selectionStart || field.selectionStart == '0') { cursorPos = field.selectionStart; }
	}
	return cursorPos;
}

/* Returns currently typed word and its start-/endIndex from a text- or Input-Field (id='idObj') depending on cursorposition */
function getCurrentTypedWord(idObj) {
	// Init
	var wordObj = new Array();
	wordObj['currentWord'] = '';
	wordObj['idxStart'] = 0;
	wordObj['idxEnd'] = 0;
	var currentWord="";
	if (!document.getElementById || idObj=='' ) { return wordObj; }
	var text = document.getElementById(idObj).value;
	// Get current cursorposition
	var cursorPos=getCursorPositon(idObj);
	if (cursorPos == -1) { return wordObj; }
	// Get indexes from word around cursorposition
	var len = text.length;
	var i=cursorPos;
	var idxStart = cursorPos-1;
	var idxEnd = cursorPos;
	while (idxStart >= 0 ) {
		if ( text.charAt(idxStart) == ' ' ) {idxStart++; break; } 
		idxStart--;
	}
	while (idxEnd < len) {
		if ( text.charAt(idxEnd) == ' ' ) { break; } 
		idxEnd++;
	}
	if (idxStart < 0) { idxStart = 0; }
	if (idxStart > idxEnd) { idxStart = idxEnd; }
	
	// Extract current word around cursorposition using indexes and return Object
	wordObj['currentWord'] = text.substring(idxStart,idxEnd);	
	wordObj['currentWord'] = wordObj['currentWord'].replace(/'/, "?"); 
	wordObj['idxStart'] = idxStart;
	wordObj['idxEnd'] = idxEnd;	
	return wordObj;
}



/* Returns number of totalHits */
function getTotalHits( idTotalHits ) {
	var totalHits = parseInt(document.getElementById(idTotalHits).value);		
	if ( isNaN(Number(totalHits)) ) { totalHits = 0;}
	return totalHits;
}


/* Compares totalHits with limitation and returns true if more hits */ 
/* If no SearchTerm the return-value= false							*/
function checkHitsGreaterLimitation( idTotalHits, idLimit ) {
	
	var totalHits = parseInt(document.getElementById(idTotalHits).value);		
	var limit = parseInt(document.getElementById(idLimit).value);								
	if ( isNaN(Number(totalHits)) ) { totalHits = 0;}
	if ( isNaN(Number(limit)) ) { return false; } // limit = 'all'
	if ( totalHits <= limit )  {	
		return false;
	}	
	else{
		return true;
	}
}


/* Sets checked status of 'Continous Update' (status = "true" or "false") */
function setCheckedContUpdate(idContUpdate, status) {
	if (!document.getElementById ) { return; }
	if ( status == "true" ) {
		document.getElementById(idContUpdate).checked = true;
	}
	else {
		document.getElementById(idContUpdate).checked = false;
	}
}


/* Checks if SelectBox 'Continous Update' is checked and returns true on success */
function checkOnContUpdate(idContUpdate) {
	if (!document.getElementById ) { return false; }
	if ( document.getElementById(idContUpdate).checked) {
		return true;
	}
	else {
		return false;
	}
}


/* Sets the 'disabled' Status of ShowResult-Button to 'true' or 'false' */ 
/* depending on number of total Hits, limitation, baseQuery, and cont. Update */
function setAttributeDisabledShowResultButton(idShowResult, idContUpdate, idTotalHits, idLimitationHits, baseQuery ) {
	var statusDisabled = true;
	
	if ( !document.getElementById ) { return; }
	
	if ( !checkOnContUpdate(idContUpdate ) ) {
		if ( !checkHitsGreaterLimitation( idTotalHits, idLimitationHits ) && getTotalHits(idTotalHits)>0 && trim(baseQuery) != '' ) {
			statusDisabled = false;
		}		
	}	
	document.getElementById(idShowResult).disabled = statusDisabled;
	//alert("Show Result-Button: Attribute 'disabled' = "+document.getElementById(idShowResult).disabled);
}



/* Deletes White-Spaces from the Beginning and the Ending of a String */
function trim( charSequence ) {
	if ( charSequence == null) { return ""; }
	return charSequence.replace (/^\s+/, '').replace (/\s+$/, '');
}


/* Prepares charSequence for Display in Javascript, deletes Tags and Backslashes */
function fixText(charSequence){
	if (!charSequence) { return ''; }
	charSequence = charSequence.replace(/\\/g,"");
	charSequence = charSequence.replace(/'/, "\\'"); 
	charSequence = charSequence.replace(/</, ""); 
	charSequence = charSequence.replace(/>/, ""); 		
	charSequence = charSequence.replace(/&lt;/, ""); 
	charSequence = charSequence.replace(/&gt;/, ""); 	
	var arr = charSequence.split('&#');
	var resultString='';
	for (var i=0;i<arr.length;i++){ 
		str=arr[i];
		len=str.length;
		j=str.indexOf(';');
		if(j >= 0){
			st=str.substring(0,j);
			resultString+=String.fromCharCode(st);
			if(len > 3)
			resultString+=str.substring(j+1,len);
		}
		else{
			resultString+=str;
		}
	}
	return resultString;
}


// Cuts 'charSequence' on Position 'position-3' if length exceeds 'position' and appends 3 dots 
function cutText( charSequence, position ) {
	if ( charSequence.length > position && position >= 5) {
		charSequence = charSequence.substring(0,position-3)+"...";
	}
	return charSequence;
}

// Bookmark functions:



// Adds TextNode with Text 'textToDisplay' to Anchor with id 'idAnchor', deletes Childs if exist
function createText(idAnchor, textToDisplay) {
	if (!document.getElementById) { return };
	if (document.getElementById(idAnchor) != null ) {
		// delete Elements if exists
		var anchorElement = document.getElementById(idAnchor);
		if ( anchorElement.hasChildNodes() ) {
		    while ( anchorElement.childNodes.length >= 1 ) {
		        anchorElement.removeChild( anchorElement.firstChild );       
		    } 
		}
		// add new TextNode to Anchor
		var textElem = document.createTextNode(textToDisplay);
		anchorElement.appendChild(textElem);
	}
	return;
}



function readCookie(name){
    var Cookies = document.cookie;
    var cookiename ='';
    var cookiewert = '';
    var res='';
    var i = 0;
    var idx_name;
    var idx_content;
    while(Cookies != ''){
    	idx_name = Cookies.search('=');
  		cookiename = Cookies.substring(0,idx_name);
  		cookiename=cookiename.replace(/^\s*(.*)/, "$1");
  		cookiename=cookiename.replace(/(.*?)\s*$/, "$1");
  		idx_content = Cookies.search(';');
  		if (idx_content==-1)idx_content=Cookies.length;
  		cookiewert = Cookies.substring(idx_name+1,idx_content);
		if(name == cookiename){
			res = cookiewert;
			return unescape(res);
		}
  		i = Cookies.search(';')+1;
  		if(i == 0){i = Cookies.length}
  		Cookies = Cookies.substring(i,Cookies.length);
 	}
	return unescape(res);
}




// convertes String s to UTF8 
function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}


// decodes UTF-String s 
function decode_utf8( s )
{
  return decodeURIComponent( escape( s ) );
}

/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/

var Utf8 = {

    // public method for url encoding
    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;
    },

    // public method for url decoding
    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;
    }

}