/* AspSupport.js
 * functions to help asp pages communicate with .net pages
 * This script is in /common dir of asp servers and .net servers
 */

/* Scenario:
 * --------- 
 * A .net page contains an asp page from different domain in an iframe.
 * Only the inner page knows its content's size, only the parent page may resize the iframe, 
 * and they are not allowed to refer to each other beyond the "window" pointer.
 *
 * New method (Acknowledgements to Albert Ribakovsky) - a PURE CLIENT SIDE solution:
 * ----------
 * Inner page loads a page (/common/AspSupport/resize.htm) from parent domain in a more inner iframe, and passes the size to it as qureystring.
 * That page calls its parent. parent with a reference to the window to resize (which both documents may reach)
 * and the size wanted. The parent frame resizes...
 * If the parent frame domain may vary between some values (website with some domain names), the alternative names are passed
 * in the querystring to the most inner frame which if fails to resize redirects itself to the next alternative.
 *
 * Implementation:
 * ---------------
 * In parent page:
 * just make sure virtual directory /common is mapped, and add reference to /common/AspSupport.js. 
 * (CrossDomainIframe does that but sometimes requires custom syntax for the src. 
 *  No use to maintain a custom control only for a reference to a common script and some shortcuts to config.)
 * In inner page:
 *   Simple usage:
 *     Include a server script (FrameResize.asp) that includes /Common/AspSupport.js and generates a client script that sets 2 variables: 
 *     the parent domain name and the default width.
 *     Optionally, it can set alternative domains, for sites with synonym host names (for example: civics.org.il).
 *     IMPORTANT: FrameResize.asp must be included in the <head> element, AFTER the <meta> charset element.
 *     Example:
         <script src="/Common/AspSupport.js" type="text/javascript"></script>
         <script language="javascript">
           AspSupport_sParentFrameDomain = 'bh.<%=CetConfig_Get("Common" ,"//Common/Computer/@sDotNetDomain") %>';
           AspSupport_nFrameWidth = 560;
           // optional:
          AspSupport_aAltDomains = new Array("civics.org.il"."any other valid domain that may host the page");
         </script>
 *        
 *     Then just call AspSupport_FitFrameSize onload, and optionally onclick. 
 *     AspSupport_FitFrameSize uses the default width set in FrameResize.asp, but a different value may be passed to it.
 *       <body onload="AspSupport_FitFrameSize()">
 *     or
 *       <body onload="AspSupport_FitFrameSize(600)">
 *     onclick is required only if clicks in the page may change the page size by showing and hiding elements,
 *     without navigating to another url.

 *   Custom usage:
 *     1. Include a script that sets AspSupport_sParentFrameDomain to the parent domain name. For example:
          AspSupport_sParentFrameDomain = "bh.cet.ac.il";
 *     or better a server generated script to work on both dev and prod:
          AspSupport_sParentFrameDomain = "bh.<%=CetConfig_Get("Common" ,"//Common/Computer/@sDotNetDomain") %>"
 *     2. In each page (or in a common script), put the script (560 is the fix width):
       <script language="javascript">
         function CheckPageHeight ()
         //       ~~~~~~~~~~~~~~~
         {
           AspSupport_ResizeParentFrame(560, document.body.scrollHeight);
         }
         document.body.onload = document.body.onclick = CheckPageHeight;
       </script>
 *     The use of document.body.onclick is required only if clicks in the page may change the page size by showing and hiding elements,
 *     without navigating to another url.
 */
 
// NEW METHOD: Pure client communication
// parent frame function:
function AspSupport_ResizeFrame (oContentWindow, nWidth, nHeight) 
//       ~~~~~~~~~~~~~~~~~~~~~~
{
  // find oContentWindow among frames and resize it
  oFrames = document.getElementsByTagName("IFRAME");
  for (var i = 0; i < oFrames.length; i++)
  {
    var oFrame = oFrames[i];
    if (oFrame.contentWindow == oContentWindow)
    {
      oFrame.width = nWidth; 
      oFrame.height = nHeight; 
      oFrame.style.pixelWidth = nWidth; 
      oFrame.style.pixelHeight = nHeight; 
      break;
    }
  }
}
//-----------------------------------------------

// helper child frame function:
function  AspSupport_FitFrameSize (nWidth)
//       ~~~~~~~~~~~~~~~~~~~~~~~~
{
  if (nWidth == undefined)
    nWidth = AspSupport_nFrameWidth;

  AspSupport_ResizeParentFrame(nWidth, document.body.scrollHeight);
}
//-----------------------------------------------

// child frame function:
function  AspSupport_ResizeParentFrame (nWidth, nHeight)
//       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{
  var s_CHILD_FRAME_ID = "AspSupport_CHILDFRAME";
  var s_CHILD_FRAME_SRC = "http://" + AspSupport_sParentFrameDomain + "/common/AspSupport/Resize.htm?size=" + nWidth + "," + nHeight;
  if (typeof(AspSupport_aAltDomains) != "undefined" && AspSupport_aAltDomains.length > 0)
    s_CHILD_FRAME_SRC += "&alt=" + AspSupport_aAltDomains.join(",");

  // load an intermediate page in parent domain
  var oChildFrame = document.getElementById(s_CHILD_FRAME_ID);
  if (!oChildFrame)
  {
    oChildFrame = document.createElement("iframe");
    oChildFrame.id = s_CHILD_FRAME_ID;
    oChildFrame.height = 0;
    document.body.appendChild(oChildFrame);
  }
  oChildFrame.src = s_CHILD_FRAME_SRC;
}
//-----------------------------------------------

