/*
 * jQuery serializeObject - v0.2 - 1/20/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,a){$.fn.serializeObject=function(){var b={};$.each(this.serializeArray(),function(d,e){var f=e.name,c=e.value;b[f]=b[f]===a?c:$.isArray(b[f])?b[f].concat(c):[b[f],c]});return b}})(jQuery);

function resizeScrollArea(panel) {
	var pcheight=($('#'+panel+' .panelContent').css('height'));
	var pcheight=parseInt(($('#'+panel+' .panelContent').outerHeight(true)))+20;
	var toheight=(pcheight>350)?pcheight:350;
	$('#scrollView').animate({height: toheight}, 'fast');
}
function validateList(target, source, highlight) {
	$(target+' tbody input:visible, '+target+' tbody select:visible').each(function(){
		if (($(this).val().length>0 || $(this).hasClass('optional')) && !($(this).hasClass('currency') && isNaN($(this).val()))) {
			$(source).parentsUntil('.panelContent').last().children('h2, h3').removeClass('incomplete');
		} else {
			driversValid=false;
			if (highlight) $(source).parentsUntil('.panelContent').last().children('h2, h3').addClass('incomplete');
			//return false;
		}
	});
}
function validateSection(section, highlight) {
	sectionValid=true;
	$('#'+section+' h2:visible, #'+section+' h3:visible').each(function() {
		var subsectionValid=true;
		$(this).parent().find('input[type=text]:visible, select:visible, input.required:hidden').each(function() {
			var ok=false;
			if ($(this).val().length>0 || $(this).hasClass('optional')) {
				if ($(this).hasClass('dd') || $(this).hasClass('yyyy')) {
					ok=!isNaN($(this).val());
				} else if ($(this).hasClass('cipostcode')) {
					$(this).val($(this).val().toUpperCase());
					var postcode=$(this).val();
					ok=(postcode.indexOf('GY')==0/* || postcode.indexOf('JE')==0*/);
				} else {
					ok=true;
				}
			}
			
			if (ok) {
				if (subsectionValid) $(this).parentsUntil('.panelContent').last().children('h2, h3').removeClass('incomplete');
			} else {
				sectionValid=subsectionValid=false;
				if (highlight) $(this).parentsUntil('.panelContent').last().children('h2, h3').addClass('incomplete');
			}
			
			/*if (($(this).val().length>0 || $(this).hasClass('optional')) && !(($(this).hasClass('dd') || $(this).hasClass('yyyy')) && isNaN($(this).val()))) {
				if (subsectionValid) $(this).parentsUntil('.panelContent').last().children('h2, h3').removeClass('incomplete');
			} else if (subsectionValid) {
				sectionValid=subsectionValid=false;
				if (highlight) $(this).parentsUntil('.panelContent').last().children('h2, h3').addClass('incomplete');
			}*/
		});
		var radios=new Object();
		$(this).parent().find('input[type=radio]:visible').each(function() {
			if (radios[$(this).attr('name')]==undefined) {
				radios[$(this).attr('name')]=(($(this).attr('checked'))?$(this).val():-1);
			} else if ($(this).attr('checked')) {
				radios[$(this).attr('name')]=(($(this).attr('checked'))?$(this).val():-1);
			}
		});
		for (key in radios) {
			if (radios[key]<0) {
				sectionValid=subsectionValid=false;
				if (highlight) $('#'+key+'Yes').parentsUntil('.panelContent').last().children('h2, h3').addClass('incomplete');
			} else {
				if (radios[key]>0) {
					validateList('#'+key+'Details', '#'+key+'Yes', highlight);
				} else if (subsectionValid) {
					$('#'+key+'Yes').parentsUntil('.panelContent').last().children('h2, h3').removeClass('incomplete');
				}
			}
		}
	});

	if (sectionValid) {
		$('ul#scrollerNav li a.'+section+'tab').addClass('complete');
	} else {
		$('ul#scrollerNav li a.'+section+'tab').removeClass('complete');
	}
	return sectionValid;
}

