// UI - specific functions
jQuery.fn.extend({
	// roundCorners inserts the HTML and CSS necessary to make 
	// our boxes round.
	roundCorners: function() {
		var completedClassName = 'roundCornered';
		var elements = this.not('.' + completedClassName);
		console.log('roundCorners called on ' + this.size() + ' elements, and there are only ' + elements.size() + ' that we need to work on.');
		// jQuery functions return themselves for chaining purposes.
		if (elements.size() == 0) return this;
		// add the style sheet for rounding if it doesn't exist
		if (jQuery('link#roundedBoxes').size() == 0) {
			jQuery('head').append('<link id="roundedBoxes" rel="stylesheet" href="/stylesheets/pageWrapper/roundedBox.css" type="text/css" media="screen, print" />');
		}
		elements.prepend('<div class="boxTop"><div class="cornerLeft"></div><div class="cornerRight"></div></div>');
		elements.append('<div class="boxBottom"><div class="cornerLeft"></div><div class="cornerRight"></div></div>');
		// Add the completed class so we can ensure we don't get the same guys twice
		elements.addClass(completedClassName);
		// Find all secondary boxes within these and add the class chain for display purposes
		elements.filter('.secondaryBox').addClass('chain');
		// ...again return our findings for chaining purposes
		return this;
	},
	// This appends the current window to each of the found elements
	// Used mainly for MyIdealist/Login
	appendRedirect: function() {
		var location = window.location.toString();
		return this.each(function() {
			this.href += this.href.indexOf('?') > 0 ? '&amp;' : '?';
			this.href += 'redirect=' + escape(location);
			console.log('appendRedirect appended successfully and href is now ' + this.href);
		});
	},
	//This makes the selection the rss feed for the current document
	//using special head parameters
	markAsRssFeed: function() {
		return this.each(function() {
			var rss = this.href;
			var text = jQuery(this).text();
			jQuery('head').append('<link rel="alternate" type="application/rss+xml" title="' + escape(text) + '" href="' + rss + '" />');
			console.log('markAsRssFeed is marking ' + rss + ' (' + text + ')');		
		});
	},
	//This is used create proper XHTML without needing to add a separator to the dictionary list.
	addDLRowSeparators: function() {
		this.addDLRowSeparatorsWithClass();
	},	
	addDLRowSeparatorsWithClass: function(additionalRowClass) {
		console.log('addDLRowSeparatorsWithClass(' + additionalRowClass + ') called on ' + this.length + ' dictionary lists.');
		var rowSeparatorClassName = 'break';
		//Find all dd elements that are not of the row separator class and add the separator with the class after each one.
		this.find('dd').not('.' + rowSeparatorClassName).after(jQuery('<dd>').addClass(rowSeparatorClassName).addClass(additionalRowClass));		
	},
	//This is used in Org::Suggest
	orgSuggest: function(suggestComponent) {
		return this.each(function() {
			console.log('orgSuggest was setup on #' + this.id + ' for component ' + suggestComponent.bindingName);
			// wire the component back to the text field too
			suggestComponent._textField = this;
			// Set the autocomplete to false
		    jQuery(this).attr('autocomplete', 'off');
			jQuery(this).bind('keyup', function(e) {
				//Ignore arrow keys which are 37 through 40
				if (e.keyCode >= 37 && e.keyCode <= 40) {
					return false;
				}
				//Ignore the enter as a valid key
				if (e.keyCode == 13) {
					return false;
				}
				var valBefore = this.value;
				var inputId = this.id;
				//This little trick will save us from refreshing that page if they've typed more
				// without waiting. 
				setTimeout(function() {
					var valCurrent = jQuery('#' + inputId).val();
					if (valBefore == valCurrent) {
						suggestComponent.reloadWithActionAndExtraQueryKeyValuePairs('search', {'partial-name': valCurrent});
					}
				}, 600);				

			});
		});
	},
	// This throws a warning right after the input if the words match anything in the field's value
	warnOnWordsWithMessage: function(words, message) {
		var suffix = 'warnOnWords';
		return this.each(function() {
			console.log('warnOnWordsWithMessage was setup on #' + this.id + ' for [' + words + '] with message ' + message);
			jQuery(this).blur(function() {
				//console.log('Blur called checking...');
				var key = this.id + '-' + suffix;
				var val = jQuery(this).val().toLowerCase();
				for (var i = 0; i < words.length; i++) {
					var word = words[i].toLowerCase();
					//console.log('Is ' + word + ' in ' + val);
					if (val.indexOf(word) >= 0) {
						// As long as we haven't warned them already...
						if (jQuery('#' + key).length == 0) {
							var content = jQuery("<div>").addClass("warning").attr("id", key).html(message);
							jQuery(this).after(content);
						}
						return;
					}
				}
				jQuery('#' + key).remove();
			});
		});
	}	
});