/**
 *	wag.core.js
 *	- Core JS functions for wildaboutgardens.org
 *
 ********************************************************************************/

$(document).ready(function(){
		change_background();
		
		if($('#home-slides img').size() > 0){
			build_home_slides();	
		}	
		init_image_grid_content_slider();
		$('.hidden').css('display', 'none');
		
		if($('#tabs-wrapper').size() > 0){
			if(init_tabs()){
				$('#tabs-wrapper img').simple_captions();
			}			
		}else{
			$('img').not('#home-slides img').simple_captions();
		}
		
		equalHeight($(".row .col"));
		input_hint();
		validate_sign_up();
		build_drop_downs();
		show_print_button();
		$('#other-to-do').hide();
		do_local_scroll()
});

/**
 *	Swaps the backgournd images randomly
 */
function change_background(){
	var bg_image_url = '/img/page-backgrounds/';
	var num_bgs = 10;
	var randno = Math.floor ( Math.random() * num_bgs+1 );
	$('body').css('background', 'url('+bg_image_url+'bg-'+randno+'.jpg) no-repeat top center');
}

/*
*	Checks if browser is IE6
*/
function isIe6(){
	if( $.browser.msie && ($.browser.version < 7) ){
		return true;
	}else{
		return false;
	}
}

/**
 *	Home page slide show
---------------------------------------------------------------------------------*/
/**
 *	Build the slides
 */
function build_home_slides(){
	var target_elem = '#home-slides li#first'
	var html = '';
	$.getJSON("/json/home-slides.json",
		function(data){
			$.each(data.items, function(i,item){
			html += '<li>';
			html += '<div class="caption-wrapper">';
			html += '<img src="/img/home-slides/'+data.items[i]['img_src']+'.jpg" width="530" height="250" alt="'+data.items[i]['alt']+'" />';
			html += '</div>';
			html += '</li>';
			$("<img/>").attr("src", item.img_src).appendTo("#images");
				//if ( i == 3 ) return false;
			});
			if($(target_elem).after(html)){
				startHomeSlides();
			}
	  });
}

/**
 *	Init the home page slide hsow
 */
function startHomeSlides(){
	$('#home-slides ul').cycle({ 
	    fx:     'fade', 
	    speed:   1000, 
	    timeout: 3000, 
	    pause:   1, 
		before:  cycleOnBefore, 
		after:   cycleOnAfter
	});
}
/**
 *	Called before the transition starts
 */
function cycleOnBefore() { 

	if($(this).find('.caption_wrapper').size() > 0){
		var caption = $(this).find('.caption');
		caption.attr('id', 'curr_caption')
	}else{
		var caption = buildCaption(this);
	}
	
	if(isIe6()){
		caption.fadeOut(500).css('display', 'block');
		//$(this).mouseleave(function(){caption.css('display', 'none');})
} else {

    if (jQuery.support.opacity) {
        caption
		.fadeTo(0, 0).css('bottom', '0px').fadeTo(1000, 1);
    }
    else {
        caption
		.animate({ bottom: '0px' }, 1000)
		.animate({ bottom: '0px' }, 2000)
    }

	}
} 
/**
 *	Called when the transition ends
 */
function cycleOnAfter() { 
	var caption = $('#curr_caption');
	
	if(isIe6()){
		//caption.css('display', 'none');
	}else{

	    if (jQuery.support.opacity) {
	        setTimeout(function() { caption.fadeTo(500, 0) }, 1500);
	    }
	    else {
	       caption.animate({ bottom: '-55px' }, 500);
	    }
		caption.attr('id', '');		
	}
}

/**
 *	The credit captions
---------------------------------------------------------------------------------*/
/**
 *	Build the caption and caption wrapper
 */
