// ********************************************************************
// Copyright (C) 2001 Microsoft Corporation. All rights reserved.
//
//	IMPORTANT.  Please read the legal.txt file, located in the 
//	"<CMS Install Directory>\Server\httpexec\WBC\Internals" 
//	directory, governing the use of this internal file."
// ********************************************************************

//Constants.
SEP_PADDING = 5
HANDLE_PADDING = 7

var yToolbars = new Array();  // Array of all toolbars.

// Initialize everything when the document is ready
var YInitialized = false;
function document.onreadystatechange() {
  if (YInitialized) return;
  YInitialized = true;

  var i, s, curr;

  // Find all the toolbars and initialize them.
  for (i=0; i<document.body.all.length; i++) {
    curr=document.body.all[i];
    if (curr.className == "yToolbar") {
      if (! InitTB(curr)) {
        alert("Toolbar: " + curr.id + " failed to initialize. Status: false");
      }
      yToolbars[yToolbars.length] = curr;
    }
  }

  //Lay out the page, set handler.
  DoLayout();
  window.onresize = DoLayout;

  Composition.document.designMode="On"
}

// ---- [Public] Filter Clipboard or D&D data
function FilterClipboardData() {
	// retrieve data from either event.dataTransfer or event.clipboardData
	var dt = Composition.event.dataTransfer;	// (in the case of Drag & Drop)
	if (!dt) 
		dt = window.clipboardData;				// (in the case of Copy & Paste)
	
	/*
	dt.getData("URL");
	dt.getData("Text");
	*/

	// There is no good way of handling the data because we cannot filter
	// out content that contains local resources (i.e. file://xyz.gif)
	// Therefore we allow any content and rely on ROM to parse them out
	Composition.event.returnValue = true;
}


// Initialize a toolbar button
function InitBtn(btn) {
  btn.onmouseover = BtnMouseOver;
  btn.onmouseout = BtnMouseOut;
  btn.onmousedown = BtnMouseDown;
  btn.onmouseup = BtnMouseUp;
  btn.ondragstart = YCancelEvent;
  btn.onselectstart = YCancelEvent;
  btn.onselect = YCancelEvent;
  btn.YUSERONCLICK = btn.onclick;
  btn.onclick = YCancelEvent;
  btn.YINITIALIZED = true;
  return true;
}

//Initialize a toolbar. 
function InitTB(y) {
  // Set initial size of toolbar to that of the handle
  y.TBWidth = 0;
    
  // Populate the toolbar with its contents
  if (! PopulateTB(y)) return false;
  
  // Set the toolbar width and put in the handle
  y.style.posWidth = y.TBWidth;
  
  return true;
}


// Hander that simply cancels an event
function YCancelEvent() {
  event.returnValue=false;
  event.cancelBubble=true;
  return false;
}

// Toolbar button onmouseover handler
function BtnMouseOver() {
  if (event.srcElement.tagName != "IMG") return false;
  var image = event.srcElement;
  var element = image.parentElement;
  
  // Change button look based on current state of image.
  if (image.className == "Ico") element.className = "BtnMouseOverUp";
  else if (image.className == "IcoDown") element.className = "BtnMouseOverDown";

  event.cancelBubble = true;
}

// Toolbar button onmouseout handler
function BtnMouseOut() {
  if (event.srcElement.tagName != "IMG") {
    event.cancelBubble = true;
    return false;
  }

  var image = event.srcElement;
  var element = image.parentElement;
  yRaisedElement = null;
  
  element.className = "Btn";
  image.className = "Ico";

  event.cancelBubble = true;
}

// Toolbar button onmousedown handler
function BtnMouseDown() {
  if (event.srcElement.tagName != "IMG") {
    event.cancelBubble = true;
    event.returnValue=false;
    return false;
  }

  var image = event.srcElement;
  var element = image.parentElement;

  element.className = "BtnMouseOverDown";
  image.className = "IcoDown";

  event.cancelBubble = true;
  event.returnValue=false;
  return false;
}

// Toolbar button onmouseup handler
function BtnMouseUp() {
  if (event.srcElement.tagName != "IMG") {
    event.cancelBubble = true;
    return false;
  }

  var image = event.srcElement;
  var element = image.parentElement;

  if (element.YUSERONCLICK) eval(element.YUSERONCLICK + "anonymous()");

  element.className = "BtnMouseOverUp";
  image.className = "Ico";

  event.cancelBubble = true;
  return false;
}

