/* Functions for the advlink plugin popup */

tinyMCEPopup.requireLangPack();

function preinit() {
	var url;

	if (url = tinyMCEPopup.getParam("external_link_list_url"))
		document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
}

function init() {
  
	var formObj = document.forms[0];
	var ed = tinyMCEPopup.editor;
	var node = ed.selection.getNode();

	node = ed.dom.getParent(node, "A");
	
	if(node != null && typeof node != 'undefined' && node.nodeName == 'A'){
	  formObj.insert.value = tinyMCEPopup.getLang('update', 'Insert', true); 
	  
	  var url = ed.dom.getAttrib(node,"href");
	  var txt = node.firstChild.nodeValue;
	  
	  formObj.urlField.value = url;
	  formObj.descField.value = txt;
	}else{
	  var selTxt = ed.selection.getContent();
	  
	  if(isURL(selTxt)){
	    formObj.urlField.value = selTxt.replace(/^\s*/,"");
	  }
	  if(selTxt.length > 0){
	    document.getElementById("urlDescription").style.visibility = "hidden";
	  }	  
	  formObj.descField.value = selTxt;
	  
	}
	
	
}
function insertAction() {
	var formObj = document.forms[0];
	var ed = tinyMCEPopup.editor;
	var node = ed.selection.getNode()

	if (node && node.nodeName == 'A') {
		ed.dom.setAttrib(node, "href", document.getElementById("urlField").value);
		node.firstChild.nodeValue = document.getElementById("descField").value;
	}else {
		ed.execCommand('mceInsertContent', false, '<a href="'+formObj.urlField.value+'">'+formObj.descField.value+'</a>', {skip_undo : 1});
		ed.undoManager.add();
	}
	
	tinyMCEPopup.close();
}

function isURL(str){
  if(str.match(/^http(s){0,1}:\/\//) || str.match(/^\s*www.*\..+/)){
    return true;
  }
  
  return false;
}

// While loading
preinit();
tinyMCEPopup.onInit.add(init);
