/// <reference path="jquery-vsdoc.js" />
/*
#############################
#############################
N.B. WITH ANY JQUERY MAKE SURE THAT SOME SORT OF JQUERY NO CONFLICT METHOD IS USED DUE TO THE USE OF PROTOTYPE IN COMPOSER WHICH STEALS THE USE OF $
ANYTHING IN DOCUMENT.READY SHOULD BE FINE, AND NEW FUNCTIONS SHOULD AT LEAST WRAP THEMSELVES IN 

(function($) {
    *some code*
})(jQuery)

so that the use of $ is recognised 
#############################
#############################
*/

function heroRotator() {
(function($) {
    if ($('#hero-flash').length == 0) return;
    if ($('#hero-flash li').length < 2) return;

    var speedRotation = 5000;
    var speedFade = 3000;

    var index = 1;
    var lastIndex = $('#hero-flash li').length;
    var $currentItem;
    $('#hero-flash li').not(':eq(' + (index-1) + ')').hide();

    setInterval(function() {
        $currentItem = $('#hero-flash li:visible');
        if(jQuery.support.opacity) {
            $('#hero-flash li:eq(' + (index) + ')').fadeIn(speedFade, function() {  
                $currentItem.fadeOut(speedFade);
            });
        }
        else {
            $currentItem.hide();
            $('#hero-flash li:eq(' + (index) + ')').show();
        }
        index++;
        if (index == lastIndex) index = 1;
    }, speedRotation);
})(jQuery)
}

function initGallery() {
(function($) {
    if($('.ad-gallery').length == 0) return;
    var galleries = $('.ad-gallery').adGallery({
        slideshow: {
            enable:false
        }
    });
    $('#ad-extra-next').click(function() {
        galleries[0].nextImage();
        return false;
    });
    $('#ad-extra-previous').click(function() {
        galleries[0].prevImage();
        return false;
    });
})(jQuery)
}

function ValidateAndSubmit(evt) {
(function($) {
    //replace placeholders with nothing
    $('input[placeholder], textarea[placeholder]').each(function() {
        var placeholder = $(this).attr('placeholder');
        if($(this).val() == placeholder) $(this).val('');
    });
    var $group = $(evt.currentTarget).parents('fieldset');
    var isValid = true;
    $group.find(':input').each(function (i, item) {
        if (!$(item).valid())
            isValid = false;
    });
    if (!isValid) { 
        evt.preventDefault();
        placeholders();
    }
    else {
        if($(evt.currentTarget).hasClass('warnUser')) alert('Thank you for making a donation to Variety. To complete the payment process you will be temporarily directed to a secure Westpac page. This will happen automatically, please do not refresh your browser.');
    }
})(jQuery)
}

jQuery.validator.addMethod("minChecked", function(value, element, param) {
    var $p = $(element).parent();
    var selected = $p.children('input:checked').length;

    if (selected >= param) {
        $p.children().removeClass('error');
        $p.siblings('.error').remove();
        return true;
    }

    $p.children('input').addClass('error');

    return false;
    }, 
    jQuery.validator.format("Please check at least {0} items.")
);

jQuery.validator.addMethod("dateAU", function (value, element) {
    if(value.length == 0){ return true; }
        var check = false;
        var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
        if( re.test(value)){
            var adata = value.split('/');
            var gg = parseInt(adata[0],10);
            var mm = parseInt(adata[1],10);
            var aaaa = parseInt(adata[2],10);
            var xdata = new Date(aaaa,mm-1,gg);
            if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
                check = true;
            else
                check = false;
        } else
            check = false;
            return this.optional(element) || check;    
        }, 
        jQuery.validator.format("Please enter a correct date in the format DD/MM/YYYY")
);

jQuery.validator.addMethod("validPostcode", function (value, element, param) {
    var $p = $(element).parent();
    if(value.length == 0) return true;
    var reg = /^\d{4}$/;
    if (value.match(reg) != null) {
        $p.removeClass('error');
        $p.find('label.error').remove();
        $(element).removeClass('error');
        return true;
    }
    $p.addClass('error');
    return false;
},
    jQuery.validator.format("Please enter a valid postcode 4 digits in length")
);

