﻿// This file will provide the java scipt function
// required for the proper working of ajax 
// framwork.

    // This code is to 
    //  1. disable mouse right button click.
    //  2. disable browser back button.
    //  3. disable refresh (F5). (for IE Browser)
    //

    // document.onmousedown="if (event.button==2) return false"; 
    // document.oncontextmenu=new Function("return false"); 
    // document.onkeydown = TrapKeyPress; 
    // 
    // function TrapKeyPress()
    // {
    //    if( (event.KeyCode) = 116)
    //    {
    //        CancelKeyEvent(event) 
    //    }
    //    document.oncontextmenu=new Function("return false"); 
    // }
    // 
    // function CancelKeyEvent(evt) 
    // { 
    //     if(evt!=null)
    //     {
    //        if (evt.preventDefault) 
    //        { 
    //        evt.preventDefault(); 
    //        return false; 
    //        } 
    //        else 
    //        { 
    //        evt.keyCode = 0; 
    //        evt.returnValue = false; 
    //        }
    //     }
    // } 
    
    // This is to trap the __dopostback function of Asp.net
    // framework
    // This function works as delegator between client side
    // events and Asp.net framework by making the ajax request.
    
    
   theForm = null; 
   var browser;
   var SetFocusFlag = true;
   browser = navigator.appName;
   
   if (!theForm) 
       theForm = document.forms[0];
        
     theForm.__AJAX_FormActionURL.value = theForm.action;
        
    function __doPostBack(eventTarget, eventArgument)
     {
        if (!theForm.onsubmit || (theForm.onsubmit() != false))
         {
            theForm.__EVENTTARGET.value = eventTarget;
            theForm.__EVENTARGUMENT.value = eventArgument;
            
            if(theForm.__AJAX_DoSubmitForControls.value.indexOf(eventTarget) >=0 )
            {
                theForm.submit(); // Sumit for controld neglected from Ajax
                return;
            }
                
            theForm.__AJAX_TARGETEVENT.value = eventTarget;
            
            if(theForm.__AJAX_FormActionURL.value != "")
                theForm.action = theForm.__AJAX_FormActionURL.value;
       
            // following block is to Identify the Parent Control ID
            eventTarget = ReplaceCharBy(eventTarget,'$',"_");

            var item;
             if (document.getElementById) // Netscape, Mozilla, IE
                item = document.getElementById(eventTarget);
             else //Konqueror
                item =   document.all[eventTarget];
                
             if(item == null)
             {
              alert('Invalid ID .. Element Not Found');
              return;
             }
           
                
             var Parent;
             if(browser == "Netscape")
             {
                Parent = item.parentNode;
             }
             else if(browser == "Microsoft Internet Explorer")
             {
                Parent = item.parentElement;
             }
                
             var ParentID = Parent.id;
            
             if(browser == "Netscape")
             {
                while(Parent.id.indexOf("Div_") < 0)
                {
                    if(Parent.parentNode)
                    {
                      Parent = Parent.parentNode;
                      ParentID = Parent.id;
                    }
                    else
                    {
                      ParentID ="";
                      break;
                    }
                }
             }
             else if(browser == "Microsoft Internet Explorer")
             {
                while(Parent.id.indexOf("Div_") < 0)
                {
                    if(Parent.parentElement)
                    {
                      Parent = Parent.parentElement;
                      ParentID = Parent.id;
                    }
                    else
                    {
                      ParentID ="";
                      break;
                    }
                 }
             }
             
             ParentID = ParentID.replace("Div_","");
            if(ParentID == "")
                theForm.__AJAX_TARGETCONTROL.value = "NOTHING_TO_RENDER";
             else
                theForm.__AJAX_TARGETCONTROL.value = ParentID;
             
           // alert('ok AjaxMethod');
            AjaxMethod(theForm.action)
         }
      }
      
   // This is the function where actual Ajax is  implemented.
   // it makes call to the server side by making use of
   // XmlHtttp object.
   // This XmlHttp object makes an postback request to the same
   // page, by forming request url and parameters required on it's own.
   
   function AjaxMethod(ActionURL)
    {
       var requestUrl;
       var XmlHttp;
        
        if(ActionURL.indexOf("?") > 0)
           ToEncodeUrl = "&CALLTYPE=AJAX&AJAXTARGETEVENT="+theForm.__AJAX_TARGETEVENT.value +"&AJAXTARGETCONTROL="+ theForm.__AJAX_TARGETCONTROL.value +"";
           else
           ToEncodeUrl = "?CALLTYPE=AJAX&AJAXTARGETEVENT="+theForm.__AJAX_TARGETEVENT.value +"&AJAXTARGETCONTROL="+ theForm.__AJAX_TARGETCONTROL.value +"";
    
           //Javascript Encoding for the parameters
           EncodedURL = encodeURI(ToEncodeUrl);
           requestUrl = ActionURL + EncodedURL;
          
           //alert(requestUrl);
               
       var data ="Start";
       var TypesNotAllowed ="button"
       var TargetValue = '';
       var ItemValue = '';
       SetFocusFlag = true;
       for (var i=0; i< document.forms[0].elements.length;i++)
		{
			  var item = document.forms[0].elements[i];  
			  if (theForm.__EVENTTARGET.value != item.name)
			  {
			    if(TypesNotAllowed.indexOf(item.type) < 0)
			     {
		           if (data == "Start")
		           {
		                if (IsXSSPresent(item.value))
		                {		                    		                    
		                    return;
		                }
		                else
		                {
		                    data = item.name + "=" + FormatedInputData(item.value);
		                }
		           }
		           else
		            {		               
		               SetFocusToField(item);
		               switch (item.type)
	                    {
                            case "radio": 
                            case "checkbox": 
                               if(item.checked)
                               {
                                    if (IsXSSPresent(item.value))
		                            {		                                
		                                return;		                                
		                            }
		                            else
		                            {
		                                data = data + "&" + item.name + "=" + FormatedInputData(item.value);
		                            }                                    
                               }
                            break;
                            case "application/x-shockwave-flash":
                            break;
                            default :
                                if (IsXSSPresent(item.value))
	                            {                                    
	                                return;
	                            }
	                            else
	                            {
	                            	ItemValue = ReplaceCharBy(item.value,'&',"%26");
                                    data = data + "&" + item.name + "=" + FormatedInputData(ItemValue);
	                            }                                                                    
                            break;
                        }
                     }
			      }
			  }
			  else
			  {
			    if (IsXSSPresent(item.value))
                {                    
                    return;                                    
                }
                else
                {
                    TargetValue = FormatedInputData(item.value);
                }			     
			  }
			  
		}
		
		if(TargetValue != '')
		data = data + "&" + theForm.__EVENTTARGET.value+ "=" + TargetValue;
		else
		data = data + "&" + theForm.__EVENTTARGET.value+ "=";
		
		XmlHttp = CreateXmlHttpObject();
        
        if(XmlHttp)
        {
	        XmlHttp.onreadystatechange = function() { HandleResponse(XmlHttp)};
	        try
	        {
	            XmlHttp.open('POST', requestUrl,theForm.__AJAX_RequestMode.value);
	        } 
	        catch (e)
	        {
	            alert(e);
	        }
	        XmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	        
	        //setting the mouse pointer to busy icon
            for (var i=0; i< document.forms[0].elements.length;i++)
            {
                if(document.forms[0].elements[i].style.display != 'none')
	                document.forms[0].elements[i].style.cssText = "cursor:progress;";
	        }
	          
	          if(theForm.__AJAX_ShowProgessBar.value == "True")
	                ShowAjaxProgressbar();
	          
		    //Making the ajax request.        
	        XmlHttp.send(data);
        }
        else
        {
	        alert("ActiveXObject Failed to Create !");
        }
    }
   
   // This is a handler (callback) function for XmlHttp object.
   // In this function the data return by the request is analyzed (MSG,SECTION) and
   // placed in to appropriate Html blocks.
         
    function HandleResponse(XmlHttp)
	{
	    if(XmlHttp.readyState == 4)
		{
    	  for (var i=0; i< document.forms[0].elements.length;i++)
    	  {
    	    if(document.forms[0].elements[i].style.display != 'none')
                document.forms[0].elements[i].style.cssText = "cursor:default;";
          }
          
           if(theForm.__AJAX_ShowProgessBar.value == "True")
                HideAjaxProgressbar();

			if(XmlHttp.status == 200)
			{
				var ResponseText = XmlHttp.responseText;
				if( (ResponseText == "") || ((ResponseText.indexOf("<AL_SECTION_TO_REFRESH>") < 0) && (ResponseText.indexOf("<AL_EXE_JAVAS>") < 0)))
		            return; //nothing to show
				    
				ResponseText = RemoveTheformData(ResponseText);
				
				//alert(ResponseText);		   			   		  
			
				while (ResponseText.indexOf("<AL_SECTION_TO_REFRESH>") >=0 || ResponseText.indexOf("<AL_EXE_JAVAS>") >=0)
				{
			       if( ResponseText.indexOf("<AL_SECTION_TO_REFRESH>") == 0) //Refreshing part of screen
				    {
				        ResponseText = ResponseText.replace("<AL_SECTION_TO_REFRESH>","");
				        index = ResponseText.indexOf("</AL_SECTION_TO_REFRESH>");
			            BlocktoRefresh = ResponseText.substring(0,index);
			            //replace the block name
				        ResponseText = ResponseText.replace(BlocktoRefresh,"");
			            ResponseText = ResponseText.replace("</AL_SECTION_TO_REFRESH>","");
        				
			            ResponseText = ResponseText.replace("<AL_SECTION_DATA>","");
			            index = ResponseText.indexOf("</AL_SECTION_DATA>");
			            DisplayData = ResponseText.substring(0,index);
			            //replace the Data name
				        ResponseText = ResponseText.replace(DisplayData,"");
			            ResponseText = ResponseText.replace("</AL_SECTION_DATA>","");
    			        
			            if (document.getElementById) // Netscape, Mozilla, IE
		                    if(document.getElementById('Div_'+BlocktoRefresh))
		                        document.getElementById('Div_'+BlocktoRefresh).innerHTML=DisplayData;
		                    else
		                        document.getElementById(BlocktoRefresh).innerHTML=DisplayData;
       			        else //Konqueror
				            document.all['Div_'+BlocktoRefresh].outerHTML=DisplayData;
				    }
				    else
				    if(ResponseText.indexOf("<AL_EXE_JAVAS>")== 0) //Refreshing part of screen
				    {
				        ResponseText = ResponseText.replace("<AL_EXE_JAVAS>","");
				        index = ResponseText.indexOf("</AL_EXE_JAVAS>");
			            JScriptCode = ResponseText.substring(0,index);
			            //replace the block name
				        ResponseText = ResponseText.replace(JScriptCode,"");
			            ResponseText = ResponseText.replace("</AL_EXE_JAVAS>","");
			            setTimeout(JScriptCode,0);
				    }
				    
				 }
			}
			else
			{
				alert("  Request Failed \nStatus Code= "  + XmlHttp.status);
			}
		}
	}
    
    // This function creates XmlHttp object by trying
    // different variations
        
	function CreateXmlHttpObject()
	{
		//creating the xmlhttp object
		if (window.ActiveXObject)
        {
    		try
			{
				return new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e)
			{
				try
				{
					return new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e)
				{
					return null;
				}
			}
	    }
	    else if (window.XMLHttpRequest)
        {	
			//Creating object of XMLHTTP in Mozilla and Safari
			if(typeof XMLHttpRequest != "undefined")
			{
				return new XMLHttpRequest();
			}
        }
	}

   //This function will invoke the page requeseted in the url
   //RequestUrl : Page url toi invoke
   //HandlerFunctionname : name of the function that will handle the respones.
   // if set to null response will be handled by HandleResponse function -(function which handle Ajax postback call response.
   //Data: data that need to be sent to sever.
   //this data must be key value pair. example: Key1=Value1&Key2=Value2
   function ALAjaxDopageRequest(RequestUrl, HandlerFunctionname, Data)
   {
       var pageRequestXmlHttp       = CreateXmlHttpObject();
       if(pageRequestXmlHttp)
        {
            if(HandlerFunctionname == null)
                pageRequestXmlHttp.onreadystatechange = function() { HandleResponse(pageRequestXmlHttp)};
            else
                pageRequestXmlHttp.onreadystatechange = function() { DopageRequestHandler(pageRequestXmlHttp, HandlerFunctionname)};
                
            pageRequestXmlHttp.open('POST', RequestUrl,true);
            pageRequestXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
            pageRequestXmlHttp.send(Data);
        }
   }
   
   //Internal function that handles the response before invoking the user
   //specified function. 
   function DopageRequestHandler(pageRequestXmlHttp, Handlerfunctionname)
   {
    var RequestResponseText;
     if(pageRequestXmlHttp.readyState == 4)
     {
        if(pageRequestXmlHttp.status == 200)
        {
            RequestResponseText = pageRequestXmlHttp.responseText;
            RequestResponseTextObj = RequestResponseText.split("$$ALRESPONSE&&");
            setTimeout(Handlerfunctionname + "(RequestResponseTextObj[0])",1);
        }
        else
		{
			alert("  Request Failed \nStatus Code= "  + pageRequestXmlHttp.status);
		}
	 }
   }
   
	// This function is to replace all th occurrences of specified 
	// character with some other character 	
    function ReplaceCharBy(inputstr,Char_To_Replace,Chart_Replace_With) 
	{
		var Outputstr = '';
		for (var i = 0; i < inputstr.length; i++) 
		{
			if (inputstr.charAt(i)!=Char_To_Replace)
			{
				 Outputstr += inputstr.charAt(i);
			}
			else
			{
				 Outputstr += Chart_Replace_With;
			}
		}
		return Outputstr;
	} 
	
    // This function is format the data to send the web Server 
	function FormatedInputData(inputstr)
	{
		var Outputstr = '';		
		
		if(inputstr == null)
		    return;
		    
		for (var i = 0; i < inputstr.length; i++) 
		{
            switch (inputstr.charAt(i))
            {
                case '+': 
                    Outputstr += '%2B';
                break;
                case '/': 
                    Outputstr += '%2F';
                break;
                case ' ': 
                    Outputstr += '+';
                break;
                case '$': 
                    Outputstr += '%24';
                break;
                default :
                    Outputstr += inputstr.charAt(i);
                break;
            }
		}
		return Outputstr
	}

    //This Function removes the Form innerHtml
    // other than the controls to render html
    function RemoveTheformData(SourceResponseText)
    {
        
         //remove the Form Data;
            var SearchToken;
               index1 = SourceResponseText.indexOf("<AL_SECTION_TO_REFRESH>");
               index2 = SourceResponseText.indexOf("<AL_EXE_JAVAS>");
              
               if(index1 < index2)
               {
                   if(index1 == -1)
                   index = index2;
                   else
                   index = index1;
               }
               else
               {
                if(index2 == -1)
                   index = index1;
                   else
                   index = index2;
              }

            ControlPreData = SourceResponseText.substring(SourceResponseText.indexOf("<form"),index);
            SourceResponseText = SourceResponseText.replace( ControlPreData,"");
            StrLength = SourceResponseText.length;
            
            var i;
            i = 0;
            //Searching from last
            do
            {
                Last_Token = SourceResponseText.substring(StrLength - 18,StrLength);
                StrLength--;
                
                if(Last_Token.indexOf("</AL_EXE_JAVAS>") ==0)
                {
                    StrLength = StrLength - 1;
                    break;
                }
            }while( (Last_Token !="</AL_SECTION_DATA>"));
            
            ControlPostData = SourceResponseText.substring(StrLength+1 ,SourceResponseText.length);
            SourceResponseText = SourceResponseText.replace( ControlPostData,"");
    			    
        return SourceResponseText;
    }
    
    //For Displaying Progess bar
    var Zindex =1;
    var Onscrollfunction;
    var Onresizefunction;
    var Xoffset;
    var Yoffset;
    function ShowAjaxProgressbar()
    {
       //Setting the Progress bar position
       PageSizearray      = GetPageSize();
       ProgessBarXoffset  = PageSizearray[2] / 2;
       ProgessBarYoffset  = PageSizearray[3] / 2;
       
       //Right-bottom
       if(theForm.__AJAX_ProgessBarXoffset.value == "0")
            Xoffset = ProgessBarXoffset - 200;
       else
            Xoffset = parseInt(theForm.__AJAX_ProgessBarXoffset.value,0);
            
       if(theForm.__AJAX_ProgessBarYoffset.value == "0")
            Yoffset = ProgessBarYoffset - 50;
       else
            Yoffset = parseInt(theForm.__AJAX_ProgessBarYoffset.value,0);
       //End of Progress bar position settings
    
        ShowWindow = document.getElementById('AjaxInProgess'); 
        ShowWindow.style.display='block'; 	

        var ScrollX = document.documentElement.scrollLeft? document.documentElement.scrollLeft :document.body.scrollLeft;
        var ScrollY = document.documentElement.scrollTop? document.documentElement.scrollTop :document.body.scrollTop;
        
        var X = ScrollX + PageSizearray[2] / 2 + Xoffset;
        var Y = ScrollY + PageSizearray[3] / 2 + Yoffset;
              
        ShowWindow.style.left = X  + 'px' ;
        ShowWindow.style.top  = Y  + 'px' ;
        
        ShowWindow.style.zIndex = Zindex++;
        
        if(browser == "Microsoft Internet Explorer")
        {
            MsiePause(1);
        }
        
        if(theForm.__AJAX_SelfFocus.value == "True")
            self.focus();
       
       Onscrollfunction = window.onscroll;
       Onresizefunction = window.onresize;
       window.onscroll  = ShowFloatingProgressbar;
       window.onresize  = onResize;
    }
    
    function HideAjaxProgressbar()
    {
        HideWindow = document.getElementById('AjaxInProgess'); 
        HideWindow.style.display='none'; 	
        
        if(Onscrollfunction!= null)        
            window.onscroll  = Onscrollfunction;
       
        if(Onresizefunction!= null)       
            window.onresize  = Onresizefunction;
        
    }
    
    //Helper functions
    function MsiePause(numberMillis) 
    {
        if(navigator.userAgent.indexOf('MSIE 7.0') < 0 && navigator.userAgent.indexOf('MSIE 8.0') < 0)
        {
            var dialogScript ='window.setTimeout(function () { window.close(); }, ' + numberMillis + ');';
            var result = window.showModalDialog('javascript:document.write("<script>' + dialogScript + '<' + '/script>")');
        }
    }
    
    function ShowFloatingProgressbar()
    {
        PageSizearray      = GetPageSize();
        var ScrollX = document.documentElement.scrollLeft? document.documentElement.scrollLeft :document.body.scrollLeft;
        var ScrollY = document.documentElement.scrollTop? document.documentElement.scrollTop :document.body.scrollTop;
        
        var ShowWindow = document.getElementById('AjaxInProgess'); 
        
        ShowWindow.style.left = ScrollX + PageSizearray[2] / 2 + Xoffset + "px";;
        ShowWindow.style.top  = ScrollY + PageSizearray[3] / 2 + Yoffset + "px"; ;
    }
    
    function onResize()
    {
      var ShowWindow = document.getElementById('AjaxInProgess'); 
      
      if(ShowWindow.style.display =='block')
            ShowAjaxProgressbar();
    }
    
    function IsXSSPresent(InputString)
    {
        var Reg_Exp = new RegExp("(<\s*(script|object|applet|embed|form|body|frame|frameset|html|iframe|img|style|layer|link|ilayer|meta)\s*.*>)|javascript\s*:", "i");
        var flag;
        flag = Reg_Exp.exec(InputString);
        if (flag != null)
        {
            alert("Malicious Input found. Embedded scripts and object not allowed.");
            return true;
        }
        else
        {
            return false;
        }
    }
    
    function SetFocusToField(item)
    {
        var Parent;
        var Visible = true;
        try
        {            
            if ((item.type.toUpperCase() == "TEXT" || item.type.toUpperCase() == "TEXTAREA" || item.type.toUpperCase() == "CHECKBOX" || item.type.toUpperCase() == "RADIO" || item.type.toUpperCase() == "SELECT-ONE") && SetFocusFlag)                             
            {                                           
                if (item.style.visibility.toUpperCase() != "HIDDEN")
                {
                    Parent = item;
                    Visible = true;
                    while(Parent.parentNode != null)
                    {
                        Parent = Parent.parentNode;
                        if (Parent.style != null && Parent.style.visibility != null)
                        {
                            if (Parent.style.visibility.toUpperCase() == "HIDDEN")
                            {                                                
                                Visible = false;
                                break;
                            }
                        }
                        if (Parent.style != null && Parent.style.display != null)
                        {                            
                            if (Parent.style.display.toUpperCase() == "NONE")
                            {                                                
                                Visible = false;
                                break;
                            }
                        }
                    }
                    if(Visible == true && !item.disabled)
                    {
                        item.focus();
                        SetFocusFlag = false;
                    }
                }                                    
            }
        }
        catch(e)
        {
            //SetFocusFlag = false;
        }
    }
    
    function GetPageSize()
    {	    
        var xScroll, yScroll;
        if (window.innerHeight && window.scrollMaxY) 
        {	
	        xScroll = document.body.scrollWidth;
	        yScroll = window.innerHeight + window.scrollMaxY;
        } 
        else if (document.body.scrollHeight > document.body.offsetHeight)
        {   
            // all but Explorer Mac
	        xScroll = document.body.scrollWidth;
	        yScroll = document.body.scrollHeight;
        } 
        else 
        { 
            // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	        xScroll = document.body.offsetWidth;
	        yScroll = document.body.offsetHeight;
        }
    	
        var windowWidth, windowHeight;
        if (self.innerHeight) 
        {	
            // all except Explorer
	        windowWidth = self.innerWidth;
	        windowHeight = self.innerHeight;
        } 
        else if (document.documentElement && document.documentElement.clientHeight) 
        {   
            // Explorer 6 Strict Mode
	        windowWidth = document.documentElement.clientWidth;
	        windowHeight = document.documentElement.clientHeight;
        } 
        else if (document.body) 
        { 
            // other Explorers
	        windowWidth = document.body.clientWidth;
	        windowHeight = document.body.clientHeight;
        }	
    	
        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight)
        {
	        pageHeight = windowHeight;
        } 
        else 
        { 
	        pageHeight = yScroll;
        }
        
        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth)
        {	
	        pageWidth = windowWidth;
        } 
        else 
        {
	        pageWidth = xScroll;
        }
        
        arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight); 	    
        return (arrayPageSize);
    }
