/*****************************************************************************
 *
 * Copyright © 2009 Simon Robb
 *
 * All rights reserved
 *
 ****************************************************************************/

(function () {
	
	$.fn.dump = function () {	console.debug ($(this)); return $(this); };
	
	if(typeof String.prototype.trim !== 'function') { 
 		String.prototype.trim = function() { 
    		return this.replace(/^\s+|\s+$/, '');  
  		} 
	} 

	
	var initSelect = function () {
		$('.bvp_select li').click (function () {
			$(this)
				.parents ('.bvp_select')
				.find ('li')
				.removeClass ('selected');
			$(this)
				.addClass ('selected')
				.parents ('.bvp_select')
				.find ('input[type="hidden"]')
				.val ($(this).attr ('alt'));
		});
		
		// Convert to carousel
		var selects = $('.bvp_select');
		$.each (selects, function (i, select) {
			var panels = $(this).attr ('alt') ? $(this).attr ('alt') : 3;
			var use_default = true;
			var options = $('.options', select).Carousel ({
					'nextButton': $('.down', select),
					'prevButton': $('.up', select),
					'direction': 'vertical',
					'autoCycle': false,
					'panelsVisible': panels,
					'length': 300,
					'panelHeight': 101
				})
				
				// Test if we need to select an item by default
				.find ('li')
				.each (function () { if ($(this).hasClass ('selected')) use_default = false; });
			
			if (use_default) options.parent ().eq (0).click ();
		});
	};
	
	var initCheckbox = function () {
		$('.bvp_cb').click (function () {
			$(this)
				.toggleClass ('selected')
				.find ('input[type="hidden"]')
				.val ($(this).hasClass ('selected')?1:0);
				
		});
	};
	
	var initPickers = function () {
		$('.bvp_picker').each (function () {
			var up = $(this).find ('.up');
			var down = $(this).find ('.down');
			var value = $(this).find ('input[type="hidden"]').attr ('value');
			
			var car = $(this)
				.find ('.options')
				.Carousel ({
					'initialValue': value,
					'nextButton': down,
					'prevButton': up,
					'direction': 'vertical',
					'autoCycle': false,
					'panelsVisible': 1,
					'panelHeight': 30,
					'length': 200
				});
			
			// Set the values on button click
			up
				.add (down)
				.click (function () {
					car
						.parent ()
						.find ('input[type="hidden"]')
						.val (car.data ('carousel').getValue ());
				});
		});
	};
	
	var initContactForm = function () {
		// Mirror the selected name in the fieldset legend
		var makeInstruction = function (name) { 
			return name + ' will receive your enquiry'; 
		};
		
		var to_control = $('#select_to');
		
		var init_name = to_control
			.find ('.selected')
			.attr ('title');
		
		var instruction = $('#select_to')
			.parents ('fieldset')
			.find ('div.instruction');
			
		if (init_name)
			instruction.html (makeInstruction (init_name));
			
		to_control
			.find ('.options li')
			.click (function () {
				var name = $(this).attr ('title');
				instruction.html (makeInstruction (name));
			});
			
		// Change the contacts available upon choosing a clinic
		$('#select_clinic .options li').click (function () {
			var clinic = $(this).attr ('alt');
			var firstItem = true;
			
			// Do the show/hide and select the first one shown
			$('#select_to .options li').each (function () {
				if ($(this).hasClass (clinic)) {
					$(this).show ();
					if (firstItem) $(this).click ();
					firstItem = false;
				}
				else
					$(this).hide ();
			});
			
			// Update the panel count in the control, since it may have changed
			if ($('#select_to .options').data ('carousel'))
				$('#select_to .options').data ('carousel').recount ();
		});
		
		// Select the first clinic if none already
		var clinic = $('#select_clinic input[type="hidden"]').val ();
		if (!clinic) {
			$('#select_clinic ul.options li:first-child').click ();
		}
		else {	// Otherwise hide any contacts not belonging to selected clinic
			// Fake a click to make sure everything is kosher
			$('#select_clinic li[alt="' + clinic + '"]').click ();
			
			$('#select_to .options li').each (function () {
				if ($(this).hasClass (clinic))	$(this).show ();
				else							$(this).hide ();
			});
		}
		
		// Update the panel count in the control, since it may have changed
		if ($('#select_to .options').data ('carousel'))
			$('#select_to .options').data ('carousel').recount ();
	};
	
	var initClinics = function () {
		$('#clinic_buttons li').click (function () {
			// Unselect other clinic buttons
			$('#clinic_buttons li').removeClass ('selected');
			
			// Hide other clinic details
			$('#clinic_details div').hide ();
			
			// Show the correct details
			var clinic = $(this).attr ('class');
			$('#clinic_details .' + clinic).show ();
			
			// Select this clinic button
			$(this).addClass ('selected');
		});
	};
	
	var initNav = function () {
		// Cancel link functionality for dropdowns
		$('#nav_primary a.nav_toplevel_link').click (function () {
			if ($(this).parent ().hasClass ('dropdown'))
				return false;
		});
		
		// All dropdowns are go!
		$('#nav_primary li.nav_toplevel_item')
			.hover (
				function () { $(this).addClass ('open') },
				function () { $(this).removeClass ('open') }
			);
	}
	
	var initLatest = function () {
		$('#latest_news_short li span.body').each (function () {
			var $$ = $(this)
				.html (pixelTrimLatest (
					$(this).html (),
					422
			));
		});
	};
	
	var pixelTrimLatest = function (str, length, suffix) {
		// Default suffix
		if (!suffix) suffix = '...';
		
		var tmp = str;
		var ruler = document.getElementById ('latest_ruler'); 
		
		var pixelLength = function (str) {
			ruler.innerHTML = str;
			return ruler.offsetWidth;
		}

		while (pixelLength (tmp + suffix) > length) {
			tmp = tmp.substring (0, tmp.length-1);
		}

		return tmp.trim () + suffix;
	};
	
	var initSlideshow = function () {
		// Grab the src attribute and make it the background
		$('#latest_ss .latest_image_ss').each (function () {
			$(this).css (
				'backgroundImage',
				'url(' + $(this).attr ('src') + ')'
			);
		});
		
		var pagingControl = $('#latest_ss #latest_ss_paging');
		
		var ss = $('#latest_ss ul#latest_ss_images')
			.Slideshow ({
				'autoCycle': true,
				'panelsVisible': 1,
				'panelWidth': 412,
				'panelHeight': 345,
				'length': 1000,
				'cycleInterval': 8000,
				'pagingControl': pagingControl,
				onChangeBegin: function (obj) {
					$('.latest_description_ss')
						.hide ()
						.eq (obj._index)
						.show ();
				}
			});
	};
	
	$(document).ready (function () {
		// Initialize navigation
		initNav ();
		
		// Initialize BVP graphical selects
		initSelect ();
		
		// Initialize BVP checkboxes
		initCheckbox ();
		
		// Initialize BVP pickers
		initPickers ();
		
		// Customized contact form functionality
		initContactForm ();
		
		// Homepage links (add javascript-disabled redundancy later!)
		$('#home_buttons li').each (function () {
			var loc = $(this)
				.find ('a.location')
				.css ('display', 'none')
				.attr ('href');
				
			$(this).click (function () { window.location = loc; })
		});
		
		// Initialize clinics page
		initClinics ();
		
		// Initialize latest slideshow
		initSlideshow ();
		
		// Trim the latest news snips
		initLatest ();
		
		// Emergency dropdown
		$('#emergency_button').click (function () {
			$('#emergency_contact').addClass ('open');
			return false;
		});
		$('body').click (function () {
			$('#emergency_contact').removeClass ('open');
		});
	});
})(jQuery);
