/**
 * @author Rong
 */
zBilling = new ZBilling();

function ZBilling() {
	
	this.init = function() {
		checkStateCountry();
		/*
		checkZipcode();
		validateCreditCard();
		validateBillingForm();
		*/
			_initPayMethodListener();
			_paymethodListener();
			scheckStateCountry('edit_billing');
	};
	
    function scheckStateCountry(prefix){     
        $('#'+prefix+'_country').after('<span id="countryvalidation"></span>').unbind('change').change(function(){
            var country = $(this).val();
            if(country === null || country.length === 0){
                $('#countryvalidation').html("<em class=\"alertNote\">" + ZMsg.COUNTRY_MESSAGE + "</em>");
            }
            else{
                $('#countryvalidation').html('');
                if(country == "US"){
                    $('#'+prefix+'_zip').parent().prev().html('Zip/Postal<span>*</span>');
                    $('#'+prefix+'_state_div').css('display','');
                    $('#'+prefix+'_province_div').css('display','none');
                }
                else{
                    $('#'+prefix+'_zip').parent().prev().html('Zip/Postal');            
                    $('#'+prefix+'_state_div').css('display','none');
                    $('#'+prefix+'_province_div').css('display','');
                }
            }
        });     
    }
    
	//country must be selected
	//if selected country is US, show selections for states; otherwise show textfield
	function checkStateCountry(){		
		$('#billing_country').after('<span id="countryvalidation"></span>');
		$('#billing_country').unbind('change').change(function(){
			var country = $(this).val();
			if(country === null || country.length === 0){
				$('#countryvalidation').html("<em class=\"alertNote\">" + ZMsg['COUNTRY_MESSAGE'] + "</em>");
			}
			else{
				$('#countryvalidation').html('');
				if(country == "US"){ //state selection
				     $('#billing_zip').parent().prev().html('Zip/Postal<span>*</span>');
					 $('#billing_state_div').css('display','');
					 $('#billing_province_div').css('display','none');
				}
				else{ //replace selection with textfield
				    $('#billing_zip').parent().prev().html('Zip/Postal');			
					 $('#billing_state_div').css('display','none');
					 $('#billing_province_div').css('display','');
				}
			}
		});		
	}
	
	//zipcode is required only if country is US
	function checkZipcode(){
		
		$('#billing_zip').after('<span id="zipvalidation"></span>');
		$('#billing_zip').unbind('change').change(function(){
			if( $('#billling_country').val() == 'US'){
				if($(this).val() === null || $.trim($(this).val()).length === 0){
					$('#zipvalidation').html("<em class=\"alertNote\">" + ZMsg['ZIP_NULL_MESSAGE'] + "</em>");
					return;
				}
				else if ($.trim($(this).val()).length <4 ||$.trim($(this).val()).length > 12){
					$('#zipvalidation').html("<em class=\"alertNote\">" + ZMsg['ZIP_INVALID_MESSAGE'] + "</em>");
					return;
				}		
			}
			$('#zipvalidation').html("");
			return;			
		});
	}
    	   
	
	//validate credit card number
	// Visa: ^4[0-9]{12}(?:[0-9]{3})?$ All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.
    // MasterCard: ^5[1-5][0-9]{14}$ All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.
    // American Express: ^3[47][0-9]{13}$ American Express card numbers start with 34 or 37 and have 15 digits.
    // Discover: ^6(?:011|5[0-9]{2})[0-9]{12}$ Discover card numbers begin with 6011 or 65. All have 16 digits.
	function validateCreditCard(){
		$('#edit_cc_number').after('<span id="cardvalidation"></span>');
		$('#edit_cc_number').unbind('blur').blur(function(){
				var cardType = $('#edit_cc_type').val();
				var cardNumber = $(this).val().replace(/\s+/g, ''); //delete spaces
				var cardRegex;
				if(cardType == "0"){ //visa
					cardRegex = /^4[0-9]{12}(?:[0-9]{3})?$/; 
					if(!cardRegex.test(cardNumber)) { 
						$('#cardvalidation').html("<em class=\"alertNote\">" + ZMsg['CARD_VISA_INVALID_MESSAGE'] + "</em>");
						return;  
					} 	
				}
				else if(cardType == "1"){//master card
					cardRegex = /^5[1-5][0-9]{14}$/; 
					if(!cardRegex.test(cardNumber)) { 
						$('#cardvalidation').html("<em class=\"alertNote\">" + ZMsg['CARD_MASTER_INVALID_MESSAGE'] + "</em>");
						return;
					} 
				}
				else if(cardType == "8"){//american express
					cardRegex = /^3[47][0-9]{13}$/; 
					if(!cardRegex.test(cardNumber)) { 
						$('#cardvalidation').html("<em class=\"alertNote\">" + ZMsg['CARD_AME_INVALID_MESSAGE'] + "</em>");
						return;
					} 
				}
				$('#cardvalidation').html("");
				return;				
		});		
	}
	
	function validateExpirationDate() {
	    var d = new Date();
		$('#edit_cc_expires_year').after('<span id="expiresvalidation"></span>');
	    if ($('#edit_cc_expires_year').val() == d.getFullYear() && $('#edit_cc_expires_month').val() < d.getMonth()) {
	        $('#expiresvalidation').html("<em class=\"alertNote\">" + ZMsg['EXPIRES_INVALID'] + "</em>");
	    }
	}
	//checked by jquery-validate rules
	function validateBillingForm(){
        // validate signup form on keyup and submit
	    $.validator.addMethod('billing_state', function(value, element, param) {
	        return (value != '' || $('#billing_country').val() != 'US');
	    });
	    $.validator.addMethod('expires', function(value, element, param) {
	        var d = new Date();
	        $('#edit_cc_expires_year').after('<span id="expiresvalidation"></span>');
	        if ($('#edit_cc_expires_year').val() == d.getFullYear() && $('#edit_cc_expires_month').val() < d.getMonth()) {
	            return false;
	        }
	        return true; 
	    });
        $("#billing_form").validate({
            rules: {
                billing_first_name: "required",
                billing_last_name: "required",
                billing_street: "required",
                billing_state: { billing_state: true },
                billing_city: "required",
                billing_phone: {
                    required: true,
                    rangelength: [10, 30]
                },
                cc_owner: "required",        
                cc_number: {
                    required: true,
                    creditcard: true,
                    rangelength: [13, 16]
                },  
                cc_cvv: {
                    required: true,
                    digits: true,
					rangelength: [3, 4]
                },
                accept_tos: "required"
            },
            messages: {
                billing_first_name: "<em class=\"alertNote\">"+ZMsg['FIRSTNAME_MESSAGE']+"</em>",
                billing_last_name: "<em class=\"alertNote\">"+ZMsg['LASTNAME_MESSAGE']+"</em>",
                billing_street: "<em class=\"alertNote\">"+ZMsg['ADDRESS_MESSAGE']+"</em>",
                billing_city: "<em class=\"alertNote\">"+ZMsg['CITY_MESSAGE']+"</em>",
                billing_state: "<em class=\"alertNote\">"+ZMsg['STATE_MESSAGE']+"</em>",
                billing_phone: {
                    required: "<em class=\"alertNote\">"+ZMsg['PHONE_NULL_MESSAGE']+"</em>",
                    rangelength: "<em class=\"alertNote\">"+ZMsg['PHONE_INVALID_MESSAGE']+"</em>"
                },
                cc_owner: "<em class=\"alertNote\">"+ZMsg['CARD_HOLDER_MESSAGE']+"</em>",
                cc_number: {
                    required: "<em class=\"alertNote\">"+ZMsg['CARD_NUMBER_NULL_MESSAGE']+"</em>",
                    creditcard: "<em class=\"alertNote\">"+ZMsg['CARD_NUMBER_INVALID_MESSAGE']+"</em>",
                    rangelength: "<em class=\"alertNote\">"+ZMsg['CARD_NUMBER_INVALID_MESSAGE']+"</em>"
                },
                cc_cvv: {
                    required: "<em class=\"alertNote\">"+ZMsg['CVV_NULL_MESSAGE']+"</em>",
                    digits: "<em class=\"alertNote\">"+ZMsg['CVV_INVALID_MESSAGE']+"</em>",
					rangelength: "<em class=\"alertNote\">"+ZMsg['CVV_INVALID_MESSAGE']+"</em>"
                },
                accept_tos: "<em class=\"alertNote\">"+ZMsg['AGREE_MESSAGE']+"</em>"
            }
        });        
        
    }
	
	
    function _cleanPaymethodForm() {
        $('#edit_cc_type_read, #edit_cc_number_read').empty();
        $('#error_message_list').empty();
        $('#paymethod_form :text').val('');
        $('#paymethod_form #edit_billing_state').val('');
        $('#paymethod_form #edit_billing_country').val('US');
        $('#edit_billing_zip').parent().prev().html('Zip/Postal<span>*</span>');
        $('#paymethod_form_area').animate({scrollTop: 0}, 1);
    }
    
    function _initPayMethodListener() {
        $('#z_paymethod_add_button').click(function(e){
            _cleanPaymethodForm();
            $('#stored_paymethod_list').hide();
            $('#paymethod_form').modal({
                onClose:function() {
                    $('#z_cancel_paymethod_button').trigger('click');
                }
            });
            $('#edit_cc_type, #edit_cc_number, #edit_cc_expires_year, #edit_cc_expires_month, #cvv_form').show();
            e.preventDefault();
        });
        $('#z_cancel_paymethod_button').click(function(e){
            _cleanPaymethodForm();
            $('#paymethod_form, #edit_billing_province_div, #error_form').hide();
            $('#stored_paymethod_list, #edit_billing_state_div').show();
            _selectedPaymethodId = 0;
            $.modal.close();
        });
        $('#z_save_paymethod_button').click(function(){
            $('#error_message_list').empty();
            $('#error_form').hide();
            var data = {};
            
            data.billing_first_name = $('#edit_billing_first_name').val();
            data.billing_last_name = $('#edit_billing_last_name').val();
            data.billing_street = $('#edit_billing_street').val();
            data.billing_street2 = $('#edit_billing_street2').val();
            data.billing_city = $('#edit_billing_city').val();
            data.billing_state = $('#edit_billing_state').val();
            data.billing_province = $('#edit_billing_province').val();
            data.billing_zip = $('#edit_billing_zip').val();
            data.billing_country = $('#edit_billing_country').val();
            data.billing_phone = $('#edit_billing_phone').val();
            data.email = $('#email').val();
            
            data.cc_number = $('#edit_cc_number').val();
            data.paymethod_id = _selectedPaymethodId;
            data.cc_expires_month = $('#edit_cc_expires_month').val();
            data.cc_expires_year = $('#edit_cc_expires_year').val();
            data.cc_type = $('#edit_cc_type').val();
            $.ajax({
                type:'POST',
                url:urlPrefix+'/settings/postPaymethod/checkout/1',
                data:data,
                timeout:30000,
                success:function(response) {
                    response = JSON.parse(response);
                    if(response.status == '0') {
                        for(error in response.error) {
                            $('#error_message_list').append(response.error[error]+'<br/>');
                        }
                        $('#error_form').show();
                        $('#paymethod_form_area').animate({scrollTop: 0}, 1);
                    } else {
                        $('#add-paymethod').hide();
                        $('#stored_paymethod_list').html(response.html);
                        $('#z_cancel_paymethod_button').trigger('click');
                        _paymethodListener();
                    }
                }
            });
        });
    }
    
    function _paymethodListener() {
        $('.paymethod_delete_button').unbind('click').click(function(e){
            var targer = $(this);
            if(confirm(ZMsg.PAYMETHOD_DEL_CONFIRM)) {
                var tempId = $(this).attr('name');
                $.ajax({
                    type:'POST',
                    url:urlPrefix+'/settings/deletePaymethod/checkout/1',
                    data:{paymethod_id:tempId},
                    timeout:30000,
                    success:function(response) {
                        response = JSON.parse(response);
                        if(response.status == 1) {
                            $('#stored_paymethod_list').html(response.html);
                            _paymethodListener();
                        } else {
                            alert(response.error);
                        }
                    }
                });
            }
            e.preventDefault();
        });
        $('.paymethod_edit_button').unbind('click').click(function(e){
            $('#edit_cc_read_form').show();
            $('#edit_cc_edit_form').hide();
            _selectedPaymethodId = $(this).attr('name');
            $.ajax({
                type:'POST',
                url:urlPrefix+'/settings/getPaymethod',
                data:{paymethod_id:_selectedPaymethodId},
                timeout:30000,
                success:function(response) {
                    response = JSON.parse(response);
                    if(response.status == '1') {
                        _cleanPaymethodForm();
                        $('#edit_billing_first_name').val(response.paymethod.first_name);
                        $('#edit_billing_last_name').val(response.paymethod.last_name);
                        $('#edit_billing_street').val(response.paymethod.street);
                        $('#edit_billing_street2').val(response.paymethod.street2);
                        $('#edit_billing_city').val(response.paymethod.city);
                        $('#edit_billing_zip').val(response.paymethod.zip);
                        $('#edit_billing_phone').val(response.paymethod.phone);
                        $('#edit_billing_country').val(response.paymethod.country);
                        $('#edit_cc_type').val(response.paymethod.cc_type);
                        $('#edit_cc_expires_month').val(response.paymethod.cc_expires_month);
                        $('#edit_cc_expires_year').val(response.paymethod.cc_expires_year);
                        $('#edit_cc_number').val(response.paymethod.cc_number);
                        $('#email').val(response.paymethod.email);
                        if(response.paymethod.country == 'US') {
                            $('#edit_billing_state').val(response.paymethod.state);
                        } else {
                            $('#edit_billing_zip').parent().prev().html('Zip/Postal');           
                            $('#edit_billing_state_div').css('display','none');
                            $('#edit_billing_province_div').css('display','');
                            $('#edit_billing_province').val(response.paymethod.state);
                        }
                        $('#edit_cc_type, #edit_cc_number, #edit_cc_expires_year, #edit_cc_expires_month, #cvv_form').hide();
                        $('#edit_cc_type_read').html($('#edit_cc_type option[value='+response.paymethod.cc_type+']').html());
                        $('#edit_cc_number_read').html(response.paymethod.cc_number);
                        $('#paymethod_form').modal({
                            onClose:function() {
                                $('#z_cancel_paymethod_button').trigger('click');
                            }
                        });
                        $('#stored_paymethod_list').hide();
                        $('#edit_cc_expires_year, #edit_cc_expires_month, #edit_cc_number_read, #edit_cc_type_read').show();
                        $('#edit_cc_type, #edit_cc_number, #cvv_form').hide();
                    } else {
                        alert(response.error);
                    }
                }
            });
            e.preventDefault();
        });
    }
    
}
