/***************************************************************************

========================= TREAD CAREFULLY ALL YE WHO WANDER HERE ==============================

        System              :        Bigroom Internet Ajax comms calls
        Program Name        :        servercomms.js
        Author              :        P.Colclough
        Date                :        17 April 2007
        Version             :   	 1.0
        Description         :        Javascript functions for XMLHttpRequest functionality (Ajaxy server calls)

        History             :        17 April 2007  1.0      First Cut
        							 19 April 2007  1.1      SLightly modified... see notes

        Functions           :   	 sendData  		Send the XMLHttpRequest
        							 receiveData 	CallBack function for the server
        							 getTagValue	Get a Tag from the receive string
        							 $				Short form of getElementById.. and browser independant
        							 strreplace		What it says on the tin

        Notes				: 		Slightly modified to get around a few issues
        							with curl(), as we are querying across
        							web sites.

        							1. The parameter passed to teh curl() function via ajax,
        							   contains the URI in quotes, and urlencoded. In teh curl()
        							   function we have to strip teh quotes out. This needs to be done because
        							   the HTTPREquestObject baulks if it isn't.
        							2. Have disposed of the request.responseXML in teh receiving
        							   function... because we are returning XML which is recognised as such.
        							   Sure it is easy , but it is 1:00 am, and I am too tired. Basically, using
        							   the request.resonseText element instead. This hold more data anyway,
        							   so is better to use.
        							3. Replacing all occurrences of '/' with '~'. The escape() function
        							   doesn't touch this, and Ajax Baulks again. Teh curl()
        							   function needs to reverse the process....


***************************************************************************/
/**************************************************************************
                Name        :      sendData()
                Author      :      P.Colclough
                Date        :      17/04/2007
                Desc.       :      Make a XMLHttpRequest Call
                                   If ActiveXObject(), then we are in MS mode, else
                                   we are a Mozilla Browser... yippeee
                Parameters  :      mtype = type of data:
                							1 = Article info
                							2 = Product.list
                							3 = product detail
                                   melement = Lement to fill with returned data
                                   postslug = Reuired postslug, as translated in import.home.php
                                   content_id = content_id from main site.. passed by direct reference
                                   m_id     = m_id from main site .. passed by direct reference
                Version     :     1.0
                History     :     17/04/2007        - First Cut
**************************************************************************/
var request;
var sCurrentUrl;
var sCurrentvars;

/*************************************************************************
	The following 2 items (siteRoot and remoteRoot)
	need changing when you move between local/prrof and live
**************************************************************************/
var siteRoot   = 'http://localhost/23420';
//var siteRoot = 'http://proof.rapid.campbellshaw.co.uk';
var remoteRoot = 'http://localhost/23417';
//var remoteRoot = 'http://proof.rapid.campbellshaw.co.uk';

var sDefaultUrl = remoteRoot + '/external.getDataXML?';

var sHTTPurl = siteRoot + '/import.getURLresult';