function bindDatePickers() {
	if ($('.datepicker').length>0) {
		/*$(document).click(function(event) {
			if ($(event.target).closest('.datepicker, .ui-datepicker-prev, .ui-datepicker-next').length<1) $('.ui-datepicker:visible').hide();
		});*/
		$('.datepicker').each(function() {
			if ($(this)[0].tagName=='DIV') {
				$field=$(this).children(':first');
				var date=($(this).find('input').val());
				
				var dpOptions={dateFormat:'yy-mm-dd', changeMonth:true, changeYear:true, yearRange:'-90:+2', showOtherMonths: true, selectOtherMonths: true};
				dpOptions.onSelect=	function(dateText, inst){
										$('#'+inst.id).children('input:first').val(dateText);
										var dateComponents=dateText.split('-',3);
										var date=new Date(dateComponents[0], dateComponents[1]-1, dateComponents[2])
										$(this).children('span:first').html(date.toDateString()+' (Click to set date)');
										$(this).children('.ui-datepicker').hide();
									}
				if ($(this).hasClass('nopast')) {
					dpOptions.yearRange='0:+2';
					dpOptions.minDate=0;
				} else if ($(this).hasClass('nofuture')) {
					dpOptions.yearRange='-100:+0';
					dpOptions.maxDate=0;
				} else if ($(this).hasClass('over16dob')) {
					dpOptions.yearRange='-100:-15';
					dpOptions.maxDate='-15y -11m';
				}
				$(this).datepicker(dpOptions);
				if (date.length>0) $(this).datepicker('setDate', date);
				$(this).children('.ui-datepicker').hide();
				$(this).children('span:first').click(function (event) {
					$(this).siblings('.ui-datepicker').show();
				});
			} else if ($(this)[0].tagName=='INPUT'){
				$(this).datepicker({dateFormat:'yy-mm-dd', changeMonth:true, changeYear:true, maxDate:'+0', yearRange:'-6:+0', showOtherMonths: true, selectOtherMonths: true});
			}
		});
	}
}

