var index = 0;
var c = 0;
var keycode = 0;
var fBspace = 0;
var fEnglish=0;
var fLanguage = 1;

//delimeter it keep track of cursor.
var CursorMarker='##';

//This buffer contains the unicode what we typed in the textbox.
//buffer value will assigned to textbox.
var buffer = new Array();

//gbuffer stores the buffer just before the key is pressed
//CaretPos stores the position of cursor in buffer
var gbuffer,CaretPos;

arrA['pop']=undefined;

var Consonants = new Array();
Consonants['b'] = 1;
Consonants['c'] = 1;
Consonants['d'] = 1;
Consonants['f'] = 1;
Consonants['g'] = 1;
Consonants['h'] = 1;
Consonants['j'] = 1;
Consonants['k'] = 1;
Consonants['l'] = 1;
Consonants['m'] = 1;
Consonants['n'] = 1;
Consonants['p'] = 1;
Consonants['q'] = 1;
Consonants['r'] = 1;
Consonants['s'] = 1;
Consonants['t'] = 1;
Consonants['v'] = 1;
Consonants['w'] = 1;
Consonants['x'] = 1;
Consonants['y'] = 1;
Consonants['b'] = 1;
Consonants['z'] = 1;
Consonants['D'] = 1;
Consonants['J'] = 1;
Consonants['S'] = 1;
Consonants['T'] = 1;
Consonants['N'] = 1;
Consonants['L'] = 1;
Consonants['ng'] = 1;
Consonants['G'] = 1;

