﻿/**
  *
  *		Copyright 2006 Sentica Limited
  *
  *		ajaxLoader by Raj Curwen
  *
  *		Create 11th October 2006
  *
  Notes on the class structure. 
  
    class templates follow this structure
    
    function myClass()
    {
	    var m = new Object();
    	
	    m.localvariable = "hello";
        m.cantOverride = "me"; 
        
	    m.memberFunction = function()
	    {								
		    alert("in here");
		    this.localvariable = "hello2";
		    m.cantOverride = "You";		    
	    }; 
    	
    	m.print = function()
    	{
    	    alert(this.localvariable);
    	    alert(m.cantOverride);   
    	}
    	
	    return m;
    };  
    
  I use m.varname in the class to use the local copy only of the variable. So this cannot be used in overridden function 
  outside the class. However, I use this.varname inside the class for variables that can be used in overriden functions. 
  For example. 
  
  var mc = new myClass();
  
  mc.memberFunction = function()
  {
    //  in this override we can't use m, but we can use this!
    this.cantOverride = "New Message";
    this.localvariable = "Hello3";
    
    this.print();
  }
  
  results in Hello3 and You - because print refers to m.cantOverride (the local copy) and not this.cantOverride (the copy on the current object)
  
**/

/*
    Notes
    
    Sending Async requests
    
    The async parameter specifies whether the request should be handled asynchronously or not. 
    True means that script continues to run after the send() method, without waiting for a response 
    from the server. false means that the script waits for a response before continuing script 
    processing. By setting this parameter to false, you run the risk of having your script hang if 
    there is a network or server problem, or if the request is long (the UI locks while the request 
    is being made) a user may even see the "Not Responding" message. It is safer to send asynchronously 
    and design your code around the onreadystatechange event!
*/

