/*
   Copyright 2008 Yakabod, Inc.

   $Revision: 1.15 $
   $Date: 2009/08/11 19:11:22 $
   Last edited by: $Author: jauldrid $
*/
///////////////////////////////////////////////////////////////////////////////

function getJavascriptFromResponse( data )
{
  retval = { 'includes' : [],
             'blocks'   : [] };

  // we have to get rid of any '//<![CDATA[' marks in javascript and strip
  // line breaks so we can do a match for <script> elements
  RegExp.escape = function(text) {
    if (!arguments.callee.sRE) {
      var specials = [
        '/', '.', '*', '+', '?', '|',
        '(', ')', '[', ']', '{', '}', '\\'
      ];
      arguments.callee.sRE = new RegExp(
        '(\\' + specials.join('|\\') + ')', 'g'
      );
    }
    return text.replace(arguments.callee.sRE, '\\$1');
  }

   // Strip out all line breaks so that we can use regexp below.
   var strSingleLineText = data.replace(
   // Replace out the new line character.
   new RegExp( "\\n", "g" ),

   // Put in ... so we can see a visual representation of where
   // the new line characters were replaced out.
   " "
   );

   var cdata = RegExp.escape( "//<![CDATA[");
   var strippedCDATA = strSingleLineText.replace(
   // Replace out the new line character.
   new RegExp( cdata, "g" ),

   // Put in ... so we can see a visual representation of where
   // the new line characters were replaced out.
   " "
   );

  // Code blocks second.
  var theRegex = /<\s*script(?:\s*\w+\s*=\s*"[^"]*"\s*)*[^\/]*?>(?:[^<]|(?:<(?!\/script>)))+?<\/script>/ig;

  retval['blocks']    = strippedCDATA.match(theRegex);
  retval['includes']  = strippedCDATA.match(/<\s*script[^>]*\bsrc=[^>]*>/ig);

  return retval;
}

function processScripts(data, placeholder)
{
  var oJSInfo = getJavascriptFromResponse( data );

  // Includes first.
  var includes = oJSInfo['includes'];
  if (includes != null)
  {
    appendScriptsToDOM(placeholder, includes, true);
  }

  var blocks = oJSInfo['blocks'];
  if (blocks != null)
  {
    appendScriptsToDOM(placeholder, blocks, false)
  }
}
///////////////////////////////////////////////////////////////////////////////
var srcs = (function()
{
  var included = [];

  return {
    isIncluded: function(srcUrl)
    {
      var returnValue = false;
      if( included.length > 0 )
      {
        for(var i=0;i<included.length;i++)
        {
          if((included[i]===srcUrl) ||
             ( srcUrl.match( /scriptImport\.js$/ )) ||
             (( srcUrl.match( /dojo\.js$/ )) && ( typeof dojo != 'undefined' )))
          {
            returnValue = true;
            break;
          }
        }
      }
      else
      {
        if(( srcUrl.match( /scriptImport\.js$/ )) ||
           (( srcUrl.match( /dojo\.js$/ )) && ( typeof dojo != 'undefined' )))
        {
          srcs.addInclude( srcUrl );
          returnValue = true;
        }
      }
      return returnValue;
    },
    addInclude: function(srcUrl)
    {
      included.push(srcUrl);
    }
  };
})();
///////////////////////////////////////////////////////////////////////////////
function appendScriptsToDOM(placeholder, scripts, setSource)
{
  if(( scripts != null ) &&
     ( typeof scripts != 'undefined' ) &&
     ( typeof scripts.length != 'undefined' ))
  {
    for (var idx = 0; idx < scripts.length; ++idx)
    {
      var scriptElement = document.createElement('SCRIPT');

      var current = scripts[idx];
      if (setSource)
      {
        // Pull the source.
        var src = current.match(/src=\"(.*?)\"/i);
        if (src != null && !srcs.isIncluded(src[1]))
        {
          scriptElement.text = loadInclude(src[1]);
          srcs.addInclude(src[1]);
        }
      }
      else
      {
          // Pull the content.
        var content = current.match(/<script .*?>(.*?)<\/script>/i);
        if (content != null)
        {
          scriptElement.text = content[1];
        }
      }

      // Append to the DOM.
      try
      {
        placeholder.appendChild(scriptElement);
      }
      catch( e ) { alert( e.toSource()); }
    }
  }
}
///////////////////////////////////////////////////////////////////////////////
function loadInclude(src)
{
  var retval = '';

  // Re-use the static xmlhttp object.
  xmlhttp = XHR.getStaticXHRObject();

  if (xmlhttp === null)
  {
    alert ("Browser does not support asynchronous HTTP requests");
    return;
  }

  // Make the call.
  xmlhttp.open("GET", src, false);
  xmlhttp.send(null);

  var sContentType = xmlhttp.getResponseHeader( 'Content-Type' );
  if(( sContentType == 'application/x-javascript' ) ||
     ( sContentType == 'application/javascript' ) ||
     ( sContentType == 'text/x-javascript' ) ||
     ( sContentType == 'text/javascript' ))
  {
    retval = xmlhttp.responseText;
  }
  return retval;
}
