/**
 * @author Rong
 */
zShipping = new ZShipping();

function ZShipping() {
	
	this.init = function() {
		checkStateCountry();
		/*
		checkZipcode();
		validateCreditCard();
		validateshippingForm();
		*/
        _initAddressListener();
        checkStateCountry('edit_shipping');
        _shippingAddressListener();
	};
	
	//country must be selected
	//if selected country is US, show selections for states; otherwise show textfield
	function checkStateCountry(){		
		$('#shipping_country').after('<span id="countryvalidation"></span>');
		$('#shipping_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
				     $('#shipping_zip').parent().prev().html('Zip/Postal<span>*</span>');
					 $('#shipping_state_div').css('display','');
					 $('#shipping_province_div').css('display','none');
				}
				else{ //replace selection with textfield
				    $('#shipping_zip').parent().prev().html('Zip/Postal');			
					 $('#shipping_state_div').css('display','none');
					 $('#shipping_province_div').css('display','');
				}
			}
		});		
	}
	
	//zipcode is required only if country is US
	function checkZipcode(){
		
		$('#shipping_zip').after('<span id="zipvalidation"></span>');
		$('#shipping_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(){
		$('#cc_number').after('<span id="cardvalidation"></span>');
		$('#cc_number').unbind('blur').blur(function(){
				var cardType = $('#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();
		$('#cc_expires_year').after('<span id="expiresvalidation"></span>');
	    if ($('#cc_expires_year').val() == d.getFullYear() && $('#cc_expires_month').val() < d.getMonth()) {
	        $('#expiresvalidation').html("<em class=\"alertNote\">" + ZMsg['EXPIRES_INVALID'] + "</em>");
	    }
	}
	//checked by jquery-validate rules
	function validateshippingForm(){
        // validate signup form on keyup and submit
	    $.validator.addMethod('shipping_state', function(value, element, param) {
	        return (value != '' || $('#shipping_country').val() != 'US');
	    });
	    $.validator.addMethod('expires', function(value, element, param) {
	        var d = new Date();
	        $('#cc_expires_year').after('<span id="expiresvalidation"></span>');
	        if ($('#cc_expires_year').val() == d.getFullYear() && $('#cc_expires_month').val() < d.getMonth()) {
	            return false;
	        }
	        return true; 
	    });
        $("#shipping_form").validate({
            rules: {
                shipping_first_name: "required",
                shipping_last_name: "required",
                shipping_street: "required",
                shipping_state: { shipping_state: true },
                shipping_city: "required",
                shipping_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: {
                shipping_first_name: "<em class=\"alertNote\">"+ZMsg['FIRSTNAME_MESSAGE']+"</em>",
                shipping_last_name: "<em class=\"alertNote\">"+ZMsg['LASTNAME_MESSAGE']+"</em>",
                shipping_street: "<em class=\"alertNote\">"+ZMsg['ADDRESS_MESSAGE']+"</em>",
                shipping_city: "<em class=\"alertNote\">"+ZMsg['CITY_MESSAGE']+"</em>",
                shipping_state: "<em class=\"alertNote\">"+ZMsg['STATE_MESSAGE']+"</em>",
                shipping_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 _addressCleanup() {
        $('#error_message_list').empty();
        $('#error_form').hide();
        $('#z_account_address_form :text').val('');
        $('#z_account_address_form').hide();
        $('.address-box').show();
        $('#z_account_address_form #edit_shipping_state').val('');
        $('#z_account_address_form #edit_shipping_country').val('US');
        $('#edit_shipping_zip').parent().prev().html('Zip/Postal<span>*</span>');
        $('#edit_shipping_state_div').show();
        $('#edit_shipping_province_div').hide();
        _selectedAddressId = 0;
        $('#z_account_address_form_area').animate({scrollTop: 0}, 1);
    }
    
    function _initAddressListener() {
        $('#z_address_add_button').click(function(e){
            _addressCleanup();
            $('#z_account_address_form').modal({
                onClose: function() {
                    $('#z_cancel_address_button').trigger('click');
                }
            });
            $('.address-box').hide();
            e.preventDefault();
        });
        $('#z_cancel_address_button').click(function(e) {
            _addressCleanup();
            $.modal.close();
        });
        $('#z_save_address_button').click(function(e){
            $('#error_message_list').empty();
            $('#error_form').hide();
            var data = {};
            $('#z_account_address_form :text').each(function(){
                data[$(this).attr('id')] = $(this).val();
            });
            data.shipping_first_name = $('#edit_shipping_first_name').val();
            data.shipping_last_name = $('#edit_shipping_last_name').val();
            data.shipping_street = $('#edit_shipping_street').val();
            data.shipping_street2 = $('#edit_shipping_street2').val();
            data.shipping_city = $('#edit_shipping_city').val();
            data.shipping_state = $('#edit_shipping_state').val();
            data.shipping_province = $('#edit_shipping_province').val();
            data.shipping_zip = $('#edit_shipping_zip').val();
            data.shipping_country = $('#edit_shipping_country').val();
            data.shipping_phone = $('#edit_shipping_phone').val();
            data.email = $('#email').val();
            
            data.address_id = _selectedAddressId;
            $.ajax({
                type:'POST',
                url:urlPrefix+'/settings/postAddress/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();
                        var position = $('#z_account_address_form').offset();
                        $('#z_account_address_form_area').animate({scrollTop: 0}, 1);
                    } else {
                        $('#stored_address_list').html(response.html);
                        $('#z_cancel_address_button').trigger('click');
                        _shippingAddressListener();
                    }
                }
            });
        });
    }
    
    function _shippingAddressListener() {
        $('.shipping_delete_button').unbind('click').click(function(e){
            var targer = $(this);
            if(confirm(ZMsg.SHIPPING_ADDRESS_DEL_CONFIRM)) {
                var addressId = $(this).attr('name');
                $.ajax({
                    type:'POST',
                    url:urlPrefix+'/settings/deleteAddress/checkout/1',
                    data:{address_id:addressId},
                    timeout:30000,
                    success:function(response) {
                        response = JSON.parse(response);
                        if(response.status == '1') {
                            $('#stored_address_list').html(response.html);
                            _shippingAddressListener();
                        } else {
                            alert(response.error);
                        }
                    }
                });
            }
            e.preventDefault();
        });
        $('.shipping_edit_button').unbind('click').click(function(e){
            var addressId = $(this).attr('name');
            $.ajax({
                type:'POST',
                url:urlPrefix+'/settings/getAddress',
                data:{address_id:addressId},
                timeout:30000,
                success:function(response) {
                    response = JSON.parse(response);
                    if(response.status == '1') {
                        //$('#z_address_add_button').trigger('click');
                        $('#z_account_address_form').modal({
                            onClose:function() {
                                $('#z_cancel_address_button').trigger('click');
                            }
                        });
                        _selectedAddressId = addressId;
                        $('#edit_shipping_first_name').val(response.address.first_name);
                        $('#edit_shipping_last_name').val(response.address.last_name);
                        $('#edit_shipping_street').val(response.address.street);
                        $('#edit_shipping_street2').val(response.address.street2);
                        $('#edit_shipping_city').val(response.address.city);
                        $('#edit_shipping_zip').val(response.address.zip);
                        $('#edit_shipping_phone').val(response.address.phone);
                        $('#edit_shipping_country').val(response.address.country);
                        $('#email').val(response.address.email);
                        if(response.address.country == 'US') {
                            $('#edit_shipping_state').val(response.address.state);
                        } else {
                            $('#edit_shipping_zip').parent().prev().html('Zip/Postal');          
                            $('#edit_shipping_state_div').css('display','none');
                            $('#edit_shipping_province_div').css('display','');
                            $('#edit_shipping_province').val(response.address.state);
                        }
                    } else {
                        alert(response.error);
                    }
                }
            });
            e.preventDefault();
        });
    }
    
}
