/**
 * Xaraya XML HTTP Requests
 *
 * @package modules
 * @copyright (C) 2004-2010 The Digital Development Foundation
 * @license GPL {@link http://www.gnu.org/licenses/gpl.html}
 * @link http://www.xaraya.com
 *
 * @subpackage Base module
 * @link http://xaraya.com/index.php/release/68.html
 * @author Marcel van der Boom <marcel@hsdev.com>
 * @author Chris Powis <crisp@crispcreations.co.uk>
**/
/**
 * Load Content
 *
 * Perform XML HTTP request using jQuery ajax() method
 *
 * @author  Marcel van der Boom <marcel@hsdev.com>
 * @author Chris Powis <crisp@crispcreations.co.uk>
 * @access  public
 * @param string href target url for GET requests, form action url for POST requests, default GET, required
 * @param string tagId element to replace, must exist in current template, required
 * - tagId must exist in GET or POST reponse template.
 * - tagId must be a valid jQuery selector, eg 'form', 'div#elementid', 'span.classname'
 * @param string method, one of GET or POST, default GET, required for POST requests
 * @param string form_obj, form identifier, must exist in current template, required for POST requests
 * - form_obj optional in GET or POST reponse template.
 * - form_obj must be a valid jQuery selector, eg 'form#elementid', 'form.classname'
 * @param string pageName optional themes/yourtheme/pages/pageName.xt template to use, default module
 * @TODO: handle responseTypes...
 * @param string responseType optional dataType to expect from the response, default html, options xml|json|html?
 * @param integer timeout optional request timeout, default 5000
 * @TODO: optionally specify loading_box element
 * @param string loading_box optional loading element to show during AJAX request, default '' (none)
 * @param boolean local_debug optionally alert debug info during script execution, default false
 * @return  false
 * @throws  no exceptions
**/
function loadContent(href, tagId, method, form_obj, pageName, responseType, timeout, loading_box, local_debug) {
    // local debug option, set true to see alerts during script operation
    if (local_debug == null || local_debug == '') local_debug = false;
    // this just lets you know debug is running :)
    if (local_debug) {
        alert('Debug: loadContent('+href+', '+tagId+', '+method+', '+form_obj+', '+pageName+', '+responseType+', '+timeout+', '+loading_box+', '+local_debug+')');
    }
    // tagId element can be any jQuery identifier in current template
    // NOTE: tagId element must also exist in the responseText 
    if (jQuery(tagId).length)
    { // found an html element matching tagId, eg .classname or #elementid in current template
        jQtag = tagId;
    } else {
        // assume tagId is an element id, eg <div id="mytagId"> in current template
        jQtag = '#'+tagId;
    }
    // make sure the element we want to target exists
    if (jQuery(jQtag).length)
    {
        // set defaults
        argstr = '';
        // default method = GET
        if (method == null || method == '') 
        { 
            method = 'GET';
        } else {
            method = method.toUpperCase();
        }
        // scan url for existing ? path separator
        join = (href.match(/\?/)) ? "&" : "?";
        // scan url for existing pageName param
        if (!(href.match(/pageName/)))
        {
            // default pageName = module
            if (pageName == null || pageName == '') 
            { 
                pageName = 'module';
            }
            // add pageName param to args
            argstr +=  join + 'pageName=' + pageName;
            // reset path separator
            if (join == "?") { join = "&"; }
        }
        // default responseType = html
        if (responseType == null || responseType == '') 
        { 
            responseType = 'html';
        }
        // default timeout = 6000
        if (timeout == null || timeout == '') 
        { 
            timeout = 10000;
        }
        // @TODO: default loading_box = '' (none)
        if (loading_box == null || loading_box == '') 
        { 
            loading_box = '#loading_box';
        }
        // for POST method we get all input from the form_obj specified
        if (method == 'POST')
        {
            if (form_obj !== undefined) 
            {
                // form_obj can be any jQuery identifier
                if (jQuery(form_obj).length)
                { // found an html element matching form_obj, eg #elementid or form in current template
                } else {
                    // assume form_obj is a form element id, eg <form id="mytagId"> in current template
                    form_obj = 'form#'+form_obj;
                }
                // make sure we have a form
                if (jQuery(form_obj).length)
                {
                    // get all form input elements
                    jQuery(form_obj).find(':input').each(function()
                    {
                        // only need elements with a name attribute
                        if (jQuery(this).attr('name') !== undefined) {
                            // add param=value to args
							if (jQuery(this).attr('type') == 'checkbox') {
								argstr += join + jQuery(this).attr('name') + '=' + jQuery(this).attr('checked');
							}
							else {
                            	argstr += join + jQuery(this).attr('name') + '=' + escape(jQuery(this).val());
							}
							// reset path separator
                            if (join == "?") { join = "&"; }
                        }
                    }
                    );
                } else {
                    // template displayed is missing the form_obj element specified
                    if (local_debug) { alert('Missing form_obj '+form_obj+' for POST method in loadContent'); }
                }
            } else {
                // method was POST but no form object was specified
                if (local_debug) { alert('Missing form_obj for POST method in loadContent'); }
            }

        }
        
        // let the user know we're working
        document.body.style.cursor = 'wait';
		jQuery(loading_box).show();

        // build the full requestURL
        requestURL = href+argstr;

        // finally, call our request
        jQuery.ajax({
            url: requestURL,
            type: method,
            dataType: responseType,
            data: '',
            timeout: timeout,
            error: function(){
                document.body.style.cursor='default'; 
				jQuery('#loading_box').hide();
                if (local_debug) {
                    // a problem here means the request failed
                    // target url,  return url, params, target function,
                    // privileges, authid and shorturls are some possible causes
                    alert('Error loading document at URL: '+requestURL+' using method: '+method);
                }
                // redirect to requested url
                document.location = requestURL;
            },
            success: function(responseText){
                // @TODO: handle other dataTypes?
                if (responseType == 'html') {
                    if (!jQuery(responseText).find(jQtag).length)
                    {
                        // the tagId is not found if it is the root element of the response text
                        // so we add an anonymous container as root (this is never displayed) :)
                        responseText = jQuery(jQuery('<div></div>')).append(responseText);
                    }
                    // see if there's a tagId element in the response
                    if (jQuery(responseText).find(jQtag).length)
                    {
                        if (local_debug) { 
                            alert('Success loading tagId '+jQtag+' for document at URL: '+requestURL+' using method: '+method)
                        };
                        // and replace the html in tagId with the response html
                        jQuery(jQtag).html(jQuery(responseText).find(jQtag).html());
                    } else {
                        // response template is missing the specified tagId element
                        if (local_debug) {
                            alert('Error loading tagId '+jQtag+' for document at URL: '+requestURL+' using method: '+method);
                       }
                    }
                    document.body.style.cursor='default'; 
                    jQuery(loading_box).hide();
                    fdTableSort.init();
                }
            }
        });
        return false;
    } else {
        // current template displayed is missing the specified tagId element
        if (local_debug) { alert('Missing tagID in current template: '+tagId); }
        return false;
    }

}
