/**
 * falklands_app
 *
 * site-wide javascript
 */

var testEl;

$(document).ready(function() {
	var header_status = $.cookie('fitb_header_status');

	$('a[rel=external]').click(function() {
		window.open($(this).attr('href'));
		return false;
	});


	//initialise the jQuery Modal plugin
	$('#modal').jqm({closeClass:'jqmClose'});

	$('body').addClass('jsok');

	// generic ajax form submit function
	$('body.jsok #modal form').live('submit', function() {
		var href = $(this).attr('action');
		var postData = {};
		var submitted = $(this).find('input, select, textarea');
		submitted.each(function() {
			postData[this.name] = this.value;
		});

		// submit the form data via Ajax
		$.ajax({
			type:			postData['_method'],
			url:			href,
			data:			postData,
			success:	function(result) {
				var res = eval('(' + $.trim(result) + ')');
				if (res.status == 1)
				{
					$('#modal').jqmHide();
				} else {
					$('#modal > div').replaceWith(result);
				}

			}
		});

		return false;
	});

	$('a.confirm').click(function() {
		if(confirm('Are you sure?')) {
			return true;
		} else {
			return false;
		}
	});

	$('a.lang_switch').click(function() {
		$(this).next('.sub').slideToggle('fast');

		return false;
	});

	$('body').click(function() {
		$('#main_navigation li.container.active > a').click();
		return true;
	});

	$('#page_header #header_image li').hover(function() {
		$(this).children('.header_img_info').fadeIn('fast');
		$(this).children().children('.image_controls:not(.off)').fadeIn('fast');
	}, function() {
		$('.header_img_info').fadeOut('fast');
		$(this).children().children('.image_controls:not(.off)').fadeOut('fast');
	});

	$('#page_header #header_image').cycle({
		fx: 'fade',
		timeout: 8000,
		speed: 1000,
		pause: true,
		next: 'a.next',
		prev:	'a.prev'
	});

	$('.cycler').cycle({
		fx: 'fade',
		timeout: 4000,
		speed: 2000,
		next: 'a.cnext',
		prev: 'a.cprev'
	});

	$('a.toggle_header').click(function() {
		var closed = $('#page_header').hasClass('closed');
		if(closed) {
			$('#header_image').animate({'height': '248px'}, 500);
			$('#main_navigation').animate({'top': '240px'}, 500);
			$('#search').animate({'top': '239px'}, 500);
			$('#breadcrumb').animate({'top': '245px'}, 500);
			$('#page_header').animate({'height': '378px'}, 500);
			$(this).html('close');
			$(this).addClass('open');
			$(this).removeClass('closed');
			$('#page_header').removeClass('closed');
			$.cookie('fitb_header_status', 'open', { expires: 7, path: '/' });
		} else {
			$('#header_image').animate({'height': '9px'}, 500);
			$('#main_navigation').animate({'top': '2px'}, 500);
			$('#search').animate({'top': '0'}, 500);
			$('#breadcrumb').animate({'top': '5px'}, 500);
			$('#page_header').animate({'height': '140px'}, 500, 'linear', function() {
				$('#page_header').addClass('closed');
				$.cookie('fitb_header_status', 'closed', { expires: 7, path: '/' });
			});

			$(this).html('open');
			$(this).addClass('closed');
			$(this).removeClass('open');
		}

		return false;
	});

	$('a.expand').click(function() {
		if($(this).next().hasClass('closed')) {
			$(this).next().slideDown('fast').removeClass('closed');
			$(this).children('img').attr('src', '/img/icons/arrow_state_grey_collapsed.png');
			return false;
		} else {
			$(this).next().slideUp('fast').addClass('closed');
			$(this).children('img').attr('src', '/img/icons/arrow_state_grey_expanded.png');
			return false;
		}
	});

	// section / category sub navigation tree
	$('#section_nav li.full:not(.active) ul.subcontent').hide();
	$('#section_nav > li.full:not(.active) > a').click(function() {
		$(this).parent().children('ul.subcontent').slideToggle('fast');
		return false;
	});

	// sidebar
	$('div.sidebar_section').hide();
	$('div.sidebar_section.active').slideDown('fast');
	$('h3.sidebar_title').click(function() {
		if($(this).hasClass('active')) {
			// do nothing
		} else {
			$('#admin_sidebar h3.active').removeClass('active');
			$('#admin_sidebar .sidebar_section.active').slideUp('fast').removeClass('active');
			$(this).addClass('active');
			$(this).next().slideDown('fast').addClass('active');
		}
	});

	// side-bar nav trees
	$('.container .sub_cats, .container .sub_list').hide();
	$('.container > a').toggle(function() {
		$(this).siblings('.sub_cats, .sub_list').slideDown('fast');
		$(this).css('background-image', 'url(/img/icons/admin/8-arrow-down.png)');
		return false;
	}, function() {
		$(this).siblings('.sub_cats, .sub_list').slideUp('fast');
		$(this).css('background-image', 'url(/img/icons/admin/8-em-plus.png)');
		return false;
	});

	/**
	 * asset image stuff
	 *
	 * TODO: this only works for images atm - needs to work with all asset types
	 */
	$('#page_content img[rel=asset]').each(function(i, el) {
		var aw = $('<div class="asset"></div>');
		aw.height($(el).height());
		aw.width($(el).width());
		aw.css('float', $(el).css('float'));
		aw.css('margin-top', $(el).css('margin-top'));
		aw.css('margin-right', $(el).css('margin-right'));
		aw.css('margin-bottom', $(el).css('margin-bottom'));
		aw.css('margin-left', $(el).css('margin-left'));
		$(el).wrap(aw);
		$(el).after('<img src="/img/icons/arrow_state_grey_collapsed.png" width="16" height="16" class="asset_overlay" />');
	});

	$('.asset').live('click', function() {
		var overlay = $(this).children('.asset_overlay');
		if(!overlay.hasClass('open')) {
			overlay.addClass('open');
			overlay.attr('src', '/img/icons/arrow_state_grey_expanded.png');
			var asset_id = overlay.siblings('*[rel=asset]').attr('id');
			var asset_info = $('<div class="asset_info" id="asset-' + asset_id + '"></div>');
			asset_info.height($(this).height() / 4);
			asset_info.width($(this).width() - 26);
			asset_info.append('<ul class="asset_links"><li><a class="asset_view" href="/images/viewasset/' + asset_id + '/600">View</a></li><li><a class="scrap_add" href="#">Add to Scrapbook</a></li><li><a class="asset_send" href="/images/sendpostcard/' + asset_id + '/1">Send to a friend</a></li></ul>');
			overlay.before(asset_info);
		} else {
			overlay.siblings('.asset_info').remove();
			overlay.attr('src', '/img/icons/arrow_state_grey_collapsed.png');
			overlay.removeClass('open');
		}
	});

	// view an asset pop-up
	// TODO: only works for images atm
	$('a.asset_view').live('click', function() {
		$('#activity_indicator').show();
		var image_href = $(this).attr('href');
		var asset_id = $(this).parent().parent().parent('.asset_info').attr('id');
		asset_id = asset_id.split('-')[1];

		$.ajax({
			type: 'GET',
			url: '/images/viewmeta/' + asset_id + '/byasset:1',
			success: function(result) {
				$('#activity_indicator').hide();
				var asset = eval("(" + result + ")");
				var title = '<h2>' + asset.title + '</h2>';
				var desc = '<p>' + asset.desc + '</p>';
				var copyright = '<p class="copyright">Image by ' + asset.meta.photographer + ' / &copy; ' + asset.meta.copyright + '</p>';
				$('#modal').html('<img class="jqmClose" src="/img/icons/22_close.png" /><img class="asset" src="/images/viewasset/' + asset_id + '/600" />' + title + desc + copyright);
				var scrollPosition = $(window).height() + $(window).scrollTop();
				$('#modal').css('top', scrollPosition - $(window).height() + $(window).height() * 0.05);
				$('#modal').jqmShow();
			}
		});

		return false;
	})

	// send an asset pop-up
	// TODO: only works for images atm
	$('a.asset_send').live('click', function() {
		$('#activity_indicator').show();
		var asset_id = $(this).parent().parent().parent('.asset_info').attr('id');
		asset_id = asset_id.split('-')[1];

		$.ajax({
			type: 'GET',
			url: '/images/sendpostcard/' + asset_id + '/1',
			success: function(result) {
				$('#activity_indicator').hide();
				//TODO: can this be refactored so it happens on any modal window opening?
				var scrollPosition = $(window).height() + $(window).scrollTop();
				$('#modal').css('top', scrollPosition - $(window).height() + $(window).height() * 0.05);
				$('#modal').html('<img class="jqmClose" src="/img/icons/22_close.png" />' + result).jqmShow();
			}
		});
		return false;
	})

	// add an asset to the scrapbook
	$('a.scrap_add').live('click', function() {
		$(this).parent().parent().parent().parent().effect("transfer", { to: "div#scrapbook" }, 500);
		$('#scrap_count').html(parseInt($('#scrap_count').text()) + 1);

		return false;
	});

	// add a page to the scrapbook
	$('#scrapbook #scrap_tools #bookmark a').click(function() {
		$.ajax({
			type: 'GET',
			url: $(this).attr('href'),
			success: function(result) {
				$('#scrap_count').text(result);
			}
		});

		return false;
	})

	// asset popup menu controls
	$('a.popup_control').toggle(function() {
		$(this).parent().animate({height: '100px'}, 300);
		$(this).siblings('.image_controls').hide();
		$(this).css({'background-image': 'url(/img/icons/less.png)'});
	}, function() {
		$(this).parent().animate({height: '0'}, 300);
		$(this).siblings('.image_controls').show();
		$(this).css({'background-image': 'url(/img/icons/more.png)'});
	});

	// add select all in a text box on focus
	$("input[type=text], input[type=password]").focus(function() {
		this.select();
	});

	// add rounded corners to top navigation (for IE / Opera)
	$('#top_navigation > li').rounded(8, 1, '/img/corners/top_tab_', false, true, 0, 0, 0, 3);

	// language-select
	$('#top_navigation li.container > a').toggle(function() {
		return false;
	}, function() {
		return false;
	});

	$('input, textarea').focus(function() {
		$(this).parent('.input').addClass('active');
	});

	$('input, textarea').blur(function() {
		$(this).parent('.input').removeClass('active');
	});

	$(".tabbed").tabs();

	$(".datepicker").datepicker({
		dateFormat: 'yy-mm-dd 00:00:00',
		altFormat: 'yy-mm-dd'
	});

	$('form#compentry div.comp_entry_cat').css('height', '275px');

});