// OLD METHOD: using a "Ticket".

///<Summary>
///This function will do the following:
///Get the ticket data for the given sTicketID.
///Load to xml object.
///If the ticket is not valid (no xml is returned from SQL) – nothing is done.
///If the ticket value is the empty string – AspSupport_CheckFrameResizeValues is called again by window.setTimeout to wait data.
///If the ticket value is not the empty string – the iframe is resized (according to the iframe id),
///then AspSupport_CheckFrameResizeValues is called again by window.setTimeout to wait next resize request.
///The expected ticket value format is width,height.
///</Summary>

// xmlhttpAsynchHandle is used to hang on it many xmlhttp objects so many "CrossDomainIFrames" in a page are supported.
var xmlhttpAsynchHandle = new Object();
function AspSupport_CheckFrameResizeValues (sIframeID, TicketId) 
//       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{
    var widthAndHeight;
    var sPointerName = "xmlhttpAsynchHandle.z" + TicketId;
    while (sPointerName.indexOf("-") >= 0)
      sPointerName = sPointerName.replace("-","_");
    
    //Get the ticket data
    eval(sPointerName + " = new ActiveXObject('Microsoft.XMLHTTP');");
    var xmlhttpAsynch = eval(sPointerName);
    xmlhttpAsynch.open("GET" ,"/Common/Tickets/GetTicketAndReset.aspx?id=" + TicketId , true);
    xmlhttpAsynch.setRequestHeader("Content-Type", "charset=utf-8")
    xmlhttpAsynch.onreadystatechange = new Function("AspSupport_OnGetTicketReady('" + sIframeID + "', '" + TicketId + "')");
    xmlhttpAsynch.send(null);
}
//-----------------------------------------------

function AspSupport_OnGetTicketReady (sIframeID, TicketId) 
//       ~~~~~~~~~~~~~~~~~~~~~~~~~~~
{
    var sPointerName = "xmlhttpAsynchHandle.z" + TicketId;
    while (sPointerName.indexOf("-") >= 0)
      sPointerName = sPointerName.replace("-","_");

    var xmlhttpAsynch = eval(sPointerName);
    if (xmlhttpAsynch.readyState != 4)
      return;
                            
    //Check what we got
     var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");            
    
    var sTicketData = xmlhttpAsynch.responseText;
    //If no entry was found exit
    if(sTicketData == "")
    {
        return;
    }
    
     //Its an xml
     else if(xmlDoc.loadXML(sTicketData) == true)
     {

       widthAndHeight = xmlDoc.selectSingleNode("//sData").text;    
          
       if(widthAndHeight == "")
       {            
           window.setTimeout("AspSupport_CheckFrameResizeValues('" + sIframeID + "','" + TicketId + "');",1000);                   
       }
       else
       {       
         var width = widthAndHeight.split(",")[0];
         var height = widthAndHeight.split(",")[1];       
         
         document.all[sIframeID].width = width; 
         document.all[sIframeID].height = height; 
         
         //Continue waiting for another update of the frame size may be from another page.
         window.setTimeout("AspSupport_CheckFrameResizeValues('" + sIframeID + "','" + TicketId + "');",1000);              
       }
    }     
}
//-----------------------------------------------

///<Summary>
///This function will do the following:
///Update the ticket data in the db for the given sTicketID.
///Get a result to see if the update succeded.
///</Summary>
function  AspSupport_RegisterFrameSize(sTicketID, nWidth, nHeight)
{  
    var url = "/Common/Tickets/UpdateTicket.asp?id=" + sTicketID + "&data=" + nWidth + "," + nHeight;   
   
    //Get the ticket data
    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.open("GET" ,url , true);
    xmlhttp.setRequestHeader("Content-Type", "charset=utf-8");        
    xmlhttp.send(null); 
}
//-----------------------------------------------

function  AspSupport_RegisterFrameSizeDotNet(sTicketID, nWidth, nHeight)
{  
    var url = "/Common/Tickets/UpdateTicket.aspx?id=" + sTicketID + "&data=" + nWidth + "," + nHeight;   
   
    //Get the ticket data
    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.open("GET" ,url , true);
    xmlhttp.setRequestHeader("Content-Type", "charset=utf-8");        
    xmlhttp.send(null); 
}
//-----------------------------------------------

//function AspSupport_CreateEmptyTicket()
//{ 
//    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
//    xmlhttp.open("GET" ,"/Common/Tickets/CreateEmptyTicket.aspx", false);
//    xmlhttp.setRequestHeader("Content-Type", "charset=utf-8");        
//    xmlhttp.send(null); 
//    
//    return xmlhttp.responseText;
//}
//-----------------------------------------------
