//
// Generalized AJAX
//
    
// Dynamically attach the AJAX onclick event to any elements with CSS class "ajaxClick".
//
$(document).ready(function(){
	$(".ajaxClick").click(function()
	{
		// Parse it into a JQuery object so we can look up the attribute.
		var t = jQuery(this);

		var beginRequestFuncName = t.attr("beginrequest");
		var endRequestFuncName = t.attr("endrequest");

		return (new AjaxRequest(this, beginRequestFuncName, endRequestFuncName)).run();
	});
});

/// <summary>
/// The generalized AjaxRequest object.
/// Usage: onclick="return (new AjaxRequest(this, beginRequest, endRequest)).run();"
/// </summary>
/// <param name="s">
///     The event sender. That is, a DOM element (or any object) containing either the href property 
///     or the "ajaxhref" custom attribute containing the AJAX target URL.
/// </param>
/// <param name="begin">
///     An optional JavaScript function that's called before the AJAX request is sent.
///     If this function returns false it will stop the AJAX request from being sent.
///     The function is passed the event sender (param "s") and the detected AJAX url.
///     The function should have the following form:
///         function beginRequest(sender, url)
///         {
///             // Do something useful. Return false if you want to stop the AJAX request
///             // or return an alternate string to use as the AJAX url.
///         }
/// </param>
/// <param name="end">
///     An optional JavaScript function that's called after the AJAX request is completed.
///     The function is passed the event sender (param "s"), the HTTP status code, the raw HTTP response, 
///     and the target AJAX url.
///     The function should have the following form:
///         function endRequest(sender, statusCode, rawResponse, url)
///         {
///             // Do something useful, such as convert the rawResponse to JSON or 
///             // write it into a DOM element if it's HTML.
///         }
/// </param>
/// <param name="post">
///     An optional param. If true, the AJAX request is sent as a POST. All the data contained in the
///     first form of the document posted.
/// </param>
function AjaxRequest(s, begin, end, post)
{
    //
    // Define object properties.
    //
    
    this.sender = s;
    this.beginRequest = begin;
    this.endRequest = end;
    this.doPost = post;
    this.httpRequest = null;
    
    //
    // Convert beginRequest and endRequest to function references (if needed).
    //
    // If beginRequest is defined as a string, then attempt to convert it to a function reference.
    if ((this.beginRequest != null) && (typeof(this.beginRequest) == "string") && this.beginRequest.length > 0)
    {
    	try
    	{
    		this.beginRequest = eval(this.beginRequest);
    	}
    	catch (e)
    	{
    		alert("Failed to convert [" + this.beginRequest + "] to a function reference.\n" + e);
    	}
    }
    // If endRequest is defined as a string, then attempt to convert it to a function reference.
    if ((this.endRequest != null) && (typeof(this.endRequest) == "string") && this.endRequest.length > 0)
    {
    	try
    	{
    		this.endRequest = eval(this.endRequest);
    	}
    	catch (e)
    	{
    		alert("Failed to convert [" + this.endRequest + "] to a function reference.\n" + e);
    	}
    }
            
    //
    // Get the URL.
    //
    
    this.url = "";
    
    if (this.sender != null)
    {
        // Look for the special "ajaxhref" attribute.
        var ajaxHref = jQuery(this.sender).attr("ajaxhref");
           
        if (ajaxHref != null && ajaxHref.length > 0)
        {
            this.url = ajaxHref;
        }
        // Otherwise look for the "href".
        else if (this.sender.href != null)
        {
            this.url = this.sender.href;
        }
        // Otherwise if sender is a string then use it directly.
        else if (typeof(this.sender) == "string")
        {
            this.url = this.sender;
        }
    }
    
    //
    // Define the "on complete" callback function.
    //
    
    this.onCompleteCallback = function(httpRequest, status)
    {
        // If endRequest is defined, then call it and pass the event sender, the HTTP status code to it, and the raw response.
        if ((this.ajaxRequest.endRequest != null) && (typeof(this.ajaxRequest.endRequest) == "function"))
        {
            try
            {
                this.ajaxRequest.endRequest(
                    this.ajaxRequest.sender, 
                    httpRequest.status,
                    httpRequest.responseText,
                    this.ajaxRequest.url);
            }
            catch (e)
            {
                alert(e);
            }
        }
    }
    
    //
    // Define the run function. This executes the AJAX call.
    //
    
    this.run = function()
    {
        try
        {
            //
            // If beginRequest is defined, then call it and pass the event sender to it.
            //
            
            if ((this.beginRequest != null) && (typeof(this.beginRequest) == "function"))
            {
                var retVal = this.beginRequest(this.sender, this.url);
                
                // If the function explicity returned false then abort the request.
                if (retVal == false)
                {
                    return false;
                }
                else if (retVal != null && typeof(retVal) == "string")
                {
                    this.url = retVal;
                }
            }
            
            //
            // Make sure we have a URL.
            //
            
            if (this.url == null || this.url.length <= 0)
            {
                alert("Error AJAX URL is empty! [" + this.url + "]");
                return false;
            }
            
            //
            // Build up the request data.
            //
            
            var requestDataBuffer = new Array();
            
            // Start with a random number to avoid caching problems.            
            requestDataBuffer.push("r=" + parseInt(Math.random() * 100000));
            
            var formData = "";
            
            // If we're doing a post then add in the form data.            
            if (this.doPost)
            {
                if (document.forms != null && document.forms.length > 0)
                {
                    formData = serializeForm(document.forms[0]);
                    
                    requestDataBuffer.push("&");
                    requestDataBuffer.push(formData);
                }
            }
            
            if (this.sender != null)
            {
            	// Lump in the post back control, if found.
            	var postBackCtrl = jQuery(this.sender).attr("name");
            	// If defined, write the raw response to the target div.
            	if (postBackCtrl != null && postBackCtrl.length > 0)
            	{
            		requestDataBuffer.push("&");
            		requestDataBuffer.push(postBackCtrl + ".x=1");
            		requestDataBuffer.push("&");
            		requestDataBuffer.push(postBackCtrl + ".y=1");
            	}
            
            	// Lump in the targetdiv custom attribute, if found.
            	//
                // Look for the special "targetdiv" attribute.
                var targetDiv = jQuery(this.sender).attr("targetdiv");
                // If defined, write the raw response to the target div.
                if (targetDiv != null && targetDiv.length > 0 && formData.indexOf("&targetdiv=") < 0)
                {
                    requestDataBuffer.push("&targetdiv=" + targetDiv);
                }
            }
            
            //
            // Make the AJAX request (asynchronous).
            //
          
            // Use jquery to make an AJAX call, however get the raw response. That is,
            // don't attempt to convert it to a JSON object or write it to a DIV yet.
            // Let the custom endRequest handle that.
            this.httpRequest = $.ajax({
                type: (this.doPost ? "POST" : "GET"),
                url: this.url,
                dataType: "html",
                async: true,
                complete: this.onCompleteCallback,
                data: requestDataBuffer.join(''),
                ajaxRequest: this
            });
        }
        catch (e)
        {
            alert(e);
        }
        
        return false;
    }
}

