﻿ 


  // functions for	ajax get and post	methods

  // retrieve some content without a page refresh
  // url is the address to reference
  // callback should be a function(xhr, status)
  // if status is true, the request was successful
  // xhr is a reference to the XMLHttpRequest object
  // caller can access xhr.responseText or xhr.responseXML
  // if postParams is null, we do a GET
  // otherwise we do a POST, and the postParams are sent as the Form values
  function PT_ajaxRequest(url, callback, postParams)
  {
  var xhr = PT_getXHR();
  if (xhr == null)
  return;	// error
  var isPost = (postParams != null);
  xhr.onreadystatechange = function() {PT_XHRStateChangeHandler(xhr, callback);};
  xhr.open(isPost ? "POST" : "GET", url, true);
  if (isPost)
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send(postParams);
  }

  // load content into a page without a page refresh
  // like PT_loadFrame, but this uses XmlHttpRequest instead of iframes
  // this requests the content at the given url
  // when the content is loaded, we copy the loaded HTML (in its entirety)
  // into destination (the id - or the element itself) in the current page where the content should be placed
  // the previous contents of destination are overwritten
  // onload is an additional function to be run after the content is loaded and copied
  // onload takes two parameters: xhr is a reference to the XMLHttpRequest object
  // status is a boolean: true means the request was successful
  // if the request is not successful, we don't attempt to copy any data, but the onload function is still called
  // if destination is null or empty, then we don't copy any data
  // if postParams is null, we do a GET
  // otherwise we do a POST and the postParams are sent as the Form values
  function PT_loadFrameAjax(url, destination, onload, postParams)
  {
  // destination can either be an id or the element itself
  if (destination != null && typeof destination == "string")
	{
	   		destination = document.getElementById(destination);
	}

	// create a callback function that will run when the content has been loaded
	// this is used to
	// 1. transfer the loaded contents to the desired destination
	// 2. run a caller-specified onload function

	var callback = function(xhr, status) 
	{ 
		if (status && destination != null)
		{
			// get the loaded content
			// and insert it in the destination
			var loadedText = xhr.responseText;
			destination.innerHTML = loadedText; 
			
			// activate any scripts that have been loaded
			// by evaluating them
			var newScripts = destination.getElementsByTagName("script");

      for (var ix = 0; ix < newScripts.length; ix++)
			{
        if(window.PT_SCRIPTREGISTRY != null && newScripts[ix].src!="")
        {
          window.PT_SCRIPTREGISTRY.AddScript(new PT_Script_Reference(newScripts[ix].src));
        }
        else
        {
        
				  eval(newScripts[ix].innerHTML);
        }
			}
		}
		// run the caller-specified onload function
		if (onload) onload(xhr, status);
	};

	// request the content
	PT_ajaxRequest(url, callback, postParams);
}