function ajaxLoader()
{
	var m = new Object();
	
	m.XMLHttpRequestObject = null;
	m.onLoadComplete = null;
	m.responseHTML = null; 
	
	if (window.XMLHttpRequest) 
	{
		m.XMLHttpRequestObject = new XMLHttpRequest();
	} 
	else if (window.ActiveXObject) 
	{
		m.XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	m.onReadyStateChange = function()
	{								
	    //  ready state 4 = complete and ready state 200 = server response OK
		if (m.XMLHttpRequestObject.readyState == 4) 
		{						
		    if (m.XMLHttpRequestObject.Status == 200)
			    m.responseHTML = m.XMLHttpRequestObject.responseText;
            else
            {
                //  error occurred
                m.responseHTML = m.XMLHttpRequestObject.responseText;
            }
            
			m.onLoadComplete();
		}
	}; 
	
	m.load = function(service, onServiceLoaded)
	{	
	    //	send the GET request with a timestamp to prevent page caching
	    //  first check if parameters already exist - if so append the time
	    //  stamp, otherwise add the timestamp
        
	    var separator = "?";

	    if (service.indexOf("?") != -1)
	        separator = "&";
	    	        
	    var url = service + separator + "timeStamp=" + new Date().getTime();
	    
		//	prepare the request
		m.XMLHttpRequestObject.open("GET", url, true);
        
		m.XMLHttpRequestObject.onreadystatechange = m.onReadyStateChange;
        
        if (onServiceLoaded != null)
		    m.onLoadComplete = onServiceLoaded;

		//	send the request - for GET use a value of null
		m.XMLHttpRequestObject.send(null);
	};
    
    
    m.formGetValues = function(formID, validationFunc)
    {
        var str = "";
              
        var result = true;
        var cmd = "";
        
        //  if a validation function has been passed then result = false 
        if (validationFunc)
            result = false;
            
        var fobj = document.getElementById(formID);
        
        for(var i = 0;i < fobj.elements.length;i++)
        {
            switch(fobj.elements[i].type)
            {
                case "hidden":
                    if (validationFunc)
                    {
                        //  call the validation function passed in to validate the output
                        result = validationFunc(fobj.elements[i]);
                    }
                    
                    if (result)
                        str += fobj.elements[i].id + "=" + escape(fobj.elements[i].value) + "&";
                    break; 
                    
                 case "checkbox":
                 case "radio":
                    {
                        var value = -1; 
                        if (fobj.elements[i].selectedIndex != -1)
                        {
                            value = fobj.elements[i].checked;
                        }
                        
                        str += fobj.elements[i].id + "=" + value + "&";
                    }                    
                    break;
                                  
                case "select-one":
                    {
                        var value = -1; 
                        if (fobj.elements[i].selectedIndex != -1)
                        {
                            value = fobj.elements[i].options[fobj.elements[i].selectedIndex].value;
                        }
                        
                        str += fobj.elements[i].id + "=" + value + "&";
                    }                    
                    break;
                case "button":
                    break;
                case "password":
                case "text":
                default:
                    if (validationFunc)
                    {
                        //  call the validation function passed in to validate the output
                        result = validationFunc(fobj.elements[i]);
                    }   
                    
                    if (result)                 
                        str += fobj.elements[i].id + "=" + escape(fobj.elements[i].value) + "&";                        
                    break;
               
            }
        }
        
        str = str.substr(0,(str.length - 1));

        return str;        
    }   
    
    m.submit = function(service, onServiceLoaded, formID)
    {
        var postData = ""; 
        
        m.post(service, onServiceLoaded, postData);     
    }
    
    /*
        postData is id=value pairs like:-
        
            firstName=Raj&middleName=Kumar&lastName=Curwen
            
        send a timestamp to prevent the browser caching the page  
        timestamp adding should be based on a property
        m.addTimeStamp = true;           
    */
    m.post = function (service, onServiceLoaded, postData)
    {
        //  ajax post request
        m.XMLHttpRequestObject.open("POST", service, true);
        
        //  make sure the server knows we are sending id=value pairs so it reads the values correctly
        //  and makes them available in the Request and Post (php) objects.
        m.XMLHttpRequestObject.setRequestHeader(
            "Content-Type", 
            "application/x-www-form-urlencoded; charset=UTF-8");
        
        m.XMLHttpRequestObject.onreadystatechange = m.onReadyStateChange;
        
        if (onServiceLoaded != null)
		    m.onLoadComplete = onServiceLoaded;
		
		postData = "timeStamp=" + new Date().getTime()+"&"+postData;
		
        m.XMLHttpRequestObject.send(postData);
    }
    
    m.readyStateChangeLoadScript = function()
	{
	    var newScript = document.createElement("script");
        newScript.type = "text/javascript";
        newScript.src =  m.scriptURL + "?timeStamp=" + new Date().getTime();
        newScript.id = m.scriptID + "Script";
        						
	    //  ready state 4 = complete and ready state 200 = server response OK
		if (m.XMLHttpRequestObject.readyState == 4) 
		{						
		    if (m.XMLHttpRequestObject.Status == 200)
		    {
		        var preScriptTag = document.getElementById(m.scriptID + "Script");
		        
		        if(preScriptTag)
		            document.getElementsByTagName('head')[0].removeChild(preScriptTag)
		            
		        document.getElementsByTagName('head')[0].appendChild(newScript);
		        m.responseHTML = m.XMLHttpRequestObject.responseText;
			}
                        
			m.onLoadComplete();
		}  
	}; 
    
    m.loadScript = function (script, onServiceLoaded, metabookName)
    {
       
        //	send the GET request with a timestamp to prevent page caching
        //  first check if parameters already exist - if so append the time
        //  stamp, otherwise add the timestamp
                   	        
	    m.scriptURL = script;
	    m.scriptID = metabookName;
	    
	    //	prepare the request
	    m.XMLHttpRequestObject.open("GET", script, true);
        
	    m.XMLHttpRequestObject.onreadystatechange = m.readyStateChangeLoadScript;
        	    
        if (onServiceLoaded != null)
	        m.onLoadComplete = onServiceLoaded;
       	    
	    //	send the request - for GET use a value of null
	    m.XMLHttpRequestObject.send(null);
    }
    
    m.CallService = function(metabookName, object, method, objectID, postData, onServiceLoaded)
    {
        var data = "";
        
        postData =postData.replace(/\'/g, "\"");
        
        var xmlToSend = "";
        var url = window.parent.SERVER + object + ".asmx";
        var methodPath = object + "/" + method;
        
//        if(postData.indexOf('&') != -1)
        data = "<![CDATA["+ postData +"]]>";
       
        //  ajax post request
        m.XMLHttpRequestObject.open("POST",  url , false);
        
        //  make sure the server knows we are sending id=value pairs so it reads the values correctly
        //  and makes them available in the Request and Post (php) objects.
        m.XMLHttpRequestObject.setRequestHeader("Content-Type", "text/xml");
        
        m.XMLHttpRequestObject.setRequestHeader("SOAPAction", methodPath);
        
        xmlToSend += "\<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "; 
        xmlToSend += " \ xmlns:xsd='http://www.w3.org/2001/XMLSchema' "; 
        xmlToSend += "\ xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> "; 
        
        if(objectID == null)
            xmlToSend += "\ <soap:Body> \ <"+ method +" xmlns='" + object + "'> \ <metabookName>" + metabookName + "</metabookName> \ <data>" + data + "</data> \</"+ method +"> "; 
        else
            xmlToSend += "\ <soap:Body> \ <"+ method +" xmlns='" + object + "'> \ <metabookName>" + metabookName + "</metabookName> \ <data>" + data + "</data> \ <metaDataTagID>" + objectID + "</metaDataTagID> \</"+ method +"> "; 
            
        xmlToSend += "\ </soap:Body> \ </soap:Envelope> \ "; 
        
        m.XMLHttpRequestObject.send(xmlToSend);
        
        //m.XMLHttpRequestObject.send(" \<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \ xmlns:xsd='http://www.w3.org/2001/XMLSchema' \ xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \ <soap:Body> \ <"+method+" xmlns='" + object + "'> \ <data>" + data + "</data> \ </"+method+"> \ </soap:Body> \ </soap:Envelope> \ ");
                                                                                                                                                                                                                                    
        var xmlText = m.XMLHttpRequestObject.responseText;
        //fireFox--
        var doc = null;
        
        if (window.ActiveXObject)
        {
            doc=new ActiveXObject("Microsoft.XMLDOM");
            doc.async="false";
            doc.loadXML(xmlText);
        }
        // code for Mozilla, Firefox, Opera, etc.
        else
        {
            var parser=new DOMParser();
            doc=parser.parseFromString(xmlText,"text/xml");
        }

        var x=doc.documentElement;
        var result = x.childNodes[0].childNodes[0].childNodes[0].childNodes[0].nodeValue;
       
    }

	return m;
};

//  global serviceLoader - only one ajaxLoader can be exist at anyone time
var serviceLoader = new ajaxLoader();

function showImage(divId)
{
    var elem = document.getElementById(divId);

    if (elem)
    {
        var loadingImg = document.createElement('img');

        loadingImg.src = "images/ajax-loader-menu.gif";
        loadingImg.style.position = "absolute";
        loadingImg.style.top = "50%";
        loadingImg.style.left = "50%";
        
        elem.innerHTML = "";

        elem.appendChild(loadingImg);
    }
}
/*
    Notes
    
    First, we’re going to loop through the page once it loads and add an event handler to any form with the class “ajaxify.” 
    The event handler will be fired when the form is submitted:

    addEvent(window, 'load', init, false);

    function init() {
        if (!Sarissa || !document.getElementsByTagName) return;
        
        var formElements = document.getElementsByTagName('form');
        for (var i = 0; i < formElements.length; i++) {
            if (formElements[i].className.match(/\bajaxify\b/)) {
                addEvent(formElements[i], 'submit', submitRating, false);
            }
        }
    }

    So here we’re first checking if the user’s browser has correctly loaded the Sarissa object, 
    and is also able to do the document.getElementsByTagName method. If this doesn’t work out, 
    we return early. Then we’re looping through all the forms on the page and adding an event 
    handler to any that have a class name that matches the string “ajaxify.” Next we have to 
    actually write that submitRating function. It looks like this:
*/


