
///////////////////////// Custom Error Message Display //////////////////////////

// Custom Error handling.
//window.onerror = errorHandler;
function errorHandler(msg,url,lno)
{ 
  var alertmsg = "There has been an internal error." + 
                 " We apologize for inconvenience." + 
  		 "\n\nPlease refresh this page and this error should go away.\n\n" + 
  		 "If problem persists please contact site helpdesk.";
  
  alert (alertmsg);
  return (true);
}


function Webduniactrl(common)
{
 this.common = common;
 this.CONST_NL = "\n";
 this.bufferAfterSpace=""; // This variable store the value of textbox after space will be inserted (i.e. for Mozilla / firefox )
 this.controlKey = 0; // Handling control key for MOZILLA 
 this.isEnglishEnabled = false; // check for english enabled or not
 this.checkForFirstTime = 0; // Set the cursur position at first time after selecting english enabled
 this.bufferStartIndex = 0;  // Start Index for Current Word.
 this.runningCaretIndex = 0; // Running Index for tracking the cursor.
 this.bSet = "N";
 this.buffer = new Array(); //this.buffer for Current Word.
 this.mouseStartIndex = 0;	// To Trap Mouse Clicks.
 this.mouseLastSelectionLength = 0;
 this.lastMouseCaretIndex = 0; 
 
 this.updatePositionOnHelp=updatePositionOnHelp;
 this.controlKeyUp=controlKeyUp;
 this.controlKeyDown=controlKeyDown;
 this.updatePositionUpDown=updatePositionUpDown;
 this.updatePosition=updatePosition;
 this.clearSelection=clearSelection;
 this.transferContent=transferContent;
 this.clearBuffer=clearBuffer;
 this.getCaret=getCaret;
 this.setCaret=setCaret;
 this.insertAtCaret=insertAtCaret;
 this.fixCaret=fixCaret;
 this.leftTrim=leftTrim;
 this.rightTrim=rightTrim;
 this.printBuffer=printBuffer;
 this.gotFocusCtrl = gotFocusCtrl;
}


// Empty this method.
function printBuffer (){
//	document.getElementById('dispalyValues1').value = this.buffer.join("") + ".\nBufLen>" + this.buffer.length + " MStart>" + this.mouseStartIndex + " MLength>" + this.mouseLastSelectionLength;	
}



// For Insertion from mouse.
function updatePositionOnHelp(textBox, engWord , forceClean, addToBuffer, startChar) 
{   
	var browser=navigator.appName;	
	 if(browser != "Microsoft Internet Explorer"){	 
        this.bSet = "N";
		this.clearBuffer ();	 
        this.bufferAfterSpace = textBox.value;	
        	
       if(textBox.selectionEnd > 0){
         this.bufferStartIndex = this.getCaret (textBox).position + this.getCaret (textBox).selectionLength;
       }else{       
         this.bufferStartIndex = this.getCaret (textBox).position;	
       }
       this.setCaret (textBox, {position:this.bufferStartIndex});    
	 }else{
      this.setCaret (textBox, {position:this.lastMouseCaretIndex});    
    }
      
	 this.insertAtCaret (textBox, '', this.common.toUnicode(this.leftTrim(this.rightTrim(engWord)),startChar), 'true', false);	 
	 this.lastMouseCaretIndex = this.getCaret(textBox).position;     
     var engGlyphtmp = engGlyph;
     
     this.common.setTextBox(textBox.id);
     
     this.common.DisplayHelp(this.common.toUnicode(engBase,startChar),engBase,startChar,engGlyphtmp);
          	  
     /*	
	//Remove Last Printed Word.
	this.setCaret (textBox, {position:this.mouseStartIndex, selectionLength:this.mouseLastSelectionLength});
	this.insertAtCaret (textBox, '', '', 'true', true);
	
	//this.mouseLastSelectionLength = 0;
	//this.setCaret (textBox, {position:this.mouseStartIndex, selectionLength:this.mouseLastSelectionLength});
	
	
	// Add Word to this.buffer.
	this.buffer.push (this.leftTrim(this.rightTrim(engWord)));
	this.insertAtCaret (textBox, '', toUnicode(this.buffer.join(""),startChar), 'true', 'true');
	this.runningCaretIndex = this.getCaret (textBox);
	
	//Modify this.buffer Indexes.
	this.mouseStartIndex = this.getCaret(textBox).position;
	this.mouseLastSelectionLength = this.getCaret(textBox).selectionLength;	
	this.printBuffer ();*/	
   this.transferContent (textBox);    
}