if (!document.layers && !document.all && !document.getElementById)
event="test";
// JScript File
/**
This function recreate the word which is being modified
*/
function makeWords(e,name)
{
    e=e||window.event;

	//FireFox
	if(e.which){  
		keycode = e.which;
	}
	//IE
	else{
		keycode = e.keyCode;
	}
	//If space,left arrow,right arrow, backspace is pressed do nothing
	if(keycode==37 || keycode ==32 || keycode==8 ||keycode==39)
	{
		lastCharTyped=keycode;return;
	}
    //reinitialize buffer
    buffer.length=0;
    index=0;
	if(name=="form_vern_top")
		var temp=document.form_vern_top.q.value;
	else
		var temp=document.form_vern_bottom.q.value;
      
      
   //Special case where users types i or u, to handle matras ai,au
   //eg. ka ->i->kai   
   //Otherwise code will make k -> i -> ki
   if(lastCharTyped=='a' && (String.fromCharCode(keycode).toLowerCase()=='i' || String.fromCharCode(keycode).toLowerCase()=='u')) 
   {
       for(var xx=0;xx<temp.length&&temp.charAt(xx)!='#';++xx)
            if(temp.charAt(xx)!=gbuffer.charAt(xx)&&xx>0&&temp.charAt(xx)!=Halant) //Get where the user has typed
            {   //Check if previous char is consonant, then append it with "a"
                if(Consonants[arrA[temp.charAt(xx-1)]]||arrHA[temp.charAt(xx-1)])
                {
                
                    var tt=temp.substring(0,xx);
                    tt+=arrA['a'+String.fromCharCode(keycode).toLowerCase()];
                    tt+=temp.substring(xx+1,temp.length);
                    temp=tt;
                    break;
                }    
            }
    }
    else if(String.fromCharCode(keycode)=='a' && lastCharTyped!='a' && lastCaretPos != CaretPos && CaretPos!=temp.length-1 && (Consonants[arrA[temp.charAt(CaretPos-1)]]||Consonants[arrHA[temp.charAt(CaretPos-1)]]))
    {   
        //document.form_vern_top.q.value=gbuffer;        
        temp=gbuffer.substring(0,CaretPos);
        temp+=CursorMarker;
        temp+=gbuffer.substring(CaretPos,gbuffer.length);
        if(name=="form_vern_top")document.form_vern_top.q.value=temp;
		else document.form_vern_bottom.q.value=temp;
        setCursor(name);
        
        //IE
        if(e.keyCode)
            e.keyCode=0; 
        else
        //FF
            e.which=0; 
            
        lastCharTyped=String.fromCharCode(keycode);      
        return false;
    }    
    
    var lastspace=0,tlastspace=0; 
    //Find the current word which is being modified.   
    for(var xx=1;xx<temp.length && xx<CaretPos;++xx)
          if(temp.charAt(xx)==' ')
            lastspace=xx+1;
    if(lastspace!=0)
        for(var xx =0;xx<lastspace;xx++)
        buffer[index++]=temp.charAt(xx);

    for(var xx=CaretPos;xx<temp.length ;++xx)
          if(temp.charAt(xx)==' ')
            tlastspace=xx+1;
    if(tlastspace==0)
        tlastspace=temp.length;
    var i;    
   
    //Recreate the current word.
    for(i=lastspace;i<tlastspace && temp.charAt(xx)!=' ' ;i++)
    {
        var vFound=false;
	    var value=temp.charAt(i);
	    //If its a space or some non hindi char, append it to buffer as it is.
	    if(value.charCodeAt(0)==32||value.charCodeAt(0)<2300)
		{
			buffer[index++]=value;
			continue;
		}
	    //If the current letter is a vowel 'aa' type
	    if(Vowels[value])
		{
			if(arrA[arrA[value]+arrA[temp.charAt(i+1)]]){
				++i;
				buffer[index++]=arrA[arrA[value]+arrA[temp.charAt(i)]];
			}
			else
				buffer[index++]=value;
							
			continue;
		}
	    //If the current letter is a single vowel 'a' type
        else if(Vowels2[value])
		{
			buffer[index++]=value;    
			continue;
		}
        //If the letter is not a vowel.
        else if(arrA[value])
        {
            //roman value of char
            value=arrA[value]; 
            //try to make largest possible valid letter
            while(arrA[value]&&i<temp.length)
            {
                var nextchar=temp.charAt(i+1); //next char
                ++i;
                //Figure  out if the letter is complete,append a 'a' so that look ups may be correct
                //If its ot a arrHA lookup
                if(!(arrA[value+'h'] && arrA[nextchar]=='h')|| (value.length==1) )
                {
                //Current letter is consonant
                //Next is either consonant,space,Chandrabindi,Anusvara,NGA
                if (Consonants[value] && (Consonants[arrA[nextchar]]||Consonants[arrHA[nextchar]]||arrA[nextchar]=='a'||nextchar==' '||(Chandrabindu && nextchar==Chandrabindu)||nextchar==Anusavra||nextchar==Visarga||nextchar==NGA))
                    value+='a';
                //Current char is consonant, and end of line without halant
                else if(Consonants[value] && nextchar!=Halant&& i==temp.length)
                    value+='a';
                }
                
                //If nextchar is halant, or a arrHA char is valid or followed by some vowel or matra
                //drop the halant
                //
                if(nextchar==Halant )
                {
                    if(Vowels[temp.charAt(i+1)]||Matras[temp.charAt(i+1)]||Matras2[temp.charAt(i+1)] || (arrA[value+'h'] && arrA[temp.charAt(i+1)]=='h') || (arrA['A'] && arrA[temp.charAt(i+1)]=='A') || arrA[temp.charAt(i+1)]=='g')
                    {
                        nextchar=temp.charAt(i+1);
                        ++i;
                    }
                }
                //Make a larger letter
                if(arrA[nextchar]&&arrA[value+arrA[nextchar]] )
                    value+=arrA[nextchar];
                //If a 2 roman char matra, vowel append using 1,2
                //||Vowels2[nextchar]
                else if((Matras[nextchar]||(Vowels2[nextchar] &&((lastCharTyped=='a' &&(lastCaretPos==CaretPos+1 || lastCaretPos==CaretPos)) || i==temp.length-3)))&& arrA[value+arrA[nextchar+1]+arrA[nextchar+2]])//&&arrA[value+arrA[temp.charAt(i)]])
                    {
                        value+=arrA[nextchar+1];
                        value+=arrA[nextchar+2];
                        break;
                        //break because not larger letter is possible
                    }
                else if(Vowels2[nextchar]&& arrA[value+arrA[nextchar+1]+arrA[nextchar+2]])
                {
                    value+='a';
                    i--;
                    break;
                }
                //if it can be made a arrHA lookup
                else if(arrHA[value]&&arrA[nextchar]=='h')
                    value+=arrA[nextchar];
                    
                //Special case for G->Gh 
                else if(value=='j' && nextchar==Halant && String.fromCharCode(e.keyCode)=='h' && arrA[temp.charAt(i+1)]=='J' && temp.charAt(i+2)== Halant && arrA[temp.charAt(i+3)]=='h' && arrA['Gh'])
                    {
                        value='Gh';
                        i+=4;
                    }
                //Cannot make larger word.
                else{
                    --i;
                    break;
                    }                    
            }            
        }
        //Current letter is arrHA lookup
        else if(arrHA[value])
        {   
            //this flag checks if current letter has  a vowel with it. if yes it doesn't appends 
            // a 'a' to it
            vFound=false;
            //Check if it 'D' or 'dH' lookup up append capital 'H'
            //arrHA[value]=='D'||
            if(arrA['DH'] && ( value.charCodeAt(0)==0x095d || value.charCodeAt(0)==0x095c))
                value = arrHA[value]+'H';
            else
                value=arrHA[value]+'h';
                
            //try to create longest letter
            while(arrA[value]&&i<temp.length)
            {
                var nextchar=temp.charAt(i+1);
                ++i;
                
                if(!(arrA[value+'h'] && arrA[temp.charAt(i)]=='h'))
                {
			if (!vFound&&(Consonants[arrA[nextchar]]||Consonants[arrHA[nextchar]]||arrA[nextchar]=='a'||nextchar==' '||(Chandrabindu && nextchar==Chandrabindu)||nextchar==Anusavra||nextchar==Visarga &&arrA[temp.charAt(i+1)]!='A'))
			    value+='a';
			else if( !vFound &&nextchar!=Halant&& i==temp.length && arrA[value+'a'] && value.length==2)
			    value+='a';
                
                }
                if(nextchar==Halant )
                {
                    if(Vowels[temp.charAt(i+1)]|| (arrA[temp.charAt(i+1)]=='A' && arrA['A']))
                    {
                        nextchar=temp.charAt(i+1);
                        ++i;
                    }
                }
                
                if(Matras[nextchar]||Matras2[nextchar])
                    vFound=true;    
                if(arrA[nextchar]&&arrA[value+arrA[nextchar]])
                    value+=arrA[nextchar];
                    //||Vowels2[nextchar]
                //else if((Matras[nextchar]||(Vowels2[nextchar] && ((lastCharTyped=='a' &&lastCaretPos==CaretPos+1) || i==temp.length-3)))&& arrA[value+arrA[nextchar+1]+arrA[nextchar+2]])//&&arrA[value+arrA[temp.charAt(i)]])
                
                else if((Matras[nextchar]||(Vowels2[nextchar] &&((lastCharTyped=='a' &&(lastCaretPos==CaretPos+1 || lastCaretPos==CaretPos)) || i==temp.length-3)))&& arrA[value+arrA[nextchar+1]+arrA[nextchar+2]])
                {
                        value+=arrA[nextchar+1];
                        value+=arrA[nextchar+2];
                        break;
                }
                else if(Vowels2[nextchar]&& arrA[value+arrA[nextchar+1]+arrA[nextchar+2]])
                {
                    value+='a';
                    i--;
                    break;
                }

                else{
                    --i;
                    break;
                    }                    
            }            
        }
        
        //if its a digit  
        if(Digits[value])
            buffer[index++]=value;
        else 
            buffer[index++]=arrA[value];
    }
    
    //Copy rest of buffer 
    for(var xx =i+1;i<temp.length;i++)
        buffer[index++]=temp.charAt(i);   
    Display(name);
    
    //Its works in IE.Giving error in FF.
    if(e.keyCode)
        e.keyCode=0;
 
	setCursor(name);
    lastCharTyped=String.fromCharCode(keycode);
    
    return ;
}


