﻿function ShowHyperlink(strCtrl)
{
  if (Ext.isReady)
  {
    if(!window.oUtil.obj.checkFocus()) { return; }//Focus stuff
      
    //store the ctrl that Hyperlink will animate To/From
    AV.Hyperlink.setAnimCtrl(Ext.get(strCtrl));
    
    //begin processing to show Hyperlink
    AV.Hyperlink.createHtml();
  }
  else { alert('Ext not ready.  Please reload the page and try again.'); }
}

function HyperlinkSuccess(response, options)
{
  AV.Hyperlink.setHyperlinkHtml(response.responseText);    
  AV.Hyperlink.getWin().show(Ext.get(AV.Hyperlink.getAnimCtrl()));     
}

function HyperlinkFail(response, options)
{
	Ext.MessageBox.alert("Failure", "The request failed.  Please try again.");
}

AV.Hyperlink = new function(){

  var hyperlink_html;
  var hyperlink_panel;
  var win;
  var ctrl;
  var animCtrl;
  var editorSelection;
  var editorSelectionText;
  
    
  function GetCtrl() { return ctrl; }
  
  function GetAnimCtrl() { return animCtrl; }
  
  return {
		
		isImage: false, 
  
    setCtrl: function(strCtrl) { ctrl = strCtrl; },
    
    getCtrl: function() { return GetCtrl(); },
    
    setAnimCtrl: function(strCtrl) { animCtrl = strCtrl; },
    
    getAnimCtrl: function() { return GetAnimCtrl(); },
    
    setHyperlinkHtml: function(html){ hyperlink_html = html; },
    
    setEditorSelection: function() {    //IE: Used to keep track of the selected text in the Editor.
      if(editorSelection && Ext.isIE) { editorSelection.select();}    
    },
    
    getEditorSelectionText: function() { return editorSelectionText; },
    
    clear: function() {    
      //clear all inputs from Hyperlink window
		  Ext.get('inpURLTitle').dom.value = '';
		  Ext.get('inpBookmarkTitle').dom.value = '';
		  Ext.get('inpDisplay').dom.value = '';
		  Ext.get('inpURL').dom.value = '';
      Ext.get("selBookmark").dom.value = 0;      
      Ext.get("chkNewWin").dom.checked = false;   
      
      //ensure that the display is enabled for the next display of window..
      Ext.get("inpDisplay").dom.disabled = false;              
    },
    
    saveSelectionInfo: function() {
      //used to keep track of the selected text in the editor -- in IE, clicking in a textbox unselects the text in the editor.      
      
      //get editor's selected range
      var oSel = getEditorSelection();
                         
      //set selected text                         
      if (window.getSelection) { editorSelectionText = oSel.toString(); }      //Mozilla
      else {editorSelectionText = oSel.text;}                                 //IE
      
      //set selected range --store the editor's selected range within this object
      editorSelection = oSel;     
    },
    
    createHtml: function(){  
      
      this.saveSelectionInfo();
      
      if(!hyperlink_html)
      {
        Ext.Ajax.request({
         url: '/link/Hyperlink.asp',
         success: HyperlinkSuccess,
         failure: HyperlinkFail
        });       
      }
      else
      {
        //if the html already exists, show the window
        this.getWin().show(Ext.get(GetAnimCtrl()));             
      }                                  
    },
    
    getHtml: function(){
      if(!hyperlink_html)
      {
        createHtml();
      }
    },
    
    getPanel: function(){
      
      if(!hyperlink_panel)
      {
        hyperlink_panel = new Ext.Panel({             
          region: 'west',
          //collapsible: true,
          border:false,
          html: hyperlink_html        
        });
      }                   
    },
    
    getWin: function(){
      if(!win)
      {
        if(!hyperlink_panel) { this.getPanel(); }
               
        win = new Ext.Window({
          title: 'Hyperlink',
          closable:true,
          width:450,
          height:300,
          plain:true,
          modal: true,
          resizable: true,
          autoDestroy: false,
          closeAction: 'hide',
          bodyStyle: "padding:10px;",
          buttons:  [
                      {
                        id:       'btn_insert',
                        text:     'Insert',                              
                        handler:  function() { 
                                                //make sure that the original text is selected in the editor
                                                if(Ext.isIE) { AV.Hyperlink.setEditorSelection(); }
                                                applyHyperlink(); 
                                              }
                      },                      
                      {
                        id:       'btn_ok',
                        text:     'OK',
                        handler:  function() { 
                                                //make sure that the original text is selected in the editor
                                                if(Ext.isIE) { AV.Hyperlink.setEditorSelection(); }
                                                applyHyperlink(); 
                                              },
                        hidden:   true
                      },
                      {
                        id:       'btn_cancel',
                        text:     'Cancel',
                        handler:  function() { 
                                                AV.Hyperlink.clear();
                                                win.hide(); 
                                                //make sure that the original text is selected in the editor
                                                //if(Ext.isIE)
                                                //  AV.Hyperlink.setEditorSelection();   
                                             } 
                      }
                    ],

          items: [hyperlink_panel]
        });    
        win.on("show", this.winShow); 
        win.on("hide", this.winHide);                 
      }
      
      if (document.getElementById('headerHide')) 
			{
				document.getElementById('headerHide').style.display = "none"; 
			}
      return win;      
    },
    
    winShow: function() 
    { 
			checkEditorSelection(); 
		},
		
    winHide: function() 
    { 
			if (document.getElementById('headerHide')) 
			{
				document.getElementById('headerHide').style.display = ""; 
			}
		}
                    
  }
};