// called by ptt:button when action=ajaxPost
// controlList is a comma-delimited list of (possibly wild-carded) control ids whose values we should include
function PTButtonCmdAjax(url, destination, onload, cmd, controlList)
{
	var postParams = "ptButtonCmd=" + cmd + "&ptButtonValidate=false";
	// Don't require controls to be in main ptt form
	//var form = document.getElementById('_pttmf');
	// build up a regexp that matches the controls we want
	if (controlList)
	{
		var controlsToGet = "^" + controlList.replace(",", "$|^").replace("*", ".*") + "$";
		var controlsRE = new RegExp(controlsToGet, "i");
		var ctlList = document.getElementsByTagName("*");
		//for (var i = 0; i < form.elements.length; i++)
		for (var i = 0; i < ctlList.length; i++)
		{
			//var el = form.elements[i];
			var el = ctlList[i];
			if (el.id.search(controlsRE) != -1)
			{
				// this control is in our list
				var ctlVal = PT_getControlValue(el);
				if (ctlVal != null)
				{
					postParams += "&" + el.name + "=" + ctlVal;
  }
  }
  }
  }
  PT_loadFrameAjax(url, destination, onload, postParams);
  }

  // this is called by ajaxGet to decide when the retrieval is finished
  // when it is, we relay the call to the user supplied callback function
  function PT_XHRStateChangeHandler(xhr, userCallback)
  {
  // ignore anything other than completed
  if (xhr.readyState != 4)
  return;
  // second param indicates successful retrieval
  // caller can access xhr.responseText or xhr.responseXML
  userCallback(xhr, xhr.status == 200);
  }

  // construct and return an XMLHttpRequest object, based on the browser's capabilities
  function	PT_getXHR()
  {
  if	(window.XMLHttpRequest)
  {
  try
  {
  return new	XMLHttpRequest();
  }
  catch(e)
  {
  return null;
  }
  }
  else	if(window.ActiveXObject)
  {
  try
  {
  return new	ActiveXObject("Microsoft.XMLHTTP");
  }
  catch(e)
  {
  return null;
  }
  }
  }

  // based on the control's type, returns the value that would be posted back
  // to the server. Returns null if no value should be returned for this control
  function PT_getControlValue(ctl)
  {
  switch(ctl.type)
  {
  case "checkbox":
  case "radio":
  if (!ctl.checked)
  return null;
  break;
  case "select-one":
  return ctl.options[ctl.selectedIndex].value;
  // TODO: handle "select-multiple"
  }
  return ctl.value;
  }


  // Use this as a callback function to PTButtonCmdAjax
  // This will grab the HTML content that would otherwise be placed in the
  // destination element and instead place it in a floating element
  // which is located in the visible portion of the current window.
  //var PT_curAlert = null; // only allow one alert at a time (pseudo-modal)
  function PT_ajaxShowAlert(xhr, status)
  {
  if (status)
  {

  PT_ajaxRemoveAlert();
  // create a new DIV and attach it to the document
  window.PT.PT_curAlert = document.createElement("DIV");
  document.body.appendChild(window.PT.PT_curAlert);
  // position the DIV relative to the current scrolling position of the page

  window.PT.PT_curAlert.style.position = "absolute";
  window.PT.PT_curAlert.style.top = (document.body.scrollTop + 155) + "px";
  window.PT.PT_curAlert.style.left = (document.body.scrollLeft + 100) + "px";
  // and copy the content from the ajax request into the div
  window.PT.PT_curAlert.innerHTML = xhr.responseText;

  var winH = document.body.clientHeight;
  var winW = document.body.clientWidth;

  var ptH = window.PT.PT_curAlert.clientHeight;
  var ptW = window.PT.PT_curAlert.clientWidth;

  if(ptH > (winH + 310)  || ptW >(winW + 200))
  {
    window.PT.PT_curAlert.style.width= (winW - 200)+"px";
    window.PT.PT_curAlert.style.height= (winH - 310)+"px";
    window.PT.PT_curAlert.style.overflow = "auto";
  }
  // activate any scripts that have been loaded
  // by evaluating them

  var newScripts = window.PT.PT_curAlert.getElementsByTagName("script");

  // first iterate through all the refrenced scripts and insert them
  for (var ix = 0; ix < newScripts.length; ix++)
    {
      if(window.PT_SCRIPTREGISTRY != null && newScripts[ix].src!="")
      {
        window.PT_SCRIPTREGISTRY.AddScript(new PT_Script_Reference(newScripts[ix].src));
      }
    }
    // then iterate through the evaluated scripts and evaluate them
    for (ix = 0; ix < newScripts.length; ix++)
    {
      if(newScripts[ix].src=="")
      {
        var scriptText = newScripts[ix].innerHTML;
        scriptText =scriptText.replace("<!--","") ;
        scriptText = scriptText.replace("-->","");
        if(window.execScript){
          window.execScript(scriptText);
        }
        else
        {
          window.setTimeout(scriptText,0);
        }
      }
    }
  }
  else
  {
  // display the best error message we can
  alert("Ajax error: " + xhr.statusText);
  }
  }

  function PT_ajaxRemoveAlert()
  {
  if (window.PT.PT_curAlert != null)
  {
    window.PT.PT_curAlert.parentNode.removeChild(window.PT.PT_curAlert);
    window.PT.PT_curAlert = null;
    if (window.PT.PT_OnAlertDismiss && window.PT.PT_OnAlertDismiss != null)
			window.PT.PT_OnAlertDismiss();
	  }
};
// Do a synchronous GET
function PT_ajaxGetUrl(url)
{
	var xhr = PT_getXHR();
	if (xhr == null)
		return null;	// error
	xhr.open("GET", url, false);
	xhr.send();
	return xhr;
};


