/// <reference name="MicrosoftAjax.debug.js" />
/// <reference name="SharePoint.Ajax.js" />
/// <reference name="XmlComponent.js" />
/// <reference name="XHtmlComponent.js" />
//-----------------------------------------------------------------------
// SharePoint AJAX Library : me@danlarson.com 
//-----------------------------------------------------------------------
// Shared Source License: www.codeplex.com/sharepointajax.
////////////////////////////////////////////////////////////////
// NAMESPACE SharePoint.Ajax
if (typeof(SharePoint) == 'undefined'){
    Type.registerNamespace('SharePoint');
}
if (typeof(SharePoint.Ajax) == 'undefined'){
    Type.registerNamespace('SharePoint.Ajax');
} 

if (!Sys.Application.get_enableHistory){
    alert('The SharePoint AJAX Toolkit requires the .NET 3.5 Framework with SP1 or newer.\nThe 3.5 ScriptHandler must also be registered in web.config.');
}
        

///////////////////////////////////////////////////////////////////
// HttpStatusCode enum
// Contains the values of status codes defined for HTTP.
HttpStatusCode = function(){};
HttpStatusCode.prototype = 
{
    OK:200, Created:201, Accepted:202,
    // Browser will return 304 responses with the cached 200 response. 
    NotModified:304,
    Unauthorized:401, Forbidden:403, NotFound:404, MethodNotAllowed:405, RequestTimeout:408,  Gone:410, InternalServerError:500,
    // Browser should automatically follow 301 and 310
    MovedPermanently : 310, Moved : 301,
    // Obscure codes:
    Continue:100, SwitchingProtocols:101,NotAcceptable:406, ProxyAuthenticationRequired:407,Conflict:409,
    NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultipleChoices:300,Ambiguous:300,
    Found:302,Redirect:302,SeeOther:303,RedirectMethod:303, NotImplemented:501,
    BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,
    LengthRequired:411,PreconditionFailed:412,RequestEntityTooLarge:413,RequestUriTooLong:414,
    UnsupportedMediaType:415,RequestedRangeNotSatisfiable:416,ExpectationFailed:417,
    UseProxy:305,Unused:306,TemporaryRedirect:307,RedirectKeepVerb:307,BadRequest:400
};
HttpStatusCode.registerEnum("HttpStatusCode");

SharePoint.Ajax.SetDivContent = function(element, id, content, display){ 
    SharePoint.Ajax.SetTagContent(element, 'DIV', id, content, display);
}
SharePoint.Ajax.SetSpanContent = function(element, id, content, display){ 
    SharePoint.Ajax.SetTagContent(element, 'SPAN', id, content, display);
}
SharePoint.Ajax.SetTagContent = function(element, tag, id, content, display, visibility){ 
    if (display == null)
        display = '';
    var divs = element.getElementsByTagName(tag);
    for(var i=0;i<divs.length;i++){
        if (divs[i].id == id){
            divs[i].innerHTML = content;
            divs[i].style.display=display;
            if (visibility != null)
                divs[i].style.visibility=visibility;
        }
    }
}        

// Looks up the control tree to find the control with the controlType expando property
SharePoint.Ajax.FindParentControl = function(child, controlType){
	var control = child;
	if (control == null) return;
	
	while (control != null && control.controlType != controlType){
		if (control.parentElement)
		   control = control.parentElement;
		else if (control.parentNode)
		   control = control.parentNode;      
		else if (control.controlType != controlType)
		   return null;
	}
	if (control.controlType == controlType){
		return control;
	}  
	return null;
}

//: DL: This is a HORRIBLE design pattern-- we should use Function.createDelegate, not pass references.
// Loads XML data specified in the path. 
SharePoint.Ajax.DataLoader = function(path, method, reference){
  // path: the URL to the Xml resource
  // method: the method name (a quoted literal)
  // the object reference to the component with the method
  // remarks - the method must take an Xml object as the parameter
  
   if (path == null || path == '')
      return;
  
    var request = new Sys.Net.WebRequest();
    Sys.Debug.trace("Data load: "+ path);
    request.get_headers()["X-SPAJAX"] = "DataLoader";
    var userContext = new Object();
    userContext.method = method;
    userContext.object = reference;
    request.set_userContext(userContext);
    request.set_url(path);
    if (reference.xrefresh){
        request.get_headers()["X-FORCE"] = "true";
        reference.xrefresh = null;
        userContext.refresh = true;
    }
    request.requestdate = new String(new Date());
    request.get_headers()["X-REQUESTDATE"] = request.requestdate;
    
    request.add_completed(SharePoint.Ajax.DataLoaderHandler);
    request.invoke();
}
 