//switch between hindi and english
function ToggleFlags(e)
{
	e=e||window.event;
	if(e.keyCode==123)
	{
		if(fEnglish)
		{
			fEnglish=0;   
			fLanguage=1;
		}
		else if(fLanguage)
		{
			fEnglish =1;   
			fLanguage=0;
		}
	}
}

function setCursor(name)
{
	if(name=="form_vern_top")
	{
		//IE
		if(document.selection)
		{
			var rng =document.form_vern_top.q.createTextRange();
			rng.collapse();
			rng.findText(CursorMarker,100000);
			rng.text=""; 
			rng.select();
		}
		else if(window.getSelection)
		{
			//Firefox
			var rng=document.createRange();
			rng.selectNode(document.form_vern_top.q);

			var temp=document.form_vern_top.q.value;

			var cursormarkerstart=CursorMarker.charAt(0);
			//Iterate upto cursormarker start.
			for(var i=0;i<temp.length;i++)
			if(temp.charAt(i)==cursormarkerstart) 
				break;
			//Ignore cursor marker, copy rest of string back to textarea.
			document.form_vern_top.q.value=temp.substring(0,i)+temp.substring(i+CursorMarker.length,temp.length);
			document.form_vern_top.q.setSelectionRange(i,i);   

		}
	}
	else
	{
		//IE
		if(document.selection)
		{
			var rng =document.form_vern_bottom.q.createTextRange();
			rng.collapse();
			rng.findText(CursorMarker,100000);
			rng.text=""; 
			rng.select();
		}
		else if(window.getSelection)
		{
			//Firefox
			var rng=document.createRange();
			rng.selectNode(document.form_vern_bottom.q);

			var temp=document.form_vern_bottom.q.value;

			var cursormarkerstart=CursorMarker.charAt(0);
			//Iterate upto cursormarker start.
			for(var i=0;i<temp.length;i++)
			if(temp.charAt(i)==cursormarkerstart) 
				break;
			//Ignore cursor marker, copy rest of string back to textarea.
			document.form_vern_bottom.q.value=temp.substring(0,i)+temp.substring(i+CursorMarker.length,temp.length);
			document.form_vern_bottom.q.setSelectionRange(i,i);   

		}
	}
}
function AppendChar(value)
{	
	var name = "form_vern_top";
	if (window.getSelection)
	{
		gbuffer=document.form_vern_top.q.value;
		document.form_vern_top.q.focus();
		var Sel = window.getSelection();
		//here u get the cursor position.
		CaretPos = document.form_vern_top.q.selectionStart;
	}
	else if (document.selection) 
	{
		// gbuffer global past buffer.
		gbuffer=document.form_vern_top.q.value;
		document.form_vern_top.q.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart('character', -document.form_vern_top.q.value.length);
		//here u get the cursor position.
		CaretPos = Sel.text.length;
	}

	var temp=document.form_vern_top.q.value.substring(0,CaretPos);

	//If a consonant is typed we want it to appear without halant
	//so append a halant and a 'a' so that it will eventually become 
	//a compelete word
	if(Consonants[arrA[value]])
		temp+=value+Halant+arrA['a']+CursorMarker;
	else if(Consonants[arrHA[value]])
		temp+=value+Halant+arrA['a']+CursorMarker;
	else if(value==32)
		temp+=' '+CursorMarker;
	else
		temp+=value+CursorMarker;


	temp+=document.form_vern_top.q.value.substring(CaretPos,document.form_vern_top.q.value.length);

	document.form_vern_top.q.value=temp;
	  
	 //local event to pass parameter to  makeWords().
	var evt={};
	evt.type='keypress';
	evt.keyCode=value;
	evt.which=value;
	//if a vowel was clicked dont call the make word function, so as to kepe the placement of letters as it is.
	if(!Vowels[value] && !Vowels2[value]&& value!=32)
		makeWords(evt,name);
	else
		setCursor(name);
		
	return true;
}
function showtip(current,e,text)
{ 
	if (document.all||document.getElementById)
	{
		thetitle=text.split('<br>');
		
		if (thetitle.length > 1)
		{
			thetitles='';
			
			for (i = 0; i < thetitle.length; i++)
				thetitles += thetitle[i];
				
			current.title = thetitles;
		}
		else
			current.title=text;
	}

	else if (document.layers)
	{
		document.tooltip.document.write('<layer bgColor="white" style="border:1px solid black;font-size:12px;">'+text+'</layer>');
		document.tooltip.document.close();
		document.tooltip.left=e.pageX+5;
		document.tooltip.top=e.pageY+5;
		document.tooltip.visibility="show";
	}
}
function hidetip()
{
	if (document.layers)
		document.tooltip.visibility="hidden";
}