var PTLib;
if (!PTLib)
{
	PTLib = new Object();
};


PTLib.Popin = function(id, innerHTML)
{
	this.isActive = false; // not attached to the DOM
	this.element = document.createElement("DIV");
	this.element.innerHTML = innerHTML;
	this.onLoad = new Array();
	this.onBeforeUnload = new Array();
	this.onUnload = new Array();
	
	// Find any scripts
	var newScripts = this.element.getElementsByTagName("script");
		for (var ix = 0; ix < newScripts.length; ix++)
		{
			var scriptText = newScripts[ix].innerHTML;
			// TODO - make a "require" function that waits for script; add it to DOM;
			// have a built-in "loaded" function.
			if (scriptText == "" && newScripts[ix].getAttribute("src") != "")
			{
				// reference to external script
				var srcRef = newScripts[ix].getAttribute("src");
				var req = PT_ajaxGetUrl(srcRef);
				scriptText = req.responseText;
			};
      // TODO - figure out how to remove comments  around script, if present
      scriptText = scriptText.replace("<!--",""); 
      scriptText = scriptText.replace("-->","");
  eval(scriptText);
  }
  return this;
  };
  PTLib.Popin.prototype.constructor = PTLib.Popin;
  //no need for the addition protototype
  PTLib.Popin.prototype.show = function(left, top)
  {
  document.body.appendChild(this.element);
  this.element.style.position = "absolute";
  this.element.style.top = (document.body.scrollTop + left) + "px";
  this.element.style.left = (document.body.scrollLeft + right) + "px";
  this.isActive = true;
  };

  // ***************************************************
  // AJAX file upload stuff 9/5/06
  // Per PTech 9226.32 (or thereabouts)
  var PT_nextUploadFileIndex = 0;   // Global counter
  // calling page should set ... NOW passed as param to PT_ajaxPrepareToUploadFile
  // var PTU_dest = "/n/pfx/profile.aspx?template=UploadFile&nav=iframe&webtag=vs-profpropsz";

  // user has clicked on the "attach a file" button
  // construct the elements necessary to choose the file and display its status
  // parentEl: where to house the file input element
  // msgGuid: the guid of the message to which the file will be attached
  // fileChosenCallback: a function with signature f(fileCtl)
  //	this function will be called when the user has chosen a file. fileCtl will be the input type=file
  //	caller can process this event, e.g. display some UI that says that this file is being uploaded
  //	and then should call PT_ajaxUploadFile(), below
  function PT_ajaxPrepareToUploadFile(parentEl, msgGuid, fileChosenCallback, postActionDest)
  {
  // the form that houses the input element
  var frm = document.createElement("form");
  parentEl.appendChild(frm);
  frm.method = "post";
  frm.enctype = "multipart/form-data";
  frm.encoding = "multipart/form-data";
  frm.action = postActionDest;

  // build an input type="text" element

  // build an input type="file" element
  var fileCtl = document.createElement("input");
  fileCtl.type = "file";
  fileCtl.name = "fileCtl";

  // when the user presses OK, actually upload the file

  fileCtl.onchange = function(evt) {fileChosenCallback(fileCtl);};
  // put the fileCtl in the form
  frm.appendChild(fileCtl);




  frm.style.margin = "0";

  // hidden controls for the parameters
  PT_addHiddenField(frm, "uf_msgGuid", msgGuid);

  // TODO: extraFields
  // hidden controls for the command
  PT_addHiddenField(frm, "ptButtonCmd", "cmdUploadFile(uf,true,64)");  // TODO - don't hardcode thumb size
  PT_addHiddenField(frm, "ptButtonValidate", "false");




  // the user will next press the "Browse" button and choose a file
  }

  // begin a background upload of a file to be attached
  // frm: the posting form built by PT_ajaxPrepareToUploadFile
  // fileLoadedCallback: a function with signature f(errorMsg, results, stateObj)
  //   that is called when the upload completes
  //	if errorMsg is not null, then some error occurred, and the errorMsg gives details
  //	otherwise results is a structure that holds information about the uploaded file,
  //	e.g. its file size, height and width, guid, mimeType, etc. see below for details
  function PT_ajaxUploadFile(frm, fileLoadedCallback, stateObj)
  {
  // get a unique index and name for this upload
  var index = PT_nextUploadFileIndex++;
  var frameName = "PTU_frame_" + index;

  // build an iframe to post the upload
  var ifr = document.createElement("iframe");

  ifr.style.height =0;   // make it invisible
  ifr.style.width = 0;
  document.body.appendChild(ifr);
  ifr.id = frameName;
  // just setting ifr.name doesn't seem to work
  frames[frames.length-1].name = frameName;

  // point the posting form at the iframe
  frm.target = frameName;

  var ifrLoaded = function(evt)
  {
  // get the document of the iframe and get upload status and size
  var ifrDoc = PT_getIFrameDoc(ifr);
  var resultsDoc = ifrDoc.body.innerHTML;
  if (resultsDoc.substring(0, 6) == "Error:")
  {
  fileLoadedCallback(resultsDoc);	// indicate error
  }
  else
  {
  var results = new Object();
  results["document"] = resultsDoc;
  results["docSizeKB"] = PT_getAttribute(resultsDoc, "docSize");
  results["docGuid"] = PT_getAttribute(resultsDoc, "cguid");
  results["currHeight"] = PT_getAttribute(resultsDoc, "height");
  results["currWidth"] = PT_getAttribute(resultsDoc, "width");
  results["mimeType"] = PT_getAttribute(resultsDoc, "mimeType");
  results["isImage"] = results["mimeType"].substr(0, 6) == "image/";
  results["url"] = PT_getAttribute(resultsDoc, "url");
  results["thumbUrl"] = PT_getAttribute(resultsDoc, "thumbUrl");
  results["index"] = index;

  //alert(results.index + ': ' + results.thumbUrl);

  fileLoadedCallback(null, results, stateObj);
  }
  // remove the form and the iframe

  if (frm)
  frm.parentNode.removeChild(frm);
  if (ifr)
  window.setTimeout("var ifr = document.getElementById('" + ifr.id + "'); ifr.parentNode.removeChild(ifr);", 0);
  };	// end ifrLoaded function

  // add the hook to call ifrLoaded
  // we can't use a simple ifr.onload - that doesn't work
  if (ifr.addEventListener)
  {
  ifr.addEventListener("load", ifrLoaded, false);
  }
  else
  {
  ifr.attachEvent("onload", ifrLoaded);
  }

  // upload the document
  frm.submit();
  }

  // return the value of the attribute of the specified name from the specified XML document string
  function PT_getAttribute(doc, attrName)
  {
  // build a reg exp that looks for the attribute name plus everything inside the following quotes
  var re = new RegExp(attrName + '="(.+?)"');
  // execute the reg exp against the input, and return the group inside the quotes
  var m = re.exec(doc);
  if (!m || m.length == 0) return "";
  return m[1];
  }

  // worker function to add a hidden field
  function PT_addHiddenField(frm, name, value)
  {
  var ctl = document.createElement("input");
  ctl.type = "hidden";
  ctl.name = name;
  frm.appendChild(ctl);
  ctl.value = value;
  }
  // *** END AJAX FILE UPLOAD STUFF ***

  
 