$(document).ready(function() {
    //custom equal heights
    $('.fbox_cols').equalHeights();

    //feature boxes config
    var intentConfig = {
        over: menuIn,
        timeout: 500,
        out: menuOut
    }
    $('#feature_boxes div').hoverIntent(intentConfig);

    //select boxes config
    var selectMenuConfig = {
        over: selectMenuIn,
        timeout: 600,
        out: selectMenuOut
    }
    $('nav.select').hoverIntent(selectMenuConfig);

    //how invoice finance works config
    var hifwConfig = {
        over: guideBoxIn,
        timeout: 600,
        out: guideBoxOut
    }
    $('.hifw_guide area').hoverIntent(hifwConfig);

    //valign banner
    var vAlign = $('.page_banner');

    vAlign.bind('setup', function()  {
        parentHeight = $(this).height();

        child = $(this).children('p');

        childHeight = child.height();

        vAlignCal = Math.ceil((parentHeight - childHeight) / 2);

        $(child).css('padding-top', vAlignCal + 'px');
    });

    if(vAlign.length)   {
        vAlign.trigger('setup');
    }

    //Quick contact form config
    selectCheck();
    $('select#method').change(selectCheck);

    //Scroll to top top config
    $('.top a').click(moveToTop);

    //Scrool to config
    $('ul#faqs li a').click(scrollAnchor);

    //banner carousel config
    $('#carousel').cycle({
        fx: 'fade',
        speed: 2500,
        timeout: 10000,
        cleartype: 1,
        fit: 1,
        next: '.next',
        prev: '.prev',
        activePagerClass: 'active',
        pager: 'ul.carousel_nav',
        pagerAnchorBuilder: function(idx, slide) {
            return 'ul.carousel_nav li a:eq(' + idx + ')';
        },
        fastOnEvent: 300,
        manualTrump: true,
        onPagerEvent: function(zeroBasedSlideIndex, slideElement) {
            $('#carousel').cycle('toggle');
            $('a.play').toggleClass('pause');
        },
        pause: 0
    });

    //toggle the banner carousel controls
    $('a.play').click(function(){
        $('#carousel').cycle('toggle');
        $(this).toggleClass('pause');
    });

    //banner carousel config
    $('#download_carousel').cycle({
        fx: 'scrollHorz',
        speed: 2000,
        timeout: 0,
        cleartype: 1,
        fit: 1,
        next: 'a.next-download',
        prev: 'a.prev-download',
        activePagerClass: 'active',
        pager: 'nav.downloads',
        pagerAnchorBuilder: function() {},
        fastOnEvent: 800,
        manualTrump: true,
        onPagerEvent: function() {},
        pause: 1
    });

    //overlay config
    $("a[rel]").overlay({
        fixed: false, /*ie6 wont work!*/
        mask: {
            color: '#000000',
            loadSpeed: '200',
            opacity: 0.5
        }
    });

    //hide form elements
    $('.success-msg').click(hideThis);
    $('.error-msg').click(hideThis);

    /**
         * Code to show and hide the placeholder text in fields when the user
         * clicks on the field.
         *
         * The data stored against the element is later used by the validator.
         */
    $('input[type="text"], input[type="email"], textarea').each(function(){

        var toggle = true;

        if(false === $(this).attr('readonly'))  {
            toggle = false;
        }

        if(false === toggle)    {
            $(this).data('placeholder', null);
            $(this).focus(function(){
                if(null === $(this).data('placeholder')) {
                    $(this).data('placeholder', $(this).val());
                }
                if($(this).data('placeholder') == $(this).val()) {
                    $(this).val('');
                }
            });
            $(this).blur(function(){
                if('' == $(this).val()) {
                    $(this).val($(this).data('placeholder'));
                }
            });
        }
    });

    var dateinput = $('input[type="date"]').dateinput({
        "format": "dd/mm/yyyy",
        "offset": [10, -125],
        "min": -1,
        "onShow": function(event) {
            var calendar = this.getCalendar();
            var conf = this.getConf();
            var classes = conf.css.off + ' ' + conf.css.disabled;
            function disableWeekends() {
                var weeks = calendar.find('.calweek');
                weeks.find('a:first, a:last').addClass(classes);
            }
            calendar.find('#calprev, #calnext').click(disableWeekends);
            disableWeekends();
        }
    });

    $('#quick_contact_reason_for_enquiry').change(function(){
        if(null !== $(this).val().match(/Other/)) {
            var other_input_field = $('<input>', {
                "id": "",
                "class": "text",
                "name": "reason_for_enquiry_other"
            });
            var fieldset = $('<fieldset>', {
                "id": "quick_contact_reason_for_enquiry_other_fieldset"
            });
            fieldset.append(other_input_field);
            $(this).parent().after(fieldset);
        } else {
            $('#quick_contact_reason_for_enquiry_other_fieldset').remove();
        }
    });

    $('a.download_guide').click(function(){
        var title = $(this).data('guide-title');
        var id = parseInt($(this).data('guide-id'), 10);
        var page_stub = $(this).data('page-stub');
        _gaq.push([
            '_trackEvent',
            'Guide Download',
            title,
            'Page: ' + page_stub,
            id
            ]);
    });

    //jQuery Tools
    //tooltips
    $('a.tip[title]').tooltip({
        tipClass: 'rangetip',
        effect: 'fade',
        position: 'top right',
        offset: [0,-5]
    });

    //range input
    $("input[type='range']").rangeinput({
        progress: true
    });

    //LEZ Calculator
    var used_calculator = false;
    $("input#count, input#value, input#days").change(function(event, value) {
        if(false === used_calculator) {
            _gaq.push(['_trackEvent',"LEZ Calculator","Started"]);
            window.onbeforeunload = function(event) {
                _gaq.push(['_trackEvent',"LEZ Calculator","Finished","Calculation Result", $('#result').val()]);
            };
            used_calculator = true;
        }

        c = parseInt($('#count').val());
        v = parseInt($('#value').val());
        d = parseInt($('#days').val());

        calculation = Math.ceil(((((c * v) * 12) / 365) * d) * 0.95);

        result = formatCurrency(calculation);

        $('#result').val(result);
    });

});

