$.nah = new Object();

// dynamic input lables (focus and blur)

// add filter selector if only certain inputs must use dynamic inputs
$.fn.dynamicInputLabels = function(filter) {

	var removeLabel = function($input) {

		if ($input.hasClass('dummy')) {
			$input.prev('input').show().focus().end().hide();
		}

		if ($input.val() === $input.data('label')) {
			$input.removeClass('blur').val('');
		}
	};

	var addLabel = function($input) {

		if ($input.is('input:password') && $input.val() === '') {
			$input.next('input').val($input.data('label')).show().end().hide();
		}

		if ($input.val() === '' || $input.val() === $input.data('label')) {
			$input.addClass('blur').val($input.data('label'));
		}
	};

	return this.each(function() {

		var $form, $inputs;
		$form = $(this);
		if (!filter) {
			$inputs = $form.find('input[type=text], input[type=password]');
		}
		else {
			$inputs = $form.find('input[type=text], input[type=password]').filter(filter);
		}

		$inputs.each(function() {

			var $input, label;
			$input = $(this);
			label = $form.find('label[for=' + $input.attr('id') + ']').hide().text();
			$input.data('label', label);

			$input.focus(function() {
				removeLabel($input);
			}).blur(function() {
				addLabel($input);
			});

			if ($input.is('input:password')) {

				var dummy = $('<input type="text" class="dummy" />').insertAfter($input).focus(function() {
					removeLabel(dummy);
				});

				if ($input.val() !== '') {dummy.hide();}
			}

			addLabel($input);

		});

		$form.submit(function() {
			$inputs.each(function() {
				removeLabel($(this));
			});
		});
	});
};

// contact form interactions (hide/show, etc)
$.nah.contactForm = {
	open: false,
	init: function() {
		this.$form = $('#callback');
        this.$formElement = this.$form.find('form');
		if (!this.$form.length) {return false;}

		this.$hiddenFields = this.$form.find('.fieldset'); // initially hidden with CSS (using .jsenabled)
        this.$claimonlineButton = this.$form.find('#claimonline-button')
		this.$form.find('#id_phone_1').focus($.proxy(this, 'show'));
		this.$hiddenFields.find('input[type=reset]').click($.proxy(this, 'hide'));
		this.$errors = this.$form.find('ul.errorlist');
        this.$claimonlineButton.click($.proxy(this, 'claimonlineRedirect'));

		if (this.$errors.length) {this.show();}
	},
	show: function() {
		this.$hiddenFields.show();
		this.open = true;
	},
	hide: function() {
		this.$errors.remove();
		this.$hiddenFields.hide();
		this.open = false;
		return false;
	},
    claimonlineRedirect: function () {
        // This grabs any filled out data in the callback form
        // and does a GET request to the daddy claimonline form
        // which autopopulates it with the data.
        var redirect_to = this.$claimonlineButton.attr('href');
        this.$wantedFields = this.$formElement.find('#id_phone_1, #id_phone_2, #id_phone_3, #id_name, #id_surname, #id_title');
        var query_string = ''
        this.$wantedFields.each(function(i) {
            $input = $(this);
            if (($input.val() != $input.data('label')) && ($input.val() != '')) {
                if (i == 0) {
                    query_string = $input.serialize();
                } else {
                    query_string += "&" + $input.serialize();
                }
            }
        });
        if (query_string != '') {
            redirect_to += "?" + query_string;
        }
        window.location.replace(redirect_to);
        return false;
    }
};

// fade contact form opacity
$.nah.contactFormFade = {
	scrollTop: 0,
	transitionSpeed: 200,
	init: function() {
		this.$form = $('#callback');
		if (!this.$form.length) {return false;}

		this.$form.hover($.proxy(this, 'fadeIn'), $.proxy(this, 'fadeOut'));

		$(window).scroll($.proxy(this, 'scrollHandler'));
	},
	scrollHandler: function() {
		this.scrollTop = $(document).scrollTop();

		if ($(this).scrollTop() === 0) {
			this.fadeIn();
		}
		else {
			this.fadeOut();
		}
	},
	fadeIn: function() {
		this.$form.stop().fadeTo(this.transitionSpeed, 1);
	},
	fadeOut: function() {
		if (this.scrollTop > 0 && !$.nah.contactForm.open) {
			this.$form.stop().fadeTo(this.transitionSpeed, 0.2);
		}
	}
};

