/**
 * Dependencies: jquery.js 1.2.6, jquery.delegate.js 1.0, jquery.validate.js 1.4
 *
 * Some basic utilities
 */
Utils = {
    debug: function(text){
    },
    debugActive: false
}

/**
 * Custom validator method: hardens the email validation
 */
jQuery.validator.addMethod("email2", function(value, element, params) {
    var pattern1 = /^\S+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/;
    var pattern2 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
    return this.optional(element) || (value.match(pattern1) && !(value.match(pattern2))); 
}, "Enter a valid email address");

/**
 * Custom validator method: checks that the amount is in the correct format
 */

jQuery.validator.addMethod("amountFormat", function(value, element, params) {

    return this.optional(element) || value.match(/^\d+\.\d{2}$/); 

}, "Format should be '99.99'");


/**
 * Custom validator method: checks that there isn't an error with the barcode
 */
jQuery.validator.addMethod("barcode", function(value, element, params) {

  if($(element).hasClass('error')){
    
    return false;
    
  }else{
    
    return true;
    
  }
}, '');


/**
 * Custom validator method: checks that the amount is in the correct format
 */
jQuery.validator.addMethod("amountFormat2", function(value, element, params) {
    return this.optional(element) || (value > 0 && value < 1000000);
}, "Please enter an valid amount");

/**
 * Logic for the donate form
 */