//GLOBAL FUNCTIONS

//contact form drop down contact check
function  selectCheck (){
    if($('select#method').val() == 'phone') {
        $('fieldset#phone_method').fadeIn('slow');
    } else  {
        $('fieldset#phone_method').fadeOut('slow');

        if($('#calroot').css('display', 'block'))    {
            $('#calroot').hide();
        }
    }

}

//top of page
function moveToTop ()   {
    $('html, body').animate({
        scrollTop:0
    },
    'slow'
    );
    return false;
}

//scroll to anchor
function scrollAnchor ()  {
    var id = $(this).attr('href');
    $('html, body').animate({
        scrollTop: $(id).offset().top
    },
    'slow'
    );
    return false;
}

//menu functions
function menuIn() {
    var ul = $(this).find('ul li ul');
    $(this).toggleClass('active');
    ul.show('slow');
}

function menuOut() {
    var ul = $(this).find('ul li ul');

    $(ul).hide();
    $(this).toggleClass('active');

}

//dropdown select menu function
function selectMenuIn() {
    var ulSel = $(this).find('ul li ul');

    var liSel = $(this).find('ul li a:first');

    liSel.toggleClass('active');

    ulSel.show('slow');

}

function selectMenuOut(){
    var ulSel = $(this).find('ul li ul');

    var liSel = $(this).find('ul li a:first');

    liSel.toggleClass('active');

    ulSel.hide('slow');
}


//how invoice finance rollover image map
function guideBoxIn()   {
    /*if($('#start').length){
       $('#start').fadeOut('slow');
    }*/
    var id = $(this).attr('href');
    $(id).fadeIn('slow');

}

function guideBoxOut()  {
    var id = $(this).attr('href');
    $(id).fadeOut('fast');
}

//hide form elements function
function hideThis() {
    $(this).fadeOut('slow');
}

//equal heights function
(function($) {
	$.fn.equalHeights = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			if($(this).height() > tallest) {
				tallest = $(this).height();
			}
		});
		if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			var returnHeights = {
                'min-height' : tallest,
                'height' : 'auto',
                '_height': tallest
            }
            $(this).css(returnHeights);
		});
	}
})(jQuery);

//currency converter (convert int to currency)
function formatCurrency(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return '£' + x1 + x2;
};