//Alert Dialog
var Alert = function(){

  return{
    show : function(title, message){
       Ext.MessageBox.alert(title, message);
    }
  };
           
}(); 

  
//=========================================================================
//Original (MODIFIED) javascript from hyperlink_custom.htm 
//=========================================================================
  
function changeLinkTo()
{   
  if(Ext.get('rdoLink').dom.checked && Ext.get('div_address').dom.style.display == 'none')
  {
    Ext.get('div_bookmark').slideOut('t', {callback: function(){
                                                                  Ext.get('div_bookmark').dom.style.display='none';
                                                                  Ext.get('div_address').slideIn();
                                                               }});
  }
  else if(Ext.get('rdoBookmark').dom.checked && Ext.get('div_bookmark').dom.style.display == 'none')
  {
    Ext.get('div_address').slideOut('t', {callback: function(){
                                                                Ext.get('div_address').dom.style.display='none'
                                                                Ext.get('div_bookmark').slideIn();
                                                              }});
  }
}		

function GetElementParentByTag(oElement,sMatchTag)
{
  while (oElement!=null&&oElement.tagName!=sMatchTag)
  {
    if(oElement.tagName=="BODY") { return null; }
    oElement = oElement.parentElement ? oElement.parentElement : oElement.parentNode;
  }
  return oElement;
}

function GetElementChildByTag(oElement,sMatchTag)
{
	if (!oElement) { return null; }
	var iChildCount = oElement.childNodes.length;
	for (var i=0; i<iChildCount; i++)
	{
		var oEl = oElement.childNodes[i];
		if (oEl && oEl.tagName && oEl.tagName.toUpperCase() == sMatchTag) { return oEl; }
	}
	return null;
}
	
function updateList()
{  
  var oEditor=window.oUtil.oEditor;
	var sel_bookmark = document.getElementById('selBookmark');
	
  while(sel_bookmark.options.length!=0) 
  {
    if(Ext.isIE) { sel_bookmark.options.remove(sel_bookmark.options(0)); }
    else { sel_bookmark.remove(0); }
  }
  for(var i=0;i<oEditor.document.anchors.length;i++)
  {
    if (oEditor.document.anchors[i].name.length > 0)
    {
	    var op = document.createElement("OPTION");
	    op.text=oEditor.document.anchors[i].name;
	    op.value="#"+oEditor.document.anchors[i].name;
	    sel_bookmark.options.add(op);	
    }	
  }
}

function getAnchor(oEditor)
{
  var oEl;
  
  if(Ext.isIE)
  {
		var oSel = getEditorSelection();
    if (oSel.parentElement)	{ oEl = GetElementParentByTag(oSel.parentElement(),"A"); } //text
    else { oEl = GetElementParentByTag(oSel.item(0),"A"); }   //control
  }
  else 
  {
    if (oEditor.getSelection) 
    { 
      //12/30/2008 Ticket 46467 -- commented the line below and changed it to .focusNode
			//var oSel = oEditor.getSelection().anchorNode;
			
			var oSel = oEditor.getSelection().focusNode;
			
			// firefox is selecting the outer TD tag when selecting an image
			if (oSel && oSel.tagName && oSel.tagName.toLowerCase() == 'td') { oEl = GetElementChildByTag(oSel, "A"); }
			else { oEl = GetElementParentByTag(oSel,"A"); }
		}
  }
  return oEl;
}

