var guestbookHover = false;
var guestbookUploading = false;
$(document).ready(function() {
	if (($.browser.msie) && ($.browser.version == '9.0')) {
		$(".slideshow").show();
		$(".slideshow div").css('display', 'block');
		$(".slideshow img").each(function() {
			$(this).css("height", $(this).height()).css("width", $(this).width());
			//$(this).css("left", (($(this).parent().innerWidth() - $(this).width()) / 2));
			//$(this).css("top", (($(this).parent().innerHeight() - $(this).height()) / 2));
		});
		$('.slideshow').cycle({
			fx: 'fade',
			cleartypeNoBg: false,
			timeout: 0
		});
		$('.slideshowNext').live('click', function() {
			$(this).prev(".slideshow").cycle('next');
		});
	}
	else {
		$(".slideshow").imagesLoaded(function($images) {
			$(".slideshow").show();
			$(".slideshow div").css('display', 'block');
			$(".slideshow img").each(function() {
				$(this).css("height", $(this).height()).css("width", $(this).width());
				//$(this).css("left", (($(this).parent().innerWidth() - $(this).width()) / 2));
				//$(this).css("top", (($(this).parent().innerHeight() - $(this).height()) / 2));
			});
			$('.slideshow').cycle({
				fx: 'fade',
				cleartypeNoBg: true,
				timeout: 0
			});
			$('.slideshowNext').live('click', function() {
				$(this).prev(".slideshow").cycle('next');
			});
		});
	}
	
	$('#homenav li, #nav li').hover(function() {
		$(this).addClass('active');
	},function() {
		$(this).removeClass('active');
	});
	$('#obitSign a.btn').click(function(e) {
		e.preventDefault();
		var gbpf = $("#gbpf").val();
		$.ajax({
			type: 'POST',
			url: '/inc/gbf.php',
			data: 'gbpf='+gbpf,
			success: function(h) {
				$('#guestbookMod').html(h);

				$('#guestbookMod').toggle();
				//uploader.destroy() is available
				var uploader = new plupload.Uploader({
					runtimes : 'gears,flash,silverlight,browserplus',
					container: 'guestbookMod',
					browse_button : 'guestbookImgPick',
					max_file_size : '4mb',
					url : '/inc/gbimg.php',
					resize : {width : 425, height : 261, quality : 90},
					flash_swf_url : '/inc/plupload/js/plupload.flash.swf',
					silverlight_xap_url : '/inc/plupload/js/plupload.silverlight.xap',
					filters : [
						{title : "Image files", extensions : "jpg,gif,png"}
					],
					multi_selection: false,
					multipart: true,
					//multipart_params: {obid: $("#obid").val()},
					preinit: {
						Init: function(up, info) {
							//$('#filelist').html("<div>Current runtime: " + info.runtime + "</div>");
							//console.log('[Init]', 'Info:', info, 'Features:', up.features);
						},
						UploadFile: function(up, file) {
							//console.log('[UploadFile]', file);
							up.settings.multipart_params = {obid: $("#obid").val(), uniqueid: file.id};

							// You can override settings before the file is uploaded
							// up.settings.url = 'upload.php?id=' + file.id;
							// up.settings.multipart_params = {param1: 'value1', param2: 'value2'};
						}
					},
					init: {
						Refresh: function(up) {
							// Called when upload shim is moved
							//console.log('[Refresh]');
						},

						StateChanged: function(up) {
							// Called when the state of the queue is changed
							//console.log('[StateChanged]', up.state == plupload.STARTED ? "STARTED": "STOPPED");
						},

						QueueChanged: function(up) {
							// Called when the files in queue are changed by adding/removing files
							//console.log('[QueueChanged]');
						},

						UploadProgress: function(up, file) {
							// Called while a file is being uploaded
							//console.log('[UploadProgress]', 'File:', file, "Total:", up.total);
							$("#"+file.id+" b").html('<span>' + file.percent + "%</span>");
						},

						FilesAdded: function(up, files) {
							guestbookUploading = true;
							$("#guestbookImgUpload .uploadok").hide();
							$("#guestbookImgUpload .uploadmax").hide();
							$("#guestbookImgUpload .uploading").show();
							// Callced when files are added to queue
							//console.log('[FilesAdded]');

							plupload.each(files, function(file) {
								//console.log('  File:', file);
							});

							if ($("#guestbookImgs .preview").length > 4) {
								up.RemoveFile(file);
							}

							var h = '';
							for (var i in files) {
								h += '<div id="' + files[i].id + '">' + files[i].name + ' (' + plupload.formatSize(files[i].size) + ') <b></b></div>';
							}
							//$('#filelist').append(h);
							uploader.start();
						},

						FilesRemoved: function(up, files) {
							// Called when files where removed from queue
							//console.log('[FilesRemoved]');

							plupload.each(files, function(file) {
								//console.log('  File:', file);
							});
						},

						FileUploaded: function(up, file, info) {
							// Called when a file has finished uploading
							//console.log('[FileUploaded] File:', file, "Info:", info);
							//$('#submit-form').append('<input type="hidden" name="file-' + file.id + '" value="' + file.name + '" />');
							var resp = jQuery.parseJSON(info.response);
							$('#guestbookMod').append('<input type="hidden" class="guestbook_img" name="guestbook[img][]" value="' + resp.gbimg + '" rel="'+file.id+'" />');
							$('#guestbookImgs').append('<a href="#"><img id="' + file.id + '" class="preview" src="' + resp.gbimg + '" /><img class="del" rel="'+file.id+'" src="/img/obituaries/icon-delete.gif" /></a>');
							if ($("#guestbookImgs .preview").length >= 4) {
								$("#guestbookImgUpload .uploadok").hide();
								$("#guestbookImgUpload .uploadmax").show();
								$("#guestbookImgUpload .uploading").hide();
								guestbookUploading = false;
							}
							else {
								$("#guestbookImgUpload .uploadok").show();
								$("#guestbookImgUpload .uploadmax").hide();
								$("#guestbookImgUpload .uploading").hide();
								guestbookUploading = false;
							}
						},

						ChunkUploaded: function(up, file, info) {
							// Called when a file chunk has finished uploading
							//console.log('[ChunkUploaded] File:', file, "Info:", info);
						},

						Error: function(up, args) {
							// Called when a error has occured

							// Handle file specific error and general error
							if (args.file) {
								//console.log('[error]', args, "File:", args.file);
							} else {
								//console.log('[error]', args);
							}
							guestbookUploading = false;
						}
					}
				});
				uploader.init();
			}
		});
	});
	function pluploadRemove(id) {
		plupload.each(files, function(file) {
			//console.log('Checking File:', file);
			if (file.id == id) {
				up.RemoveFile(file);
			}
		});
	}
	$('#obitSign').mouseover(function() {
		guestbookHover = true;
	}).mouseout(function () {
		guestbookHover = false;
	});
	$("body").click(function() {
		if (!guestbookHover) {
			$("#guestbookMod").hide().html('');
		}
	});
	$('#guestbookImgs .del').live('click', function(e) {
		e.preventDefault();
		var id = $(this).attr('rel');
		$('#guestbookMod input[type="hidden"]').each(function() {
			if ($(this).attr('rel') == id) {
				$(this).remove();
			}
		});
		$(this).parent('a').remove();
		if ($("#guestbookImgs .preview").length < 4) {
			$("#guestbookImgUpload .uploadok").show();
			$("#guestbookImgUpload .uploadmax").hide();
			$("#guestbookImgUpload .uploading").hide();
			guestbookUploading = false;
		}
	});
	$('#guestbook_message').live('keyup', function() {
		var msg = $(this).val();
		//console.log(msg.length);
		if (msg.length >= 2000) {
			$(this).val(msg.substr(0, 2000));
			$('#guestbook_warn').html('<br /><br />Limited to 2000 chars');
		}
		else {
			$('#guestbook_warn').html('&nbsp;');
		}
	});
	$('#guestbookDone').live('click', function(e) {
		e.preventDefault();
		if (guestbookUploading) {
			alert("Please wait while your image is processed.");
		}
		else {
			var fields = {'full_name':'Full Name', 'city':'City', 'state':'State', 'message':'Message'};
			var err = new Array();
			var qry = new Array();
			for (k in fields) {
				if (fields.hasOwnProperty(k)) {
					if ($('#guestbook_'+k).val() == '') {
						err[err.length] = fields[k];
					}
					else {
						qry[qry.length] = k + '=' + encodeURIComponent($('#guestbook_'+k).val());
					}
				}
			}
			if (err.length > 0) {
				alert("Please fill in the following fields: "+err.join(', '));
			}
			else {
				var imgs = new Array();
				$('.guestbook_img').each(function() {
					imgs[imgs.length] = 'img[]='+$(this).val();
				});
				var qstr = qry.join('&')+'&tkn='+$("#tkn").val()+'&obid='+$("#obid").val()+'&'+imgs.join('&');
				$.ajax({
					dataType: 'json',
					type: 'POST',
					url: '/inc/gb.php',
					data: qstr,
		  		success: function (jsonObj) {
		  			$("#guestbookMod").fadeOut();
		  			if (jsonObj != null) {
							if (jsonObj.hasOwnProperty("error")) {
								alert("Your submission has timed out. Please refresh this page and try again");
							}
							else {
								window.location.reload(true);
							}
						}
		  		}
		  	});
			}
		}
	});
	var gbSlideshowOpen = false;
	$('.uploads img').click(function(e) {
		var t = $(this).parents(".comment").find(".guestbookSlideMod");
		var start = $(this).attr("rel");
		start = parseInt(start) - 1;
		if (t.is(":visible").length) {
			t.find('.gbSlideShow').cycle(start);
		}
		else {
			if (gbSlideshowOpen == true) {
				//another open so close it
				$('.gbSlideShow').cycle('destroy');
				$(".guestbookSlideMod").hide();
			}
			gbSlideshowOpen = true;
			t.show();
			t.imagesLoaded(function($images) {
				t.find(".gbSlideShow img").each(function() {
					$(this).css("height", $(this).height()).css("width", $(this).width());
					$(this).css("left", (($(this).parent().innerWidth() - $(this).width()) / 2));
					$(this).css("top", (($(this).parent().innerHeight() - $(this).height()) / 2));
				});
				t.find('.gbSlideShow').cycle({
					fx: 'fade',
					startingSlide: start,
					timeout: 0
				});
			});
		}
	});
	$('.gbSlideshowNext').live('click', function() {
		$(this).prev(".gbSlideShow").cycle('next');
	});
	$('.gbImgClose').live('click', function() {
		$('.gbSlideShow').cycle('destroy');
		$(this).parent(".guestbookSlideMod").hide();
		gbSlideshowOpen = false;
	});
	fixH();
});
function fixH() {
	var bodyH = $("#body").height();
	var sidebarH = $("#sidebar").height();
	if (sidebarH > bodyH) {
		$("#body").css("height", sidebarH+"px");
		bodyH = $("#body").height();
	}
}
function isFormFilled()
{
	var errors = '';
	$('form.contact input').css('border', '1px solid #EBE5D2');
	$('form.contact label').css('color', '#605C58');
	if($('input[name=email-fn]').val() == '')
	{	
		$('input[name=email-fn]').css('border', '1px solid #ff0000');
		$('label[for=email-fn]').css('color', '#ff0000');
		errors += "First name, ";
	}
	if($('input[name=email-ln]').val() == '')
	{
		$('input[name=email-ln]').css('border', '1px solid #ff0000');
		$('label[for=email-ln]').css('color', '#ff0000');
		errors += "Last name, ";
	}
	if($('input[name=email-cte]:checked').val() == 'Email'){
		if(!validateEmail($('input[name=email-em]').val()))
		{
			$('input[name=email-em]').css('border', '1px solid #ff0000');
			$('label[for=email-em]').css('color', '#ff0000');
			errors += "Email, ";
		}
	}
	if($('input[name=email-cte]:checked').val() == 'Telephone')
	{
		if($('input[name=email-ac]').val() == ''){
			$('input[name=email-ac]').css('border', '1px solid #ff0000');
			$('label[for=email-ac]').css('color', '#ff0000');
			errors += "Area code, ";
		}
		if($('input[name=email-ph]').val() == '')
		{	
			$('input[name=email-ph]').css('border', '1px solid #ff0000');
			$('label[for=email-ph]').css('color', '#ff0000');
			errors += "Phone number";
		}
	}

	if($('input[name=email-cte]:checked').val() == 'Postal Mail')
	{
		if($('input[name=email-a1]').val() == ''){
			$('input[name=email-a1]').css('border', '1px solid #ff0000');
			$('label[for=email-a1]').css('color', '#ff0000');
		}
		if($('input[name=email-ct]').val() == '')
		{	
			$('input[name=email-ct]').css('border', '1px solid #ff0000');
			$('label[for=email-ct]').css('color', '#ff0000');
		}
		if($('input[name=email-st]').val() == '')
		{	
			$('input[name=email-st]').css('border', '1px solid #ff0000');
			$('label[for=email-st]').css('color', '#ff0000');
		}
		if($('input[name=email-zp]').val() == '')
		{	
			$('input[name=email-zp]').css('border', '1px solid #ff0000');
			$('label[for=email-zp]').css('color', '#ff0000');
		}
	}
	
	if(errors.length > 0)
	{
		$('#errors').html('You are missing the fields highlighted in red.<br /><br />');
		$('#errorsf').html('You are missing the fields highlighted in red.<br /><br />');
		return false;
	}
	return true;
}

function validateEmail(email)
{
 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
 return email.match(re)
}