/// <summary>
/// Using the given form, generates a URL param string containing the 
/// form element and the corresponding values.
/// </summary>
function serializeForm(form)
{
    if (form != null)
    {
        var dataBuffer = new Array();

        for (i = 0; i < form.elements.length; i ++)
        {
            formElem = form.elements[i];
            
            if (formElem.name != null && formElem.name.indexOf("__") != 0)
            {
                if (formElem.type == 'checkbox')
                {
                    if (formElem.value == null || formElem.value == '')
                    {
			if (dataBuffer.length > 0)
			{
				dataBuffer.push('&');
			}

			// We don't care about the value, just whether it's checked
			if (formElem.checked)
			{
				dataBuffer.push(formElem.name + '=true');
			}
			else
			{
				dataBuffer.push(formElem.name + '=false');
			}
                    }
                    else
                    {
			// We don't care about the value, just whether it's checked
			if (formElem.checked)
			{
				if (dataBuffer.length > 0)
				{
					dataBuffer.push('&');
				}

				dataBuffer.push(formElem.name + '=' + formElem.value);
			}
                    }
                }
                else
                {
			if (dataBuffer.length > 0)
			{
			    dataBuffer.push('&');
			}

			dataBuffer.push(formElem.name + '=' + escape(formElem.value));
                }
            }
        }

        return dataBuffer.join('');
    }

    return '';
}

/// <summary>
/// A convenience function which can be passed as the "endRequest" parameter
/// of an AjaxRequest.
///
/// This function simply looks for the "targetdiv" custom attribute of the
/// sender and writes the raw response to it.
/// </summary>
function writeToDiv(sender, statusCode, rawResponse, url)
{
    if (sender == null)
    {
        return;
    }
    
    if ((statusCode + "") != "200")
    {
      // 2008-11-05 jmock: Commented out this alert since it is a distraction for the user.
      //alert("The server encountered an unexpected error. Please try again later.");
    	return;
    }

    // Look for the special "targetdiv" attribute.
    var targetDiv = jQuery(sender).attr("targetdiv");

    // If defined, write the raw response to the target div.
    if (targetDiv != null && targetDiv.length > 0)
    {
        jQuery("#" + targetDiv).html(rawResponse);
    }
}

//
// Custom component-specific calls.
//
    
    function UserAvatarSetup(serverPath)
    {
    
        $(document).ready(function() 
        {
            $("a").filter(".hover_on_user").mouseover(function() {

                var t = jQuery(this);       // hyperlink
              
                var userName = t.attr("cuname");            
                var popup_target = t.attr("target");            
                var loading_target = "#loading_icon_" + popup_target;           
                var targetDiv = document.getElementById(popup_target);
                           
                if (targetDiv.className == "loaded")
                {
                    targetDiv.style.display = "block";  
                }
                else
                {   
                     $(loading_target).css("visibility", "visible");      

                    $("#" + popup_target).load(serverPath,
                        { 
                            cuname: userName,
                            aop: "UserAvatar" 
                        },

                            function() 
                            {                     
                                $(loading_target).css("visibility", "hidden");    
                                targetDiv.className ="loaded";     
                            }                    
                                            
                    );    
                }
               
                 
                return false;
            });

             $("a").filter(".hover_on_user").mouseout(function() {            
                
                var t = jQuery(this);       // hyperlink
                var popup_target = t.attr("target");
                var targetDiv = document.getElementById(popup_target);            
                targetDiv.style.display = "none";            
                return false;
            });
            
        });
    }

    
    //JSON functions
           
    function GetCommunityUser(serverPath)
    {
    
        $(document).ready(function() 
        {
            $("a").filter(".get_user").click(function() {
            
                    var t = jQuery(this);       // hyperlink
                    var userName = t.attr("cuname");   
            
                   $.getJSON(serverPath,
                   { 
                        cuname: userName,
                        aop: "UserTester" 
                    },
                   function(json){
                     alert("JSON Data: " + json);
                   }
                 );
            
            
            });
            
        });
    }
