$(document).ready(function(){
	/* conflicks with pretty photo in multimedia.js
pp = $("a[rel^='prettyPhoto']");
	if ( pp.length ) {
		pp.prettyPhoto({counter_separator_label:' of ',show_title:false});
	}
*/
	
	$(document).bind('onShowEditModal', function(e, data) {
		mod_slideshow_edit_onload();	
	});
	setTimeout(function(){mod_slideshow_onload();}, 400);
	
	
});
mod_slideshow_edit_onload = function(){
	styleTabs('.mod_slideshow_tabs');
	$('.mod_slideshow_sort').sortable({
		 axis: 'y'
		,update: function(event, ui){
			var items = $(this).sortable('toArray').toString();
			$.post($('.mod_slideshow_cfc_uri').text() + '?method=updateSortOrder', {
				sortedList: items
			}, function() { 
				mod_slideshow_reload_module();
				$.gritter.add({
					title: 'SlideShow Updated',
					text: 'Changed Sort Order.',
					time: 3000
				}); 
			});
		}
	});
	$('.mod_slideshow_advanced_form').ajaxForm({
		success: function() {
			mod_slideshow_reload_module();
			$.gritter.add({
					title: 'SlideShow Updated',
					text: 'Updated Advanced Settings.',
					time: 3000
				});
		}, 
		beforeSubmit: function(formData, jqForm, options) {
			var f = {};
			for (var i=0;i<formData.length;i++) {
				f[formData[i].name] = formData[i].value;
			}
			if (f.size == "custom") {
				if (f.custom_width.length > 0 && f.custom_width.search(/^[0-9]+$/) != 0) {
					alert('Please specify a numeric custom width value');
					return false;
				}
				if (f.custom_height.length > 0 && f.custom_height.search(/^[0-9]+$/) != 0) {
					alert('Please specify a numeric custom height value');
					return false;
				}
				if (f.custom_width.length == 0 && f.custom_height.length == 0) {
					alert('You must specify a height and/or width when choosing custom size');
					return false;
				}
			}
		}
	});
	$('.mod_slideshow_time_slider').slider({
		animate:true,
		min:100,
		max:15000,
		step:100,
		value: $('.mod_slideshow_advanced_form').find('[name=slideTime]').val(),
		slide: function() {
			$('#slideTimeSpan').html( ($(this).slider('option', 'value')/1000).toFixed(1) );
			$(this).siblings('[name=slideTime]').val($(this).slider('option', 'value'));
		}
	});
	$('.mod_slideshow_time_slider').css('margin', '8px');
	if ($('#mod_slideshow_displayType').val() != "inplace") {
		$('#mod_slideshow_inplace_settings').hide();
		//$('.mod_slideshow_slide_linkto').hide();
	}
	$('#mod_slideshow_displayType').change( function() {
		if ($(this).val() == 'inplace') {
			$('#mod_slideshow_inplace_settings').slideDown(500);
			$('.mod_slideshow_slide_linkto').show();
		} else {
			$('#mod_slideshow_inplace_settings').slideUp(500);
			$('.mod_slideshow_slide_linkto').hide();
		}
	});
	if (!$('#mod_slideshow_autoplay:checked').length) {
		$('.mod_slideshow_duration_container').hide();
	}
	$('#mod_slideshow_autoplay').click(function() {
		if (this.checked) {
			$('.mod_slideshow_duration_container').slideDown(500);
		} else {
			$('.mod_slideshow_duration_container').slideUp(500);
		}
	})
	if ($('#mod_slideshow_size').val() != 'custom') {
		$('#mod_slideshow_custom_height_width').hide();
	}
	$('#mod_slideshow_custom_height_width>input').css('width', 50);
	$('#mod_slideshow_size').change( function() {
		if ($(this).val() == 'custom') {
			$('#mod_slideshow_custom_height_width').slideDown(500);
		} else {
			$('#mod_slideshow_custom_height_width').slideUp(500);
		}
	});
	
	
	
	mod_slideshow_attach_slide_form_events();
}

mod_slideshow_open_mediamanager = function(mediaURI, slideshowID, slideshowCFC) {
	setMediaManagerURI(mediaURI);
	hidePageWindow();
	openMediaManager(function(data) {
		if (data.action=='insert') {
			data.slideshowId = slideshowID;
			data.multimediaID = data.id;
			data.insertFormObject = null;
			$.post(slideshowCFC+'?method=ajaxAddSlide', data, function(resultData) {
				$('.mod_slideshow_sort').html(resultData);
				$.gritter.add({
					title: 'SlideShow Updated',
					text: 'Inserted New Slide.',
					time: 3000
				});
				showPageWindow();
				mod_slideshow_reload_module();
				
				mod_slideshow_attach_slide_form_events();
			});	
		}
	}, {
		allowInsert:true, 
		mediaTypes:'image',
		title: 'Insert Slideshow Image',
		showAdvanced: false,
		showSizeOnInsert: false
	});
}

