/**
 * Controls: Link plugin
 *
 * Depends on jWYSIWYG
 *
 * By: Esteban Beltran (academo) <sergies@gmail.com>
 */
(function ($) {
	if (undefined === $.wysiwyg) { throw "wysiwyg.image.js depends on $.wysiwyg"; }
	if (!$.wysiwyg.controls) { 	$.wysiwyg.controls = {}; }
	/*
	* Wysiwyg namespace: public properties and methods
	*/
	$.wysiwyg.controls.link = {
		init: function (Wysiwyg) {
			var self = this, elements, dialog, szURL, a, selection,
				formLinkHtml, formTextLegend, formTextUrl, formTextTitle, formTextTarget;
			formTextLegend  = "Insert Link";
			formTextUrl     = "Link URL";
			formTextTitle   = "Link Title";
			formTextTarget = "_BLANK";

			if ($.wysiwyg.i18n) {
				formTextLegend = $.wysiwyg.i18n.t(formTextLegend, "dialogs.link");
				formTextUrl    = $.wysiwyg.i18n.t(formTextUrl, "dialogs.link");
				formTextTitle  = $.wysiwyg.i18n.t(formTextTitle, "dialogs.link");
				formTextTarget = $.wysiwyg.i18n.t(formTextTarget, "dialogs.link");
			}

			formLinkHtml = 
				'<form class="wysiwyg">'+
				'<label>' + formTextUrl + ': <input type="text" name="linkhref" id="new_url" value=""/></label>' +
				'<label>' + formTextTitle + ': <input type="text" name="linktitle" id="new_url" value=""/></label>' +
				'</form>';

			a = {
				self: Wysiwyg.dom.getElement("a"), // link to element node
				href: "http://",
				title: "",
				target: ""
			};

			if (a.self) {
				a.href = a.self.href ? a.self.href : a.href;
				a.title = a.self.title ? a.self.title : "";
				a.target = a.self.target ? a.self.target : "";
			}

			if ($.fn.dialog) {
				elements = $(formLinkHtml);
				elements.find("input[name=linkhref]").val(a.href);
				elements.find("input[name=linktitle]").val(a.title);
				elements.find("input[name=linktarget]").val(a.target);

				if ($.browser.msie) {
					dialog = elements.appendTo(Wysiwyg.editorDoc.body);
				} else {
					dialog = elements.appendTo("body");
				}
			function getDomain(str) {
			   if (str == null || str.length == 0)
				  return "";
			   
			   str = str.toLowerCase();
			   str = str.replace('http://','');
			   
			   var i = str.indexOf("/");
			   if (i > -1)
				  str = str.substring(0, i);
				  
			   var parts = str.split('.');
			   
			   var len = parts.length;
			   
			   if (len < 3)
				  return str;
			
			   var lastPart = parts[len-1];
			   var secondPart;
					 
			   secondPart = parts[len-2];
			   
			   var two = 2;
			   
			   if (lastPart == "uk" && secondPart == "co")
				  ++two;
			   
			   if (len >= 0)
				  return parts.splice(len-two, two).join('.');
			   
			   return "";
			}

				dialog.dialog({
					modal: true,
					width: '250',
					open: function () { $(this).dialog("option", "title", formTextLegend); },
					buttons: {
						'Insert Link': function(ev, ui) {
							var szURL = $('input[name="linkhref"]', dialog).val(),
								title = $('input[name="linktitle"]', dialog).val(),
								target = formTextTarget;
							if (getDomain(szURL) == 'bakerconsultants.co.uk') {
								var link_target = '_SELF';
							} else {
								var link_target = '_BLANK';
							}
							if (a.self) {
								if ("string" === typeof (szURL)) {
									if (szURL.length > 0) {
										// to preserve all link attributes
										$(a.self).attr("href", szURL).attr("title", title).attr("target", link_target);
									} else {
										$(a.self).replaceWith(a.self.innerHTML).attr("target", link_target);
									}
								}
							} else {
								if (getDomain(szURL) == 'bakerconsultants.co.uk') {
									var link_target = '_SELF';
								} else {
									var link_target = '_BLANK';
								}
								if ($.browser.msie) { Wysiwyg.ui.returnRange();}
								//Do new link element
								selection = Wysiwyg.getRangeText();
								img = Wysiwyg.dom.getElement("img");

								if ((selection && selection.length > 0) || img) {
									if ($.browser.msie) { Wysiwyg.ui.focus(); }
									if ("string" === typeof (szURL)) {
										if (szURL.length > 0) {
											Wysiwyg.editorDoc.execCommand("createLink", false, szURL);
										} else {
											Wysiwyg.editorDoc.execCommand("unlink", false, null);
										}
									}

									a = Wysiwyg.dom.getElement("a");
									$(a).attr("href", szURL).attr("title", title).attr("target", link_target);
								} else if (Wysiwyg.options.messages.nonSelection) {
									window.alert(Wysiwyg.options.messages.nonSelection);
								}
							}
							$(this).dialog("close");
						},
						Cancel: function() {
							$(this).dialog("close");
						}
					},
					close: function (ev, ui) {
						dialog.dialog("destroy");
					}
				});
			} else {
				if (a.self) {
					szURL = window.prompt("URL", a.href);

					if ("string" === typeof (szURL)) {
						if (szURL.length > 0) {
							$(a.self).attr("href", szURL);
						} else {
							$(a.self).replaceWith(a.self.innerHTML);
						}
					}
				} else {
					//Do new link element
					selection = Wysiwyg.getRangeText();
					img = Wysiwyg.dom.getElement("img");

					if ((selection && selection.length > 0) || img) {
						if ($.browser.msie) {
							Wysiwyg.ui.focus();
							Wysiwyg.editorDoc.execCommand("createLink", true, null);
						} else {
							szURL = window.prompt(formTextUrl, a.href);

							if ("string" === typeof (szURL)) {
								if (szURL.length > 0) {
									Wysiwyg.editorDoc.execCommand("createLink", false, szURL);
								} else {
									Wysiwyg.editorDoc.execCommand("unlink", false, null);
								}
							}
						}
					} else if (Wysiwyg.options.messages.nonSelection) {
						window.alert(Wysiwyg.options.messages.nonSelection);
					}
				}
			}

			$(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg");
		}
	};

	$.wysiwyg.createLink = function (object, szURL) {
		if ("object" !== typeof (object) || !object.context) {
			object = this;
		}

		if (!object.each) {
			console.error($.wysiwyg.messages.noObject);
		}

		return object.each(function () {
			var oWysiwyg = $(this).data("wysiwyg"),
				selection;

			if (!oWysiwyg) {
				return this;
			}

			if (!szURL || szURL.length === 0) {
				return this;
			}

			selection = oWysiwyg.getRangeText();

			if (selection && selection.length > 0) {
				if ($.browser.msie) {
					oWysiwyg.ui.focus();
				}
				oWysiwyg.editorDoc.execCommand("unlink", false, null);
				oWysiwyg.editorDoc.execCommand("createLink", false, szURL);
			} else if (oWysiwyg.options.messages.nonSelection) {
				window.alert(oWysiwyg.options.messages.nonSelection);
			}
		});
	};
})(jQuery);

