// Site scripts
$(document).ready(function () {

	// Load JS Libraries
	$.refractiv.core.load([
		$.refractiv.libraries.placeholder,
		$.refractiv.libraries.validate,
		$.refractiv.libraries.tabsConvert,
		$.refractiv.libraries.repeater,
		$.refractiv.libraries.elastic,
		$.refractiv.libraries.qtip,
		$.refractiv.libraries.ui.mouse,
		$.refractiv.libraries.ui.datepicker,
		$.refractiv.libraries.ui.monthpicker,
		$.refractiv.libraries.ui.button,
		$.refractiv.libraries.ui.dialog,
		$.refractiv.libraries.ui.themes.aristo
	]);

	// Namespace for bespoke robinwood functionality
	$.robinwood = {
		tooltips: function(context) {
			// Search through each element and add the title attribute to the element as jQuery data
			// Then remove the original title
			$(context).each(function (index, element) {
				if ($(element).attr("title") > "") {
					$(element)
					.data("title", $(element).attr("title"))
					.parent()
					.addClass("tip")
					.end()
					.attr({title: null});
					if ($(element).data("title") > "") {
						$(element).qtip({
							content: function () {
								return $(element).data("title"); 
							},
							position: {
								target: $(element),
								my: 'bottom center',
								at: 'top center'
							},
							style: {
								classes: 'ui-tooltip-shadow ui-corner-all',
								widget: true
							}
						});						
					}
				}
			});
		},
		groups: {
			container: 'div.form-section-groups div.refractiv-tabs-container',
			populate: function() {
				// Get values from the bookings object generated by a hacky dblist
				// It's absolutely awful but it will have to do
				if (typeof(bookings) !== 'undefined') {
					// Convert to tabs
					$('div.form-section-tabs').refractiv_tabsConvert({
						clean: false,
						min: 1
					});
					var el = $('div.refractiv-tabs-container');
					el.bind("tabsselect", function(event, ui) {		
						if (el.tabs("length") == parseInt(ui.index + 1)) {
							$('button.cms-forms-button-submit').button("enable");
						}
					});
					// Disable button temporarily
					$('button.cms-forms-button-submit').button("disable");
					// For each adult record
					for (record in bookings) {
						if (typeof(bookings[record]) == 'object') {
							// Set the tab name
							$('div.form-section-tabs a[href="#refractiv-tabs-' + record + '"]').html(bookings[record]["name"]);						
							// Setup adult rows
							$('div#refractiv-tabs-' + record + ' div.group-adults.repeater').refractiv_repeater({
								min: 1,
								max: 2
							});
						}
					}
				}
			}
		},
		activities: function() {
			if (typeof(activities) !== 'undefined') {
				$('div.activities div.fields').each(function(i){
					$(this).find('div.activity-name').html(activities[i]["name"]);	
				});
			}
		},
		staff: function() {
			if (typeof(staff) !== 'undefined') {
				$('div.staff div.fields').each(function(i){
					$(this).find('div.input div.staff-name').html(staff[i]["name"]);
					$(this).find('div.input div.staff-role').html(staff[i]["role"]);
				});
			}
		},
		confirm: function(options) {
			// Extend confirm
			var options = $.extend({
				form: 'form#frmCMSForm',
				dialog: '#dialog',
				submit: 'button.cms-forms-button-submit',
				save: 'button.cms-forms-button-save',
				hidden: 'input#submitFake'
			}, options);
			// Check dialog exists
			if($(options.dialog).length !== '') {
				// jQuery UI Dialog Settings 
				$(options.dialog).dialog({
					autoOpen: false,
					width: 400,
					modal: true,
					resizable: false,
					buttons: {
						"Submit Form": function() {
							$(this).dialog("close");
							$(options.form).submit();							
						},
						"Cancel": function() {
							$(this).dialog("close");
						}
					}
				});
				// Add event to submit button in order to set the value of the hidden input
				// This will also fire the dialog and deny the form submission
				$(options.submit).click(function(){
					$(options.hidden).val('submit');
					$(options.dialog).dialog('open');
					return false;
				});
				// Destroy the validator to prevent validation
				// Add event to save button in order to set the value of the hidden input
				// This will also submit the form
				$(options.save).click(function(){					
					var validator = $(options.form).data("validator");
						validator.destroy();
					$(options.hidden).val('save');
					$(options.form).submit();
				});
			}
		}
	};

	// Robinwood functionality
	$.robinwood.tooltips("label");
	$.robinwood.groups.populate();
	$.robinwood.staff();
	$.robinwood.activities();
	$.robinwood.confirm();

	// HTML5 Placeholder
	$('input[placeholder]').refractiv_placeholder();

	// Render Dashboard Tabs
	/*
	$('div.dashboard-tabs').refractiv_tabsConvert({
		clean: false,
		ajax: 'a',
		children: 'div.tab-content',
		title: 'a',
		min: 1					
	});
	*/
	
	// Dashboard Links
	$('#dashboard-nav a').button();
	
	// Fieldset Styling
	$('fieldset').addClass('ui-widget ui-widget-content');
	$('fieldset legend').addClass('ui-widget-header ui-corner-all');
	
	/*
	
	// Convert submit buttons to buttons
	$('#container.youraccount input:submit, #container.youraccount input[class="submit"]').each(function(){
		$(this).replaceWith($('<button />', {
			'type': $(this).attr('type'),
			'class': $(this).attr('class') + ' ' + $(this).val()
		}).html($(this).val()));
	});
	
	// Conver buttons
	$('button').button();

	*/

	// Check form status, if it's in view mode, set the buttons to disabled
	if ($("#frmCMSForm").hasClass("view")) {
		$.robinwood.disabled = true;
		// Add print button
		$("<button />", {
			id: "print-button"
		})
		.html("Print")
		.appendTo("div#print")
		.button({
			icons: {
				primary: 'ui-icon-print'
			}
		})
		.click(function(){
			window.print();
		});
		// Add <pre> wrap to textareas
		$("div.input-type-textarea span").wrapInner("<pre />");
	} else {
		$.robinwood.disabled = false;
	}

	$.robinwood.tipConf = {
		position: {
			my: 'bottom center',
			at: 'top center'
		},
		style: {
			classes: 'ui-tooltip-shadow ui-corner-all',
			widget: true
		}
	}

	// Setup styles
	$('button.cms-forms-button-submit').button({
		disabled: $.robinwood.disabled,
		icons: {
			primary: 'ui-icon-circle-check'
		}
	}).qtip(
		$.extend(
			true, 
			{
				content: "Once submitted, any changes would have to be made by contacting Head Office.",
				position: {
					target: $('button.cms-forms-button-submit')
				}
			},
			$.robinwood.tipConf
		)
	);

	$('button.cms-forms-button-save').button({
		disabled: $.robinwood.disabled,
		icons: {
			primary: 'ui-icon-disk'
		}
	});

	// Convert DOB field into jQuery UI Datepicker
	$("input.dob").each(function(){
		$(this).datepicker({
			dateFormat: 'dd/mm/yy',
			changeMonth: true,
			changeYear: true,
			yearRange: '1997:2011',
			minDate: "-14Y",
			maxDate: "+0D",
			buttonImage: "/cms/images/famfamfam/silk/icons/calendar.png",
			buttonImageOnly: true
		});
	});

	//Convert Date field into jQuery UI Datepicker
	$("input.form-date").each(function(){
		$(this).datepicker({
			dateFormat: 'dd/mm/yy',
			changeMonth: true,
			changeYear: true,
			yearRange: '1911:2011'
		});
	});

	$('input.form-date-month').monthpicker({
		yearRange: '1900:2011'
	});

	// Setup email field validation
	$('input.form-input-email').attr({onblur: null}).unbind("onblur");
	
	// Convert text areas to elastic areas on click
	$("form#frmCMSForm textarea").each(function (index, element) {
		if ($(element).html().length > 0) {
			$(element).elastic();
		} else {
			$(element).click(function(){
				$(this).elastic();
			});
		}
	});

	// HTML5 Validation
	$('form').refractiv_validate({
		focus: {
			enabled: true,
			tabs: true,
			time: 800
		},
		validator: {
			effect: 'refractiv'
		}
	});
	
});