/*
 *This method is used for handling control key on mozilla browser
 */

function controlKeyUp(textbox,keyPressed){
 	//Check for browser identification
	var browser=navigator.appName;
	var code;	
	if (browser=="Microsoft Internet Explorer"){
	   code =  keyPressed.keyCode;
	}else{
	   code =  keyPressed.which;	   
	}		
	
	if(code == 17){
	  this.controlKey = 0;
	}
}

/*
 *This method is used for handling control key on mozilla browser
 */

function controlKeyDown(textbox,keyPressed){
 	//Check for browser identification
	var browser=navigator.appName;
	var code;	
	if (browser=="Microsoft Internet Explorer"){
	   code =  keyPressed.keyCode;
	}else{
	   code =  keyPressed.which;	   
	}		
	
	if(code == 17){
	  this.controlKey = 1;
	}
}


/* 
 * This method update the carat position and calls for this.buffer clean.
 */
function updatePositionUpDown(textBox, keyPressed, forceClean, addToBuffer) { 

	this.clearSelection(keyPressed, textBox);
	//Check for browser identification
	var browser=navigator.appName;
	var code;	
	if (browser=="Microsoft Internet Explorer"){
	   code =  keyPressed.keyCode;
	}else{
	   code =  keyPressed.which;		  
	}		
		
	// Check for English Language or control key
	if(this.isEnglishEnabled == false && code != 17 && this.controlKey != 1 && code != 63){  
	
       if (textBox.value.length > 800) 
       {
       			textBox.focus();   
                textBox.value = textBox.value.substring(0, 800); 
                this.bufferAfterSpace =  textBox.value;
                return false;
        }
        
        //Check for clean this.bufferAfterSpace (i.e. for Mozilla / Firefox)
       if (textBox.value.length <= 0 && browser != "Microsoft Internet Explorer") 
       {   
           textBox.focus();            
           textBox.value = ""; 
           this.bufferAfterSpace =  textBox.value;                                            
        }
        

             	
	// For this.buffer and all.			
	if (this.bSet == "N") {	    
		this.bufferStartIndex = this.getCaret (textBox).position;
		this.bSet = "Y";
		this.clearBuffer ();				
		this.bufferAfterSpace =  textBox.value;    
	}else if (
		   code == 46 || // del key
		   code == 8  || // bksp		   
		   code == 35 || // end key
		   code == 36 || // home key
		   code == 37 || // Arrow key
		   code == 38 || // Arrow key
		   code == 39 || // Arrow key
		   code == 40 )  // Arrow key		   
	{     	 
		this.bufferStartIndex = this.getCaret (textBox).position;			
		this.bSet = "N";		
		this.clearBuffer ();	
		this.bufferAfterSpace =  textBox.value;   	    	    	    
	}else if(code == 13 || code == 32){		   	   	 
	  this.bufferStartIndex = this.getCaret (textBox).position;	
	  this.bSet = "N";		
	  this.clearBuffer ();	
	  this.bufferAfterSpace =  textBox.value;	
	  
	}           
   else if (forceClean == "true") {			
		this.bufferStartIndex = this.getCaret (textBox).position;
		this.bSet = "N";
		this.clearBuffer();		
	}else {			    
	}    
      this.transferContent (textBox);  
 }
   // check for mozilla
 else if((code == 13 || // Enter Key
		   code == 32) && (browser!="Microsoft Internet Explorer")){		   
	  this.bSet = "N";		
	  this.clearBuffer ();	
	  this.bufferAfterSpace =  textBox.value;
       if(textBox.selectionEnd > 0){
         this.bufferStartIndex = this.getCaret (textBox).position + this.getCaret (textBox).selectionLength;
       }else{       
         this.bufferStartIndex = this.getCaret (textBox).position;	
       }
      this.setCaret (textBox, {position:this.bufferStartIndex});            	   	 			 
 }else if(browser!="Microsoft Internet Explorer"){	
      this.bSet = "N";
	  this.clearBuffer ();	
	  this.bufferAfterSpace =  textBox.value;	
	   if(textBox.selectionEnd > 0){
         this.bufferStartIndex = this.getCaret (textBox).position + this.getCaret (textBox).selectionLength;
       }else{       
         this.bufferStartIndex = this.getCaret (textBox).position;	
       }  
      
        if(this.checkForFirstTime == 1){
 		 this.setCaret (textBox, {position:this.bufferStartIndex}); 				  
		  this.checkForFirstTime = 0;
		}
 		
 }else if(browser=="Microsoft Internet Explorer"){
     this.bufferStartIndex = this.getCaret (textBox).position + this.getCaret (textBox).selectionLength;			
		this.bSet = "N";		
		this.clearBuffer ();	
		this.bufferAfterSpace =  textBox.value;  
	   if(this.checkForFirstTime == 1){
		this.setCaret (textBox, {position:this.bufferStartIndex});	 
		  this.checkForFirstTime = 0;
		}
		
 }
}