// fairly nasty but effective browser sniffing
(function($) {
	var userAgent = navigator.userAgent.toLowerCase();
	$.browser = {
		version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
		safari: /webkit/.test( userAgent ),
		opera: /opera/.test( userAgent ),
		msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
		mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
	};
})(jQuery);

// add additional "corner" elements to a container for rounded corners
jQuery.fn.rounded = function(radius, border_width, style, top, bottom, offset_t, offset_r, offset_b, offset_l) {
	if($.browser.opera || $.browser.msie) {
		if(top) {
			$(this).prepend('<div class="tl"></div><div class="tr"></div>');
		}

		if(bottom) {
			$(this).append('<div class="bl"></div><div class="br"></div>');
		}

		//if(!/^(left|right)$/.test($(this).css("float"))) {
			$(this).css({
				//'padding' : border_width,
				'position'	: 'relative'
			});
		//}

		$(this).children('.tl, .tr, .bl, .br').css({
			'width': radius + 'px',
			'height': radius + 'px',
			'position': 'absolute'
		});

		$(this).children('.tl').css({
			'background': 'transparent url(' + style + 'tl.png) top left no-repeat',
			'top': offset_t + 'px',
			'left': offset_l + 'px'
		});

		$(this).children('.tr').css({
			'background': 'transparent url(' + style + 'tr.png) top left no-repeat',
			'top': offset_t + 'px',
			'right': offset_r + 'px'
		});

		$(this).children('.bl').css({
			'background': 'transparent url(' + style + 'bl.png) top left no-repeat',
			'bottom': offset_b + 'px',
			'left': offset_l + 'px'
		});

		$(this).children('.br').css({
			'background': 'transparent url(' + style + 'br.png) top left no-repeat',
			'bottom': offset_b + 'px',
			'right': offset_r + 'px'
		});
	}
};