function buildCaption(elem){	
	if(elem.tagName !== 'IMG'){
		var img = $(elem).find('img');
	}else{
		var img = elem;
	}	
	//var w = $(img).css('width');
	
	if($('#home-slides').size() > 0){
		//console.log($(elem).parents());
		
		if($(elem).parents('#home-slides').size() > 0){
			var w = 530;
			var h = 250;
		}else{
			var w = 235;
			var h = 155;
		}
	}else{
		var w = $(img).width();
		var h = $(img).height();
	}
	

	
	var caption_html = '<div class="caption"><span>'+$(img).attr('alt')+'</span></div>';
	var wrapper = '<div class="caption_wrapper"></div>';
	var wrapper_outer = '<div class="caption_wrapper_outer"></div>';
	
	$(img)
	.wrap(wrapper)
	.parent()
	.css('position', 'relative')
	.wrap(wrapper_outer);
	
	$(img).after(caption_html).siblings('div');
	//$(img).attr('alt', '');
	
	var caption = $(img).siblings('div.caption');
	var caption_wrapper = $(img).parent('div.caption_wrapper');
	var caption_wrapper_outer = $(caption_wrapper).parent();
	caption_wrapper
	//.css('width',w)
	//.css('height',h)
	.css('overflow', 'hidden');
	
	if(	h > 0) {
		caption_wrapper
		.css('height',h)
	}
	
	caption_wrapper_outer
	.css('overflow', 'hidden')
	//.css('width', w)
	//.css('background-image', 'url("/img/common/bg-img-'+w+'.gif")')
	$(caption_wrapper_outer).parents('a').addClass('captioned')
	nw = Number(w) - Number(20);

	if($('ul.image-grid').size() == 0 || $('#home-slides').size() == 0) {
		//caption_wrapper_outer.css('background-image', 'url("/img/common/bg-img-'+w+'.gif")')
	}
	
	$('.three-col #primary img').each(function(){
		if($(this).css('width')=='425px'){
			$(this).parents('.caption_wrapper_outer').css('background-image', 'url("/img/common/bg-img-425.gif")')
		}
	})
	$('.two-col #primary .img-holder img').each(function(){
		if($(this).css('width')=='645px'){
			$(this).parents('.caption_wrapper_outer').css('background-image', 'url("/img/common/bg-img-645.gif")')
		}
	})	
	
	caption
	.css('bottom', '-60px')
	.css('font-size', '10px')
	.css('left', '0px')
	.css('padding-left', '10px')
	.css('padding-right', '10px')
	.css('position', 'absolute')
	.css('width', nw)
	//.attr('id', 'curr_caption');

	if($(caption_wrapper_outer).parents('a').size() > 0){
		$(caption_wrapper_outer).css('cursor', 'pointer').click(function(){
			var link_ref = $(this).parents('a').attr('href')
			window.location = link_ref;
		})
	}	
	
	// Block the animation from IE6 and FF2
	if(isIe6() || ($.browser.mozilla && (parseFloat($.browser.version) < 1.9))){
		caption.css('bottom', '0px').css('display', 'none').css('width');
	}
	return caption;	
}

/**
 *	Show the captions on image rollover
 */
jQuery.fn.simple_captions = function(options) {	
	// default settings
	var options = jQuery.extend( {
		colour: '#ffffff',
		slide_speed: 500, // speed at which the caption needs to slide
		caption_class_name: 'caption',
		caption_height: '55px',
		caption_background: 'url(/img/common/bg-caption.png)'
	},options);

	return this.each(function() {
		var caption = buildCaption(this);
		var caption_wrapper_outer = $(this).parents('div.caption_wrapper_outer');
		var this_caption = $(caption_wrapper_outer).find('div.caption');
		
		// Block the animation from IE6 and FF2
		
		if(isIe6() || ($.browser.mozilla && (parseFloat($.browser.version) < 1.9))){
			$(this).mouseenter(function(){caption.css('display', 'block');})
			$(this).mouseleave(function(){caption.css('display', 'none');})
		}else{
			/*if ($.browser.mozilla && (parseFloat($.browser.version) < 1.9)) {
			   console.log('hello')
			}*/
			
			caption_wrapper_outer.mouseenter(function(){
				var this_wrapper_height = $(this).height();
				var this_caption = $(this).find('.caption');
				this_caption.fadeTo(0, 0).css('bottom', '0px');
				if (jQuery.support.opacity) {
				    this_caption.fadeTo(500, 1)
	            }
	            else {
	                this_caption.fadeTo(500, 0.7)
	            }
			})
			caption_wrapper_outer.mouseleave(function(){
				var this_wrapper_height = $(this).height();
					$(this).find('.caption').fadeTo(500, 0);
            	})
		}
	});
}


