(function ($) {

    $.fn.crossfade = function (startOptions, endOptions) {
        var defaults = {
            'start' : {
                'type' : 'mouseenter',
                'delay' : 300,
                'callback' : null,
                'condition' : function () { return true; }
            },
            
            'end' : {
                'type' : 'mouseleave',
                'delay' : 300,
                'callback' : null,
                'condition' : function () { return true; }
            }
        };
        
        if (typeof options == 'number') {
            options = {
                'start' : { 'delay' : options },
                'end' : { 'delay' : options }
            };
        }
        
        var settings = {};
        settings.start = $.extend({}, defaults.start, startOptions);
        settings.end = $.extend({}, defaults.end, endOptions);

        // return this;
        return this.each(function (i) { 
            var $$ = $(this);
            var targetImage = $$.css('backgroundImage').replace(/^url|[\(\)']/g, '');

            var hiddenImage = $$.wrap('<span style="position: relative;"></span>')
                .parent()
                .prepend('<img>')
                .find(':first-child')
                .height($$.height())
                .width($$.width())
                .attr('src', targetImage);
                
            // CSS tweaks to position the starting image correctly
            if ($.browser.msie || $.browser.mozilla) {
                $$.css({
                    'position' : 'absolute', 
                    'left' : 0,
                    'background' : '',
                    'top' : $$.offsetTop
                });
            } else if ($.browser.opera && $.browser.version < 9.5) {
                // opera < 9.5 has a render bug - so this is required to get around it
                // we can't apply the 'top' : 0 separately because Mozilla strips
                // the style set originally somehow...
                $$.css({
                    'position' : 'absolute', 
                    'left' : 0,
                    'background' : '',
                    'top' : "0"
                });
            } else {
                $$.css({
                    'position' : 'absolute', 
                    'left' : 0,
                    'background' : ''
                });
            }
            
            if (settings.start.type) {
                $$.bind(settings.start.type, function () {
                    if (settings.start.condition.call(this)) {
                        $(this).stop().animate({
                            opacity: 0
                        }, settings.start.delay);
                    }
                    if (settings.start.callback) return settings.start.callback.call(this);
                });
            }
            
            if (settings.end.type) {
                $$.bind(settings.end.type, function () {
                    if (settings.end.condition.call(this)) {
                        $(this).stop().animate({
                            opacity: 1
                        }, settings.end.delay);
                    }
                    if (settings.end.callback) return settings.end.callback.call(this);
                });
            }
        });
    };
    
})(jQuery);

function mycarousel_initCallback(carousel) {
    $('#slideShowMenu a').bind('click', function() {
	 $(this).blur();
        carousel.scroll($.jcarousel.intval($(this).attr('id').slice(3)));
        carousel.startAuto(0);
        return false;
    });
};

function mycarousel_VisibleInCallbackBeforeAnimation(carousel,item,idx,state) {
	$("#slideShowMenu a").removeClass('selected');
	$("#slideShowMenu a#ss_"+idx).addClass('selected');
	
	$("#slideShowMenu a:not(#ss_"+idx+") img.fade").each(function(){
		$(this).attr('src',($(this).attr('src').replace('colour','bw')));
	});

	var img = $("#slideShowMenu a#ss_"+idx+" img.fade");
	img.attr("src",img.attr("src").replace('bw','colour'));
};

function mycarousel_VisibleInCallbackAfterAnimation(carousel,item,idx,state) { };

function calc_res(num) {

	//var fee = num<50 ? (20*num) : 1000+(num-50)*10;
	var fee = 30*num;
	if (fee<500) { fee = 500; }
	if (fee>10000) { fee = 10000; }
	return num>0 ? fee : 0;

}

function calc_nonres(num) {

	//var fee = num<5000 ? (20*Math.ceil(num/100)) : 1000+(10*Math.ceil((num-5000)/100));
  var fee = 30*Math.ceil(num/100);
  if (fee<500) { fee = 500; }
	if (fee>10000) { fee = 10000; }
	return num>0 ? fee : 0;

}

$(document).ready(function(){

	$("#slideShowContainer").jcarousel({
   	   scroll: 1,
	   auto: 4,
	   wrap: 'both',
	   easing: 'easeOutQuad',
	   animation: 'slow',
   	   initCallback: mycarousel_initCallback,
	   itemVisibleInCallback: {
		onBeforeAnimation: mycarousel_VisibleInCallbackBeforeAnimation,
		onAfterAnimation: mycarousel_VisibleInCallbackAfterAnimation
	   }
	});

	$(".homeSection ul li a.hotLink img.fade").removeClass('fade').attr('alt','').each(function(){
		$(this).parent().css('background-image',$(this).css('background-image'))
			.hover(function(){$(this).find(':first-child').fadeOut();},function(){$(this).find(':first-child').fadeIn();});
	});


	$("input#DwRes").keyup(function(){
		var num = parseInt($(this).val());
		var fee = calc_res(num);
		$("#DwRes_Fee").html(num>0 ? "&pound;"+fee.toFixed(2) : "");
	});

	$("input#DwCom").keyup(function(){
		var num = parseInt($(this).val());
		var fee = calc_nonres(num);
		$("#DwCom_Fee").html(num>0 ? "&pound;"+fee.toFixed(2) : "");
	});
	
	$("form#serviceCalcCombined input:text").each(function(){

		$(this).keyup(function(){
			var num1 = parseInt($("#Com1").val());
			var num2 = parseInt($("#Com2").val());
			var fee = (30*num1) + (30*Math.ceil(num2/100));
//			var fee = calc_res(num1) + calc_nonres(num2);
			if (fee<500) { fee = 500; }
			if (fee>10000) { fee = 10000; }
			$("#Com_Fee").html((num1+num2)>0 ? "&pound;"+fee.toFixed(2) : "");
		});
	});
	
	$('#Attachments').MultiFile();

	$("a.lightbox").fancybox();

	$("#slideShowMenu.isIE li a").each(function(){
		$(this).click(function(){
			$("#slideShowContainer ul li img.isIE").attr('src',$(this).find("img:first").attr('src').replace("/^url|[\(\)']/g", '').replace('thumbs\/colour','main').replace('main\/main','main'));
			$("#slideShowMenu a img").removeClass('selected');
			$("#slideShowMenu.isIE li a img").each(function(){
				$(this).attr('src',$(this).attr('src').replace('colour','bw'));
			});
			$(this).find("img:first").addClass('selected').attr('src',$(this).find("img:first").attr('src').replace('bw','colour	'));
			return false;
		});
	});

    $('#copyApplicantData').bind('click', function() {
		$(".applicant input").each(function(index) {
			var aInput = $(this);
			var cInput = $('#'+aInput.attr('id').replace('Applicant','Client'));
			if($("input#copyApplicantData:checked").length){
				cInput.val(aInput.val());
			} else {
				cInput.val('');
			}
		}); 
    });

	$(".cisAppForm").submit(function(){

		var errors = 0;
		if ($("input#Applicant_Phone_").val()=="") { errors++; }
		if ($("input#Applicant_Contact_").val()=="") { errors++; }
		if ($("input#Agent_Phone_").val()=="") { errors++; }
		if ($("input#Agent_Contact_").val()=="") { errors++; }
		if ($("input#Invoice_Name_").val()=="") { errors++; }
		if ($("input#Invoice_Business_").val()=="") { errors++; }
		if ($("input#Invoice_Address__1_").val()=="") { errors++; }
		if ($("input#Invoice_Postcode_").val()=="") { errors++; }
		if ($("input#Attachments").val()=="") { errors++; }
		if ($("input#recaptcha_response_field").val()=="") { errors++; }
		if ($("select#PointOfContact option:selected").val()=="") { errors++; }
		if ($("#Residential_Apartments").attr('checked') && $("#Residential_Apartments_Text").val() == "") { errors++; }
		if ($("#Residential_Houses").attr('checked') && $("#Residential_Houses_Text").val() == "") { errors++; }
		if ($("#Residential_Hotel").attr('checked') && $("#Residential_Hotel_Text").val() == "") { errors++; }
		if ($("#Residential_CareHome").attr('checked') && $("#Residential_CareHome_Text").val() == "") { errors++; }
		if ($("#Residential_Student").attr('checked') && $("#Residential_Student_Text").val() == "") { errors++; }
		if ($("#Commercial_Offices").attr('checked') && $("#Commercial_Offices_Text").val() == "") { errors++; }
		if ($("#Commercial_Retail").attr('checked') && $("#Commercial_Retail_Text").val() == "") { errors++; }
		if ($("#Commercial_Industrial").attr('checked') && $("#Commercial_Industrial_Text").val() == "") { errors++; }
		if ($("#Commercial_Leisure").attr('checked') && $("#Commercial_Leisure_Text").val() == "") { errors++; }
		if ($("#Commercial_Medical").attr('checked') && $("#Commercial_Medical_Text").val() == "") { errors++; }
		if ($("#Commercial_Eduation").attr('checked') && $("#Commercial_Eduation_Text").val() == "") { errors++; }
		if ($("#Commercial_Transport").attr('checked') && $("#Commercial_Transport_Text").val() == "") { errors++; }
		if ($("#Commercial_PlacesOfWorship").attr('checked') && $("#Commercial_PlacesOfWorship_Text").val() == "") { errors++; }
    if ($("#Commercial_LicensedPremises").attr('checked') && $("#Commercial_LicensedPremises_Text").val() == "") { errors++; }
    if ($("#Commercial_").attr('checked') && $("#Commercial__Text").val() == "") { errors++; }
    if ($("#CarParks_Multi-storey").attr('checked') && $("#CarParks_Multi-storey_Text").val() == "") { errors++; }
    if ($("#CarParks_Surface").attr('checked') && $("#CarParks_Surface_Text").val() == "") { errors++; }

		$('#Attachments').MultiFile();
		
		if (errors>0) { alert("Please fill in all fields marked with an asterisk (*). Also ensure you have chosen whether the applicant or agent should be the point of contact and filled in the image verification field."); return false; }
		else { return true; }

	});

	$(".sbdAccredApp").submit(function(){

		var errors = 0;
		if ($("input#Applicant_Phone_").val()=="") { errors++; }
		if ($("input#Applicant_Contact_").val()=="") { errors++; }
		if ($("input#Client_Phone_").val()=="") { errors++; }
		if ($("input#Client_Contact_").val()=="") { errors++; }
		if ($("input#recaptcha_response_field").val()=="") { errors++; }
		if ($("select#PointOfContact option:selected").val()=="") { errors++; }
		
		if (errors>0) { alert("Please fill in the client, applicant phone and contact details. Also ensure you have chosen whether the applicant or client should be the point of contact and filled in the image verification field."); return false; }
		else { return true; }

	});

});

// Not only when the DOM is ready, but when the images have finished loading,
// important, but subtle difference to $(document).ready();
$(window).bind('load', function () {
  // run the cross fade plugin against selector
if ($.browser.msie && $.browser.version<7) {
	$('img.fade').each(function(){
		$(this).hover(function(){
			$(this).attr('src',$(this).attr('src').replace('bw','colour'));
		},function(){
			if ($(this).hasClass('selected')) { }
			else { $(this).attr('src',$(this).attr('src').replace('colour','bw')); }
		});
	});

}
else { $('img.fade').crossfade(); }
});
