
function newAjax ()
{
    // initialize the xmlhttp object variable as false
	var xmlhttp = false;

	try
	{
        // try different methods of instanciating an xmlhttprequest object
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch ( obj_error )
	{
		try
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch ( obj_error )
		{
			xmlhttp = false;
		}
	}

    // again, if nothing has worked so far, try the base XMLHttpRequest object
	if ( !xmlhttp && typeof XMLHttpRequest != 'undefined' )
	{
		xmlhttp = new XMLHttpRequest();
	}

    // if we don't have an xmlhttp object
    if ( !xmlhttp )
    {
        // return false to indicate error
        return false;
    }

    // and return.
	return xmlhttp;
}

function ajaxRequest( str_url, str_method, str_vars, obj_container_div )
{
    // locally instantiate a new xml http request object
    var obj_xmlhttp = newAjax ();

    // if we got an error from the object creation, then fail
    if ( !obj_xmlhttp )
    {
        // remains to bee seen if we're going to give some kind of alert to the users
        return false;
    }

    // define a constant for the xmlhttp request status id
    var int_state_loaded = 4;

    // define a constant for the HTTP1.1 ok return status code
    var int_status_ok = 200;

    // make sure we're RFC2616 compliant!
    str_method = str_method.toUpperCase ();

    // just in case, adding error support never hurt
    try
    {
        // everything good so far, now check the method
        if ( "GET" == str_method )
        {
            // check if we don't have a querystring for this URI
            if ( -1 == str_url.indexOf ( '?' ) )
            {
                // then, if the variables are not null, add those to the URI as querystring
                str_url += '?' + str_vars;
            }

            // open the request to the specified URL
            obj_xmlhttp.open ( str_method, str_url );

			// Set x request with header, I mark this request as "XMLHttpRequest" to use the Zend_Controller_Request_Http method "isXmlHttpRequest" (Is the request a Javascript XMLHttpRequest?).
			obj_xmlhttp.setRequestHeader( "X-Requested-With", "XMLHttpRequest" );			

            // RFC2616 - set variables to null on GET method request
            str_vars = null;
        }
        // now, if we're sending using post
        else if ( "POST" == str_method )
        {
            // open the connection
            obj_xmlhttp.open ( str_method, str_url );

            // set the request header to RFC2616 compliant values
            obj_xmlhttp.setRequestHeader ( "Method", "POST " + str_url + " HTTP/1.1" );

            // notice the x-www-form-urlencoded application content type for POST data requests
            obj_xmlhttp.setRequestHeader ( "Content-Type", "application/x-www-form-urlencoded" );

			// Set x request with header, I mark this request as "XMLHttpRequest" to use the Zend_Controller_Request_Http method "isXmlHttpRequest" (Is the request a Javascript XMLHttpRequest?).
			obj_xmlhttp.setRequestHeader( "X-Requested-With", "XMLHttpRequest" );			
        }

        // define the event handler for the readystatechange event
        obj_xmlhttp.onreadystatechange = function ()
        {
            // check the status for the xml http request object
            if ( int_state_loaded == obj_xmlhttp.readyState && int_status_ok == obj_xmlhttp.status )
            { 
                // Set regular expression.
                // sha1 has to be hardcoded (for now) since I can't seem to make this file work as .php
                var regEx = /5a0e30f378bc23547c79e1840cfa2b277f7adc8f/;

                // Check if the user's session has expired.
                if ( regEx.test( obj_xmlhttp.responseText ) )
                {
                    // 'force' a reload of the page to make sure the system sends the user back to the login page
                    window.location.href = "/admin/login";

                    return false;
				}

				/*	
				// Load the responseText string into an xml object
				// this is needed to parse the javascript (if any) embedded into 
				// the responseText
				var objDomDoc = loadStringXml ( obj_xmlhttp.responseText );

				// check for errors
				if ( false == objDomDoc )
				{
					return false;
				}

				if ( false == ajaxJavaScriptParser( obj_xmlhttp.responseText ) )
				{
					alert ( 'plop' );
					return false;
				}
				*/

                // set the target div's inner html to the xmlhttprequest's response text
                obj_container_div.innerHTML = obj_xmlhttp.responseText;

				// Parse javascript inside the response text.
				ajaxJavaScriptParser( obj_xmlhttp.responseText ); 
            }
        };

        // and away!
        obj_xmlhttp.send ( str_vars );

        // we return the obj_xmlhttp itself, that way we can set a new attribute to it
        // "returnContainer", which will store a reference to the html div container the responseText
        // will go to.
        return obj_xmlhttp;
    }
    // failed
    catch ( obj_error )
    {
        // return false
        return false;
    }
}

function ajaxLink2( str_url, str_container_id, str_waiting_msg, bln_display_default_message )
{
    // I'm gonna getcha!
    try 
	{
		if ( typeof ( str_container_id ) == "string" )
		{
			obj_html_container = document.getElementById ( str_container_id );

			// if it's not valid
	        if ( null == obj_html_container )
    	    {
        	    return false;
	        }
		}
		else
		{
			obj_html_container = str_container_id;
		}

		/*
        // check for valid container id
        var obj_html_container = document.getElementById ( str_container_id );

        // if it's not valid
        if ( null == obj_html_container )
        {
            return false;
		}
		*/

		if ( "" == bln_display_default_message || null == bln_display_default_message )
		{
			bln_display_default_message = "true";
		}

		// If the waiting message parameter is empty then try to set one per default and off course a nice little animate gif :P
		if ( ( !str_waiting_msg || "" == str_waiting_msg ) && ( "true" == bln_display_default_message ) )
		{
			var objWaitingImage = new Image();

			if ( !objWaitingImage )
			{
				return false;
			}

			objWaitingImage.src = "/images/load.gif";

		    if ( typeof( strMessageDefaultAjaxWaiting ) == "undefined" )
	    	{
		        strMessageDefaultAjaxWaiting = "please wait...";
			}

			// Set default waiting message in the current container.
	        obj_html_container.innerHTML = "<img src=\"/images/load.gif\" /> " + strMessageDefaultAjaxWaiting;
		}
		else
		{
	        // set a nice waiting msg for the user
    	    obj_html_container.innerHTML = str_waiting_msg;
		}

        // call ajaxRequest and get the return value (xmlhttprequest obj)
        var obj_xmlhttp = ajaxRequest ( str_url, 'GET', '', obj_html_container );

        // verify the return value
        if ( !obj_xmlhttp )
        {
            return false;
        }

        // draw the ajax return
//      obj_html_container.innerHTML = ajax_return;

        return true;
    }
    catch ( obj_error )
    {
        return false;
    }

} // end function ajaxLink

 
function ajaxLink( strUrl, strContainerId, strWaitingMessage, blnDisplayDefaultMessage )
{
	if ( !strUrl || !strContainerId )
	{
		return false;
	}
	
	if ( "" == blnDisplayDefaultMessage || null == blnDisplayDefaultMessage )
	{
		blnDisplayDefaultMessage = "true";
	}
	
	// If the waiting message parameter is empty then try to set one per default and off course a nice little animate gif :P
	if ( ( !strWaitingMessage || "" == strWaitingMessage ) && ( "true" == blnDisplayDefaultMessage ) )
	{
		var objWaitingImage = new Image();

		if ( !objWaitingImage )
		{
			return false;
		}

		objWaitingImage.src = "/images/load.gif";

	    if ( typeof( strMessageDefaultAjaxWaiting ) == "undefined" )
    	{
	        strMessageDefaultAjaxWaiting = "please wait...";
		}

		// Set default waiting message in the current container.
        strAjaxMessageWaiting = "<img src=\"/images/load.gif\" /> " + strMessageDefaultAjaxWaiting;
	}
	else
	{
        // Set a nice waiting msg for the user.
        strAjaxMessageWaiting = strWaitingMessage;
	}
	
	// Now let's do this with jQuery!.
	if ( strAjaxMessageWaiting )
    {
		$( "#" + strContainerId ).block( { message: strAjaxMessageWaiting, css: { border: "3px solid #FEA700" } } ).load(
			strUrl,
			function ( strResponseText )
			{
				$( "#" + strContainerId ).unblock();
				
				var objRegEx = /5a0e30f378bc23547c79e1840cfa2b277f7adc8f/;

				// Check if the user's session has expired.
				if ( objRegEx.test( strResponseText ) )
				{
					$.blockUI( { message: strAjaxMessageWaiting, css: { border: "3px solid #FEA700" } } );
					
                	// Force a reload of the page to make sure the system sends the user back to the login page.
					window.location.href = "/admin/login";

					return false;
				}
			}
    	);
	}
	else
	{
    	$( "#" + strContainerId ).block( { message: strAjaxMessageWaiting, css: { border: "3px solid #FEA700" } } ).load(
        	strUrl,
            function ( strResponseText )
            {
            	$( "#" + strContainerId ).unblock();
            	
            	var objRegEx = /5a0e30f378bc23547c79e1840cfa2b277f7adc8f/;

                // Check if the user's session has expired.
                if ( objRegEx.test( strResponseText ) )
                {
                	$.blockUI( { message: strAjaxMessageWaiting, css: { border: "3px solid #FEA700" } } );
                	
                	// Force a reload of the page to make sure the system sends the user back to the login page.
                    window.location.href = "/admin/login";

                    return false;
				}
			}
		);
	}

	return true;
}

function ajaxSubmitForm2( theForm, strHtmlElementId, strWaitingMsg )
{
	var objXmlHttp = new newAjax();

    if ( !objXmlHttp )
	{
		document.getElementById ( strHtmlElementId ).innerHTML = "<span class=\"errors\">xmlHttpRequest is not available. Please report this immediately giving your browser information.\n\n" +  myBrowser.browserString + "</span>";
		return false;
	}
	else
	{
		if ( typeof (theForm) == "string" )
		{
			objForm = document.getElementById ( theForm );
			if ( !objForm )
			{
				objForm = document.all [ theForm ];
			}
		}
		else
		{
			objForm = theForm;
		}

		var strFormValues = ajaxProcessForm ( objForm );

		if ( false == strFormValues )
		{
			return false;
		}

		// If the waiting message parameter is empty then try to set one per default and off course a nice little animate gif :P
		if ( !strWaitingMsg || "" == strWaitingMsg )
		{
			var objWaitingImage = new Image();

			if ( !objWaitingImage )
			{
				return false;
			}

			objWaitingImage.src = "/images/load.gif";

		    if ( typeof( strMessageDefaultAjaxWaiting ) == "undefined" )
	    	{
		        strMessageDefaultAjaxWaiting = "please wait...";
			}

			// Set default waiting message in the current container.
	        document.getElementById ( strHtmlElementId ).innerHTML = "<img src=\"/images/load.gif\" /> " + strMessageDefaultAjaxWaiting;

		}
		else
		{
	        // set a nice waiting msg for the user
    	    document.getElementById ( strHtmlElementId ).innerHTML = strWaitingMsg;
		}
		
		if ( !strFormValues )
		{
			return false;
		}
		else
		{
			//objXmlHttp.connect ( objForm.action, "POST", strFormValues, ajax_drawXmlResponse, strHtmlElementId );
			var obj_html_container = document.getElementById ( strHtmlElementId );
			
			if ( !obj_html_container )
			{
				return false;
			}

			var obj_xmlhttp = ajaxRequest ( objForm.action, 'POST', strFormValues, obj_html_container );
		}
	}
}

function ajaxSubmitForm( strFormId, strContainerId, strWaitingMsg )
{
	if ( !strFormId || !strContainerId )
	{
		return false;
	}
	
	// Get form object.
	var objForm = document.getElementById( strFormId );
	
	if ( !objForm )
	{
		return false;
	}
	
	// Validate form.
	if ( objForm.getAttribute( "validate" ) == "true" && false == validateForm( objForm ) )
	{
		return false;
	}
	
	// Create options object.
	var objOptions = new Object();
	
	// Set target, target identifies the element(s) to update with the server response.
	objOptions.target = "#" + strContainerId;
	
	// If we have a waiting message, set it into the options, beforeSubmit identifies what to do with the form before submit it.
	if ( strWaitingMsg )
	{
		objOptions.beforeSubmit = function() { $( "#" + strContainerId ).html( strWaitingMsg ); };
	}
	
	// Bind form using jQuery Form Plugin.
    $( "#" + strFormId ).ajaxSubmit( objOptions );

    // return true;
    return false;	
}

function ajaxProcessForm( theForm )
{
	var objForm;

   	var submitDisabledElements = false;

    if ( arguments.length > 1 && arguments[1] == true )
	{
    	submitDisabledElements = true;
	}

    var prefix = "";

    if ( arguments.length > 2 )
	{
    	prefix = arguments[2];
	}

    if ( typeof ( theForm ) == "string" )
	{
    	objForm = document.getElementById ( theForm );
		if ( !objForm && document.all )
		{
			objForm = document.all[ theForm ];
		}
	}
    else
	{
    	objForm = theForm;
	}

	if ( objForm.getAttribute( 'validate' ) == 'true' && false == validateForm( objForm ) )
	{
		return false;
	}

    var strXmlReturn = "";

    if ( objForm && objForm.tagName == 'FORM' )
    {
            var formElements = objForm.elements;

            for ( var intFormElement = 0 ; intFormElement < formElements.length; intFormElement++ )
            {
                if ( !formElements[intFormElement].name )
				{
                    continue;
				}
                if ( formElements[intFormElement].name.substring ( 0, prefix.length ) != prefix )
				{
                    continue;
				}
                if ( formElements[intFormElement].type && ( formElements[intFormElement].type == 'radio' || formElements[intFormElement].type == 'checkbox' ) && formElements[intFormElement].checked == false )
				{
                    continue;
				}
                if ( formElements[intFormElement].disabled && formElements[intFormElement].disabled == true && submitDisabledElements == false )
				{
                    continue;
				}

                var name = formElements[intFormElement].name;

                if ( name )
                {
                    if ( strXmlReturn != "" )
					{
                        strXmlReturn += '&';
					}

                    if ( formElements[intFormElement].type == 'select-multiple' )
                    {
                        for ( var intSubElement = 0; intSubElement < formElements[intFormElement].length; intSubElement++ )
                        {
                            if ( formElements[intFormElement].options[intSubElement].selected == true )
							{
                                strXmlReturn += name + "=" + encodeURIComponent ( formElements[intFormElement].options[intSubElement].value ) + "&";
							}
                        }
                    }
                    else
                    {
						/*
						// if it's a hidden type, and it's got the '_FCKEDT_' prefix.
						if ( -1 != name.indexOf ( '_FCKEDT_' ) )
						{
							// then doublecheck for the FCKeditorAPI object to exist and be properly defined
							if ( 'object' != typeof ( FCKeditorAPI ) )
							{
								alert ( 'An error occurred while processing the form: FCKeditorAPI object not available' );
								
								return false;
							}
							
							// if everything's going according to plan, then add the correct FCKeditor container value to the XmlReturn data.
							strXmlReturn += name + "=" + encodeURIComponent ( FCKeditorAPI.GetInstance ( name ).GetXHTML() );
						}
						else
						{
	                        strXmlReturn += name + "=" + encodeURIComponent ( formElements[intFormElement].value );
						}
						*/

						strXmlReturn += name + "=" + encodeURIComponent ( formElements[intFormElement].value );
                    }
                }
            }
        }

        return strXmlReturn;
}

function ajaxJavaScriptParser( strTextToParse )
{
	// We dont have a response text?, errghhhh...
	if ( !strTextToParse )
	{
		return false;
	}

	// Scripts container variable.
	var strJavaScripts = "";
	// Javascript code container.
	var strJsCode = "";
	// Structure of script includes into the response text, Ex: <script src="js"></script>.
	var arrJsSrcs = new Array();
	// Counter of scripts includes.
	var intCounterScripts = 0;

	// Loop all the response text and look for each javascript code there.
	while ( strTextToParse.indexOf( "<script" ) > 0 )
	{
		// Find initial position on the current script.
		objJSIni = strTextToParse.indexOf( "<script" );

		// Get the current javascript code.
		objNextHtml = strTextToParse.substring( objJSIni, strTextToParse.length );					   

		// Find the end of the script tag.
		objJSIniTagEnd = objNextHtml.indexOf( ">" );	

		// W00 capture text inside the <script> tag.
		strJsCode = objNextHtml.substring( 0, objJSIniTagEnd );

		// Look if we have some javascrit include there.
		if ( strJsCode.indexOf( "src" ) > 0 )
		{
			// Initial position of the src.
			intSrcPosInit = strJsCode.indexOf( "src" );

			// Get the string in the middle of the first position and the en of the script.
			strJsCode=strJsCode.substring(intSrcPosInit, objJSIniTagEnd);

			// Get the initial position of the double quote.
			intDoubleQuotePosInit = strJsCode.indexOf( '"' );

			// Get all text between the start of the end of the string and initial position of the doble quote.
			strJsCode = strJsCode.substring( intDoubleQuotePosInit + 1, objJSIniTagEnd );

			// Final position of the doble quote.
			intDoubleQuotePosFinal = strJsCode.indexOf( '"' );
			// Get the string.
			strJsSrc = strJsCode.substring( 0, intDoubleQuotePosFinal );

			// Set to the sources structure.
			arrJsSrcs[intCounterScripts] = strJsSrc;

			intCounterScripts++;
		}
					   
		// New portion of to sent into the head.
		objNextHtml = objNextHtml.substring( objJSIniTagEnd + 1, strTextToParse.length );

		// Lets find the end of the script code.
		objJSTagEndSc = objNextHtml.indexOf( "script>" );

		// Get new javascript code, minus 2 to drop the "</".
		objJSText = objNextHtml.substring( 0, objJSTagEndSc - 2 );

		// Get all scripts there.
		strTextToParse = objNextHtml;

		// Save js data.
		strJavaScripts = strJavaScripts + "\n" + objJSText;
	}					   

	// Eval javascript code.
	eval( strJavaScripts );

	/*
	 * NOTE: We don't need to append all this things into the head.
	// Create a new script tag and set all scripts found there.
	objNewScriptTag = document.createElement( "script" );
	// Set text there.
	objNewScriptTag.text = strJavaScripts;

	// Add this new script to the head of the container page.
	document.getElementsByTagName( 'head' )[0].appendChild( objNewScriptTag );
	*/

	// Add the javascripts includes.
	for ( intSrcsCounter = 0; intSrcsCounter < arrJsSrcs.length; intSrcsCounter++ )
	{
		objNewScriptTag = document.createElement( "script" );

		objNewScriptTag.src = arrJsSrcs[intSrcsCounter];

		document.getElementsByTagName( 'head' )[0].appendChild( objNewScriptTag );
	}
}


function loadStringXml ( strXml )
{
	// why are you calling me in the first place if you've got nothing to show?
	// WEAKSAUCE!!!
	if ( 'string' != typeof ( strXml ) || !strXml )
	{
		// told you so
		return false;
	}

	// let's make this work all around the browser world!
	// got IE?
	try
	{
		// create a new xml domdocument object using msft's activex
		var objDomDoc = new ActiveXObject ( "Microsoft.XMLDOM" );

		// we don't want to return control to the script until the whole thing has loaded
		objDomDoc.async = "false";

		// aaaand load!
		objDomDoc.loadXML ( strXml );
	}
	// no IE? let's try gecko
	catch ( objException )
	{
		// we don't want any sudden errors
		try
		{
			// create a DOM parser for the xml string
			var objXmlParser = new DOMParser ();

			// load the document into a domxml object using the parser
			var objDomDoc = objXmlParser.parseFromString ( strXml, "text/xml" );
		}
		// no gecko love either? :s
		catch ( objException )
		{
			alert ( 'Your browser is not compatible with this application. Please contact your system administrator.' );

			return false;
		}
	}

	// extra error check
	if ( !objDomDoc )
	{

		return false;
	}

	// a que vinimos? LOL!
	return objDomDoc;
}

function FckContents()
{
	this.UpdateEditorFormValue = function()
	{
		for ( intFckCounter = 0; intFckCounter < parent.frames.length; ++intFckCounter )
		{
			if ( parent.frames[intFckCounter].FCK )
			{
				parent.frames[intFckCounter].FCK.UpdateLinkedField();
			}
		}
    }
}