/*
*This method handles control lost focus
*/
function gotFocusCtrl(textBox, keyPressed, forceClean, addToBuffer)
{  
  this.bufferStartIndex = this.getCaret (textBox).position;		
  this.bSet = "N";
  this.clearBuffer ();	
  this.bufferAfterSpace =  textBox.value;	
}
function updatePosition(textBox, keyPressed, forceClean, addToBuffer,lang)
{       
     
       var unicode;        
       this.common.setTextBox(textBox.id);
       //check for browser identification
       var browser=navigator.appName;
  		var code;
		if (browser=="Microsoft Internet Explorer"){
		   code =  keyPressed.keyCode;
		}else{
		   code =  keyPressed.which;		
		}	
					
	// Check for English Language
  	if(this.isEnglishEnabled == false && code != 17  && this.controlKey != 1 && code != 63){  
				     
        if(lang == '')
        {
            lang = "HI";
        }
 
        if (textBox.value.length > 800) 
        {
              textBox.value = textBox.value.substring(0, 800); 
               this.bufferAfterSpace =  textBox.value;
               return false;
        }
         //Check for clean this.bufferAfterSpace (i.e. for Mozilla / Firefox)
      if (textBox.value.length <= 0 && browser != "Microsoft Internet Explorer") 
       {           
           textBox.value = ""; 
           this.bufferAfterSpace =  textBox.value;                                            
        }
        
       var startChar = getIndicStart(lang);	
	// For this.buffer and all.
	if (this.bSet == "N") {	   
		this.bufferStartIndex = this.getCaret(textBox).position;
		this.bSet = "Y";
		this.clearBuffer ();			
	}else if (
		   code == 8  || // bksp
		   code == 13 || // Enter Key
		   code == 32)		   
	{      		 	    	   
		this.bufferStartIndex = this.getCaret (textBox).position;		
		this.bSet = "N";
		this.clearBuffer ();	
		this.bufferAfterSpace =  textBox.value;	
	    		
	} else if (forceClean == "true") {	
		this.bufferStartIndex = this.getCaret (textBox).position;
		this.bSet = "N";
		this.clearBuffer ();
		this.lastMouseCaretIndex = this.bufferStartIndex;		
		this.bufferAfterSpace =  textBox.value;			
	} else {
		if (addToBuffer == "true" && code != 0) {		
				       
			this.buffer.push(String.fromCharCode(code));						
			
			this.insertAtCaret(textBox, '', this.common.toUnicode(this.buffer.join(""), startChar), 'true', 'true');			
			
			this.runningCaretIndex = this.getCaret (textBox);			
            
            var engGlyphtmp = engGlyph;

            this.common.setTextBox(textBox.id);
            
      		this.common.DisplayHelp(this.common.toUnicode(engBase,startChar),engBase,startChar,engGlyphtmp);			
      		
			if (browser=="Microsoft Internet Explorer"){
	   			keyPressed.keyCode="";
			}else{
				keyPressed.preventDefault();			
			}				
			code="";				
 			this.printBuffer();		 			
			this.lastMouseCaretIndex = this.getCaret(textBox).position + this.getCaret(textBox).selectionLength; 						
		}
	}      
 this.transferContent (textBox);     

 }
  // check for mozilla
 else if (
		   (code == 8  || // bksp
		   code == 13 || // Enter Key
		   code == 32) && browser!="Microsoft Internet Explorer")		   
	{      		 	  	    
		this.bSet = "N";
		this.clearBuffer ();	
		this.bufferAfterSpace =  textBox.value;				  	 
}else if(browser!="Microsoft Internet Explorer"){
	
      this.bSet = "N";
	  this.clearBuffer ();	
	  this.bufferAfterSpace =  textBox.value;	
	   if(textBox.selectionEnd > 0){
         this.bufferStartIndex = this.getCaret (textBox).position + this.getCaret (textBox).selectionLength;
       }else{       
         this.bufferStartIndex = this.getCaret (textBox).position;	
       }   
       if(this.checkForFirstTime == 1){        
		  this.setCaret (textBox, {position:this.bufferStartIndex}); 
	
		  this.checkForFirstTime = 0;
		}
  }else if(browser=="Microsoft Internet Explorer"){
        this.bufferStartIndex = this.getCaret (textBox).position + this.getCaret (textBox).selectionLength;			
		this.bSet = "N";		
		this.clearBuffer ();	
		this.bufferAfterSpace =  textBox.value;   
		if(this.checkForFirstTime == 1){
  		  this.setCaret (textBox, {position:this.bufferStartIndex});		
		  this.checkForFirstTime = 0;
		}		
 }
}