$.nah.claimsCalculator = {
	init: function() {
		this.$container = $('#claims-calculator');
		if (!this.$container.length) {return false;}
		this._setUp();
	},
	jumpTo: function(injuryDetailId) {
		this._switchGender(injuryDetailId.split('-')[0] + '-injury-nav');
		this.$container.find('a[href=' + injuryDetailId + ']').click();
		this._enable();
		return false;
	},
	reset: function() {
		this._hideInjuryDetails();
		this._hideInjuryDetailnotlisted();
		this._switchGender('#male-injury-nav', true);
		this.$genderContainers.addClass('disabled-injury');
		this.$disableOverlay.show();
		$(window).scrollTop(0);
		return false;
	},
	_setUp: function() {
		this.$genderLinks = this.$container.find('#gender a').click($.proxy(this, '_genderLinksHandler'));
		this.$genderContainers = this.$container.find('#male-injury, #female-injury').filter('#female-injury').hide().end();
		this.$injuryLinks = this.$genderContainers.find('div.injury-nav a').click($.proxy(this, '_injuryLinksHandler')).hover(function() {
			// I've no idea why this works but adding any arbitrary class name to the list element on hover allows the CSS :hover to work in ie6...no styles are associated with the class 'ie6-fix'...very odd
			$(this).closest('li').addClass('ie6-fix');
		}, function() {
			$(this).closest('li').removeClass('ie6-fix');
		});
		this.$injuryDetails = this.$genderContainers.find('#male-injury-details li, #female-injury-details li');
		this.$injuryNotListed = this.$container.find('.injury-not-listed').hide();
		this.$startAgainBtn = this.$injuryNotListed.find('.start-again').click($.proxy(this, 'reset'));
		this.$disableOverlay = $('<div class="disabled-overlay">').appendTo(this.$genderContainers.filter('#male-injury'));
		this.reset();
	},
	_genderLinksHandler: function(e) {
		this._enable();
		this._hideInjuryDetails();
		this._hideInjuryDetailnotlisted();
		this._switchGender(e.target.hash);
		return false;
	},
	_injuryLinksHandler: function(e) {
		var injuryNavItem = e.currentTarget;
		var injuryDetailId = e.currentTarget.hash;

		this._hideInjuryDetails();
		this._showInjuryDetail(injuryNavItem, injuryDetailId);
		this._showInjuryDetailnotlisted();
		return false;
	},
	_enable: function() {
		this.$genderContainers.removeClass('disabled-injury');
		this.$disableOverlay.hide();
	},
	_switchGender: function(genderNavId, reset) {
		this.$genderContainers.hide().find(genderNavId).parents('#male-injury, #female-injury').show();

		if (reset) {
			this.$genderLinks.removeClass('type-5').addClass('type-4');
			return false;
		}

		var genderItem = this.$genderLinks.filter('a[href=' + genderNavId + ']');
		this.$genderLinks.not(genderItem).removeClass('type-5').addClass('type-4');
		$(genderItem).removeClass('type-4').addClass('type-5');

	},
	_showInjuryDetail: function(injuryLink, injuryDetailId) {

		if ($(injuryLink).parent().is('h3')) {
			$(injuryLink).closest('li').find('p a').addClass('current');
		}
		else {
			$(injuryLink).addClass('current');
		}

		var $injuryDetail = this.$injuryDetails.filter(injuryDetailId).show();
		var offset = $injuryDetail.offset();
		$('html, body').animate({'scrollTop': offset.top}, 800);
		//this.$injuryDetails.filter(injuryDetailId).show();

	},
	_hideInjuryDetails: function() {
		this.$injuryLinks.removeClass('current');
		this.$injuryDetails.hide();
	},
	_showInjuryDetailnotlisted: function() {
		this.$injuryNotListed.show();
	},
	_hideInjuryDetailnotlisted: function() {
		this.$injuryNotListed.hide();
	}
};

$.nah.calendarPicker = {
    init: function(){
		if (!$('input.datepicker-box').length) {return false;}

        $('input.datepicker-box').datepicker({ dateFormat: 'dd-mm-yy' });
        $('input.datetimepicker-box').datepicker({
            dateFormat: 'dd-mm-yy',
            duration: '',
            showTime: true,
            constrainInput: false,
            stepMinutes: 1,
            stepHours: 1,
            altTimeField: '',
            time24h: true  });
    }
};

/** requires swfObject **/
$.nah.videos = {
	flashvars: {
		lightcolor: 'white',
		frontcolor: 'white',
		backcolor: 'black',
		fullscreen : true,
		stretching: 'exactfit',
		plugins: 'gapro-1',
		'gapro.accountid': 'UA-1074435-1'
	},
	params: {
		allowfullscreen: true,
		wmode: 'transparent',
		allowscriptaccess: 'always'
	},
	init: function() {
		var $nav = $('#video-nav');
		if (!$nav.length) {return false;}
		var $anchors = $nav.find('a').click($.proxy(this, 'switchVideo'));
	},
	switchVideo: function(e) {
		var anchor  = e.target,
			videoUrl = anchor.href,
			imageUrl = $(anchor).attr('rel'),
			flashvars = {
				'file': videoUrl,
				'image': imageUrl
			};
			
		this.embed(flashvars);
		
		return false;

	},
	embed: function(flashvars) {
		this.flashvars = $.extend(this.flashvars, flashvars);
		
		swfobject.embedSWF('/assets/swf/player-licensed.swf', 'video', '390', '220', '9.0.0', false, this.flashvars, this.params);
	}
};

$(document).ready(function() {
	$('body').addClass('jsenabled'); // Enables css when js is enabled

	$.nah.contactForm.init();
	//$.nah.contactFormFade.init();
	$.nah.claimsCalculator.init();
	$.nah.calendarPicker.init();

	$('#callback form, #callback-alt form').dynamicInputLabels();
	$("#main-content #callback_form_id:not('#callback-alt form')").dynamicInputLabels('#id_name, #id_surname');
    $("#crumpleddog-december-2010").dynamicInputLabels('#id_name');
	
	$.nah.videos.init();
});