jQuery.validator.addMethod("validPhone", function (value, element, param) {
    var $p = $(element).parent();
    if(value.length == 0) return true;
    var reg = /^\d{10}$/;
    if (value.match(reg) != null) {
        $p.removeClass('error');
        $p.find('label.error').remove();
        $(element).removeClass('error');
        return true;
    }
    $p.addClass('error');
    return false;
},
    jQuery.validator.format("Please enter a valid phone number 10 digits in length")
);

function placeholders() { // Adapted from http://www.beyondstandards.com/archives/input-placeholders/
    (function($) {
        var supported = !!("placeholder" in document.createElement( "input" ));
        if (supported) return;
        $('input[placeholder], textarea[placeholder]').each(function() {
            var placeholder = $(this).attr('placeholder');
            if ($(this).val() == '' || $(this).val() == placeholder) {
                $(this).addClass('placeholder').val(placeholder); 
            }
            $(this).focus(function() {
                if ($(this).val() == placeholder) $(this).removeClass('placeholder').val('');
            }).blur(function() {
                if ($(this).val() == '') $(this).addClass('placeholder').val(placeholder);
            });
        });
    })(jQuery)
}

jQuery(document).ready(function($) {

    /*######################### VALIDATION ##########################*/

    //validation options
    $("#aspnetForm").validate({
        errorPlacement: function(error, element) {
            if(element.rules().minChecked > 0) {
                var $p = $(element).parent();
                if($p.siblings().hasClass("error") == false) {
                    //error.insertBefore($p);
                    $(element).parents('li').prepend(error);
                }
            }
            else {
                $(element).parents('li').prepend(error);
            }
        },
        highlight: function(element, errorClass) {
            $(element).parents('li').addClass(errorClass);
        },
        unhighlight: function(element, errorClass) {
            $(element).parents('li').removeClass(errorClass);
        },
        onsubmit: false,
        onkeyup: false,
        focusInvalid: true,
        ignoreTitle: true,
        messages: {
            stateoption: "Please select a state",
            cardtype: "Please select a card type for your donation"
        },
        rules: {
            txtRePassword: {
                equalTo: "#txtPassword"
            }
        }
    });
    $(".option-list.required, .option-list-inline.required").children('input').each(function(){ $(this).rules("add", { minChecked: 1}); });
    if ($(".validPostcode").length != 0) $(".validPostcode").rules("add", { validPostcode: true });
    if ($(".dateAU").length != 0) $(".dateAU").rules("add", { dateAU: true });
    if ($(".validPhone").length != 0) $(".validPhone").rules("add", { validPhone: true });
    
    $.validator.addClassRules({
         compareEmail: {
            equalTo: '.email-compare'
         }
    });

    //submitting the form
    $('.validateForm').click(ValidateAndSubmit);

    //dealing with the enter button
    $('fieldset :text').keydown(function (evt) {
        if (evt.keyCode == 13) {
            ValidateAndSubmit(evt);
        }
    });
    
    /*######################### VALIDATION ##########################*/
    
    $('body').addClass('js');
    
    placeholders();
    
    heroRotator();
    
    initGallery();
    
    $('.date-picker').datePicker({clickInput:true, startDate:'01/01/1996', constrainInput:true });
    
    $("img.rounded-right, img.rounded-left").load(function() {
        src = $(this).attr('src').replace(/\(/g, '%28').replace(/\)/g, '%29');
        $(this).wrap(function(){
            return '<span class="' + $(this).attr('class') + '" style="width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px; background:url(' + src + ') no-repeat center center;" />';
        });
        $(this).css("opacity","0");
    });
});

jQuery(document).ready(function ($) {
    $('.maling-preferences-control-container.all-preferences input').click(function () {
        if ($(this).is(':checked') == true) {
            $('.maling-preferences-control-container input').attr('disabled', true);
            $('.maling-preferences-control-container input').attr('checked', false);
            $('.maling-preferences-control-container.all-preferences input').attr('checked', true);
        }
        else {
            $('.maling-preferences-control-container input').removeAttr('disabled');
        }
        $('.all-preferences input').attr("disabled", false);
    });
});