/*
 * Clears the Selected Text from the TextArea.
 *
 */
function clearSelection(keyPressed, textBox) {     
    var browser=navigator.appName;
   	var code;
	if (browser=="Microsoft Internet Explorer"){
	   code =  keyPressed.keyCode;
	}else{
	   code =  keyPressed.which;
	   
	}	
	
	
	if (
	   code == 46 || // del key
	   code == 8  || // bksp
	   code == 13 || // Enter Key
	   code == 32 || // Space Bar
	   code == 37 || // Arrow key
	   code == 38 || // Arrow key
	   code == 39 || // Arrow key
	   code == 40 )  // Arrow key		   
	{  
		if (this.buffer.length > 0) {
		
			var selLength = this.runningCaretIndex.position;			
			textBox.value = textBox.value;					
			this.bufferAfterSpace =  textBox.value;									    			
			this.setCaret (textBox, parseInt(this.runningCaretIndex.position + this.runningCaretIndex.selectionLength));			

		}
	}	
	this.transferContent (textBox);
}


function transferContent (textbox)
{  
           //host.InputWindowText= document.getElementById('txtLayoutViewer').value; // Uncommented beast	             
}

/*
 * Clears the this.buffer.
 *
 */
function clearBuffer(){     
	this.buffer = new Array();
	this.runningCaretIndex = this.bufferStartIndex;
	this.mouseStartIndex = this.runningCaretIndex;
	this.mouseLastSelectionLength = 0;
	this.printBuffer();
	this.lastMouseCaretIndex = this.bufferStartIndex;		   
}

/*
 *  ----------------------------- DON'T MAKE CHANGES TO METHODS BELOW. ------------------------------------------
 */

///////////////////////// TextBox Operation Methods //////////////////////////