mod_slideshow_remove_slide = function(linkElement) {
	var formElement = $(linkElement).parents('form:first');
	var formAction = $(formElement).attr('action');
	var removeURL = formAction.substring(0, formAction.indexOf('?')) + '?method=ajaxRemoveSlide';
	if (confirm('Are you sure you want to remove this slide from the slideshow?')) {
		$.post(removeURL, {
			slideID: $(formElement).find('[name=id]:first').val()
		}, function(response){
			$('.mod_slideshow_sort').html(response);
			$.gritter.add({
				title: 'SlideShow Updated',
				text: 'Removed slide.',
				time: 3000
			});
			mod_slideshow_reload_module();
			mod_slideshow_attach_slide_form_events();
		});
	}
	
}

mod_slideshow_edit_slide = function(linkElement) {
	var formElement = $(linkElement).parents('form:first');
	$(formElement).ajaxSubmit({success: function() {
		$.gritter.add({
			title: 'SlideShow Updated',
			text: 'Saved changes to the slide.',
			time: 3000
		});
		mod_slideshow_reload_module();
	}});
}

mod_slideshow_reload_module = function() {
	if ($('.mod_slideshow_site_modules_cross_id').length && typeof(reloadModule) == 'function') {
		reloadModule($('.mod_slideshow_site_modules_cross_id').text(), function() {	
			var area = $('#ss'+ $('.mod_slideshow_site_modules_cross_id').text());
			/* this is done in reloadModule now
			if ($(area).find("a[rel^='prettyPhoto']").length) {
				$(area).find("a[rel^='prettyPhoto']").prettyPhoto();
			}*/
			mod_slideshow_onload(area);
		});
	}
	
}


mod_slideshow_attach_slide_form_events = function() {
	if (!$('.mod_slideshow_slides_end').length) {
		setTimeout(mod_slideshow_attach_slide_form_events, 100);
		return;
	}
	
	
	$('form.mod_slideshow_slide_form').each( function() { 
		if (!$(this).find('[name=showCaption]:checked').length) {
			$(this).find('.mod_slideshow_caption_box:first').hide();
		}
		$(this).find('[name=showCaption]').click( function() {
			if (this.checked) {
				$(this).siblings('.mod_slideshow_caption_box:first').show();
				mod_slideshow_size_slideform();
			} else {
				$(this).siblings('.mod_slideshow_caption_box:first').hide();
				mod_slideshow_size_slideform();
			}
		});
	});
	
	$('.mod_slideshow_drag_hint').hide();
	$('.mod_slideshow_drag_hint .ui-icon').css('width', '16px').css('display', 'inline');
	$('.mod_slideshow_edit_slide').hover(function() {
			//over
			$(this).find('.mod_slideshow_form_buttons').show();
			$(this).find('.mod_slideshow_drag_hint').show();
		}, function() {
			//out
			$(this).find('.mod_slideshow_form_buttons').hide();
			$(this).find('.mod_slideshow_drag_hint').hide();
	});
	$('.mod_slideshow_form_buttons>.ui-link').hover(function() {$(this).removeClass('ui-state-default');$(this).addClass('ui-state-hover')}, function() {$(this).removeClass('ui-state-hover');$(this).addClass('ui-state-default');});
	
	$('.mod_slideshow_slide_save').each(function() {
		$(this).siblings('.mod_slideshow_slide_remove').css('left', $(this).offset().left+$(this).width()+ 10);
	});
	
	mod_slideshow_size_slideform();
	
	$('.mod_slideshow_form_buttons').hide();
	
	
}

mod_slideshow_size_slideform = function() {
	var imgPreview = $('.mod_slideshow_edit_slide .mod_slideshow_image_preview');
	if (imgPreview.length && $(imgPreview[1]).height() == 0 && $(imgPreview[1]).width() == 0) {
		setTimeout(mod_slideshow_size_slideform, 100);
		return;
	}
	$('.mod_slideshow_edit_slide').each(function(){
		var imgHeight = $(this).find('.mod_slideshow_image_preview').height();
		var formHeight = $(this).find('.mod_slideshow_slide_form').height();
		if (imgHeight > formHeight) {
			$(this).height(imgHeight+8);
		} else {
			$(this).height(formHeight+8);
		}
		
		
	});
}