function checkEditorSelection() 
{
  if(!window.oUtil.obj.checkFocus()) { return; }//Focus stuff
  var oEditor = window.oUtil.oEditor; 
  var oSel = getEditorSelection();
  var sType, sURL, oEl;

	AV.Hyperlink.isImage = false;
	
  if(Ext.isIE) { sType = oEditor.document.selection.type; }
  else
  {
    var node_name = oSel.startContainer.nodeName;
    if(node_name == '#text' || oSel.collapsed) { sType = 'Text'; }
    else { sType = 'Control'; }
  }
	
  updateList();
  //if (_assnId == "14937") { debugger; }
  //If text or control is selected, Get A element if any
  oEl = getAnchor(oEditor);

  //Is there an A element ?
  if (oEl)
  {
    Ext.getCmp('btn_insert').hide();
    Ext.getCmp('btn_ok').show();
    
    // Can't use href becuase IE appends the domain name to it
    sURL = AV.GetAttribute((Ext.isIE ? oEl.outerHTML : oEl.parentNode.innerHTML), 'href')
		
    if(sType != "Control")
    {
      var oSelRange;
      
      //select all of an anchor tag if only part is selected
	    try
	    {			
	      if(Ext.isIE)
	      {
		      oSelRange = oEditor.document.body.createTextRange();
		      oSelRange.moveToElementText(oEl)
		      oSel.setEndPoint("StartToStart",oSelRange);
		      oSel.setEndPoint("EndToEnd",oSelRange);
		      oSel.select();
		    }
		    else
		    {		   
		      if (oEditor.getSelection) 
		      {
            var selection = oEditor.getSelection();
            oSel.selectNode(selection.anchorNode);            
          }
		    }
	    }
	    catch(e){return;}	
	    
	    if(Ext.isIE) { Ext.get("inpDisplay").dom.value = oEl.innerText; }
			else { Ext.get("inpDisplay").dom.value = oEl.textContent; }    	    
    }	
    
    //if it is a control, disable the display input			
    else 
    { 
			AV.Hyperlink.isImage = true;
			Ext.getDom("inpDisplay").value = '[Image Selected]';
			Ext.getDom("inpDisplay").disabled = true; 
		} 				
		
    // bookmark
    if ((sURL.indexOf("#") > -1) && (sURL.indexOf("/") == -1))
    {      
	    Ext.getDom("selBookmark").value = sURL;
	    Ext.getDom("chkNewWin").checked = false;
	    Ext.getDom("rdoBookmark").checked = true;	    
    }
    // link
    else
    {      
	    Ext.getDom("inpURL").value = sURL;
	    Ext.getDom("inpURL_norm").value = (oEl.getAttribute("url") ? oEl.getAttribute("url").replace("&amp;", "&") : "");
	    Ext.getDom("inpURL_popup").value = (oEl.getAttribute("popurl") ? oEl.getAttribute("popurl").replace("&amp;", "&") : "");
	    Ext.getDom("chkNewWin").checked = oEl.getAttribute("popup") == "1" ? true : false;
	    Ext.getDom("rdoLink").checked = true;	    
    }	
    
    //display bookmark or link div (make sure that the correct div is being displayed.
    changeLinkTo();  
    
    //populate proper title textbox
    if (Ext.get('rdoLink').dom.checked) 
    { 
			Ext.getDom("inpURLTitle").value = (oEl.title!=null) ? oEl.title : ""; 
			Ext.getDom("inpBookmarkTitle").value = (oEl.title!=null) ? oEl.title : ""; 
		}
    else { Ext.getDom("inpBookmarkTitle").value = (oEl.title!=null) ? oEl.title : ""; }
  }
	
  // Nothing A element selected
  else
  {
    Ext.getCmp('btn_insert').show();   
    Ext.getCmp('btn_ok').hide();   		            
		
		Ext.getDom('inpURLTitle').value = "";
		
		// check for image
		if(sType == "Control")
		{
			AV.Hyperlink.isImage = true;
			Ext.getDom("inpDisplay").value = '[Image Selected]';
			Ext.getDom("inpDisplay").disabled = true;
		}
		else
		{
			if(Ext.isIE)
			{
				if(oSel.text != '' && oSel.text != 'undefined' && oSel.text != null) { Ext.get('inpDisplay').dom.value = oSel.text; }
			}
			else { Ext.get('inpDisplay').dom.value = oSel.toString(); }
		}
		  
		//if it is a control, disable the display input
    //if(sType == "Control" && Ext.isIE) { Ext.get("inpDisplay").dom.disabled = true; } 
    //else if(sType == "Control" && oSel.toString() == '') { Ext.get("inpDisplay").dom.disabled = true; }
		  
    Ext.getDom('inpURL').value = "";
  }			
}

