var fb_apikey = '933c10c2c4e056055f79ad9acaaba9ac';
var loginCallback;
var loginWindow;

function requireLogin(onComplete) {
	var xPos = (window.screen.width / 2) - 225;
	var yPos = (window.screen.height / 2) - 180;
	var callbackUrl = window.location.protocol + "//" + window.location.host + '/user/auth/callback/popup';
	
	if (isLoggedIn) {
		return true;
	};

	jQuery.blockUI({
		message: '<h2 style="margin: 10px;">Logging you in. Please check the popup window.</h2>'
	});
	
	loginWindow = window.open('https://graph.facebook.com/oauth/authorize?client_id=' + fb_apikey +
		'&redirect_uri=' + callbackUrl + '&display=popup',
		'_blank',
		'toolbar=0,status=1,location=0,menubar=0,scrollbars=0,width=450,height=360,resizable=0,' +
		'left=' + xPos + ',top=' + yPos + ',screenX=' + xPos + ',screenY=' + yPos
	);
	
	loginWindow.focus();
	loginCallback = function () {
		jQuery.unblockUI();
		isLoggedIn = true;
		onComplete();
	};
	
	return false;
};

function loginComplete() {
	loginWindow.close();
	loginCallback();
};

$(document).ready(function () {
	$('input.autoclear,textarea.autoclear').autoclear();
	
	$('#pri-nav li').bind({
		mouseenter: function () {
			var self = $(this),
				div = self.children('div.sub-nav:first');
			
			if (div.children('ul:first').children('li').size()) {
				div.css('top', self.offset().top + self.outerHeight() - 2).stop().fadeTo(250, 1);
			};
		},
		mouseleave: function () {
			var self = $(this);
			
			self.children('div.sub-nav:first').stop().fadeTo(250, 0, function () {
				$(this).hide();
			});
		}
	});

	if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
		$('ul.image-wall a').bind('click', function (event) {		
			var self = $(this);
			var photos = self.data('photos');
			var chosen = self.attr('href');
			
			function showGallery(photos, which) {
				jQuery.slimbox(photos || [], which || 0, {
					loop: true,
					resizeDuration: 1,
					imageFadeDuration: 200,
					captionAnimationDuration: 200
				});
			};

			if (photos) {
				showGallery(photos, photos.findOne(function (a) {
					return a[0] == chosen;
				}));
			} else {
				jQuery.ajax({
					url: '/photos/photos/index/',
					method: 'get',
					dataType: 'json',
					success: function (response) {
						if (response.success) {
							photos = response.photos;
							
							self.data('photos', photos);
							
							showGallery(photos, photos.findOne(function (a) {
								return a[0] == chosen;
							}));
						};
					}
				});
			};
			
			event.preventDefault();
		});
		
		$("a[rel^='lightbox']").slimbox({
			loop: true
		}, null, function(el) {
			return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
		});
	};

	$('#flash').css('left', ($(window).width() / 2) - ($('#flash').outerWidth() / 2)).delay(1000).fadeTo(1000, 1).delay(5000).fadeTo(1000, 0);
	
	// Comment magic.
	$('ul.comments form.comment-form textarea').bind('focus', function () {
		$(this).attr('rows', 2).growfield();
	});
	
	$('ul.comments').each(function () {
		var self = $(this),
			extra = self.children('li.comment:gt(3)').hide();
		
		if (extra.size()) {
			self.children('li.comments-expand').show().find('a span:first').html(extra.size());
		};
	});

	$('ul.comments li.comments-expand a').bind('click', function () {
		var self = $(this);
		
		self.closest('li').hide();
		self.closest('ul').children('li.comment:hidden').slideDown();
		
		return false;
	});

	$('form.require-login').live('submit', function (event) {
		var self = $(this);
		var submitButton = self.find('input:submit').attr('disabled', true);
		
		if (!requireLogin(function () {
			self.trigger('submit');
			submitButton.attr('disabled', false).trigger('click');
		})) {
			event.preventDefault();
		};
	});

	$('a.require-login').live('click', function () {
		alert("a.require-login: This is out of date");
		
		return false;
		
		/**
		
				Needs refactoring to use the new FB system
		
		var target = $(this).attr('href') || window.location.href;
		
		if (!isLoggedIn) {
			if (FB.Connect) {
				FB.Connect.requireSession(function () {
					window.location.href = "/user/auth/login/?redirect=" + target;
				});
			} else {
				window.location.href = "/user/auth/login/?redirect=" + target;
			};
			
			return false;
		};
		*/
	});

	$('form.ajax').live('submit', function () {
		var self = $(this);
		
		jQuery.ajax({
			dataType: 'json',
			type: self.attr('method'),
			url: self.attr('action'),
			data: self.serialize(),
			complete: function () {
				self.find('input:submit:first').attr('disabled', false);
			},
			success: function (response) {
				if (response.success && response.content) {
					$(response.selector || self).replaceWith(response.content);
				};
			}
		});
		
		return false;
	});

	$('form').bind('submit', function () {
		$(this).find('input:submit:first').attr('disabled', true);
	});
});