/**
 * a very quick and dirty inline content editor - uses contentEditable property
 */
$.fn.inlineEditable = function(options) {
	if(this.length < 1) {
		return;
	}

	var defaults = {
		editingClass: 'editing',
		buttonText: 'Update Content',
		showEditBar: true
	};

	$.extend(defaults, options);

	return this.each(function() {
		if(null != options.triggerElement) {
			options.triggerElement.remove();
		}

		var el = $(this);
		var original = el.html();
		var controller = el.get(0).id.split('-')[0];
		var field = el.get(0).id.split('-')[1];
		var id = el.get(0).id.split('-')[2];

		if(this.contentEditable == "true") {
			return this;
		}

		var editBar = $('<div id="edit_bar"> \
							 <input title="Make selected text bold" id="bold" class="button" type="button" value="Bold" /> \
							 <input title="Make selected text italic" id="italic" class="button" type="button" value="Italic" /> \
							 <input title="Underline selected text" id="underline" type="button" value="Underline"/> \
							 <input title="Align selected text to the left" id="justifyleft" type="button" value="left"/> \
							 <input title="Align selected text to the centre" id="justifycenter" type="button" value="center"/> \
							 <input title="Align selected text to the right" id="justifyright" type="button" value="right"/> \
							 <input title="Increase selected text indent" id="indent" type="button" value="indent"/> \
							 <input title="Decrease selected text indent" id="outdent" type="button" value="outdent"/> \
							 <input title="Change the selected text to a hyperlink" id="createLink" class="button" type="button" promptText="Enter URL of link" cmdValue="promptUser" value="<a>" /> \
							 <input title="Insert a bulleted list" id="insertorderedlist" type="button" value="<ol>"/> \
							 <input title="Insert an unordered list" id="insertunorderedlist" type="button" value="<ul>"/> \
							 <input title="Undo the last action" id="undo" type="button" value="Undo"/> \
							 <input title="Redo an undone action" id="redo" type="button" value="Redo"/> \
							 </div>');

		var updateLink = $('<a class="inline_control first" href="#" title="Update this content"><img src="/img/icons/admin/button_save.png" /></a>');
		var cancelLink = $('<a class="inline_control last" href="#" title="Cancel editing this content"><img src="/img/icons/admin/button_cancel.png" /></a>');

		var removeEdit = function() {
			if(defaults.editingClass) {
				el.removeClass(defaults.editingClass);
			}

			el.get(0).contentEditable = false;
			if(defaults.showEditBar) {
				editBar.remove();
			}

			el.append(options.triggerElement);
			updateLink.remove();
			cancelLink.remove();
		};

		cancelLink.click(function(evt) {
			el.html(original);
			removeEdit();
			return false;
		});

		updateLink.click(function(evt) {
			$('#activity_indicator').show();
			var post_data = {
				'data[id]': id,
				'data[field]': field,
				'data[content]': el.html()
			};

			$.ajax({
				type: 'POST',
				url: '/admin/' + controller + '/inline/',
				data: post_data,
				success: function(result) {
					if(result) {
						removeEdit();
						$('#activity_indicator').hide();
					}
				}
			});

			return false;
		});

		el.keypress(function(evt) {
			if(evt.keyCode == 27) {
				removeEdit();
			} else if(evt.keyCode == 9) {
			}
		});

		if(defaults.showEditBar) {
			el.before(editBar);
		}

		el.after(updateLink);
		el.after(cancelLink);

		this.contentEditable = true;

		if(defaults.editingClass) {
			el.addClass(defaults.editingClass);
		}

		return this;
	});
}

function doEditCommand() {
	var cmd = this.id;
	var value = this.getAttribute('cmdValue') || null;
	if (value == 'promptUser') {
		value = prompt(this.getAttribute('promptText'));
	}
	var return_value = document.execCommand(cmd, false, value);

	return return_value;
}