// Populate a toolbar with the elements within it
function PopulateTB(y) {
  var i, elements, element;

  // Iterate through all the top-level elements in the toolbar
  elements = y.children;
  for (i=0; i<elements.length; i++) {
    element = elements[i];
    if (element.tagName == "SCRIPT" || element.tagName == "!") continue;
    
    switch (element.className) {
    case "Btn":
      if (element.YINITIALIZED == null) {
	if (! InitBtn(element)) {
	  alert("Problem initializing:" + element.id);
	  return false;
	}
      }
      
      element.style.posLeft = y.TBWidth;
      y.TBWidth += element.offsetWidth + 1;
      break;
      
    case "TBGen":
      element.style.posLeft = y.TBWidth;
      y.TBWidth += element.offsetWidth + 1;
      break;
      
    case "TBSep":
      element.style.posLeft = y.TBWidth + 2;
      y.TBWidth += SEP_PADDING;
      break;
      
    case "TBHandle":
      element.style.posLeft = 2;
      y.TBWidth += element.offsetWidth + HANDLE_PADDING;
      break;
      
    default:
      alert("Invalid class: " + element.className + " on Element: " + element.id + " <" + element.tagName + ">");
      return false;
    }
  }

  y.TBWidth += 1;
  return true;
}

function DebugObject(obj) {
  var msg = "";
  for (var i in TB) {
    ans=prompt(i+"="+TB[i]+"\n");
    if (! ans) break;
  }
}

// Lay out the docked toolbars
function LayoutTBs() {
  NumTBs = yToolbars.length;

  // If no toolbars we're outta here
  if (NumTBs == 0) return;

  //Get the total size of a TBline.
  var i;
  var ScrWid = (document.body.offsetWidth - 6);
  var TotalLen = ScrWid;
  for (i = 0 ; i < NumTBs ; i++) {
    TB = yToolbars[i];
    if (TB.TBWidth > TotalLen) TotalLen = TB.TBWidth;
  }

  var PrevTB;
  var LastStart = 0;
  var RelTop = 0;
  var LastWid, CurrWid;

  //Set up the first toolbar.
  var TB = yToolbars[0];
  TB.style.posTop = 0;
  TB.style.posLeft = 0;

  //Lay out the other toolbars.
  var Start = TB.TBWidth;
  for (i = 1 ; i < yToolbars.length ; i++) {
    PrevTB = TB;
    TB = yToolbars[i];
    CurrWid = TB.TBWidth;

    if ((Start + CurrWid) > ScrWid) { 
      //TB needs to go on next line.
      Start = 0;
      LastWid = TotalLen - LastStart;
    } 
    else { 
      //Ok on this line.
      LastWid = PrevTB.TBWidth;
      //RelTop -= TB.style.posHeight;
      RelTop -= TB.offsetHeight;
    }
      
    //Set TB position and LastTB width.
    TB.style.posTop = RelTop;
    TB.style.posLeft = Start;
    PrevTB.style.width = LastWid;

    //Increment counters.
    LastStart = Start;
    Start += CurrWid;
  } 

  //Set width of last toolbar.
  TB.style.width = TotalLen - LastStart;
  
  //Move everything after the toolbars up the appropriate amount.
  i--;
  TB = yToolbars[i];
  var TBInd = TB.sourceIndex;
  var A = TB.document.all;
  var item;
  for (i in A) {
    item = A.item(i);
    if (! item) continue;
    if (! item.style) continue;
    if (item.sourceIndex <= TBInd) continue;
    if (item.style.position == "absolute") continue;
    item.style.posTop = RelTop;
  }
}

//Lays out the page.
function DoLayout() {
  LayoutTBs();

  NumTBs = yToolbars.length;

  // If no toolbars we're outta here
  if (NumTBs == 0) return;

  //Get the total size of a TBline.
  var i;
  var ScrWid = (document.body.offsetWidth - 6); // offsetWidth - 6);
  var TotalLen = ScrWid;
  for (i = 0 ; i < NumTBs ; i++) {
    TB = yToolbars[i];
    if (TB.TBWidth > TotalLen) TotalLen = TB.TBWidth;
  }
  
  Composition.width = TotalLen;
}

// Check if toolbar is being used when in text mode
function validateMode() {
  if (! bTextMode) return true;
  alert("Please uncheck the \"HTML\" checkbox to use the toolbars");
  Composition.focus();
  return false;
}

//Formats text in composition.
function format(what,opt) {
  if (!validateMode()) return;
  
  if (opt=="removeFormat") {
    what=opt;
    opt=null;
  }

  var retValue;
  if (opt==null) 
  	retValue = Composition.document.execCommand(what);
  else 
  	retValue = Composition.document.execCommand(what,"",opt);
  
  pureText = false;
  Composition.focus();
  
  return retValue;
}