mod_slideshow_onload = function (baseElement) {
	if (baseElement == null) { baseElement = $('body');}
	if ($(baseElement).find('.mod_slideshow_inplace').length) {
		$(baseElement).find('.mod_slideshow_inplace').each( function(){
			var controls = $(this).siblings('.mod_slideshow_controls');
			var slideshow = $(this);
			var lastHeight = 0;
			var lastWidth = 0;
			var options = {
				fx: 'fade',
				//slideExpr: $('.mod_slideshow_inplace .mod_slideshow_slide img'),  //needed to prevent showing ALL images on page load
				slideExpr: 'img', //the above was loading all instances of slideshow changed it to img to getall images in the container
				before: function() {
					$(controls).siblings('.mod_slideshow_caption').fadeTo(100, 0);
					if ($(this).height() != lastHeight || $(this).width() != lastWidth) {
						//controls need to move so hide until we can reposition
						//must be repositoned in the after event in order to get current image height / width
						$(controls).hide();
					}
				},
				after: function(){
					
					var img = $(this);
					if (this.tagName.toLowerCase() == 'a') {
						img = $(this).children('img');
						$(img).css('cursor', 'pointer');
					}

//					$(controls).width($(img).width()-2);
					//$(controls).css('width',parseInt( $(controls).parent().css('width') ));
					$(controls).css("position", "relative");
					$(controls).css("top", '0px');
					$(controls).css("text-align", "left");
					$(controls).css("z-index", 999);
					$(controls).css("padding-right", "5px");
//					$(controls).height(35);
					$(controls).show();
					lastHeight = $(img).height();
					lastWidth = $(img).width();
					var cap = $(controls).siblings('.mod_slideshow_caption');	
						if (typeof img.attr("title") == "undefined")
							{ var title = '';
						} else {var title= img.attr("title")}			
					if ((img.attr("alt") != "") || (title != "")) {
						if (img.attr("alt") != "" && (title != "")) {
							cap.html(img.attr("alt")+"<br /><span class='imagecredit'>"+title+"</span>");
						} else {
							cap.html(img.attr("alt") + title);	
						}
						cap.css("text-align", "center");
						cap.css("display", "block");
//						cap.css('height',12);	
						var w = img.width();
						
						if (w != null) {
							cap.width(w);
						}					
				
						cap.css("position", "absolute");
				
						// time delay is needed inorder to get correct height of caption bar
						setTimeout(function(){
							cap.css("top", cap.parents('.mod_slideshow').offset().top + cap.parents('.mod_slideshow').children('.mod_slideshow_inplace').height() - cap.height() - 10 );
						}, 500);
						cap.css("left",$(cap).parents('.mod_slideshow').offset().left);
						cap.css("padding","5px 0");
						cap.css("z-index", 999);
						cap.css("backgroundColor", "white");
						cap.addClass("imagecaptions");
						cap.css('width', parseInt( $(controls).parent().children('.mod_slideshow_inplace').css('width') ));
						cap.fadeTo(300, 0.9);
					} else {
						cap.html("");
						cap.css("display", "none");
					}
					
				},
				next: null,
				prev: null,
				pager: null,
				timeout: 4000
				
			};
			if (controls.find('.mod_slideshow_next').length) {
				options.next = controls.find('.mod_slideshow_next');
			}
			if (controls.find('.mod_slideshow_prev').length) {
				options.prev = controls.find('.mod_slideshow_prev'); 
			}
			if (controls.find('.mod_slideshow_pager').length) {
				options.pager = controls.find('.mod_slideshow_pager');
			}
			if (controls.find('.mod_slideshow_duration').length) {
				options.timeout = controls.find('.mod_slideshow_duration').attr('class').replace(/.*duration_([0-9]+)[^0-9]*/, '$1');
				if (options.timeout==0) { options.timeout=null; }
				if (options.timeout < 1000) {
					options.speed = options.timeout / 2;
				}
			}
			if ($(this).find('img').length && $(this).find('img:first').width() == 0) { 
				setTimeout(function() {mod_slideshow_onload(baseElement);}, 300);
				return;
			}
			//options.height='auto';
			var numImgs = $(this).children('.mod_slideshow_slide').length;
			//options.height='auto';
			if (numImgs > 1){
				
				$(this).cycle(options);
			
			}
			else {
				
				//alert($this.attr('class'));
				$(this).removeClass('mod_slideshow_inplace').addClass('mod_slideshow_lightbox-multiple');
				$(this).children('.mod_slideshow_slide').css("margin","0px");
				//alert(numImgs);
				}
			
			//Adjustments to height based on whether or not there are nav buttons.
			if (controls.find('.mod_slideshow_next').length) {
			$(this).parent().height($(this).height()+40);
			}
			else {$(this).parent().height($(this).height());}
		});
	}
}

