/**
 * 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 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(){
        $('.amount-select-link').click(
            function(){
                Utils.debug($(this));
                $('#amount-text').val($(this).attr('id').substring(6) + ".00");
                DonateForm.validator.element( $('#amount-text'));
                return false;
            }
        );
        /*$('.amount-select-radio').click(
            function(){
                Utils.debug($(this));
                $('#amount-text').val($(this).attr('value'));
            }
        );*/
        $('.amount-button').click(
            function(){
                $('#amount-text').val($(this).attr('id').substring(7) + ".00");
                DonateForm.validator.element( $('#amount-text'));
                return false;
            }
        );
        $('.choose-button').click(
            function(){
            		
                $('#choose_list').val($(this).attr('id').substring(7));
                DonateForm.validator.element( $('#choose_list'));
                return false;
            }
        );
        $('#choose_list').change(
            function(){
														
							if ($("#choose_list option:selected").attr('class').match("cartid_([A-Z0-9]*)")){
							
								var newId = $("#choose_list option:selected").attr('class').match("cartid_([A-Z0-9]*)")[1];
								
								if (newId.length > 0){
									var replaceStr = $("#cartId").val().substr(($("#cartId").val().lastIndexOf('-')+1));						
									$("#cartId").val($("#cartId").val().replace(replaceStr, newId));
								}
							}
							
							if ($("#choose_list option:selected").attr('class').match("desc_([^ ]*)")){
							
								var newDesc = $("#choose_list option:selected").attr('class').match("desc_([^ \"]*)")[1];
								newDesc = newDesc.replace(/_/g,' ');
								
								if (newDesc.length > 0){
								
									if ($("#desc").val().lastIndexOf(':') > 1){
									
										var replaceStr = $("#desc").val().substr(($("#desc").val().lastIndexOf(':')+2));

										$("#desc").val($("#desc").val().replace(replaceStr, newDesc));
										
									} else {
									
										$("#desc").val($("#desc").val()+': '+newDesc);
									}
								}
							}
							
	
							return false;
            }
        );
        $("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 = $('#donateform').validate({
            rules: {
                email:{
                    required:true,
                    email2:true
                },
                amount:{
                    required:true,
                    amountFormat:true,
                    amountFormat2:true
                },
                messagetext:{
                    required: false,
                    maxlength: 200   
                }
            }
        });
        $('#donateform').submit(DonateForm.combineAddress);
        $('#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 =
        
            (($('#donateform #address1').val()) ? $('#donateform #address1').val() : '') +
            (($('#donateform #address2').val()) ? ",&#10;" + $('#donateform #address2').val() : '') +
            (($('#donateform #address3').val()) ? ",&#10;" + $('#donateform #address3').val() : '') +
            (($('#donateform #town').val())     ? ",&#10;" + $('#donateform #town').val() : '') +
            (($('#donateform #county').val())   ? ",&#10;" + $('#donateform #county').val() : '')

            $('#donateform #address').val(combinedAddress);
    },
    handleSubmit: function(){
        Utils.debug('submit');
    }
}

/**
 * init
 */
$(document).ready(DonateForm.init);