$(document).ready(function(){
	bindDatePickers();
	
	$('input.showDetails, input.hideDetails').change(function(){
		var panel=$(this).parentsUntil('.panel').parent().attr('id');
		if ($(this).hasClass('showDetails')) {
			$(this).parent().find('.extraDetails').slideDown(function(){resizeScrollArea(panel);});
		} else {
			$(this).parent().find('.extraDetails').slideUp(function(){resizeScrollArea(panel);});
		}
	});
	
	$('input.dd, input.yyyy').focus(function(){
		if ($(this).val()=='dd'||$(this).val()=='yyyy') $(this).val('');
	});
	$('input.dd').blur(function(){
		if ($(this).val()=='') {
			$(this).val('dd');
		} else if ($(this).val()<10 && $(this).val().length==1) {
			$(this).val('0'+$(this).val());
		}
	});
	$('input.yyyy').blur(function(){
		if ($(this).val()=='') {
			$(this).val('yyyy');
		} else if ($(this).val()<100) {
			var d=new Date();
			if ($(this).val()>(d.getFullYear()-2000)) {
				$(this).val(1900+parseInt($(this).val()));
			} else {
				$(this).val(2000+parseInt($(this).val()));
			}
		}
	});
	
	$('#highvalueAdd').click(function() {
		var count=$('#highvalueCount').val();
		++count;
		$('table#highvalueItems tbody').append('<tr><td><input type="text" name="highvalueItem-'+count+'_text" value="" /></td><td>&pound;<input type="text" class="currency" name="highvalueValue-'+count+'_currency" value="" /></td></tr>');
		$('#highvalueCount').val(count);
		resizeScrollArea('cover');
		return false;
	});
	$('#highvalueRemove').click(function() {
		var count=$('#highvalueCount').val();
		if ($('table#highvalueItems tbody tr').length>0) {
			$('table#highvalueItems tbody tr:last').remove();
			--count;
		}
		$('#highvalueCount').val(count);
		return false;
	});
	
	$('#claimsAdd').click(function() {
		var count=$('#claimsCount').val();
		++count;
		$('table#hasClaimsDetails tbody').append('<tr><td><input type="text" name="claimsDate-'+count+'" value="" class="datepicker" /></td><td><input type="text" name="claimsItem-'+count+'" value="" /></td><td>&pound;<input type="text" class="currency" name="claimsAmount-'+count+'" value="" /></td></tr>');
		$('#claimsCount').val(count);
		bindDatePickers();
		return false;
	});
	$('#claimsRemove').click(function() {
		var count=$('#claimsCount').val();
		if ($('table#hasClaimsDetails tbody tr').length>0) {
			$('table#hasClaimsDetails tbody tr:last').remove();
			--count;
		}
		$('#claimsCount').val(count);
		return false;
	});

	
	function selectNav() {
	  $(this).parents('ul:first').find('a').removeClass('selected').end().end().addClass('selected');
	}
	
	function beforeScroll(event, target, scroller) {
		var current=$('#scrollerNav a.selected').attr('href').substr(1);
		if (target.id=='quote') {
			validate(current,true);
			getQuote();
		}
		if (current!=target.id && event.target.value!='Back') {
			return validate(current,true);
		}
		return true;
	}
	function trigger(data) {
		var el = $('#scroller #scrollerNav').find('a[href$="'+data.id+'"]').get(0);
		selectNav.call(el);
		resizeScrollArea(data.id);
	}
	if ($('#scroller').length>0) {
		var scrollOptions = {
			target: $('#scrollView'), // the element that has the overflow
			items: $('#scrollArea .panel'), // can be a selector which will be relative to the target
			navigation: '#scrollerNav a', // selectors are NOT relative to document, i.e. make sure they're unique
			prev: '.innerBack',
			next: '.innerNext, .innerQuote',
			cycle: false,
			axis: 'xy', // allow the scroll effect to run both directions
			onBefore: beforeScroll,
			onAfter: trigger, // our final callback
			offset: (parseInt($('#scrollContent').css('paddingTop')) * -1),
			duration: 500, // duration of the sliding effect
			easing: 'swing'
		};
		$('#scrollerNav').localScroll(scrollOptions);
		$('#scroller').serialScroll(scrollOptions);
		
		$('#scrollerNav a:first').click();
	}
	
	// tooltips
	if ($('input[title], span.tth').length>0) {
		$('input[title], span.tth').tooltip({
			position: "top center",
			offset:[-10, 0],
			effect:'fade',
			opacity:0.8
		});
	}
	
	// accordion
	if ($('.accordion').length>0) {
		if ($.browser.msie) $('.accordion div').css('zoom', '1');
		$(".accordion").accordion({
			autoHeight: false,
			navigation: false
		});
		$(".accordion .accNav .next").click(function(){
			$(".accordion").accordion('activate', $(this).parent().parent().next());
			return false;
		});
		$(".accordion .accNav .back").click(function(){
			$(".accordion").accordion('activate', $(this).parent().parent().prev().prev().prev());
			return false;
		});
	}
	
	// buttons
	if ($(".button").length>0) $(".button").button();
	
	// sib specific
	if ($('#sharpIBSearchBox').length>0) {
		$('#sharpIBSearchBox').focus(function() {$(this).removeClass('empty');});
		$('#sharpIBSearchBox').blur(function() {
			if ($(this).val().length<1) {
				$(this).addClass('empty');
			}
		});
	}
	if ($('.overview').length>0) {
		$('.overview').click(function(){
			if ($(this).siblings('.extra').is(':hidden')) {
				$(this).siblings('.extra').slideDown();
			} else {
				$(this).siblings('.extra').slideUp();
			}
		});
	}
	if ($().supersleight) $('body').supersleight({shim:'/images/x.gif'});
});
