var ubbText;

var Tag = Class.create({
	initialize: function(tagName, enclosedContent, embeddedArg) {
		enclosedContent = enclosedContent || null;
		embeddedArg = embeddedArg || null;
	
		this.tag = '[' + tagName;
		if(embeddedArg) {
			this.tag += '=' + embeddedArg;
		}
		this.tag += ']';
		if(enclosedContent) {
			enclosedContent = enclosedContent.toString();
			this.tag += enclosedContent + '[/' + tagName + ']';
		}
		return this.tag;
	},
	
	toString: function() {
		return this.tag;
	}
});

var Image = Class.create(Tag, {
	initialize: function($super, imageNumber, imageSize) {
		imageSize = imageSize || 1;
		return $super('img', '/file_thumbview_approve.php?size=' + imageSize + '&id=' + imageNumber).tag;
	},
	
	toString: function() {
		return this.tag;
	}
});

function addAttribute(attribute)
{
	if(ubbText.getSelection().length > 0) {
		ubbText.replaceSelection(new Tag(attribute, ubbText.getSelection(), null).tag);
	}
	else {
		alert('please make a selection and try again.');
	}
}

var addBold = addAttribute.curry('b');
var addItalic = addAttribute.curry('i');
var addQuote  = addAttribute.curry('quote');

function addList() {
	lines = ubbText.getSelection();
	lines = lines.split(/\r*\n\r*/).inject([], function(a, v){a.push('[li]' + v + '[/li]'); return a;});
	ubbText.replaceSelection('[list]\n' + lines.join('\n') + '\n[/list]\n');
}

var imageLinkShowing = false;
var lightboxLinkShowing = false;
var linkLinkShowing = false;

/////////////////////////////////////////////////
// Keen sliding panes for Image and Lightbox
// number entries.
function closeDrawers()
{
  drawers = ['image-entry', 'lightbox-entry', 'link-entry'];
  drawers.each(function(d){ try{$(d).hide()} catch(err){} })
}

function revealImageLink()
{
  if(imageLinkShowing){
    Effect.BlindUp($('image-entry'));
  }
  else {
    closeDrawers();
    Effect.BlindDown($('image-entry'));
  }
  imageLinkShowing = !imageLinkShowing;
}

function revealLightboxLink()
{
  console.log("lightbox link is showing: " + lightboxLinkShowing);
  console.log("it is: " + $('lightbox-entry'));
  
  if(lightboxLinkShowing){
    Effect.BlindUp($('lightbox-entry'));
  }
  else {
    closeDrawers();
    Effect.BlindDown($('lightbox-entry'));
  }
  lightboxLinkShowing = !lightboxLinkShowing;
}

function revealLinkLink() {
  if(linkLinkShowing){
    Effect.BlindUp($('link-entry'));
  }
  else {
    closeDrawers();
    Effect.BlindDown($('link-entry'));
  }
  linkLinkShowing = !linkLinkShowing;
}

function getLink(image_number, text)
{
	return (new Tag('url', text, '/file_closeup.php?id=' + image_number)).tag;
}

function formExternalLink(url, text) {
	return (new Tag('url', text, url)).tag;
}

function addLinkLink() {
  lines = ubbText.getSelection();
  if(lines.length > 0) {  // Then there's a selection
    ubbText.replaceSelection(formExternalLink($('link-link-url').value.strip(), lines));
  }
  else {
    ubbText.replaceSelection(formExternalLink($('link-link-url').value.strip(), $('link-link-desc').value.strip()));
  }
}

function getImageLink(imageNumber, imageSize)
{
	if(imageNumber.include('>')) {
		parts = imageNumber.split('>')
		try {
			imageNumber = parts[0]
			linkURL = (parts[1]) ? parts[1] : '';
			return getLink(imageNumber, new Tag('img', linkURL));
		} catch(ex) {
			return '';
		}
	}
	else {
		imageNumber = imageNumber.strip();
		imageSize = imageSize.strip();
		return getLink(imageNumber, new Image(imageNumber, imageSize));
	}
}

function getLightboxLink(imageNumber, lightboxNumber) {
	if(!imageNumber.strip().match(/^\d+$/)) {
		imageRef = new Tag('img', imageNumber);
	}
	else {
		imageNumber = imageNumber.strip();
		imageSize = $('lightbox-image-size').value;
		imageRef = new Image(imageNumber, imageSize);
	}
	return new Tag('url',
											imageRef,
											'/search/lightbox/' + 
											lightboxNumber);
}

