$(document).ready(function(){

    //Open any links marked rel="external" in a new window.
    $('a').click(function(){
        if ($(this).attr('rel')=='external') {
            window.open($(this).attr("href"));
            return false;
        }
    });

    //Opens all external links in a new window
    $("a[href^=http]").each(function(){
        $(this).click(function() {
            if ($(this).attr('href') != 'http://customerarea.cabotfinancial.ib3.co.uk') {
                if($(this).attr('href').indexOf(location.hostname) == -1) {
                    window.open($(this).attr('href'));
                    return false;
                }
            }
        });
    });

    //Adds the friendlyForm class to any Zend forms that appear
    if ($('#customForm').length) {
        $('#customForm').addClass('friendlyForm');
    }

    //Home page tab selections
    $('.selector').each(function(i) {
        $(this).mouseover(function() {
            $('.homeTab:not(.tab' + i +')').css('display', 'none');  //Sets all other tabs to display: none;
            $('.tab' + i).css('display','block'); // Sets the selected tab to display: block;
            if($.browser.msie && parseFloat($.browser.version) < 7) {  //Changes to compatiblity image for IE6
                $(this).css('background','transparent url(/images/compat/grey-arrow.gif) no-repeat top left');
            } else {
                $(this).css('background','transparent url(/images/grey-arrow.png) no-repeat top left');
            };            
            $('.selector').not(this).css('background','transparent'); // Removes the tab background on the other tabs.
            return false;
        });
    });

    if ($('#rotatingImages').length != 0) {
        $('#rotatingImages').cycle({
            fx: 'fade',
            timeout: 6000,
            speed: 2000
        });
    }

	//Create the user account modal login in the top right corner
        $('#customerLoginLink__disabledfornow').click(function() {
                
         $.get('/account/login', function(data) {
            $htmlcontent = data;
            var $dialog = $('<div></div>')
                .html($htmlcontent)
                .dialog({
                        buttons: { "Login": function() { alert("Login not yet enabled") }, "Close": function() { $(this).dialog("close")} },
                        autoOpen: false,
                        modal: true,
                        resizable: false,
                        title: 'Customer Login'
                });
            $dialog.dialog('open');
            $('#loginButton').button();
            return false;
        });
    });

    //Creates a jQuery UI button from anything with the class "button"
    $('.button').button();

    //If there is an accordian - make it so!
    /*
    if ($('.accordion').length != 0) {
        $(".accordion").accordion({
            active: false,
            autoHeight: false
        });
    };
    */

   /* Setup sliders */
	$('.sliderHeader a').click(function () {
           $(this).toggleClass('on');
           $(this).parent().next('.sliderContainer').slideToggle('slow');
	   return false;
	});
	$('.sliderContainer div .close').click(function() {
		$(this).parent().parent().parent().slideUp('slow', function() {
			$(this).prev('.sliderHeader a').toggleClass('on');
		});
		return false;
	});

    if ($('#letterSelection').length != 0) {
        $('#letterSelection').buttonset();

        $('.letter').click(function() {
            $("#glossaryContainer").ajaxStart(function () {
                $(this).empty().html('<img src="/images/ajax-loader.gif" align="center" />');
            });
            $.get('/debt-help/glossary/show?letter=' + $(this).val(), function(data) {
                $('#glossaryContainer').html(data);
            });
        });
    }

    //Set up form validation....
    if ($('#customForm').length != 0) {

        jQuery.validator.messages.required = "";  //Defines that the error labels are populated.
        
        $('#customForm').validate({
        invalidHandler: function(e, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = errors == 1
                    ? 'It appears you have not completed a field.  This has been highlighted below.'
                    : errors + ' fields have not been completed. They have been highlighted below.';
                $("div.error h3").html(message);
                $("div.error").show();
                $("label.error").css('color: #fff000;');
            } else {
                $("div.error").hide();
            }
        }
     });
    };

    //FAQ Autocomplete Setup
    if ($('.faqSearchForm').length != 0) {
        $("#search").autocomplete({
            source: function(request, response) {
               $.getJSON("/faqs/search?question=" + request.term, function(questions) {
                  response(questions, function(item) {
                        return {
                            id: item.faqId,
                            label: item.question,
                            value: item.question
                        }
                    });
               });
            },
            minLength: 2,

            select: function(event, ui) {
                $.get('/faqs/show?faqId=' + ui.item.id, function(data) {
                    $('#displayDiv').html(data).fadeIn();
                    $(".accordion").accordion({ active: 0});
                });
            }
        });
    };

    if (('#budgetCalculatorForm').length != 0) {
        
        $('#budgetCalculatorForm').change(function() {
            
            var income = 0;
            var expenditure = 0;

           //Add up all the incomes...
           $('.income').each(function(index) {
               if (isNumeric($(this).attr('value'))) {
                income = income + parseFloat($(this).attr('value'));
                $('#total_income').attr('value', income.toFixed(2));
               }

           });

           //Add up all the expenditures...
           $('.expenditure').each(function(index) {
               if (isNumeric($(this).attr('value'))) {
                    expenditure = expenditure + parseFloat($(this).attr('value'));
                    $('#total_expenditure').attr('value', expenditure.toFixed(2));
               }
               
           });
           $('#result').attr('value', ((income*1) - (expenditure*1)).toFixed(2));
        });
    }

    /*
     * Contact form validation
     */

      if ($('#contactForm').length != 0) {
            jQuery.validator.messages.required = "";  //Defines that the error labels are populated.

            $('#contactForm').validate({
            rules: {
                name: {
                    required: true
                },
                telephone: {
                    required: "#mobile:blank"
                },
                email: {
                  required: true,
                  email: true
                },
                confirmEmail: {
                    required: true,
                    equalTo: "#email"
                },
                accountNumber: {
                    required: '#lenderReference:blank',
                    number: true,
                    maxlength: 7
                }
            },
            invalidHandler: function(e, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    var message = errors == 1
                        ? 'It appears you have not completed a field.  This has been highlighted below.'
                        : errors + ' fields have not been completed. They have been highlighted below.';
                    $("div.error h3").html(message);
                    $("div.error").show();
                    $("label.error").css('color: #fff000;');
                } else {
                    $("div.error").hide();
                }
            }
         });
      };

      if ($('#callMeBackForm').length != 0) {
            jQuery.validator.messages.required = "";  //Defines that the error labels are populated.

            $('#callMeBackForm').validate({
            rules: {
                surname: {
                    required: true
                },
                telephone: {
                    required: true
                },
                email: {
                  required: true
                },
                accountNumber: {
                    required: '#lenderReference:blank',
                    number: true,
                    maxlength: 7
                },
                bestTimeToCall: {
                    required: true
                },
                postcode: {
                    required: true
                }
            },
            invalidHandler: function(e, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    var message = errors == 1
                        ? 'It appears you have not completed a field.  This has been highlighted below.'
                        : errors + ' fields have not been completed. They have been highlighted below.';
                    $("div.error h3").html(message);
                    $("div.error").show();
                    $("label.error").css('color: #fff000;');
                } else {
                    $("div.error").hide();
                }
            }
         });
      };

      /* Show video functionality */
      if ($('#videoPod').length != 0) {
          $('#videoPod p a').live('click', function() {
            $('#videoContainer').slideToggle(400, function(){
                $('#videoPod').toggleClass('on');
            });
            return false;
          });
      }
});