function sendData(mtype, melement, postslug,content_id, m_id)
{


   /* branch for native XMLHttpRequest object */
   if (window.XMLHttpRequest)
   {
       //#('send (1)');
       request = new XMLHttpRequest();
   }
   else if (window.ActiveXObject)
   {
       //alert('send (2)');
       request = new ActiveXObject("Msxml2.XMLHTTP");
       if(request == null)
          request = new ActiveXObject("Microsoft.XMLHTTP");

   }
   else
   {
    //alert('send (3)');

       ;

   }
   /*
   		Set up the passthru variables
   */
   sCurrentvars = 'mtype='+mtype;
   if(melement.length > 0)
   	   sCurrentvars = sCurrentvars +'&melement='+melement;
   if(postslug.length > 0)
   {
   	  sCurrentvars = sCurrentvars + '&postslug='+postslug;
   }
   // Check for content_id
   if((content_id != undefined) && (content_id.length > 0))
   {

   	  sCurrentvars = sCurrentvars + '&content_id='+content_id;
   }

   // Check for m_id
   if((m_id != undefined) && (m_id.length > 0))
   {
   	  sCurrentvars = sCurrentvars + '&m_id='+m_id;
   }

   /* Other Object Items */

   // Now move this url into the function call, first swapping over dodgy characters.
   sCurrentvars = strreplace('/','~', sCurrentvars);
   sDefaultUrl  = strreplace('/','~', sDefaultUrl);

   sCurrentvars = escape("'"+sCurrentvars+"'");
   sDefaultUrl  = escape("'"+sDefaultUrl+"'");

   sCurrentvars = '?mpassuri='+sDefaultUrl+'&mpassvars='+sCurrentvars;

   sHTTPurl = sHTTPurl +sCurrentvars;
   
	//document.write(sHTTPurl + '\n');
	
	// article example
	//sHTTPurl = 'http://localhost/23420/import.getURLresult?mpassuri=%27http%3A%7E%7Elocalhost%7E23417%7Eexternal.getDataXML%3F%27&mpassvars=%27mtype%3D1%26melement%3Dmain%26assoc_content_id%3D143%27'
	// product list example use menu id
	// sHTTPurl = 'http://localhost/23420/import.getURLresult?mpassuri=%27http%3A%7E%7Elocalhost%7E23417%7Eexternal.getDataXML%3F%27&mpassvars=%27mtype%3D2%26melement%3Dmain%26assoc_content_id%3D155%27'
	// product example
	 sHTTPurl = 'http://localhost/23420/import.getURLresult?mpassuri=%27http%3A%7E%7Elocalhost%7E23417%7Eexternal.getDataXML%3F%27&mpassvars=%27mtype%3D3%26melement%3Dmain%26assoc_content_id%3D1165%27'
	// 			http://localhost/23420/import.getURLresult?mpassuri=%27http%3A%7E%7Elocalhost%7E23417%7Eexternal.getDataXML%3F%27&mpassvars=%27mtype%3D1%26melement%3Dmain%26postslug%3Dcooling%7Eproduct-types%27
	document.write(sHTTPurl);
	
	//sHTTPurl = 	'http://localhost/234/product.list/1319';
   /* Now check the Call is possible */
   try
   {
    	netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
   }
   catch (e)
   {
    	//alert("Permission UniversalBrowserRead denied.");
   }

   request.onreadystatechange = receiveData;
   request.open("GET", sHTTPurl, true);
   //alert('Stage 3 '+sUrl);
   /* Branch for the Send */
   if (window.ActiveXObject)
   {
      //alert('send (4)');
      request.send(null);
   }
   else
      if (window.XMLHttpRequest)
      {
         //alert('send (5)');
          request.send(null);
      }
   else
       alert('Sorry, unable to send and receive Data from the Server');


  return;
}


/**************************************************************************
                Name        :      receiveData()
                Author      :      P.Colclough
                Date        :      17/04/2007
                Desc.       :      Receives the callback from the server, and processes
                                   the XML return data

                Parameters  :      Url to call.

                Version     :      1.0
                History     :      17/04/2007        - First Cut
**************************************************************************/
function receiveData()
{

     var nRetType;
    // only if req shows "complete"
    if (request.readyState == 4)
    {
        // only if "OK"
        if (request.status == 200)
        {


            // ...processing statements go here...
            if(request.responseText == null)
               alert('Ooops! No XML here>>  '+request.responseText);
            else
                response  = request.responseText;

            //alert(request.responseText);
            // If response is null we probably have an error
            if(response != null)
            {

               nType     = parseInt(getTagValue(request.responseText, 'typeID'));
               sobjid    = getTagValue(request.responseText, 'objdata');
               // We have a problem with strings longer than 2k (DOMString), so we need to
               // use our own sometimes.
               result    = getTagValue(request.responseText, 'resdata');


            }
            else
            {

              sobjid     = 'main';
              result    = getTagValue(request.responseText, 'resdata');
              nType     = parseInt(getTagValue(request.responseText, 'typeID'));

            }

            nRetType = nType;

            /****************************************************************
             Depending on the return type, perform one of the follwoing:

				nRetType -  1 => About Cooling

             ****************************************************************/
            switch(nRetType)
            {

            default:                             // Any other Case

                 oobj      = $(sobjid);
				 // And this is all we need for a real browser
				 oobj.innerHTML = htmlspecialchars(result,1);

                 if(nRetType == 3)				// Product detail needs the Tabs Script
				 {
				 	tabsBuilt = 0;
				 	BuildTabs();
     				ActivateTab(0);
				 }



    			break;
            }    // End of Switch


         }
         else
         {
           //alert('We are in the else...'+request.responseText);

           // IE Sometimes returns a status of Zero
           if (request.status == 404)
           {
              //alert(request.responseText);
           }
           else if(request.status != 0)
               alert("There was a problem retrieving the XML data ["+request.status+"]["+request.readystate+"]:" + request.statusText + "/n"+request.responseText);
         }
    }
   //alert('Stage 9 out of Receive Data');
   return;
}

