
$(document).ready(function(){
	ready();
});

function ready(){


	// example for the form inputs based off of the label associated with the input
	$('form input, form textarea').example(function(){
		return $('label[for="'+$(this).attr('id')+'"]').text();
	});


	//set class for links to external sites and other document types
	//$('#content a[href^="http://"]').addClass('external').attr('target', '_blank');
	$('#content a[href$=".pdf"]').addClass('pdf').attr('target','_blank');
	$('#content a[href$=".ppt"]').addClass('powerpoint').attr('target','_blank');
	$('#content a[href$=".doc"]').addClass('word').attr('target','_blank');
	$('#content a[href$=".xls"]').addClass('excel').attr('target','_blank');
	$('#content a[href$=".csv"]').addClass('excel').attr('target','_blank');

	$('#content a.remove_external').removeClass('external').attr('target', '_blank');

	// GALLERY LIGHTBOX
	$('#gallery a:has(img)').attr('rel', 'gallery').fancybox({
		cyclic:true,
		transitionIn:'elastic',
		transitionOut:'elastic'
	});

	$("a.gallery").fancybox();
/*
	$(".home-img-1").rotateleft(4);
	$(".home-img-2").rotateleft(8);
	$(".home-img-3").rotateRight(12);
	$(".home-img-4").rotateRight(4);
*/
	 // ROUNDED IMAGES
	// any image that is floated right
	$('img[style*="float: right;"]').each(function(){
		if($(this).attr('class')=='no-rounding'){
			return false;
		 }
		$div = $('<div/>').addClass('rounded_image round_10').css('background',"url('"+$(this).attr('src')+"')");
		$(this).wrap($div);

	});


	// HIDE-SHOW
	$('.view_details').click(
		function(){
			var toggleHide = 'images/templates/hide.gif';
			var toggleShow = 'images/templates/view.gif';
			var eDiv = $('div.'+$(this).attr('rel'));
			var eImg = $(this).children('img');

		if(eDiv.is(':hidden')){
				$(this).children('img').attr('src', toggleHide);
				eDiv.show('slow');

			}

		else if(eDiv.is(':visible')){
				$(this).children('img').attr('src', toggleShow);
				eDiv.hide('slow');

			}

		 $(this).blur();
		return false;
	});




	/* AJAX PAGE TRANSLATION */
	$('#languages li a').click(function(){

		var lang = $('span.lang', $(this)).text();
		//show the appropriate dialog based on the language we are translating to
		$('#'+lang+'_translation_dialog').dialog('open');

		//set the cookie for the next page load
		//make sure to set the path to the root due to mod_rewrite faking directories
		$.cookie('language', lang, {expires: 0, path: '/'});

		// since there is an insane amount of js that goes into the calendar
		// and ie sucks, just reload the page if its the event page
		if(location.href.indexOf('calendar')>=0)
			window.location.reload();

		//clear out the events for events.months calendar because we are changing languages and it doesn't respond to cookies
		events.months = {};

		//now load the current document into the body
		$('body').load(location.href+' #container', function(){

			//when it loads, recall the ready function to re-initalize jquery actions
			ready();

		});
		return false;
	});
	//modal dialog for the translation system
	$('.translation_dialog').each(function(){
		var title = $('p.title', $(this)).text();
		$(this).dialog({
			autoOpen: false,
			bgiframe: true,
			resizable: false,
			closeOnEscape: false,
			modal: true,
			title: title,
			open: function(event, ui){
				//hide the close button since it will auto-close
				$(this).parents().find('.ui-dialog-titlebar-close').hide();
			}
		});
	});


	/* FTR CONTACT FORM */
	//example, use the hidden label
	$('input, textarea', $('#ftr_contact')).example(function(){
		return $('label[for="'+$(this).attr('id')+'"]').text();
	});
	//ajax submit
	$('#ftr_contact').submit(function(){
		//VALIDATION
		var from_email = $("#ftr_email"),
			subject = $("#ftr_subject"),
			message = $("#ftr_message"),
			allFields = $([]).add(from_email).add(subject).add(message),
			validate_error = $("#ftr_contact_message"),
			bValid = true,
			error_message = new Array();
		allFields.removeClass('ui-state-error');
		//validate the email address
		// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
		var valid_email = checkRegexp(from_email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
		if(!valid_email){
			bValid = bValid && false;
			from_email.addClass('ui-state-error');
			error_message.push('You must supply a properly formatted email address');
		}
		//make sure there's something in the message box
		var valid_message = checkLength(message,10,1000);
		if(!valid_message){
			bValid = bValid && false;
			message.addClass('ui-state-error');
			error_message.push('You must supply a message that is at least 10 characters long');
		}

		if (bValid) {
			//send the data
			$(this).after('<div class="ajax_loader"><p><img src="layout_imgs/loading_arrows.gif" alt="sending" />&nbsp;sending, please wait...</p></div>').hide();
			//start ajaxing the data
			$data = $(this).serialize();
			$.post("ajax_email.php",
				$data,
				function(data, textStatus){
					if(data){
						allFields.val('').blur();
						$('.ajax_loader').html('<p><strong>Success!</strong> Your email was sent successfully. <a class="show_form">Send another?</a></p>');
						//the link to show the form again
						$('#ftr .ajax_loader a.show_form').css({cursor:'pointer'}).click(function(){
							//blank the form and show the examples by calling blur
							allFields.val('').blur();
							$('#ftr_contact').show();
							$('.ajax_loader').remove();
							return false;
						});

					} else {
						makeDialog("<p><strong>Sorry</strong><p><p>Your email could not be sent at this time. Please try again later.</p>",'Email Failed to Send');
						//blank the form and show the examples by calling blur
						allFields.val('').blur();
						$('.ajax_loader').remove();
						$('#ftr_contact').show();
					}
				},
				"json"
			);
		} else {
			//throw the dialog for errors
			var text = "<p>Your email reported the following errors and could not be sent.</p><ul><li>"+error_message.join('</li><li>')+"</li></ul><p>Please fix the error(s) and try again.</p>";
			makeDialog(text,'Form Error');
			//call the blur to show the examples again
			allFields.blur();
		}
		return false;
	});





	// BLOG
	// toggle the comments
	$('a.view_comments').each(function(){
		var count = $(this).parent('.links').next('.comments').find('.comment').length;
		$(this).text($(this).text()+' ('+count+')');
	}).click(function(){
		$(this).trigger('toggle', true);
		return false;
	}).bind('toggle', function(event, jumpTo){
		$link = $(this);
		// slide the comments into place with a callback
		$(this).parent('.links').next('.comments').slideToggle('fast',function(){
			// toggle view/leave with hide
			text = $link.text();
			if(text.indexOf("View/Leave")>=0){
				text = text.replace("View/Leave","Hide");
				if(jumpTo)
					$link.trigger('jumpTo');
			} else {
				text = text.replace("Hide","View/Leave");
				// dont need a scroll to since we are already at the links
			}
			$link.text(text);
		});
		return false;
	}).bind('jumpTo', function(){
		$.scrollTo($(this).parent(),'fast');
	});
	// if there's only one blog post show the comments automatically
	if($('div.blog_post').length==1){
		$(this).find('a.view_comments').trigger('toggle',false);
	}
	// SUBMITTING COMMENTS
	$('.comment_form').submit(function(){
		if(!$(this).find('input[name="email"]').val()){
			alert('You must supply your email address');
			return false;
		} else if(!$(this).find('textarea').val()){
			alert('You must supply a comment');
			return false;
		}
		// save the parent div.comments for inserting new comment to proper place
		var $comments = $(this).parents('.comments');
		var i = $(this).find('input[name="i"]').val() * 1;
		var new_i = i;
		new_i = new_i + 1;

		var form_data = $(this).serialize();
		$.ajax({
			url:'blog_includes/ajax_comment.php',
			data: form_data,
			type: "POST",
			beforeSend: function(){
				$('body').css('cursor','wait');
				$('.comment_form input, .comment_form textarea').attr('disabled','disabled');
			},
			success: function(data){
				if(data!="0"){
					// insert the comment
					if($('.comment:last',$comments).length)
						$('.comment:last',$comments).after(data);
					else if($('.none',$comments).length)
						$('.none',$comments).replaceWith(data);
					else
						window.location.reload();// if there's neither of the two options just refresh cause I don't know whats going on

					// update the i count
					$('input[name^="i"]',$comments).val(new_i);

					// now update the comment link
					var text = $comments.prev('.links').children('a.view_comments').text();
					if(text.indexOf("(")>=0){
						text = text.replace(/\(\d+\)/, "("+i+")")
					} else {
						text += ' ('+i+')';
					}
					$link.text(text);
				} else {
					alert('Sorry, but there was an error and you comment could not be posted at this time. Please try again later');
				}
				$('body').css('cursor','auto');
				$('.comment_form input, .comment_form textarea').removeAttr('disabled').not('input[type="submit"]').not('input[type="hidden"]').val('');
			}
		});

		return false;
	});
	// ARCHIVE LIST
	$('#blog_archives li.year').click(function(){
		$(this).children('ul').toggle();
	}).find('li.month').click(function(){
		$(this).children('ul').toggle();
		return false;
	}).find('a').bind('click',function(e){
		e.stopPropagation();
	});

	// DIALOG LINKS
	$('a.dialog').click(function(){
		// do a dialog for the video embed
		makeDialog('<h3><img src="layout_imgs/loading_bar.gif" alt="loading" /> Loading '+$(this).attr('title')+'</h3><p>please wait</p>', $(this).attr('title'));
		var element_rel = $(this).attr('name');
		// ajax in the data
		$('#made_dialog').load($(this).attr('href')+(element_rel ? ' '+element_rel : ''), function(rsp){
			// animate the containers to show everything
			$(this).parent().css('width','705px').animate( {
				top: $(this).parent().offset().top - (screen.height/4) + 20,
				left: '50%',
				marginLeft: -($(this).width() / 2)
			}, 'fast');
		});

		return false;
	});



}; // end document ready


function makeDialog(text, dialog_title, buttons, width, height, hideTitleBar){
	if(!buttons){
		buttons = {
			Ok: function() {
				$(this).dialog('close');
			}
		}
	}

	$('<div id="made_dialog">'+text+'</div>').dialog({
		title: dialog_title,
		dialogClass: hideTitleBar ? 'hide_title' : 'alert',
		bgiframe: true,
		modal: true,
		stack:true,
		autoOpen:true,
		width: width ? width : 460,
		minHeight: height ? height : 220,
		draggable: true,
		resizable: true,
		buttons: buttons,
		close: function(event, ui){
			$(this).remove();
		}
	});
}

window.alert = function(txt){
	makeDialog(txt, 'The page said:');
}

//CATCH CONSOLE.LOG FOR NO-FIREBUG
if (typeof console == 'undefined' || typeof console.log == 'undefined') { console = { log : function (text) { return false; } } }

function makeGoogleMap(address){
	var base = "http://maps.google.com/maps?f=q&hl=en&geocode=&time=&date=&ttype=&q=";
	return base + escape(address);
}