/**
 * Get the caret position info of the given textfield
 *
 * @param {object} textArea	The subject of the function.
 * @param {boolean} MSIEReturnNotLogicalPosition	This parameter is used for inner purpose.
 *
 * @return {object}	Returns a simple JavaScript object with position and selectionLength properties
 */
function getCaret(textArea, MSIEReturnNotLogicalPosition)
{
	if (arguments.length < 2) MSIEReturnNotLogicalPosition = false; 
	
		
	if (typeof textArea.selectionStart != "undefined" && typeof textArea.selectionStart != "number") {		      		
		textArea.focus();
		return {
			position: textArea.selectionStart,
			selectionLength: (textArea.selectionEnd-textArea.selectionStart)
		};
	
	// Handling this issue in case of Internet Explorer need a little hack.
	// The problem is, that IE handle the concept of new line different
	// from text field value and textRange "character" unit point of view.
	// In the value the \r,\n charcters exist separately, but when use
	// the textRange.move("charcter", 1) new line is only one step.
	// That's why we need a little correction.
	
	}else if (textArea.createTextRange) {	
	    
		var newLineNumAfterCursor = 0;
		match = textArea.value.match(/\n/g);
		
		if (match) {
			newLineNumAfterCursor = match.length;
		}				
						
		textArea.focus();
		
		var position = textArea.value.length;	
		
		var selectionLength = document.selection.createRange().text.length;
		
		var cursor = document.selection.createRange().duplicate();
		
		while (cursor.parentElement() == textArea && cursor.move('character', 1)) {
			if (textArea.value.charAt(position - 1) == this.CONST_NL) {
				position -= 1;
				newLineNumAfterCursor--;
			}
			position--;
		}	
					
					
		if (MSIEReturnNotLogicalPosition) {
			return {
				position: position + 1,
				selectionLength: selectionLength
			};
		} else {			
			return {
				position: position + 1 - (newLineNumAfterCursor),
				selectionLength: selectionLength
			};
		}
	 }else{	 
	    // MOZILLA / Firefox
	    var newLineNumAfterCursor = 0;
		match = textArea.value.match(/\n/g);
		
		if (match) {
			newLineNumAfterCursor = match.length;
		}												
				
		var position =textArea.selectionStart;		
				
	    if (MSIEReturnNotLogicalPosition) {    	 
			return {			
				position:  position + 1,
				selectionLength: ((textArea.selectionEnd-textArea.selectionStart))
			};
		} else {			   
			return{			    
				position: position + 1,
				selectionLength: ((textArea.selectionEnd-textArea.selectionStart))
				
			};
		}	       	 	
	 }
}



/**
 * Set the caret in the given textfield
 *
 * @param {object} textField	The subject of the function.
 * @param {object} pos	This parameter could be a number or a simple JavaScript
 *                    	object with position and selectionLength properties.
 *                    	If number was given the function creates a position
 *                    	object, where the position property is the given number
 *                    	and the selectionLength is 0. If the parameter is an
 *                    	object and has no position property, then the function
 *                    	set it to the current caret position. The selectionLength
 *                    	property could be negative.
 * @param {number} scrollTop	If this parameter is peresent, the function
 *                          	try to set the textField's scrollTop property.
 */
 
function setCaret(textField, pos, scrollTop) { 

	// If the function was called with a number only
		
	if (typeof pos == "number" ) {				
		pos = {position: pos, selectionLength: 0}
	}
	
	// If the function was called with an object only with a selectionLength property
	if (typeof pos.position == "undefined") {	        
		pos.position = this.getCaret(textField).position;		
	}
	
	if (typeof pos.selectionLength == "undefined") {	        
		pos.selectionLength = 0;		
	}
	// If negative selectionLength was given
	if (pos.selectionLength < 0) {
		pos.position += pos.selectionLength;
		pos.selectionLength = -pos.selectionLength;		
	}
	
    if (textField.createTextRange || textField.setSelectionRange) {	   
    
       if(textField.createTextRange){      
		var textRange = textField.createTextRange();
		textRange.moveStart("character", pos.position);
		textRange.collapse();
		textRange.moveEnd("character", pos.selectionLength);
		textRange.select();			
	   }else{	  
	    //MOZILLA /firefox	    	        
		textField.setSelectionRange(pos.position,(pos.position+pos.selectionLength)+1);							        		
	   }		  	   
	}	
	else if (typeof textField.selectionStart != 'undefined') {	
	     
		textField.setSelectionRange(pos.position,pos.selectionLength);
		  		 	
	}		
		
	if (typeof scrollTop != "undefined" && typeof textField.scrollTop != "undefined") {
		textField.scrollTop = scrollTop;
	}			
}