/**************************************************************************
                Name        :      getTagValue()
                Author      :      P.Colclough
                Date        :      17 April 2007
                Desc.       :      Get a Tag Value the hard way...
                                   The XML funcs have a string limit of DOMString
                                   which is OS dependant, and blows around 3k
                                   on a Windows platform... so we do this the hard way
                                   from resonseText
                Parameters  :      sText           The text with the tags
                                   sTag            The tag WITHOUT the <> wrappers
                Version     :      1.0
                History     :      17 April 2007        - First Cut


**************************************************************************/
function getTagValue(sText, sTag)
{
  sRet   = '';                // Return value
  nstart = 0;                 // Start point
  nend   = 0;                 // end point
  sstarttag = '<'+sTag+'>';  // Start Tag
  sendtag   = '</'+sTag+'>'; // End Tag

  nstart = sText.indexOf(sstarttag) + sTag.length +2 ;
  nend   = sText.indexOf(sendtag);

  sRet   = sText.slice(nstart, nend);

  // Now set the <> flags which have been replaced with &gt; etc...
  sRet = sRet.replace(/&lt;/gi, "<");
  sRet = sRet.replace(/&gt;/gi, ">");
  sRet = sRet.replace(/&quot;/gi, "\"");
  sRet = sRet.replace(/&amp;nbsp;/gi, " ");

  return sRet;

}

/**************************************************************************
                Name        :      htmlspecialchars()
                Author      :      P.Colclough
                Date        :      17 April 2007
                Desc.       :      Mimics the PHP version. Takes a string and an INt.
                                   Will convert into or out of htmlSpcialchars
									&         - [amp;]   - Need this to stop recursion
                                    "        - &quot;
                                    '        - ~;
                                    <        - &lt;
                                    >        - &gt;
                                    #        - [hash;]  - Need this for Hash signs

                Parameters  :      sString                        String to convert
                                   nType                          0 = Into specialchars
                                                                                                                                                 1 = Into plain text
                Version     :      1.0
                History     :      17 April 2007        - First Cut

**************************************************************************/
function htmlspecialchars(sString, nType)
{
          var sret = '';
          sret = sString;
          var i;
          spound = String.fromCharCode(163);
          snot   = String.fromCharCode(172);

          switch(nType)
          {
          case 0:                                // Convert into special chars
          	sret = strreplace('&', '[amp;]', sret);
           	sret = strreplace('"', '}', sret);
            sret = strreplace("'", "~", sret);
            sret = strreplace('<', '@', sret);
            sret = strreplace('>', '{', sret);
            sret = strreplace("\n", '^', sret);
            sret = strreplace('#', '[hash;]', sret);
            sret = strreplace(spound, '[pound;]', sret);
            // Do not convert this back... just strip it.
            sret = strreplace(snot, ' ', sret);
            break;
          case 1:                                // Convert back to plain text
            sret = strreplace('[amp;]','&',  sret);
            sret = strreplace('}','"',  sret);
            sret = strreplace('~', "'", sret);
            sret = strreplace('@','<',  sret);
            sret = strreplace('{','>',  sret);
            sret = strreplace('^', "\n", sret);
            sret = strreplace('[hash;]','#', sret);
            sret = strreplace('&amp;','&', sret);
            sret = strreplace('[pound;]',spound, sret);

          // Also check the following


                        break;

          }

          return sret;

}
/****************************************************************************
                Name        :      $()
                Author      :      P.Colclough
                Date        :      17 April 2007
                Desc.       :      A short version of document.getElemetById
                Parameters  :           Object ID

                Version     :     1.0
                History     :     17 April 2007        - First Cut


*****************************************************************************/
function $() {
        var elements = new Array();
        for (var i = 0; i < arguments.length; i++) {
                var element = arguments[i];
                if (typeof element == 'string')
                {
                        if(window.ActiveXObject)
                                element = document.getElementById(element);
                        else
                                element = document.getElementById(element);
                }

                if (arguments.length == 1)
                {
                        return element;
                }
                elements.push(element);
        }
        return elements;
}
/**************************************************************************
                Name        :      strreplace()
                Author      :      P.Colclough
                Date        :      5 October 2006
                Desc.       :      Replaces all occurrences of a string
                Parameters  :      str1 - String to Search for
                                   str2 - String to Replace
                                   str3 - String to Search/ Replace in
                Version     :      1.0
                History     :      5 October 2006        - First Cut



**************************************************************************/
function strreplace(sNeedle, sRepl, sHaystack)
{
    sretstr = sHaystack;
    while (sretstr.indexOf(sNeedle) > -1)
           sretstr = sretstr.replace(sNeedle, sRepl);

    return sretstr;

}