function eventTrigger (e)
{
	if (! e)
		e = event;
		
	return (e.target || e.srcElement);
}


function radioClick (e)
{	
	var obj = eventTrigger (e);
	
	var notify = (document.getElementById && document.getElementById ('radio'));
	if (notify)
	{
		if(obj.value=="English")
		{	 	
			fEnglish=1;  				
			fLanguage=0;  
		}
		else 
		{ 
			fLanguage=1; 
			fEnglish=0;
		}
	 }
	return true;
}
function Display(name)
{
	if(name=="form_vern_top")
	{
		document.form_vern_top.q.value="";
		for(var x=0;x <= index; x++)
		{
			if( buffer[x] != undefined)
				document.form_vern_top.q.value += buffer[x];
		}
	}
	else
	{
		document.form_vern_bottom.q.value="";
		for(var x=0;x <= index; x++)
		{
			if( buffer[x] != undefined)
				document.form_vern_bottom.q.value += buffer[x];
		}
	}
}
function Search(name)
{
	if(name == "form_vern_top")
		 document.form_vern_top.submit();	
	else
		document.form_vern_bottom.submit();
}
function handleHalant(name)
{
	if(name == "form_vern_top")
        temp = document.form_vern_top.q.value;
	else
	    temp = document.form_vern_bottom.q.value;
	    
	//Strip down last Halant(if language is hindi),space 
	i=temp.length;
	    --i;
	while(i>0 && (temp.charAt(i) ==' ' || temp.charAt(i)=='\u094d'))
	    --i;
	if(name == "form_vern_top")
	{
	     document.form_vern_top.q.value=temp.substring(0,i+1);   
	}
	else
	{
	    document.form_vern_bottom.q.value=temp.substring(0,i+1);
	}
}
//gbuffer stores the buffer just before the key is pressed
//CaretPos stores the position of cursor in buffer
var gbuffer,CaretPos,lastCaretPos,lastCharTyped;

