(function($) {

$(function() { // on DOM ready

// Initialize editor
if(livewhale.has_pages_editor) {
	var login = livewhale.getCookie('lw_pages_editor'), // get the login cookie
		initPagesEditor = function() {
			var head = $('head'),
				body = $('body');
			if(body.hasClass('lw_disable_toolbar')) return; // abort if the toolbar should be disabled on this page
			body.find('script').remove(); // remove scripts so they don't execute when we
			body.wrapInner('<div id="lw_page"/>'); // wrap the document in #lw_page
			$.each(livewhale.pages_editor.styles,function() {
				head.append('<link rel="stylesheet" type="text/css" href="'+this+'"/>'); // Add each style to the document head
			});
			body.prepend(livewhale.pages_editor.html);
			if (livewhale.edit_item) $('#lw_menu_pages').append('<li id="lw_pages_edit_item"><a href="'+livewhale.edit_item+'">Edit this item</a></li>'); // add edit this item link if available
			if ($('body').hasClass('lw_no_editing')) $('#lw_menu_pages li').hide(); // hide menu items if editing disabled
			var loaded = 0, // how many scripts have loaded?
				loadlast = livewhale.pages_editor.scripts.pop();
			$.each(livewhale.pages_editor.scripts,function(index,path) { // for each script
				$.getScript(path,function() { // load&execute it, then
					loaded++; // increment the counter
					if(loaded==livewhale.pages_editor.scripts.length) { // if they've all loaded
						livewhale.jQuery.fn.tinymce = jQuery.fn.tinymce; // copy over tinymce, when added
						livewhale.jQuery.throttle = jQuery.throttle; // and throttle
						livewhale.jQuery.debounce = jQuery.debounce; // and debounce
						$.getScript(loadlast); // load that one last one
					}
				});
			});
		};
	if(login) { // if the login cookie exists
		if(livewhale.pages_editor&&livewhale.pages_editor.html) { // if the pages editor is present AND it offers the toolbar
			initPagesEditor();
		} else {
			$.ajax({
				url:livewhale.page+'?livewhale=ajax&function=getPagesEditorToolbar'+((livewhale.draft && livewhale.draft.is_loaded) ? '&lw_draft=1' : ''),
				success:function(data) {
					if(data&&data.html) { // (data has no properties if the login is invalid)
						livewhale.pages_editor = data;
				   		initPagesEditor();
				   	}
				},
				error:function(XMLHttpRequest, textStatus, errorThrown) {
					if((textStatus=='parsererror'&&!$.trim(XMLHttpRequest.response))||(textStatus=='error'&&XMLHttpRequest.status==404)) { // if empty (expired cookie), or the page is a 404
						return; // just ignore the request and don't show an error
					} else if(livewhale.ajaxError) { // otherwise, if logged available
						livewhale.ajaxError.apply(this,arguments); // pass on to the generic LiveWhale ajaxError handler
					}
				},
				dataType:'json'
			});
		}				
	}
}

if(livewhale.is_details_preview) {
	$('<div id="lw_preview_bar">Here’s the preview you requested. <a href="#" class="lw_close_window">Click to close window</a></div>').prependTo($('body'));
	$('.lw_close_window').click(function() { window.close(); return false; });

}

$('body').initFrontend(); // initialize the frontend behaviors in the entire body region

});

$.fn.extend({ // add frontend-specific plugins
	initFrontend:function() { // initialize frontend behaviors
		this.each(function() {
			var region = $(this);
			// Frontend behaviors
			var process = { // first, look up anything that needs JS processing
					paginate:{elements:region.find('.lw_widget:has(.lw_paginate)')},
					slideshow:{elements:region.find('.lw_item_images')},
					datepicker:{elements:region.find('.lw_datepicker')},
				//	timePicker:{elements:region.find('.lw_timepicker'),settings:{show24Hours:false}},
					captcha:{elements:region.find('.lw_captcha')}
				};
			$.each(process,function(fn,data) { // with each
				if(data.elements.length) { // if there are elements
					data.elements[fn](data.settings); // apply the function
				}
			});
			region.find('.lw_saveandshare_email').click(function() { // save and share email overlay
				var overlay = $('<div id="lw_email_overlay"><div class="lw_spinner"/></div>').overlay({close:'.lw_cancel a'});
				overlay.delegate('#lw_email','submit',function() {
					var spinner = $('<div class="lw_spinner"/>').appendTo(overlay);
					$.post('/livewhale/nocache.php?livewhale=ajax&function=sendSASEmail',$('#lw_email').serialize(),function(response) {
						if(response.error) {
							livewhale.prompt(response.error,'failure',{'Okay':function() { // on failure
								overlay.find('.lw_captcha').captcha('refresh'); // refresh the captcha
								spinner.remove(); // and remove the spinner
							}}); 
						} else {
							livewhale.prompt('Your email has been sent. Thanks for sharing!','success',{'Okay':function() { // on success, prompt and then
								overlay.overlay('remove'); // close the overlay
							}});
						}
					},'json');
					return false; // don’t submit the form
				});
				$.getJSON('/livewhale/nocache.php?livewhale=ajax&function=getSASEmailForm&url='+escape(window.location.href),function(data) {
					overlay.html(data.html) // add the data
						.find('.lw_captcha').captcha(); // and 
				});
				return false; // cancel the click
			});
			region.find('.lw_widget_images').delegate('a','click',function() { livewhale.previewImage($(this).attr('href')); return false; }); // apply image preview to images widget items
		});
		if ($('.lw_subnav_toggle').length) $('.lw_subnav_toggle').each(function() { // find subnav toggles
			$(this).next('ul').height($(this).next('ul').height()); // set an explicit height
			$(this).click(function() { // add click event to toggle the submenu
				var subnav=$(this).next('ul'); // get subnav to toggle
				if (subnav.is(':visible')) {subnav.slideUp(400);} // hide if shown
				else { // else if showing
					if ($('.lw_subnav_toggle').next('ul:visible').length) {
						$('.lw_subnav_toggle').next('ul:visible').slideUp(400,function() { // hide any that are shown first
							subnav.slideDown(650); // then show it
						});
					}
					else subnav.slideDown(650); // else just show it
				};
				return false;
			});
		});
		livewhale.slideshows=new Array(); // init slideshow arrays
		livewhale.slideshow_timers=new Array();
		livewhale.slideshow_on=true;
		$('.lw_widget_slideshow').each(function() { // for each slideshow widgets
			if ($(this).find('.lw_gallery_thumbnails').length==0) if ($(this).find('.lw_slideshow_interval').length) if (ms=$(this).find('.lw_slideshow_interval').html()) if (ms.match(/[0-9]+/) && ms>=100) { // if this is not an inline gallery, and is a valid slideshow widget
				$(this).find('li').hide(); // hide all lis
				$(this).find('ul').show(); // show the ul
				$(this).find('li').eq(0).show(); // show the first li
				len=livewhale.slideshows.length; // get the # of slideshows
				lis=$(this).find('li'); // get the lis for this slideshow
				if (lis.length>1) { // if there is more than 1 li
					if (!$(this).find('.lw_slideshow_no_pausing').length) { // if pausing is not disabled
						$(this).find('li').mouseover(function() {livewhale.slideshow_on=false;}); // disable slideshow on mouseover
						$(this).find('li').mouseout(function() {livewhale.slideshow_on=true;}); // enable slideshow on mouseover
					};
					livewhale.slideshows[len]=new Array(lis,0); // add a slideshow entry
					livewhale.slideshow_timers[len]=setInterval('if (livewhale.slideshow_on) {var curr=livewhale.slideshows['+len+'][1];if (livewhale.slideshows['+len+'][0].length>livewhale.slideshows['+len+'][1]+1) {livewhale.slideshows['+len+'][1]++;} else livewhale.slideshows['+len+'][1]=0;livewhale.slideshows['+len+'][0].eq(curr).fadeOut(function() {livewhale.slideshows['+len+'][0].eq(livewhale.slideshows['+len+'][1]).fadeIn();});}',ms); // add a timer for this slideshow
				};
			};
		});
		if ($('.g-plusone').length) { // enable Google Plus links
			var po = document.createElement('script');
			po.type = 'text/javascript';
			po.async = true;
			po.src = 'https://apis.google.com/js/plusone.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
		};
		return this;
	},
	captcha:function(command) { // recaptcha
		if ($('.lw_captcha').length) if(!command) { // if no command is sent
			var elements = $(this);
			$.when(window.Recaptcha || $.getScript('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js')) // get Recaptcha if it isn’t yet loaded
				.then(function() {
					elements.each(function() { // with each element
						Recaptcha.create(livewhale.recaptcha_key_public,this,{theme:'clean'}); // initialize recaptcha
					});
				});
		} else {
			if(command=='refresh') { // if refreshing the captcha
				Recaptcha.reload();
			}
		}
		return this; // return the original elements for changing
	}
});

})(livewhale.jQuery);