/**
 *	Content sliders
---------------------------------------------------------------------------------*/
/**
 *	Builds the page nav
**/
function build_page_nav(scroll_elem, num_pages, appendType){
	var nav = '';
	if(num_pages > 1){
		nav += '<ul class="slide-controls">';
		if(!isIe6()){
			nav += '<li class="slide-prev"><a href="#" title="Previous page" id="grid_prev">Previous</a></li>';
		}
		
		for(var i=1; i<num_pages+1; i++){
			nav += '<li><a href="#" title="Go to page '+i+'" class="slide-control">'+i+'</a></li>';
		}
		if(!isIe6()){
			nav += '<li class="slide-next"><a href="#" title="Next page" id="grid-next">Next</a></li>';
		}
		nav += '</ul>';
		switch(appendType){
			case 'appendTo':
				if($(nav).appendTo($(scroll_elem))){
					return true;
				}else{
					return false;
				}
			break;
			case 'before':

				if($(scroll_elem).before(nav)){
					return true;
				}else{
					return false;
				}
			break;
		}
	}else{
		$('.pagination').remove();
		
		/*var num_items = $('ul.image-grid li').not('ul.link-list li').size();
		console.log(num_items)
		switch(num_items){
			case 3:
				$('ul.image-grid li')
				.not('ul.link-list li')
				.css('background-image', 'none')
				.css('margin-bottom', '-10px')
			break;
		}
		
		$('ul.image-grid').addClass('single-page clear');*/
	}
}

function init_image_grid_content_slider(){
	if($("#scroll-pages").size() > 0){
		equalHeight($(".image-grid li").not($('.image-grid li ul.link-list li')));
		var grid_height = $('ul.image-grid').height();

		if(build_page_nav(".pagination", $('ul.image-grid').size(), 'appendTo')){
			$(".slide-controls").jFlow({
				slides: "#scroll-pages",
				controller: ".slide-control", // must be class, use . sign
				slideWrapper : "#jFlowSlide", // must be id, use # sign
				selectedWrapper: "jFlowSelected",  // just pure text, no sign
				width: "645px",
				height: grid_height+'px',
				duration: 400,
				useControlText: 'true',
				prev: ".slide-prev", // must be class, use . sign
				next: ".slide-next" // must be class, use . sign
			});

			var paging_width = (19 * $(".pagination").find('.slide-control').size() / 2);
			$(".slide-controls").css('width', paging_width);
			$(".pagination").addClass('scrollable');
		}else{
			grid_height = grid_height;
			$('ul.image-grid').height(grid_height+'px')
		}
	}
}

/**
 *	Calendars
---------------------------------------------------------------------------------*/
/**
 *	Inititlaise the tabs
**/
function init_tabs(){

	$(function() {
		
		$("#tabs-wrapper").addClass('tabbed');
		$("#tabs-wrapper ul.tabs").tabs("#tabs-wrapper div.panes > div", {
			history: false,
			effect: 'default',
			onClick: function(){
				return false;
			}	
		});	
		$("#tabs-wrapper div.panes ul.inner-tabs").tabs("#tabs-wrapper div.panes #other-to-do div", {
			history: false,
			effect: 'fade',
			initialIndex: -1
		})
		$("#tabs-wrapper div.panes ul.inner-tabs li a").click(function(){
			$('#other-to-do').show();
			/*console.log($(this));
			$(this).scrollTo({
				stop: true,
				duration: 300
			});*/
			return false;
		});	
		
	});
	if(init_tabs_slideable('inner-slide')){
		return true;
	}else{
		return false;
	}
	
}
	
	
function do_local_scroll(){
	$('a[href*=#]').click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
		 		var $target = $(this.hash);
		 		$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
		 		if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body')
					.animate({scrollTop: targetOffset}, 1000);
		  		return false;
		 		}
		}
	});
}


/*
 *	Internal tab content and sliders
**/