/**
 * Insert string at the current caret position.
 *
 * @param {object} textField	The subject of the function.
 * @param {string} beforeStr	This string will be inserted before the caret.
 * @param {string} afterStr	This string will be inserted after the caret. Its default is ''.
 * @param {boolean} replace	If this flag is set to true, the inserted string
 *                         	replace the formerly selected text by the caret.
 *                         	Its default is false.
 * @param {boolean} select	If this flag is set to true, the inserted string (and the
 *                        	formerly selected text if replace was false) is selected.
 *                         	Its default is true.
 */
 
function insertAtCaret(textField, before, after, replace, select) {
         
	if (arguments.length < 3 || !after){
		 after = '';
	}
	
	if (arguments.length < 4 || !replace){
		 replace = false;
	}
	
	if(arguments.length < 5 || select){
		 select = true;
	}
		
	if (typeof textField.selectionStart != 'undefined' && typeof textField.selectionStart != 'number') {	  	    
		var startPos = textField.selectionStart;
		var endPos = textField.selectionEnd;
		textField.value = textField.value.substr(0, startPos) + before
						+ (replace ? "" : textField.value.substring(startPos, endPos))
						+ after + textField.value.substr(endPos);								               
		if (select) {
			textField.setSelectionRange(startPos,
				(endPos + before.length + after.length - (replace ? (endPos-startPos) : 0)));
		} else {
			startPos = startPos + before.length + after.length;
			textField.setSelectionRange(startPos , startPos);
		}	
	} else if (textField.createTextRange || textField.setSelectionRange) {	 	   		 
	
		textField.focus();
		
		var pos = this.getCaret(textField);		          
		
		var range;
		
		if(textField.createTextRange){		
	    	range = document.selection.createRange();
        	// Adding the before/after text to the textRange
			range.text = after;					
			// Selecting the needed text
			if (select) {							   			
				pos.selectionLength = replace ? (before.length + after.length) : (pos.selectionLength + before.length + after.length);				
			} else {
				pos.position += (before.length + after.length);
				pos.selectionLength = 0;
			}				
			this.setCaret(textField, pos);						    	    	
			
	    }else{	    	  	   	 	      	       
   	       //MOZILLA  / firefox	      	      
    	    var data = this.bufferAfterSpace.substring(0,(this.bufferStartIndex)) + after + this.bufferAfterSpace.substring(this.bufferStartIndex) ;  	          	          	         	           	    
    	    
  	        textField.value = data;  	        
	       	// Selecting the needed text
			if (select) {			    				   	   
			    pos.position = this.bufferStartIndex-1;		
			    pos.selectionLength = after.length-1;				
			} else {			   			
				pos.position += (this.bufferStartIndex-1);
				pos.selectionLength = 0;
			}				
								
	        this.setCaret(textField,pos);
	    }	    			    
	    
	}else{			 
		   
		var position = textField.value.length+before.length;				
		textField.value += (before + after);		
		setCursorPosition(textField, position);
	}			
}


function fixCaret(textField, position) {
	var selectionLength = 0;
	this.setCaret(textField, {position:position, selectionLength:selectionLength});
}


//////////////////// Utility Methods ////////////////////
function leftTrim(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	return sString;
}

function rightTrim(sString) {
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}


 