/**
 * Merch Stuff
 *
 * @author Matt
 */
$(document).ready(function () {
	function getSampleDiv() {
		var div = $('#merch-sample'),
		sample,
		p;
		
		if (!div.size()) {
			div = $('<div />').addClass('color-hover').attr('id', 'merch-sample').appendTo('body');
			sample = $('<div />').addClass('sample');
			p = $('<p />');
			
			$('<div />').addClass('inner').append(sample).append(p).appendTo(div);
		};
		
		return div;
	};

	$('ul.merch ul.images').hide();
	$('ul.merch ul.colors li.color').bind({
		mouseenter: function () {
			var self = $(this),
				position = self.position(),
				bottom = position.top + self.outerHeight(),
				center = position.left + self.outerWidth() * 0.5,
				sample = getSampleDiv();

			sample.find('.sample:first').css('backgroundColor', self.css('backgroundColor'));
			sample.find('p:first').html(self.attr('class').split(" ")[1].replace(/-/g,' ').capitalizeWords());
			sample.css({
				top: bottom -5 ,
				left: center - (0.5  * sample.outerWidth())
			});
			sample.show();
		},
		mouseleave: function () {
			getSampleDiv().hide();
		}
	});
});

$(document).ready(function ($) {
  // TinyMce
  tinyMCE.init({
      mode: 'specific_textareas',
      editor_selector: 'tiny_mce',
      width:544,
      height:200,
      theme : 'advanced',
      theme_advanced_toolbar_align : "left",
      theme_advanced_toolbar_location : 'top',
      theme_advanced_buttons1 : 'bold,italic,|,removeformat,bullist,numlist,|,link,unlink',
      theme_advanced_buttons2: '',
      theme_advanced_buttons3: '',
      plugins : 'paste',
      paste_remove_styles: true,
      paste_retain_style_properties: ''
  });	  
});

Array.prototype.findOne = function (func, val) {
	for (var i = this.length; i--;) {
		if (func(this[i])) {
			return val ? this[i] : i;
		};
	};
};

String.prototype.capitalizeWords = function () {
	var str = this.split(" "),
	i = str.length;

	for (;i--;) {
		str[i] = str[i].charAt(0).toUpperCase() + str[i].substring(1);
	};

	return str.join(" ");
};

function textile(button) {
	var current = $('textarea#body').val();
	var range = $('textarea#body').getSelection();
	
	current = current.replace(/(\S{range.start})/g,"$1*");

	var result;

	if (button == 'bold') {
		result = current.substr(0, range.start) + "*" + current.substr(range.start, range.length) + "*" + current.substr(range.end) ;
	}
	else if (button == 'italic') {
		result = current.substr(0, range.start) + "_" + current.substr(range.start, range.length) + "_" + current.substr(range.end) ;
	}
	else if (button == 'underline') {
		result = current.substr(0, range.start) + "+" + current.substr(range.start, range.length) + "+" + current.substr(range.end) ;
	}
	else if (button == 'link') {
		var link = prompt("Enter link URL:");
		if (link != null && link != "")
			result = current.substr(0, range.start) + "\"" + current.substr(range.start, range.length) + "\":" + link + current.substr(range.end);
		else
			result = current;
	}
	else if (button == 'image') {
		var image = prompt("Enter image URL:");
		if (image != null && image != "")
			result = current.substr(0, range.start) + "!" + image + "!" + current.substr(range.start);
		else
			result = current;
	}
	
	$('textarea#body').val(result);
	
	return false;
}

function popitup(url) {
	newwindow=window.open(url,'name','height=843,width=1192');
	if (window.focus) {newwindow.focus()}
	return false;
}