DonateForm = {

    updatesVisible: false,
    messageVisible: false,
    validator:{},
    init: function(){

        //$("#yourpayment .toggle_div_next, #amount #amount-radios, #amount p").css("display", "block");

        $('.amount-select-link').click(
            function(){
                Utils.debug($(this));
                $('#edit-amount').val($(this).attr('id').substring(7) + ".00");
                DonateForm.validator.element( $('#edit-amount'));
                return false;
            }
        );
        
        $('.amount-button').click(
            function(){
                $('#edit-amount').val($(this).attr('id').substring(7) + ".00");
                DonateForm.validator.element( $('#edit-amount'));
                return false;
            }
        );
        
        $('.amount-button').click(
            function(){
                $('#edit-amount').val($(this).attr('id').substring(7) + ".00");
                DonateForm.validator.element( $('#edit-amount'));
                return false;
            }
        );
        
        // Need to turn off onblur validation to work with barcode lookup - but selects still need it so add it manually here
        $('form.webform-donate-form select, input[name=MC_confirmed_min_age]').change(
            function(){
                DonateForm.validator.element($(this));
                return false;
            }
        );
        
        $('a#copy-address').click(
            function(){
              $('div.school-element input:text').each(
                function(){
                  
                  var name = $(this).attr('name').replace("est_", ""); 
 
                    if($("#edit-cr-donate-info-wrapper input[name='"+name+"']").length){
                    
                      $("#edit-cr-donate-info-wrapper input[name='"+name+"']").val($(this).val());
                               
                    }
                  
                  
                }
              );
                return false;
            }
        );
        
        $('#edit-MC-chosen-option').change(
            function(){
                  
                var select_val = $("#edit-MC-chosen-option option:selected").val();
                var cartID = Drupal.settings.cr_donate_3_chosen_options[select_val].cartId;
                var desc = Drupal.settings.cr_donate_3_chosen_options[select_val].desc;
                
                if (cartID != undefined){
                
                    if (cartID.length > 0){
                        var replaceStr = $("#edit-cartId").val().substr(($("#edit-cartId").val().lastIndexOf('-')+1));                        
                        $("#edit-cartId").val($("#edit-cartId").val().replace(replaceStr, cartID));
                    }
                }
                
                if (desc != undefined){
                    
                    if (desc.length > 0){
                    
                        if ($("#edit-desc").val().lastIndexOf(':') > 1){
                        
                            var replaceStr = $("#edit-desc").val().substr(($("#edit-desc").val().lastIndexOf(':')+2));
    
                            $("#edit-desc").val($("#edit-desc").val().replace(replaceStr, desc));
                            
                        } else {
                        
                            $("#edit-desc").val($("#edit-desc").val()+': '+desc);
                        }
                    }
                }
                
                return false;
            }
        );
        
        $('select#edit-MC-est-role').change(
          function(){

            // Update card IDs
            var id;
            var cartId;
            var desc;
            var MC_chosen_option;
            var form = $(this).parents('form');
            var op = $('option:selected', $(this)).parents('optgroup').attr('label');


            if(op == 'Early years'){

              cartId = 'SR10-SCHOOLS-EARLYYEARS';
              desc = 'Sport Relief 2010 - Early years';
              MC_chosen_option = 'early years';

            }else{

              if(op == 'Primary'){

                cartId = 'SR10-SCHOOLS-PRIMARY';

              }else{

                cartId = 'SR10-SCHOOLS-SECONDARY';

              }
              
              desc = 'Sport Relief 2010 - Schools';
              MC_chosen_option = 'schools';

            }

            $('input[name=cartId]', form).val(cartId);
            $('input[name=desc]', form).val(desc);
            $('input[name=MC_chosen_option]', form).val(MC_chosen_option);
            
            // Split into seperate subject and roles            
            if($(this).val()){
              
              var split_val = $(this).val().split('|');
            
              $('#edit-MC-teach-subject').val(split_val[0]);
              $('#edit-MC-teach-role').val(split_val[1]);
            
            }
            
            

          }

        )
        
        

        
        
        $("textarea[class*='max_length']").keyup(
            function(){
                
                var text = $(this).val();   
                var textlength = text.length;
                
                var limit = $(this).attr('class').match("max_length_([0-9]*)")[1];
                if (limit != parseInt(limit)) return false; //test found limit is numeric
                
                var infodiv = $(this).attr('id')+'_info';
                
                if(textlength > limit)
                {
                    $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
                    $(this).val(text.substr(0,limit));
                    return false;
                }
                else
                {
                    $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
                    return true;
                }
            }
        );
        
        DonateForm.validator = $('form.webform-donate-form').validate({
            rules: {
                email:{
                    required:true,
                    email2:true
                },
                amount:{
                    required:true,
                    amountFormat:true,
                    amountFormat2:true
                },
                messagetext:{
                    required: false,
                    maxlength: 200   
                },
                MC_est_Address1:{ // Only required if postcode doesn't start with BFPO...
                  required: DonateForm.postcodeBFPO
                },
                MC_est_Town:{
                  required: DonateForm.postcodeBFPO
                },
                MC_trans_source:{
                  required: DonateForm.barcodeRequired,
                  barcode: true                  
                },      
                MC_confirmed_min_age:{
                  required: true           
                }
              },
              messages: {
                MC_confirmed_min_age: "You must be over 16 to donate"
              },
              onfocusout: false
        });            
        
        $('form.webform-donate-form').submit(function(event){
          
          if(DonateForm.validator.valid()){

            DonateForm.handleSubmit($(this), event);
          }
                    
        });
        
        $('#messagetext').click(
            function(){
                if($(this).val() == "Write your message here..."){
                    $(this).val('');
                }
            }
        );
        
        $('#updates h2 a').click(
            function(){
                if(DonateForm.updatesVisible == false){
                    $('#updates-content').show();
                    $('#updates h2').addClass('area-open');
                    $('#updates h2').removeClass('area-closed');
                    DonateForm.updatesVisible = true;
                } else {
                    $('#updates-content').hide();
                    $('#updates h2').addClass('area-closed');
                    $('#updates h2').removeClass('area-open');
                    DonateForm.updatesVisible = false;
                }
                return false;
            }
        );
        
        $('#message h2 a').click(
            function(){
                if(DonateForm.messageVisible == false){
                    $('#message-content').show();
                    $('#message h2').addClass('area-open');
                    $('#message h2').removeClass('area-closed');
                    DonateForm.messageVisible = true;
                } else {
                    $('#message-content').hide();
                    DonateForm.messageVisible = false;
                    $('#message h2').addClass('area-closed');
                    $('#message h2').removeClass('area-open');
                }
                return false;
            }
        );
    },
    
    combineAddress: function(){
        Utils.debug('combining address');
        var combinedAddress =
            (($('form.webform-donate-form input.donateform_field_MC_address1').val()) ? $('form.webform-donate-form input.donateform_field_MC_address1').val() : '') +
            (($('form.webform-donate-form input.donateform_field_MC_address2').val()) ? ",&#10;" + $('form.webform-donate-form input.donateform_field_MC_address2').val() : '') +
            (($('form.webform-donate-form input.donateform_field_MC_address3').val()) ? ",&#10;" + $('form.webform-donate-form input.donateform_field_MC_address3').val() : '') +
            (($('form.webform-donate-form input.donateform_field_MC_town').val())     ? ",&#10;" + $('form.webform-donate-form input.donateform_field_MC_town').val() : '') +
            (($('form.webform-donate-form input.donateform_field_MC_county').val())   ? ",&#10;" + $('form.webform-donate-form input.donateform_field_MC_county').val() : '')
                
        $('form.webform-donate-form #edit-address').val(combinedAddress);
    },
    
    handleSubmit: function($this, event){

      DonateForm.combineAddress();
      $this.attr("action", $('#edit-action-final').val());
      Utils.debug('submit');
        
    },
    
    postcodeBFPO: function(){
      
      if($('form.webform-donate-form input.establishment-postcode[value^=BFPO]').length){
          return false; // BFPO so other address fields are not required
      }else{
          return true; // Other fields are required
      }
    },
    
    // Only require barcode if there's not already an error - otherwise get two errors
    barcodeRequired: function(element){
      
      if($(element).hasClass('error')){

        return false;

      }else{

        return true;

      }
      
    }
    
}

/**
 * init
 */
$(document).ready(DonateForm.init);