function getEditorSelection()
{
  var oEditor = window.oUtil.oEditor;
  var oSel;
  
  //IE
  if (oEditor.document.selection && oEditor.document.selection.createRange) 
  {
    oSel = oEditor.document.selection.createRange();    
    
    // remove extraneous HTML tags from selection, also,
    //TICKET 44489 11/3/2008 added '.replace(/\s+$/,"")' to remove trailing spaces from a selection
    //This only fixes links that are fully contained within text (not broken up by html tags). because the findText
    //method call has to be able to find the exact text (without extr html tags)
    
    //if (oSel && oSel.text && oSel.findText) { oSel.findText(oSel.text); oSel.select(); }
    if (oSel && oSel.text && oSel.findText) { oSel.findText(oSel.text.replace(/\s+$/,"")); oSel.select(); }
  }
  //Mozilla
  else if (window.getSelection)   
  {              
    var selection = oEditor.getSelection();
    if (selection.rangeCount > 0) 
    { 
      oSel = oEditor.getSelection().getRangeAt(0); 
                   
      //TICKET 44489 11/3/2008  remove whitespace from end of selection
      //only for text links...if the endContainer is not a #text node, trailing spaces will not be affected
      var whiteSpaceRegex = new RegExp(/\s+$/);                     
      while( whiteSpaceRegex.test(oSel.toString()) ) 
      {                                     
        //makes sure that the endContainer is text
        if( oSel.endContainer.nodeName == '#text' )
        {       
          //if the selection is NOT at the end of a node, change the endOffset to remove the whitespace  
          if(oSel.endOffset > 0)
          { 
            oSel.setEnd(oSel.endContainer, oSel.endOffset-1); 
          } 
          else  //if the selection is at the end of a node, try using the previous text node
          { 
            var newEndContainer = oSel.endContainer.parentNode.previousSibling;
            if( newEndContainer )
            {
              if(newEndContainer.nodeName == '#text')
                oSel.setEnd(newEndContainer, newEndContainer.length-1); 
              else
              { break; }               
            }
            else
            { break; } 
          }
        }
        else
        { break; }
        
      } 
    }
  }
  
  return oSel;
}