//Switches between text and html mode.
function setMode(newMode) {
  bTextMode = newMode;
  var cont;
  
  if (bTextMode)
  {
    cleanHtml();

    cont = Composition.document.body.innerHTML;
    Composition.document.body.innerText = cont;
  }
  else 
  {
    cont = Composition.document.body.innerText;
    Composition.document.body.innerHTML = cont;
  }
  
  Composition.focus();
}

//Finds and returns an element.
function getEl(sTag,start) {
  while ((start!=null) && (start.tagName!=sTag)) start = start.parentElement;
  return start;
}

function getAncestorA( sel, rng )
{
	var elA;
	if (sel.type == "Control")
	{
		elA = getEl("A",rng.commonParentElement());
	}
	else 
	{
		elA = getEl("A",rng.parentElement());
	}
	
	return elA;
}

function getParentEl( sel, rng )
{
	var elParent;
	if (sel.type == "Control")
	{
		elParent = rng.commonParentElement();
	}
	else 
	{
		elParent = rng.parentElement();
	}
	
	return elParent;
}

// --- function to createTable()
function createTable() {
	if (!validateMode()) return;
	
	window.external.raiseEvent('onCreateTableClick', window.document); 
}

// ---- function to support createLink()
function fixTrailingSpace(rng)
{
	var strText = rng.text;
	if (strText.length > 0)
	{
		if ( strText.charAt(strText.length-1) == " " )
		{
			rng.moveEnd("character", -1);
		}
	}

	return rng;
}

// ---- function to support createLink()
function modifyAnchor(elA, strTitle, strTarget, strName)
{
	// apply attributes for the <a> tag
	if (strTitle == "")
		elA.removeAttribute("title");
	else
		elA.title = strTitle;

	if (strTarget == "")
		elA.removeAttribute("target");
	else
		elA.target = strTarget;

	if (strName == "")
	{
		elA.removeAttribute("name");
		elA.removeAttribute("id");
	}
	else
	{
		elA.name = strName;
		elA.id = strName;
	}
	
	// lastly, remove HREF attribute if it is empty
	if ( elA.href == "" || elA.href == "http://" )
	{
		elA.removeAttribute("href");	
	}
}

// ---- In response to user clicking on Hyperlink button
function createLink() {
  if (!validateMode()) return;

	// IE DOM fully-qualifies any href with relative path or #bookmark, 
	// we need to strip out the full path, which screws up relative paths
	// since the full path injected is for deditor.asp
	cleanHtml();
  
	var elA;
	var sel = Composition.document.selection;
	// check against case that there is no highlighted selection
	if (sel.type=="None")
	{
		alert("There is no selected text or object for hyperlinking.");
		return;
	}
	
	var rng = sel.createRange();
	
	// componseate for IE selecting trailing space as part of the range
	if (sel.type == "Text")
		rng = fixTrailingSpace(rng);

	elA = getAncestorA( sel, rng );
	
	// construct arguments to be passed to the dialog, in the format 
	// of "Href;Title;Target;Name"
	var strHref = elA ? elA.href : "http:\/\/";
	var strTitle = elA ? (elA.title ? elA.title : "") : "";
	var strTarget = elA ? (elA.target ? elA.target : "" ) : "";
	var strName = elA ? (elA.name ? elA.name : "" ) : "";
	var args = strHref + ";" + strTitle + ";" + strTarget + ";" + strName;

	// show hyperlink dialog
	var strDlgRet = window.showModalDialog( "/NR/System/WBC/Internals/WBCFuncPages/IE-Specific/HLink/hlink.asp", args, 
						"dialogWidth:450px;dialogHeight:265px;status:yes;help:no" );
						
	if ( typeof(strDlgRet) == "undefined" )
		return;
		
	if (strDlgRet == "Cancel")
		return;
		
	// before setting new value, remove all old hyperlinks within the range
	rng.execCommand("Unlink");

	// create new <A> only if strDlgRet is not a blank
	if ( strDlgRet != "")
	{
		// split returned string "HRef;Title;Target;Name"
		var aAttributes = strDlgRet.split(";");
		strHref = aAttributes[0];
		strTitle = aAttributes[1];
		strTarget = aAttributes[2];
		strName = aAttributes[3];

		// get IE to set the hyperlink through execCommand
		if ( rng.execCommand("CreateLink", "", strHref) )
		{
			// apply attributes for <a> tag
			elA = getAncestorA( sel, rng );
			if (elA)
			{
				// element <a> found in ancestors chain,
				// next step is to modify it
				modifyAnchor(elA, strTitle, strTarget, strName);
			}
			else
			{
				// element <a> not found in ancestors chain, try decendents
				// of the parent element.

				// From rng, look for all parent's decendents with <a> tags with 
				// href attributes equal to strHref
				colA = getParentEl( sel, rng ).all.tags("A");
				for (var i = colA.length - 1; i >= 0; i--)
				{
					modifyAnchor(colA[i], strTitle, strTarget, strName);
				}
			}

			// for some unknown reason, need to refresh placeholder 
			// for images to show up properly
			if (sel.type == "Control")
			{
				Composition.document.body.innerHTML = Composition.document.body.innerHTML;
				// previous line resulting in entire content 
				// selected, need to compensate by emptying selection
				Composition.document.selection.empty();
			}
		}
		else
		{
			alert("Failed to insert hyperlink!");
		}
	}

	return;	
}

