$(document).ready(function () {

    $("a.lightbox").fancybox({
        'autoDimensions': false,
        width: "60%",
        height: "60%"
    });

    $('#header input[type="text"]').focus(function () {
        if (this.value == this.defaultValue) this.value = '';
    });

    $('#header input[type="text"]').blur(function () {
        if (this.value == '') this.value = (this.defaultValue ? this.defaultValue : '');
    });

    // using js to for links to new windows
    $('a.new-window,a.pdf,a.doc,a.xls').click(function () {
        window.open(this.href);
        return false;
    });

    $('#content .form:not(".search, .no-bg"), #content #calendar').wrapInner('<div class="rbg1"><div class="rbg2"><div class="rbg3"><div class="rbg4"></div></div></div></div>');

    if ($('#yafpage_cp_profile').length != 0) { // if you're on the admin page

        $('.yafnet table.content').wrap('<div class="forum-box-bottom"><div class="forum-box-top"></div></div>');
        $('.yafnet table.content div').removeClass('forum-box-bottom').removeClass('forum-box-top');

    } else if (($('.yafPageLink a').eq(1).text() == 'Administration') || ($('.yafPageLink span.currentPageLink').text() == 'Administration')) { // nothing on the admin page

    } else { // all other pages

        $('.yafnet table.content').wrap('<div class="forum-box-bottom"><div class="forum-box-top"></div></div>');
        $('.yafnet iframe').wrap('<div class="forum-box-bottom"><div class="forum-box-top"></div></div>');

    }


    $('#content .form, #content #calendar, #content .form.no-bg').css('border', 'none').css('background', 'none').css('padding', '0');

    // ****** crap for forms ****** //

    // upate your detials form hide n show
    $(".update-details legend").css('cursor', 'pointer');


    $(".update-details fieldset .inner").hide();
    $(".update-details fieldset:first .inner").show();
    $(".update-details legend").addClass('closed');
    $(".update-details legend:first").removeClass('closed').addClass('open');

    $(".update-details legend").click(function () {
        if ($(this).hasClass('open')) {
            $(this).next('.inner').hide();
            $(this).removeClass('open');
            $(this).addClass('closed');
        } else {
            $(this).next('.inner').show();
            $(this).removeClass('closed');
            $(this).addClass('open');
        }
    });

    $(".expand-contract").click(function () {
        if ($(this).text() == 'Expand all tabs') {
            $(this).text('Contract all tabs').addClass('open');
            $('#content div.inner').show();
            $('#content legend').addClass('open').removeClass('closed');
            $(this).addClass('open');
        } else {
            $(this).text('Expand all tabs').removeClass('open');
            $('#content div.inner').hide();
            $('#content legend').addClass('closed').removeClass('open');
            $(this).removeClass('open');
        }
    });

	// Set default username on sign up
	$('.user-name').focus(function(){
		$(this).attr('value',$('.first-name').attr('value') + '.' + $('.last-name').attr('value'));
	});
	
	
    // hide fields that should be hidden
    $(".formrow.hide").hide();

    //show other fields that have already been selected
    $("select").children("option:selected:contains('Other')").parents('.formrow').next('.formrow').css('display', 'block');

    $(".checkbox-row label:contains('Other')").each(function () {
        if ($(this).prev('input').attr('checked') == true) {
            $(this).parents('.formrow').next('.formrow').show();
        }
    });

    //when a select box changes to 'other' show the other field below it
    $("select option:contains('Other')").parent().change(function () { // only select boxes that have an option with the text 'other'
        //if ($(this).prev('label:contains("Query type")')) { } else { // excluding the select box on the contact us page
        if ($(this).parent().hasClass('disablejq')) { } else { // modded by jw
            if ((($(this).children('option:selected').text()) == ("Other")) || (($(this).children('option:selected').text()) == ("Other (please specify)"))) { // if the select boxes currently selected option is 'Other' or 'Other (please specify)
                $(this).parents('.formrow').next('.formrow').show();
            } else {
                $(this).parents('.formrow').next('.formrow').hide();
            }
        }
    });

    //when a checkbox called 'other' is selected show the hidden field below
    $(".checkbox input").change(function () {
        if ($(this).next().is(':contains("Other")')) {
            if ($(this).is(':checked')) {
                $(this).parents('.formrow').next('.formrow').show();
            } else {
                $(this).parents('.formrow').next('.formrow').hide();
            }
        }
    });

    // hide the 2nd and 3rd qualification
    $('#qualification-2, #qualification-3').hide();

    // show qualifications if they already have values in them
    $('.qualification').each(function () {
        $(this).find('input[type="text"]').each(function () {
            if (($(this).attr('value')) != '') {
                $(this).parents('.qualification').show();
                return false;
            }
        })
    });



    // show the add qualification buttons
    $('.add-qualification').show();


    $('.add-qualification').click(function () {
        $(this).parents('.qualification').next('.qualification').show();
        $(this).hide();
    });

    // credit card validation

    $('.payment #submit').click(function () {

        var ccName = $('input[name="paymentCardName"]').val();

        var ccNum = $('input[name="paymentCardNumber"]').val();

        var ccExpiry = $('input[name="paymentCardExpiry"]').val();
        var ccExpiryMonth = ccExpiry.substr(0, 2);
        var ccExpiryYear = ccExpiry.substr(2, 4);
        var d = new Date();
        var currentYear = d.getFullYear().toString().substr(2, 4); // 4 digit year

        var isError = false;

        $('.ccnum-validation, .ccname-validation, .expiry-validation, .security-validation').hide();

        if (ccName.match('. .')) { // makes sure the name has a space in it
            // do nothing
        } else {
            $('.ccname-validation').css('display', 'inline');
            isError = true;
        }

        if (isCreditCard(ccNum) == true) { // uses the credit card checking function
            // do nothing
        } else {
            $('.ccnum-validation').css('display', 'inline');
            isError = true;
        }

        if (ccExpiryMonth <= 12) { // make sure the expiry month is between 
            // do nothing
        } else {
            $('.expiry-date').hide();
            $('.expiry-validation').css('display', 'inline');
            isError = true;
        }

        if (ccExpiry.length == 4) { // expiry date must be 4 digits
            // do nothing
        } else {
            $('.expiry-date').hide();
            $('.expiry-validation').css('display', 'inline');
            isError = true;
        }

        if (ccExpiryMonth <= 12) { // expiry month must be 1-12
            // do nothing
        } else {
            $('.expiry-date').hide();
            $('.expiry-validation').css('display', 'inline');
            isError = true;
        }

        if (ccExpiryYear >= currentYear) { // expiry year must be greater than or equal to this year
            // do nothing
        } else {
            $('.expiry-date').hide();
            $('.expiry-validation').css('display', 'inline');
            isError = true;
        }

        if ($('input[name="paymentCardCSC"]').val().length >= 3) { // security code date must be at least 3 digits
            // do nothing
        } else {
            $('.security-validation').css('display', 'inline');
            isError = true;
        }

        if (isError == true) {
            return false;
        }

    });


    //Can't type letters into the credit card number box or the security code box or the postcode box
    $('input[name="paymentCardNumber"], input[name="paymentCardExpiry"], input[name="paymentCardCSC"]').keypress(function (event) {
        // Backspace, tab, enter, end, home, left, right
        // We don't support the del key in Opera because del == . == 46.
        var controlKeys = [8, 9, 13, 35, 36, 37, 39];
        // IE doesn't support indexOf
        var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
        // Some browsers just don't raise events for control keys. Easy.
        // e.g. Safari backspace.  		
        if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
    	    (48 <= event.which && event.which <= 57) || // Always 1 through 9
    	    isControlKey) { // Opera assigns values for control keys.

            return;

        } else {
            event.preventDefault();
        }
    });


});
  
function isCreditCard(CC) {                        
    
    if (CC.length > 19)
         return (false);
    
    sum = 0; mul = 1; l = CC.length;
    for (i = 0; i < l; i++) {
         digit = CC.substring(l-i-1,l-i);
         tproduct = parseInt(digit ,10)*mul;
         if (tproduct >= 10) {
              sum += (tproduct % 10) + 1;
         } else {
              sum += tproduct;
         }
         if (mul == 1) {
              mul++;
         } else {
         	  mul--;
    	 }
    }
    if ((sum % 10) == 0) {
         return (true);
    } else {
         return (false);
	}
}

  