function applyHyperlink()
{
  var oEditor = window.oUtil.oEditor;
  var oSel = getEditorSelection();
  var isBookmark = false;
  
  window.oUtil.obj.saveForUndo();
	
	var sURL;

  // Get URL from Hyperlink window
  if(Ext.get('rdoLink').dom.checked) { sURL = document.getElementById("inpURL").value; }
  else 
  {
    var inpBookMark = document.getElementById("selBookmark");
    if(inpBookMark.length > 0)
    {      
      sURL = inpBookMark.options[inpBookMark.selectedIndex].value;
      isBookmark = true;
    }
    else { sURL = ""; }
  }
  
  // Check if selected object is an image
	if (!AV.Hyperlink.isImage)
	{
		var strLinkText = document.getElementById("inpDisplay").value;
	  
		if (strLinkText.length == 0)
		{
			alert('Please enter a value for the Display Text before attempting to insert or update a link.');
			Ext.get("inpDisplay").focus();
			return;
		}

		if(sURL != "")
		{
			if (Ext.isIE)
			{ 
				// check for partially selected A element
				var oEl = getAnchor(oEditor);
				if (oEl)
				{
					var oSelRange = oEditor.document.body.createTextRange();
					oSelRange.moveToElementText(oEl)
					oSel.setEndPoint("StartToStart",oSelRange);
					oSel.setEndPoint("EndToEnd",oSelRange);
					oSel.select();
				}

				//If there is no (text) selection or the Display Text changed, (re)build selection
				if(oSel.text=="" || oSel.text != strLinkText) 
				{
					var oSelTmp = oSel.duplicate();
					oSel.text =  strLinkText ? strLinkText : sURL;
					oSel.setEndPoint("StartToStart",oSelTmp);
					oSel.select();
				}
			}
			else    //Moz
			{
				if(Ext.isGecko)
				{
					var emptySel = false;
					if(oSel.toString()=="" || oSel.toString() != strLinkText) //If no (text) selection or strLinkText changed, then build selection
					{		    
						if (oSel.startContainer.nodeType==Node.ELEMENT_NODE) 
						{
							if (oSel.startContainer.childNodes[oSel.startOffset].nodeType != Node.TEXT_NODE) 
							{ 
								if (oSel.startContainer.childNodes[oSel.startOffset].nodeName=="BR") { emptySel = true; }
								else { emptySel=false; } 
							} 
							else { emptySel = true; }
						} 
						else 
						{ 
							// Check parent
							var oSelParent = oSel.startContainer.parentNode;
							if (oSelParent.nodeType != Node.ELEMENT_NODE) { emptySel = true; }
							// Update achor text
							if (oSelParent.tagName == "A" && oSel.startContainer.nodeType == Node.TEXT_NODE) 
							{ 
								oSel.startContainer.nodeValue = this.edText; 
							}
							else { emptySel = true; }
						}		    		    
					}	    	    
		            
					if (emptySel) 
					{
						var node = oEditor.document.createTextNode(strLinkText);
						oSel.insertNode(node);
						oEditor.document.designMode = "on";
	          
						oSel = oEditor.document.createRange();
						oSel.setStart(node, 0);
						oSel.setEnd(node, strLinkText.length);
	          
						selection = oEditor.getSelection();
						selection.removeAllRanges();
						selection.addRange(oSel);            
					}	  
				}  
			}
		}
	}
		
	if(sURL != "")
	{
		// (Re)create the link in the editor
		oEditor.document.execCommand("CreateLink", false, sURL);
    
		//get A element that was just (re)created   
		oEl = getAnchor(oEditor);
        
		if(oEl)
		{
			//Write title (and target, if a link)
			if(isBookmark)
			{
				var strTitle = document.getElementById("inpBookmarkTitle").value;	     
				if(strTitle.length == 0) oEl.removeAttribute("title",0);
				else oEl.title = strTitle;
			}
			else
			{
				var strTitle = Ext.getDom("inpURLTitle").value;
				if(strTitle.length == 0) oEl.removeAttribute("title",0);
				else oEl.title = strTitle;
	      
				var isPopup = Ext.getDom("chkNewWin").checked;
				var strPopupURL = Ext.getDom("inpURL_popup").value;
				if (isPopup) 
				{ 
				  //*DA* 6/27/2008 added  && sURL.toLowerCase().indexOf('javascript:loadviewer(') == -1 to fix
				  //an issue involving resource center links modified by the new editor that
				  //were created with the old editor (ticket 39961)
				  if (strPopupURL.length == 0 && sURL.toLowerCase().indexOf('javascript:loadviewer(') == -1) 
				  { oEl.target = "_blank"; }
				}
				else { oEl.removeAttribute("target",0);	}
	      
				// New attributes to track popups
				oEl.setAttribute("url", Ext.getDom('inpURL_norm').value);
				oEl.setAttribute("popup", isPopup ? "1" : "0");
				oEl.setAttribute("rc", "1");
				oEl.setAttribute("popurl", strPopupURL);
			}
		}
			
    window.realTime(window.oUtil.oName);   
    window.oUtil.obj.selectElement(0);
  }
  else
  {
    oEditor.document.execCommand("unlink", false, null);//unlink    
    window.realTime(window.oUtil.oName);    
    window.oUtil.activeElement=null;
  }	
	
	AV.Hyperlink.clear();
	AV.Hyperlink.getWin().hide();
}    

function setLinkUrl()
{
  try
  {
    var strURL = Ext.getDom("inpURL_norm").value;
    var strPopupURL = Ext.getDom("inpURL_popup").value;
		
    if(Ext.getDom("chkNewWin").checked && strPopupURL) { Ext.getDom("inpURL").value = strPopupURL; }
    else if(strURL) { Ext.getDom("inpURL").value = strURL; }
  }
  catch(e) {log(e, "setLinkUrl");}
}

//TICKET: 26678 hide "open in new window" when using from messenger
function hideNewWind()	
{
  //if (window.opener.document.location.href.indexOf('/messenger') > -1)
  if (window.document.location.href.indexOf('/messenger') > -1)
  {
    var oNewWindContainer = Ext.getDom('chkNewWindContainer');
    if (oNewWindContainer) { oNewWindContainer.style.visibility = 'hidden'; }
  }
}