function init_tabs_slideable(scroller_id){
	if($("#"+scroller_id).size() > 0){

		var wrapper_div = "#slidewrapper_"+scroller_id;
		var num_items = $("#"+scroller_id+" ul.items li").size();
		if(build_page_nav("#"+scroller_id+' ul.items', num_items, 'before')){

			$("#"+scroller_id+" .slide-controls").jFlow({
				slides: "#"+scroller_id+' ul.items',
				controller: ".slide-control", // must be class, use . sign
				slideWrapper : wrapper_div, // must be id, use # sign
				width: "625px",
				height: "450px",
				duration: 500,
				useControlText: 'false',
				prev: ".slide-prev", // must be class, use . sign
				next: ".slide-next" // must be class, use . sign
			});
			$("#"+scroller_id+" ul.items").css('width', (num_items)*625+'px').css('height', '450px');
			$("#" + scroller_id + " ul.items li").css('width', '625px').css('height', '450px');
			//$("#tabs-wrapper.tabbed div.panes div#inner-slide").height();
		}
		var paging_width = (19 * $(".slideable").find('.slide-control').size());
		$(".slide-controls").css('width', paging_width);
		return true;	
	}
}


/**
 *	Equal height columns
	http://www.cssnewbie.com/example/equal-heights/
---------------------------------------------------------------------------------*/

function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

/**
 *	Forms
---------------------------------------------------------------------------------*/

/**
 *	Hints for inputs
*/

function input_hint(){
	$('#signup input, form#aspnetForm input').each(function(){
		$(this).attr('autocomplete', 'off')
		var label_text = $(this).siblings('label').text();
		$(this).siblings('label').hide();
		$(this).attr('value', label_text).addClass('hint').focus(function(){
			$(this).attr('value', '').removeClass('hint');
		}).blur(function(){
			if($(this).attr('value') == ''){
				$(this).attr('value', label_text).addClass('hint')
			}
			
		})
	})
}
/**
 *	Validate the sign up form
*/
function validate_sign_up(){
	// this one requires the text "buga", we define a default message, too
	$.validator.addMethod("nameHint", function(value) {
		return value !== $('#s_name_label').text();
	}, 'Please enter your name');
	$.validator.addMethod("emailHint", function(value) {
		return value !== $('#s_email_label').text();
	}, 'Please enter a valid email address');	

	// this one requires the value to be the same as the first parameter
	$.validator.methods.equal = function(value, element, param) {
		return value == param;
	};
/*
	$("#aspnetForm, form#signup").validate({
			errorPlacement: function(error, element) {
				error.hide().insertBefore( element.parent("p") ).fadeIn(500);
			},
			rules: {
				s_name: "required",
				s_email: {
					required: true,
					email: true
				},
				s_email: "emailHint",
				s_name: "nameHint"

			},
			messages: {
				s_name: "Please enter your name",
				s_email: "Please enter a valid email address"
			}
		});		
		*/
}

/**
 *	Get the content for the drop downs
---------------------------------------------------------------------------------*/

/*
 *	Get the contents for the drop down and append to the page
 */

function build_drop_downs(){
	if($('.drop-down').size() > 0){
		// Hide the drop down from ff2 mac
		if(!($.browser.mozilla && (parseFloat($.browser.version) < 1.9))){
			var source_file = '/inc/dropdowns/'+$('.drop-down').attr('id')+'.dropdown.inc';
			$.get(source_file, function(data){ 
				$('.drop-down').append(data);
				$('.drop-down').find('select').change(go_to_url);
			});
		}

	}	
}
/*
 *	Jump to the selected URL
 */
function go_to_url(){
	var selected = $("select option:selected");		
	var output = "";
	if(selected.val() != 0){
		window.location = selected.val();
	}
}

/**
 *	Print methods
---------------------------------------------------------------------------------*/

function show_print_button(){
	$('.module').addClass('no-print');
	var btn_html = '<div class="print"><p><a href="'+window.location+'?action=print" title="Open a printable version of this page in a new window" target="_blank">Print</a></p></div>';
	if($('#breadcrumbs').append(btn_html)){
		if($('div#print-bottom').size() > 0){
			$('div#print-bottom').append(btn_html);
		}
		$('div.print a').click(function(){
			window.open(window.location+'?action=print','printWindow','width=600,height=576 0,left=250,top=200, scrollbars=yes,resizable=yes');
			return false;
		});
	}
}