function launchImageGallery() {
  if (! validateMode()) return; 
  
  window.external.raiseEvent('onShowImgGalleryClick',window.document);
}

function launchAttachmentGallery() {
  if (! validateMode()) return;  
  
  window.external.raiseEvent('onShowAttachmentGalleryClick',window.document);   
}

function launchVideoGallery() {
  if (! validateMode()) return;  
  
  window.external.raiseEvent('onShowVideoGalleryClick',window.document);   
}

//Sets the text color.
function foreColor() {
  if (! validateMode()) return;
  var arr = showModalDialog("/NR/System/WBC/Internals/WBCFuncPages/IE-Specific/Color/ColorSelect.asp", "", 
  				"dialogWidth:450px;dialogHeight:320px;status:no;help:no");
  if (arr != null) format('forecolor', arr);
  else Composition.focus();
}

//Sets the background color.
function backColor() {
  if (!validateMode()) return;
  var arr = showModalDialog("/NR/System/WBC/Internals/WBCFuncPages/IE-Specific/Color/ColorSelect.asp", "", 
  				"dialogWidth:450px;dialogHeight:320px;status:no;help:no");
  if (arr != null) format('backcolor', arr);
  else Composition.focus()
}

function cleanHtml() {
  var fonts = Composition.document.body.all.tags("FONT");
  var curr;
  for (var i = fonts.length - 1; i >= 0; i--) {
    curr = fonts[i];
    if (curr.style.backgroundColor == "#ffffff") curr.outerHTML = curr.innerHTML;
  }
	
  // IE DOM fully-qualifies any href with relative path or #bookmark, 
  // we need to strip out the full path, which screws up relative paths
  // since the full path injected is for deditor.asp
  
  var regexpHash = /.*\/NR\/System\/WBC\/Internals\/PageTemplate\/placeholdersSupport\/DhtmlPlaceholder\/deditor.asp\?width=\d+&height=\d+/;
  var reexpRelPath0 = /.*\/NR\/System\/WBC\/Internals\/PageTemplate\/placeholdersSupport\/DhtmlPlaceholder\//;
  var reexpRelPath1 = /.*\/NR\/System\/WBC\/Internals\/PageTemplate\/placeholdersSupport\//;
  var reexpRelPath2 = /.*\/NR\/System\/WBC\/Internals\/PageTemplate\//;
  var reexpRelPath3 = /.*\/NR\/System\/WBC\/Internals\//;

  var anchors = Composition.document.body.all.tags("A");
  for (var i = anchors.length - 1; i >= 0; i--)
  {
  	if (anchors[i].href != "")
  	{
		var strHrefOrig; 
		strHrefOrig = anchors[i].href;
		anchors[i].href = strHrefOrig.replace(regexpHash, "");
		strHrefOrig = anchors[i].href;
		anchors[i].href = strHrefOrig.replace(reexpRelPath0, "");
		strHrefOrig = anchors[i].href;
		anchors[i].href = strHrefOrig.replace(reexpRelPath1, "../");
		strHrefOrig = anchors[i].href;
		anchors[i].href = strHrefOrig.replace(reexpRelPath2, "../../");
		strHrefOrig = anchors[i].href;
		anchors[i].href = strHrefOrig.replace(reexpRelPath3, "../../../");
  	}
  }
}

function getPureHtml() {
  var str = "";
  var paras = Composition.document.body.all.tags("P");
  if (paras.length > 0) {
    for (var i=paras.length-1; i >= 0; i--) str = paras[i].innerHTML + "\n" + str;
  } else {
    str = Composition.document.body.innerHTML;
  }
  return str;
}