function DisplayChar(e,name)
{
	if(name == "form_vern_top")
		gbuffer=document.form_vern_top.q.value;
	else gbuffer=document.form_vern_bottom.q.value;
	
	e = e || window.event;

	//FireFox
	if(e.which)
	{  
		keycode = e.which;
	}
	//IE
	else
	{
		keycode = e.keyCode;
	}
	
	if(keycode==13)
	{
		Search(name);
		return;
	}
	if(keycode==36)
	{
		//alert("Home Key Press");
	}
	if(keycode==46)
	{
		//alert("DEL Key Press");
	}
	var character = String.fromCharCode(keycode);

	if(keycode == 32){
		handleHalant(name);
		return true;
	}
		
	if(keycode >=65 && keycode <= 90)
	{
		if(!Caps[keycode])
		character = character.toLowerCase();
	}

	//If English is selected do nothing just return 
	//Default handler will insert it it correct position
	if(fEnglish)
		return true;

	//Else change the keycode to unicode equivalent.
	if(Digits[character])
		e.keyCode=Digits[character].charCodeAt(0);	

	else if(arrA[character])
	{		    
		var character = String.fromCharCode(keycode);
		if(keycode >=65 && keycode <= 90)
		{
			if(!Caps[keycode])
				character = character.toLowerCase();
		}

		if(name == "form_vern_top")
		{
			if(document.selection)
			{
				var Sel = document.selection.createRange ();  		            
				Sel.moveStart ('character', -document.form_vern_top.q.value.length);

				//kepp track of last char
				lastCaretPos=CaretPos; 
				CaretPos = Sel.text.length;
			}
			//FF
			else if(window.getSelection)
			{	        	    
				document.form_vern_top.q.focus ();
				var Sel = window.getSelection ();
				lastCaretPos=CaretPos;
				CaretPos = document.form_vern_top.q.selectionStart;	        	    
			}

			var temp=document.form_vern_top.q.value.substring(0,CaretPos);
			temp+=arrA[character];

			//Insert Cursor Marker to set position of cursor
			temp+=CursorMarker;            		    
			temp+=document.form_vern_top.q.value.substring(CaretPos,document.form_vern_top.q.value.length);

			document.form_vern_top.q.value=temp;
			temp="";
			//recreate a buffer.
			makeWords(e,name);
		}
		else
		{
			if(document.selection)
			{
				var Sel = document.selection.createRange ();  		            
				Sel.moveStart ('character', -document.form_vern_bottom.q.value.length);

				//kepp track of last char
				lastCaretPos=CaretPos; 
				CaretPos = Sel.text.length;
			}
			//FF
			else if(window.getSelection)
			{	        	    
				document.form_vern_bottom.q.focus ();
				var Sel = window.getSelection ();
				lastCaretPos=CaretPos;
				CaretPos = document.form_vern_bottom.q.selectionStart;	        	    
			}

			var temp=document.form_vern_bottom.q.value.substring(0,CaretPos);
			temp+=arrA[character];

			//Insert Cursor Marker to set position of cursor
			temp+=CursorMarker;            		    
			temp+=document.form_vern_bottom.q.value.substring(CaretPos,document.form_vern_bottom.q.value.length);

			document.form_vern_bottom.q.value=temp;
			temp="";
			//recreate a buffer.
			makeWords(e,name);
		}
	}

	//Dont call the default event handler now Date:2 Mar for FF
	//e.stopPropagation();
	if(e && e.preventDefault && keycode !=8&& keycode !=39&& keycode !=32&& keycode !=37)
	{
		e.preventDefault();		    
		return;
	}
	else
		return false;	
	//return true;
}