function addLightboxLink()
{
  image = $('lightbox-image-number').value.strip();
  lightbox = $('lightbox-number').value.strip();

	image.split(/,\s*/).each(function(i){
		insertLinkText = getLightboxLink(i.strip(), lightbox);
		ubbText.insertBeforeSelection(insertLinkText);
	});
}

function addImageLink()
{
	/**
	 * Handle a single number (iStockphoto image number)
	 * -or-
	 * An image URL (anyplace publicly accessible)
	 * -or-
	 * A comma-separated list comprised of iStockphoto image numbers and image URLs
	 **/
	
	imageNumbers = $('image-image-number').value.split(',');
	insertionArray = [];
	imageNumbers.each(function(i) {
		is = i.strip();
		if(is.match(/^\d+$/)) {
			insertionArray.push(getImageLink(i, $('image_image_size').value));
		}
		else if(is.match(/http:\/\/\S+\./)) {
			insertionArray.push(new Tag('img', is));
		}
		else {
			alert('it does not look like ' + is + ' is an iStockphoto image or a URL');
		}
	});
	ubbText.insertBeforeSelection(insertionArray.join(' '))
}

function showSnippetDrawer() {
	new Ajax.Request('/ubb/list_snippets', {  onComplete: $('snippet-list').toggle()   });
}

function addSnippet() {
	snippet = ubbText.getSelection();
	if(snippet.empty()) {
		alert('can\'t add an empty snippet!');
	}
	else {
		new Ajax.Request('/ubb/add_snippet?snippet=' + encodeURIComponent(snippet));
	}
}

function insertSnippet(e) {
	e.stop();
	elt = e.element();
	alert(elt.tagName);
	if(elt.tagName == 'A') {
		alert(elt.up().firstChild.nodeValue);
	}
}

Control.TextArea.addMethods({
	toHTML: function() {
		ubb_text = this.getValue();
		
		r = ubb_text.gsub(/\[url=?([^\]]+)*\](.+?)\[\/url\]/, function(match) {
			if(!match[1]) {
				url = match[2];
				linkText = match[2];
			}
			else {
				url = match[1];
				linkText = match[2];
			}
			url = (url[0] == '/') ? 'http://www.istockphoto.com' + url : url;
			
			return '<a href="#{url}">#{linkText}</a>'.interpolate({url: url, linkText: linkText});
		});
		
	  r = r.gsub(/\[(\/?)list\]/, '<#{1}ul>');                         // replace list start/end
	
		r = r.gsub(/\[img\](.+?)\[\/img\]/, function(match) {
			imgURL = match[1];
			console.log('image url is: ' + match[1]);
			console.log('regex result is: ' + !imgURL.match(/http/i));
			imgURL = (!imgURL.match(/http/i)) ? 'http://www1.istockphoto.com' + imgURL : imgURL;
			console.log('so image URL should beL ' + imgURL);
			return '<img src="#{url}" />'.interpolate({url: imgURL});
		});

		r = r.replace(/\s*\[quote\]\s*((?:.|\n)+?)\[\/quote\]\s*/, '<div class="quote-style">$1</div>');
	  r = r.gsub(/\[email=([^\]]+)\](.+)\[\/email\]/, '<a href="mailto:#{1}">#{2}</a>');    // replace mailto tags
	  r = r.gsub(/\[(\/?.?.?)(?=\])\]/, '<#{1}>');                        // clean up remaining tags
	  r = r.gsub(/\n/, '<br />');
	
		return r.stripScripts();
	}
})

var contentCache;

function formatPreview(force)
{
	previewText = ubbText.toHTML();
	if(force || !contentCache || previewText != contentCache) {
  	$('preview').update(previewText);
		contentCache = previewText;
	}
	timer = window.setTimeout("formatPreview(false)", 250);
}

document.observe('dom:loaded', function() {
	// Previewing only necessary on index page.
	if($('ubb')) {
		if(window.navigator.userAgent.match(/Firefox\/1\.0/i)) {
			window.location.href = '/ubb/ff1_unsupported';
		}
		ubbText = new Control.TextArea('ubb');
		formatPreview(true);
	}
	
	$$('input', 'select').each(function(link) {
		new Tooltip(link, {mouseFollow:false});
	});
	
	// TODO: Revisit the idea of snippets
	// $('snippet-container').observe('click', insertSnippet);
});

