/*
using a seperate function call for the ajax translation system which replaces the whole body 
so the jquery ready function needs to be called again when the translated page is placed
in the dom, and since the document.ready isn't able to be bound, or called explicity (that
I could figure out), so we use a seperate function.
*/
$(document).ready(function(){
	ready();
});
function ready(){

	/* LINK ICONS */
	$('a[href^="http://"], a[href$="pdf"]').attr("target","_blank").addClass('external icon');
	$('a:not(.external)').addClass('internal icon');


	/* 	HOMEPAGE SLIDESHOW 	*/
	$('#slideshow').innerfade({
		containerheight:'335px',
		speed:'slow',
		timeout:8000
	});
	
	
	/* CONTACT FROMS */
	//example
	$('input, textarea', $('.formclass')).example(function(){
		var desc = $(this).parent().find('p.description').hide();
		return desc.text();
	});
	//set styling for the radio and checkbox containing p on focus
	$('.formclass table input').focus(function(){
		$(this).parent().addClass('focus');
	}).blur(function(){
		$(this).parent().removeClass('focus');	
	});
	//handle the label functionality ourselves to the p can trigger it and not propogate through the dom
	$('.formclass table p label').click(function(event){
		var $input = $('input#'+$(this).attr('for'));
		if($input.attr('checked'))
			$input.removeAttr('checked');
		else
			$input.attr('checked','checked');

		return false
	});
    //clicks to wrapper p tags go to the label
	$('.formclass table p').click(function(){
		$(this).children('label').trigger('click');
	});



	/* AUTOGROW TEXTAREAS */
	$('textarea').elastic();

	/* 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;
	});	

	/* MENU TWEAKS */
	//add the parent class to the top level of the open subs for the side menu
	$('#sidebar ul li:has(ul li.current):first').addClass('parent');


	/* 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('events')>=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+' #holder', 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();
			}
		});
	});


	//FLICKR GALLERY
	if($('#gallery a').length){
		$('#gallery a').lightBox({
			containerResizeSpeed: 350,
			imageLoading: 'layout_imgs/NFLightBox/loading.gif',
			imageBtnPrev: 'layout_imgs/NFLightBox/prev_over.png',
			imageBtnNext: 'layout_imgs/NFLightBox/next_over.png',
			imageBtnClose: 'layout_imgs/NFLightBox/close.png',
			imageBtnCloseOver: 'layout_imgs/NFLightBox/close_over.png',
			imageBlank: 'layout_imgs/NFLightBox/lightbox-blank.gif',
			imageBtnBottomPrev: 'layout_imgs/NFLightBox/btm_prev.gif',
			imageBtnBottomNext: 'layout_imgs/NFLightBox/btm_next.gif',
			imageBtnPlay: 'layout_imgs/NFLightBox/start.png',
			imageBtnPlayOver: 'layout_imgs/NFLightBox/start_over.png',
			imageBtnStop: 'layout_imgs/NFLightBox/pause.png',			
			imageBtnStopOver: 'layout_imgs/NFLightBox/pause_over.png'
		});
	}


	// FEATURED ITEM
	$('.featured_item div.thumbs a').live('click', function(){
	   $(this).parents('.featured_item').find('.photo img').attr('src',$(this).attr('href'));
		return false;
	});
	//handle thumb clicks
	$('.featured_item_thumb').click(function(){
		// grab the data
		var data = eval("("+$(this).find('.json').text()+")");

		// and now replace the full listing
		$('#item_info')
			.find('.photo img')
				.attr('src','images/ba_items/'+data.photos[0].photo)
				.attr('alt',data.name + ' photo')
				.end()
			.find('h2')
				.text(data.name)
				.end()
			.find('p.price span')
				.text(data.price)
				.end()
			.find('p.stock_date span')
				.text(data.stock_date)
				.end()
			.find('div.description')
				.html(data.description)
				.end()
			.find('.thumbs')
				.html('');

		// go through each photo and add it into thumbs
		$(data.photos).each(function(i){
			$('#item_info .thumbs').append('<a href="images/ba_items/'+$(this)[0].photo+'" title="view photo"><img src="images/ba_items/'+$(this)[0].thumb+'" alt="'+data.name+' thumbnail" /></a>');
		});
	});

	//ARCHIVE COOKIE CLEARER
	$('a.archive_clear').click(function(){
		$.cookie('archive_year', null, { expires: -1, path: '/'});
	});


	//PAYPAL REDIRECTION
	$('#pp_post').live('click',function(){
		$('#pp_redirect').submit();
		return false;
	});
	$('#pp_redirect').animate({opacity:1},5000,function(){
		$(this).submit();
	});



	// VIDEO CLICK TRACKING
	$('.video_page .video a').click(function(){
		data = $(this).parents('.video').data();
		
		// track in google analytics
		_gaq.push(['_trackEvent', 'Videos', 'Click', data.title + ' - ' + data.domain]);

		// track internal
		$.post('ajax_video_count.php', data);
	});

	// video description expander
	$('.all_videos .video .description').each(function(){
		p = $(this).find('p')[0];
		
		if( p.offsetWidth < p.scrollWidth ){
			$x = $('<a class="expander" href="#">+</a>').click(function(){
				$d = $(this).parents('.description');
				if($d.hasClass('expanded')){
					$d.removeClass('expanded');
					$(this).text('+');
				} else {
					$d.addClass('expanded');
					$(this).text('-');
				}
				return false; 
			});
			$(this).append($x); 
		}
	});


	//EVENT CAL
	// setup the datepicker regional for the switch the spanish translation
	$.datepicker.regional['es'] = {
		closeText: 'Cerrar',
		prevText: '&#x3c;Ant',
		nextText: 'Sig&#x3e;',
		currentText: 'Hoy',
		monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio',
		'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
		monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun',
		'Jul','Ago','Sep','Oct','Nov','Dic'],
		dayNames: ['Domingo','Lunes','Martes','Mi&eacute;rcoles','Jueves','Viernes','S&aacute;bado'],
		dayNamesShort: ['Dom','Lun','Mar','Mi&eacute;','Juv','Vie','S&aacute;b'],
		dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','S&aacute;'],
		firstDay: 0,
		isRTL: false
	};
	
	if($('#event_cal').length){
		$('#event_cal').datepicker({
			showButtonPanel: true,
			onChangeMonthYear: function(year, month, inst){
				events.onChangeMonthYear(year, month, inst);
			},
			onRefresh: function(year, month, inst){
				events.onRefresh(year, month, inst);
			},
			beforeShowDay: function(date){
				return events.beforeShowDay($.datepicker.formatDate('mm-dd-yy', date));
			},
			onSelect:function(date,inst){
				date = date.replace(/\//g,"-");
				//hide every visible event that doesn't have class of d+date
				$('#event_list .event:not(.d'+date+'):visible').slideUp('fast');
				//show every non-visible event that has a class of d+date
				$('#event_list .event.d'+date+':hidden').slideDown('fast');

				if(!$('#event_list .d'+date).length){
					// duplicate the empty event and add data to it
					$('#empty_event').clone().addClass('d'+date).find('.day_calendar').hide().end().find('.title').text('No Events on This Day').end().find('.description').text('The day you have selected does not contain any events. You can either click on a specific date on the calendar to view events on that date or click on the Month/Year at the top of the calendar to view the whole month worth of dates.').end().appendTo('#event_list').show();
				}
			},
			onTitleClick:function(year, month, inst){
				//show all the hidden events
				$('#event_list .event:hidden').slideDown('fast');			
				// delete any empty events in the event list
				$('#event_list #empty_event').remove();
			}
		});

		//set the history stuff
		$.History.bind(function(hash){
			if(hash.length){
				d = hash.split("-");
				var date = new Date();
				date.setFullYear(d[0]);
				date.setMonth(d[1]-1, 1);
				date.setDate(1);

				//update the date picker
				$('#event_cal').datepicker('setDate', date);
			} else {
				// no hash means we are back to the first time of events
				// before we loaded the current months events so the user
				// is going back, so go back
				history.back();
			}
		});

		//set translation
		if($.cookie('language') == 'spanish')
			$('#event_cal').datepicker('option', $.datepicker.regional['es']);
	}

}//end the document ready function


var events = {
	months: {},
	currentCalendar: {},
	emptyEventSelector: '#empty_event',
	eventListSelector: '#event_list',
	firstLoad: true,
	onChangeMonthYear: function(year, month, inst){
		//used for history and bookmarking
		if(!$.History.getState){
			$.History.setState(year+'-'+month);
		} else {
			$.History.setHash(year+'-'+month);
		}

		//if we don't already have the data get it
		if(this.months[year+''+month]==null)
			this._load(year, month, inst);
		else {
			//set the calendar and then refresh
			this.currentCalendar = this._exportCalendar(year, month);
			jQuery('#'+inst.id).datepicker('refresh');
		}
	},
	onRefresh: function(year, month, inst){
		//redraw the event calendar
		this._redrawList(year, month);
		jQuery('#made_dialog').remove();
	},
	beforeShowDay: function(date){
		//either return the currentCalendar date array or false
		if(this.currentCalendar[date])
			return this.currentCalendar[date];
		else
			return false;

	},
	// loads in the events using ajax
	_load: function(year, month, inst){
		var e = this;
		//load the data in with ajax
		$.ajax({
			url:'ajax_events.php',
			data: {'year':year, 'month':month},
			dataType: 'json',
			beforeSend: function(){
				makeDialog('<div style="padding:10px 10px 0 10px; font-size:12px;text-align:center;"> <img src="layout_imgs/loading_bar.gif" alt="loading bar" /><p>loading events, please wait</p></div>','Loading Events',{},250,50,true);
			},
			success: function(json){
				// ajax_events will return false if there's no events in the month
				if(json){
					var m = [];
					$(json).each(function(){
						// FORMAT THE DATA PROPERLY
						// make sure this is above category because category gets overriden
						this.calendar_color = this.category.calendar_color;
						this.category = this.category.category;
						this.date = $.datepicker.parseDate('yy-mm-dd',this.event_date);
						this.time_description = e.formatTime(this.start_time) + (this.end_time ? ' - '+e.formatTime(this.end_time) : '' );
						this.calendar_month = $.datepicker.formatDate('M', this.date).toLowerCase();
						
						//ditch the unnecessary info
						delete this.category_id;
						delete this.class_id;
						delete this.event_id;
						delete this.event_date;

						//add the data to the month holder
						m.push(this);
					});
					e.months[year+''+month] = m;
				} else {
					e.months[year+''+month] = false;
				}
				//add the calendar data to this and refresh the datepicker
				e.currentCalendar = e._exportCalendar(year, month);
				jQuery('#'+inst.id).datepicker('refresh');
			}//end success
		});
	},
	_exportCalendar: function(year, month){
		calendar_info = {};
		
		//loop through the events for the month
		$(this.months[year+''+month]).each(function(){
			formatted_date = $.datepicker.formatDate('mm-dd-yy', this.date);

			if(calendar_info[formatted_date]){
				//add the title and category span
				calendar_info[formatted_date][2] =  calendar_info[formatted_date][2] + ", " + this.title;
				
				//first check to make sure we aren't doubling up on category markers
				var span = '<span class="category" style="background:#'+this.calendar_color+';"></span>';
				if(calendar_info[formatted_date][3].indexOf(span) == -1)
					calendar_info[formatted_date][3] = calendar_info[formatted_date][3] + span;

			} else {
				calendar_info[formatted_date] = [true, 'event', this.title, '<br /><span class="category" style="background:#'+this.calendar_color+';"></span>'];
			}
		});

		return calendar_info;

	},
	_redrawList: function(year, month){
		//make sure to empty out the event list
		var $event_list = jQuery(this.eventListSelector);
		$event_list.empty();
		
		//are there events in this month?
		if(this.months[year+''+month]){
			//setup a refrence to this for the scope change in the loop
			var e = this;

			//now loop through the events in the current month
			$(e.months[year+''+month]).each(function(){
				// touchup the title and time description to keep
				if(!this.title)
					this.title = "Untitled Event";
				if(!this.time_description || this.time_description=="false")
					this.time_description = "No time supplied";

				//clone and add data to the empty event
				var event = jQuery(e.emptyEventSelector).clone().removeAttr('id').addClass('d'+jQuery.datepicker.formatDate('mm-dd-yy',this.date)).
				find('.calendar_color').
					css('background','#'+this.calendar_color).end().
				find('.day_calendar').
					addClass(this.calendar_month).append(jQuery.datepicker.formatDate('d',this.date)).end().
				find('.month').
					text(this.calendar_month).end().
				find('p.title').
					html(this.title).end().
				find('p.category').
					text(this.category).end().
				find('p.time').
					text(this.time_description).end().
				find('div.description').
					html(this.description).end();			
			
				//add in notes if its there
				if(this.notes)
					event.find('div.description').prepend('<p class="note">'+this.notes+'</p>');
			
				$event_list.append(event);
				
				//console.log(event);
			});
		} else {
			//notify that theres no events this month
			var msg = [];
			msg['english'] = 'There are currently no events scheduled for this month. Please check back at a later date.';
			msg['spanish'] = 'Actualmente no hay eventos programados para este mes. Por favor, compruebe de nuevo en una fecha posterior.';

			jQuery('<div/>').addClass('event error').append('<p><strong>'+msg[$.cookie('language')]+'</p></strong>').appendTo(this.eventListSelector);
		}
	},
	//can't _formatTime because of the scope within the ajax function in _load
	formatTime: function(time){
		if(!time)
			return false;

		time_parts = time.split(':');
		hours = time_parts[0];
		minutes = time_parts[1];	

		var suffix = "am";
		if(hours >= 12) {
			suffix = "pm";
			hours = hours - 12;
		}
		if(hours == 0) {
			hours = 12;
		}
		
		format_time = hours+':'+minutes+suffix;

		return format_time;
	}
};


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
	});
}

function checkRegexp(o,regexp) {
	if ( !( regexp.test( o.val() ) ) ) {
		return false;
	} else {
		return true;
	}
}

function checkLength(o,min,max) {
	if ( o.val().length > max || o.val().length < min ) {
		return false;
	} else {
		return true;
	}
}

