/**
 * 
 * @author: zheng
 */

function ZSetting() {
	
	var _tab = '';
	var _selectedAddressId = 0;
	var _selectedPaymethodId = 0;
	
	this.setup = function(tab) {
		_tab = tab;
		_selectedAddressId = 0;
		_selectedPaymethodId = 0;
		if(tab == 'account') {
			_initAccountListener();
		} else if (tab == 'address') {
			_initAddressListener();
			checkStateCountry('shipping');
			_shippingAddressListener();
		} else if (tab == 'paymethod') {
			_initPayMethodListener();
			_paymethodListener();
			checkStateCountry('billing');
		}
	};
	
	function _cleanPaymethodForm() {
		$('#cc_type_read, #cc_number_read').empty();
		$('#error_message_list').empty();
		$('#paymethod_form :text').val('');
		$('#paymethod_form #billing_state').val('');
		$('#paymethod_form #billing_country').val('US');
		$('#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');
				}
			});
			$('#cc_type, #cc_number, #cc_expires_year, #cc_expires_month, #cvv_form').show();
			e.preventDefault();
		});
		$('#z_cancel_paymethod_button').click(function(e){
			_cleanPaymethodForm();
			$('#paymethod_form, #billing_province_div, #error_form').hide();
			$('#stored_paymethod_list, #billing_state_div').show();
			_selectedPaymethodId = 0;
			$.modal.close();
		});
		$('#z_save_paymethod_button').click(function(){
			$('#error_message_list').empty();
			$('#error_form').hide();
			var data = {};
			$('#paymethod_form :text').each(function(){
				data[$(this).attr('id')] = $(this).val();
			});
			data.billing_country = $('#billing_country').val();
			data.billing_state = $('#billing_state').val();
			data.paymethod_id = _selectedPaymethodId;
			data.cc_expires_month = $('#cc_expires_month').val();
			data.cc_expires_year = $('#cc_expires_year').val();
			data.cc_type = $('#cc_type').val();
			$.ajax({
		        type:'POST',
		        url:urlPrefix+'/settings/postPaymethod',
		        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 {
	            		$('#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',
			        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){
			$('#cc_read_form').show();
			$('#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();
		        		$('#billing_first_name').val(response.paymethod.first_name);
		        		$('#billing_last_name').val(response.paymethod.last_name);
		        		$('#billing_street').val(response.paymethod.street);
		        		$('#billing_street2').val(response.paymethod.street2);
		        		$('#billing_city').val(response.paymethod.city);
		        		$('#billing_zip').val(response.paymethod.zip);
		        		$('#billing_phone').val(response.paymethod.phone);
		        		$('#billing_country').val(response.paymethod.country);
		        		$('#cc_type').val(response.paymethod.cc_type);
		        		$('#cc_expires_month').val(response.paymethod.cc_expires_month);
		        		$('#cc_expires_year').val(response.paymethod.cc_expires_year);
		        		$('#cc_number').val(response.paymethod.cc_number);
		        		$('#email').val(response.paymethod.email);
		        		if(response.paymethod.country == 'US') {
		        			$('#billing_state').val(response.paymethod.state);
		        		} else {
		        			$('#billing_zip').parent().prev().html('Zip/Postal');			
							$('#billing_state_div').css('display','none');
							$('#billing_province_div').css('display','');
							$('#billing_province').val(response.paymethod.state);
		        		}
		        		$('#cc_type, #cc_number, #cc_expires_year, #cc_expires_month, #cvv_form').hide();
		        		$('#cc_type_read').html($('#cc_type option[value='+response.paymethod.cc_type+']').html());
		        		$('#cc_number_read').html(response.paymethod.cc_number);
		        		$('#paymethod_form').modal({
		        			onClose:function() {
		        				$('#z_cancel_paymethod_button').trigger('click');
		        			}
		        		});
		        		$('#stored_paymethod_list').hide();
		        		$('#cc_expires_year, #cc_expires_month, #cc_number_read, #cc_type_read').show();
		    			$('#cc_type, #cc_number, #cvv_form').hide();
		        	} else {
		        		alert(response.error);
		        	}
	            }
			});
			e.preventDefault();
		});
	}
	
	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 #shipping_state').val('');
		$('#z_account_address_form #shipping_country').val('US');
		$('#shipping_zip').parent().prev().html('Zip/Postal<span>*</span>');
		$('#shipping_state_div').show();
		$('#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_country = $('#shipping_country').val();
			data.shipping_state = $('#shipping_state').val();
			data.address_id = _selectedAddressId;
			$.ajax({
		        type:'POST',
		        url:urlPrefix+'/settings/postAddress',
		        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',
			        data:{address_id:addressId},
					timeout:30000,
					success:function(response) {
			        	response = JSON.parse(response);
			        	if(response.status == '1') {
				        	$('#stored_address_list').html(response.html);
			        	    _paymethodListener();
			        	} 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');
		    			_selectedAddressId = addressId;
		        		$('#shipping_first_name').val(response.address.first_name);
		        		$('#shipping_last_name').val(response.address.last_name);
		        		$('#shipping_street').val(response.address.street);
		        		$('#shipping_street2').val(response.address.street2);
		        		$('#shipping_city').val(response.address.city);
		        		$('#shipping_zip').val(response.address.zip);
		        		$('#shipping_phone').val(response.address.phone);
		        		$('#shipping_country').val(response.address.country);
		        		$('#email').val(response.address.email);
		        		if(response.address.country == 'US') {
		        			$('#shipping_state').val(response.address.state);
		        		} else {
		        			$('#shipping_zip').parent().prev().html('Zip/Postal');			
							$('#shipping_state_div').css('display','none');
							$('#shipping_province_div').css('display','');
							$('#shipping_province').val(response.address.state);
		        		}
		        	} else {
		        		alert(response.error);
		        	}
	            }
			});
			e.preventDefault();
		});
	}
	
	function _initAccountListener() {
		$('#z_edit_account_button').click(function(e){
			$('#z_account_display_form').hide();
			$('#z_account_email').val($('#z_account_display_email').html());
			$('#z_account_edit_form').modal({
				onClose: function() {
					$('#z_cancel_account_button').trigger('click');
				}
			});
			e.preventDefault();
		});
		$('#z_save_account_button').click(function(e){
			$('.alertNote').remove();
			var dobMonth = parseInt($('#birth_month').val(), 10);
			var dobDay = parseInt($('#birth_day').val(), 10);
			var dobYear = parseInt($('#birth_year').val(), 10);
			if(dobMonth + dobDay + dobYear === 0) {
				alert(ZMsg.ACCOUNT_SAVE_DOB_EMPTY);
				return false;
			}
			var valid = true;
			if($.trim($('#z_account_first_name').val()).length === 0) {
				$('#z_account_first_name').after("<em class=\"alertNote\">" + ZMsg.FIRSTNAME_MESSAGE + "</em>");
				valid = false;
			}
			if($.trim($('#z_account_last_name').val()).length === 0) {
				$('#z_account_last_name').after("<em class=\"alertNote\">" + ZMsg.LASTNAME_MESSAGE + "</em>");
				valid = false;
			}
			
			var emails = ''; 
			$(":text[name=z_account_email]").each( 
			    function() 
			    { 
			    	/*
			    	if (!_validateEmail(this.value)) 
			        { 
			    		//$.jGrowl(this.value);
			    		$(":text[name=z_account_email][value="+this.value+"]").after(" <em class=\"alertNote\">" + ZMsg.EMAIL_INVALID_MESSAGE + "</em>");
			        	valid = false;
			        } else {
			        */
			        	emails += "&email[]=" + encodeURIComponent(this.value); 
			        //}
			    }
			);
			
			if(valid === true) { 
				var postData = {email:$('#z_account_email').val(), 
							    first_name:$('#z_account_first_name').val(),
							    last_name:$('#z_account_last_name').val(),
							    dob: dobYear + '-' + dobMonth + '-' + dobDay
							};
				postData = "first_name=" + $('#z_account_first_name').val() + "&last_name=" + $('#z_account_last_name').val() + "&dob=" + dobYear + '-' + dobMonth + '-' + dobDay + emails;
				$.ajax({
			        type:'POST',
			        url:urlPrefix+'/settings/updateAccountInfo',
			        data:postData,
					timeout:30000,
					success:function(response) {
						response = JSON.parse(response);
		            	if(response.status == '0') {
		            		alert(response.error);
		            	} else {
		            		$('#z_account_display_name').html($('#z_account_first_name').val() + ' ' + $('#z_account_last_name').val());
		            		$('#z_account_display_email').html($('#z_account_email').val());
		            		$('#z_account_display_dob').html(dobYear + '-' + dobMonth + '-' + dobDay);
		            		$('#z_account_display_form').show();
		    				$('#z_account_edit_form').hide();
		    				$.modal.close();
		    				$.jGrowl(ZMsg.ACCOUNT_UPDATE_SUCCESS);
		            	}
		            }
				});
			}
			e.preventDefault();
		});
		$('#z_cancel_account_button').click(function(e){
			$('.alertNote').remove();
			var dobMonth = $('#birth_month').val();
			var dobDay = $('#birth_day').val();
			var dobYear = $('#birth_year').val();
			var dob = dobYear + '-' + dobMonth + '-' + dobDay;
			var name = $('#z_account_first_name').val() + ' ' + $('#z_account_last_name').val();
			if(name != $('#z_account_display_name').html() || dob != $.trim($('#z_account_display_dob').html()) || $('#z_account_email').val() != $('#z_account_display_email').html()) {
				$('#z_account_first_name').val($('#z_account_display_name').html().split(' ')[0]);
				$('#z_account_last_name').val($('#z_account_display_name').html().split(' ')[1]);
				$('#z_account_email').val($('#z_account_display_email').html());
				$('#birth_month').val($.trim($('#z_account_display_dob').html()).split('-')[1]);
				$('#birth_day').val($.trim($('#z_account_display_dob').html()).split('-')[2]);
				$('#birth_year').val($.trim($('#z_account_display_dob').html()).split('-')[0]);
				$('#z_account_display_form').show();
				$('#z_account_edit_form').hide();
				$.modal.close();
			} else {
				$('#z_account_display_form').show();
				$('#z_account_edit_form').hide();
				$.modal.close();
			}
			e.preventDefault();
		});
		$('#z_change_password_button').click(function(e){
			$('#z_account_display_form').hide();
			$('#z_account_password_form').modal({
				onClose: function() {
					$('#z_cancel_password_button').trigger('click');
				}
			});
			e.preventDefault();
		});
		$('#z_save_password_button').click(function(e){
			var oldpw = $('#z_account_current_password').val();
			if(oldpw === null || $.trim(oldpw).length === 0) {
				alert(ZMsg.CURRENT_PWD_NULL_MESSAGE);
				return false;
			}
			var error = '';
			var pw = $('#z_account_new_password').val();
			var pw2 = $('#z_account_repeat_password').val();
			var length = $.trim(pw).length;
			var re1 = /[0-9]/;
			var re2 = /[A-Za-z]/;
			if (pw === null || length === 0) {
				error = ZMsg.PWD_NULL_MESSAGE;
			}
			else if( length < 6 ||  length > 15){
				error = ZMsg.PWD_LENGTH_MESSAGE;
			}
			else if (!re1.test(pw)) {
				error = ZMsg.PWD_INVALID_MESSAGE;
			}
			else if (!re2.test(pw)) {
				error= ZMsg.PWD_INVALID_MESSAGE;
			}
			if(error === '') {
				if (pw2 != pw || pw2 === null || $.trim(pw2).length === 0 ) {
					alert(ZMsg.CONFIRM_PWD_MESSAGE);
					return false;
				}
				var postData = {
						pwdold:oldpw, 
						pwdnew:pw,
						pwdconfirm:pw2
					};
				$.ajax({
			        type:'POST',
			        url:urlPrefix+'/settings/changePassword',
			        data:postData,
					timeout:30000,
					success:function(response) {
						response = JSON.parse(response);
		            	if(response.status == '0') {
		            		alert(response.error);
		            	} else {
		            		$.jGrowl(response.data.message);
		            		$('#z_cancel_password_button').trigger('click');
		            	}
		            }
				});
			} else {
				alert(error);
				return false;
			}
			e.preventDefault();
		});
		$('#z_cancel_password_button').click(function(e){
			$('#z_account_display_form').show();
			$('#z_account_password_form').hide();
			$('#z_account_password_form :password').val('');
    		$.modal.close();
			e.preventDefault();
		});
	}
	
	function checkStateCountry(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','');
				}
			}
		});		
	}
	
	function _validateEmail(email) {
		if (email.search(/^\w+((-\w+)|(\.\w+))(\+\w+)*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
			return true;
		} else {
			return false;
		}
	}
}

zSetting = new ZSetting();
