/*global jQuery,SWFUpload*/
// provides an HTML entity escaping function to String prototype
String.prototype.htmlentitize = function() {
	return this.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");
};

// provides a trim function to the String prototype
String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

// converts all whitespace to a single space character
String.prototype.spacify = function() {
	return this.replace(/\s+/g, " ");
};

(function($) {
	$.fn.adWidget = function(options) {
		// overrides defaults with specified options
		var params = $.extend($.fn.adWidget.defaults, options);
		
		return this.each(function() {
			// fetch container and set the container's border
			var container = $(this).css({ borderColor: params.borderColor });
			
			// fetch the form token
			var token = $('input[name=' + params.tokenFieldName + ']').val();
			
			// fetch title and set color
			var title = container.find(".title").css({ color: params.titleColor });
			var title_text;
			var title_field = $('<input type="hidden" class="hidden" name="' + params.titleFieldName.htmlentitize() + '" id="' + params.titleFieldName.htmlentitize() + '" value="' + title.text().htmlentitize() + '"/>').appendTo(container);
			
			// fetch description and set color
			var description = container.find(".description").css({ color: params.descriptionColor });
			var description_text;
			var description_field = $('<input type="hidden" class="hidden" name="' + params.descriptionFieldName.htmlentitize() + '" id="' + params.descriptionFieldName.htmlentitize() + '" value="' + description.text().htmlentitize() + '"/>').appendTo(container);
			
			// fetch image
			var image = container.find(".image>img");
			var image_container = container.find(".image");
			
			// set tagline colous
			container.find(".tagline").css({ backgroundColor: params.borderColor, color: params.taglineColor }); 
			
			// set up the pointer on the clickable elements
			title.add(description).add(image_container).css({
				cursor: "pointer"
			}).hover(
				function() {
					$(this).addClass("hover");
				},
				function() {
					$(this).removeClass("hover");
				}
			);
			
			
			// wrap the contents of the title and description with span elements
			title.html("<span>" + title.text() + "</span>");
			title_text = title.find("span");
			title_text.text(params.titleText);
			title_field.val(params.titleText);
			description.html("<span>" + description.text() + "</span>");
			description_text = description.find("span");
			description_text.text(params.descriptionText);
			description_field.val(params.descriptionText);
			
			// creates a popout textarea which overlays the original text
			var createPopout = function(text) {
				return $('<textarea class="popout-field" cols="20" rows="3">' + String(text).htmlentitize() + '</textarea>');
			};
			
			// title and description handler
			title.add(description).click(function() {
				var element = $(this);
				var element_text = element.find("span");
				var edit = createPopout(element_text.text());
				
				// get the dimensions related to this element
				var left = element.offset().left - 1 + "px";
				var top = element.offset().top + "px";
				var width = element.width() + 2 + "px";
				var height = element.height() + "px";
				
				// set the relevant CSS 
				edit.appendTo("body").css({
					position: "absolute",
					left: left,
					top: top,
					width: width,
					height: height,
					fontWeight: element.hasClass("title")? "bold": "normal"
				});
				
				// focus and set handlers
				edit.queue(function() {
					var maxChars = element.hasClass("title")? params.titleLength: params.descriptionLength;
					
					var publishText = function() {
						element_text.text($(this).val().trim().spacify() || params.defaultText);
						$(this).remove();
						element.removeClass("hover");
						if(element.hasClass("title")) {
							title_field.val(element_text.text());
						} else {
							description_field.val(element_text.text());
						}
						return false;
					};
					
					// blur event executes text change
					edit.blur(publishText);
					
					// listen for keypresses, catch "enter" as published
					edit.keypress(function(event) {
						if(event.which === 13) { edit.blur(); return false; }
						if(edit.val().length > maxChars) { edit.val(edit.val().slice(0, maxChars)); }
					});
					
					edit.select().focus();
				});
				edit.click(function() { return false; });
				return false;
			});
						
			// attach the titles to the appropriate elements
			title.attr("title", params.titleHoverMessage);
			description.attr("title", params.descriptionHoverMessage);
			image.attr("title", params.imageHoverMessage);
		});
	};
	
	$.fn.adWidget.defaults = {
		titleHoverMessage: "Click to edit title",
		descriptionHoverMessage: "Click to edit description",
		imageHoverMessage: "Click to change the ad image",
		defaultText: "Click to edit",
		titleText: "Lorem Ipsum Dolor Sit",
		descriptionText: "In hac habitasse platea dictumst. Mauris dolor. Sed hendrerit.",
		borderColor: "#00A6C7",
		backgroundColor: "#ffffff",
		titleColor: "#333333",
		descriptionColor: "#333333",
		taglineColor: "#ffffff",
		titleLength: 30,
		descriptionLength: 70,
		titleFieldName: "title",
		descriptionFieldName: "description",
		tokenFieldName: "token",
		uploadTarget: "http://localhost/image-upload.php", // MUST be absolute path
		initialImage: "images/default-ad-image.png",
		imageTarget: "get-image/%TOKEN%/"
	};
})(jQuery);