// A common callback for the XML Data Loader. 
// Calls the method sent in the userContext as a callback delegate.
SharePoint.Ajax.DataLoaderHandler = function(response) {
    if (response == null) return;
    var request = response.get_webRequest();
    var context = request.get_userContext();
    var delegate = context.method;
    var status = response.get_statusCode();
    var url = request.get_url();
    var obj = context.object;
    if (!obj | !delegate)
        return;
    if (status == 200) {
        try {
            var lastMod = response.getResponseHeader('LAST-MODIFIED');
            // setting header on a 304 status ONLY works in FireFox
            var xrefresh = response.getResponseHeader('X-REFRESH');
            var xdebug = response.getResponseHeader('X-DEBUG');
            var xtime = response.getResponseHeader('X-TIME');
            var forceReload = (response.getResponseHeader('X-PARTIAL-RESPONSE') == '1');

            var xreqdate = response.getResponseHeader('X-REQUESTDATE');
            if (!obj.xrefresh & xrefresh != '' && xreqdate != '' && xreqdate != request.requestdate + '') {
                // This is a 304, and we have an xrefresh timestamp.
                Sys.Debug.trace('Expecting to do a reload!!! X-REFRESH:' + xrefresh);
            } else {
                // this was processed on the server, but we can still force a refresh using the header X-PARTIAL-RESPONSE
                if (!forceReload) xrefresh = null;
            }

            // Use these HttpHeaders to return status to the debugger. Useful for performance analysis.
            if (xdebug != '') Sys.Debug.trace('X-DEBUG: ' + xdebug); ;
            if (xtime != '') Sys.Debug.trace('X-TIME: ' + xtime);

            var refresh = null;
            if (xrefresh != null & xrefresh != '') {
                try {
                    refresh = Number.parseInvariant(xrefresh);
                } catch (e) {
                    debugger;
                }
            }
            var xml = response.get_xml();
            if (xml == null) {
                xml = response.get_responseData();
            }

            // DL: This is a HORRIBLE design pattern-- we should use Function.createDelegate, not pass references.
            eval('obj.' + delegate + '(xml, lastMod, url)');
            if (obj.element != null
                & !context.refresh
                & !obj.xrefresh
                & refresh != null
                & refresh != 'NaN') {
                if (obj.element.controlType == 'XmlComponent') {
                    obj.xrefresh = true;
                    obj.timeoutID = window.setTimeout("SharePoint.Ajax.XmlComponent.Refresh(" + obj.element.id + ")", refresh);
                }
            }
        } catch (e) {
            alert(String.format('Could not process callback method in XML Component: {0}: {1}', delegate, e));
        }
    }
    else { // Process the status. Could be 401, 404 (not found), 410 (gone)
        var statusText = response.get_statusText();
        var errMsg = String.format('ERROR: {0} replied "{1}" ({2}).', url, statusText, status);
        Sys.Debug.trace(errMsg);
        if (context == null || context.object == null || context.object.errorHandler == null) {   // Default error handler
            switch (status) {
                case HttpStatusCode.Gone:
                    alert('Content has been removed.');
                    break;
                case HttpStatusCode.NotFound:
                    alert('Could not find resource.');
                    break;
                default:
                    alert(errMsg);
            }
        } else {
            try {
                context.object.errorHandler(errMsg, response, context);
            } catch (e) {
                Sys.Debug.trace(e.description);
            }
        }
    }
}

///////////////////////////////////////////////////////////////////
// XML TOOLKIT
SharePoint.Ajax.XmlTransform = function (xml, xsl, control){
  SharePoint.Ajax.XmlTransformDecode(xml, xsl, control, true);
}
SharePoint.Ajax.XmlTransformDecode = function (xml, xsl, control, decode){    
    if (typeof(xml) == "string")
        throw "Expected an XML DOM document.";
    if (typeof(xsl) == "string")
        throw "Expected an XSLT DOM document.";    
    
    SharePoint.Ajax.Purge(control);
    control.innerHTML = '';
    var content;
    try{
        if(decode == null)decode = true;
        if (!window.XSLTProcessor){ // ie	          
         content = xml.transformNode(xsl);
         var contentDiv = document.createElement('DIV');
         contentDiv.innerHTML = content;
         //control.innerHTML = content;
         control.appendChild(contentDiv);
      }else{  // MOZZILA
	    var processor = new XSLTProcessor();
	    processor.importStylesheet(xsl);
	    content = processor.transformToFragment(xml, document);
	    
	    for(var i=0; i< control.childNodes.length; i++){
            control.removeChild(control.childNodes[i]);
         }
        
        if(decode == true){
            var div = document.createElement('div');
            div.appendChild(content);     
            control.innerHTML = SharePoint.Ajax.HtmlDecode(div.innerHTML);	
        }else{
            control.appendChild(content);
        }
      }	
    }catch(e){
        throw e;
    }
}

//From crockford.com: 
SharePoint.Ajax.Purge = function(d) {    
    try{
    var a = d.attributes, i, l, n;    
    if (a) {        
        l = a.length;        
        for (i = 0; i < l; i += 1) {            
            n = a[i].name;            
            if (typeof d[n] === 'function') {   
                d[n] = null; 
            }        
        }
    }    
    a = d.childNodes;    
    if (a) {        
        l = a.length;        
        for (i = 0; i < l; i += 1) {  SharePoint.Ajax.Purge(d.childNodes[i]); }    
    }
    }catch(e){
        Sys.Debug.trace('We couldn\'t purge the element. Details: ' + e);
    }
}

//   client side version of the useful Server.HtmlDecode method
//   takes an encoded string and returns the decoded string. 
SharePoint.Ajax.HtmlDecode = function HtmlDecode(enc) {
	return enc.replace(/&quot;/gi,String.fromCharCode(0x0022)).replace(/&amp;/gi,String.fromCharCode(0x0026)).replace(/&lt;/gi,String.fromCharCode(0x003c)).replace(/&gt;/gi,String.fromCharCode(0x003e));
}

Sys.Application.notifyScriptLoaded();  