 	normalize: (number) =>
 		# Remove whitespaces, parenthesis, slashes, dots, plus sign and letters
 		return number.replace(/\ |\(|\)|\-|\.|[A-z]|\+/g, "")
+
+	testCountryCode: (countryCode, number) =>
+		countryCodeRegex = new RegExp "^"+countryCode
+
+		if countryCodeRegex.test(number) then [true, countryCodeRegex] else [false, null]
+
+	testNDC: (nationalDestinationCode, countryObj, number) =>
+		ndcPattern = "^("+countryObj.optionalTrunkPrefix+"|)"+nationalDestinationCode
+		ndcRegex = new RegExp ndcPattern
+
+		if ndcRegex.test(number) then [true, ndcRegex] else [false, null]
 
 	format: (phone, format = vtex.phone.INTERNATIONAL) =>
 		if vtex.phone.countries[phone.countryCode].format


class Phone
	constructor: ->
		# Like so: +55 (21) 9898-6565
		@INTERNATIONAL = 0

		# Like so: (21) 9898-6565

		# And: 9898-6565
		@LOCAL = 2

	validateInternational: (originalNumber, givenCountryCode, givenNationalDestinationCode) =>
		number = originalNumber
		number = @normalize(number) # Clean up number

		if givenCountryCode
			countryCode = givenCountryCode
			[foundCountryCode, countryCodeRegex] = @testCountryCode(countryCode, number)
		else
			for countryCode, countryObj of vtex.phone.countries
				[foundCountryCode, countryCodeRegex] = @testCountryCode(countryCode, number)
				break if foundCountryCode is true

		if foundCountryCode
			withoutCountryCode = number.replace(countryCodeRegex, "")
			countryObj = root.vtex.phone.countries[countryCode]

			if givenNationalDestinationCode
				nationalDestinationCode = givenNationalDestinationCode
				[foundNDC, ndcRegex] = @testNDC(nationalDestinationCode, countryObj, withoutCountryCode)
			else
				for nationalDestinationCode in countryObj.nationalDestinationCode
					[foundNDC, ndcRegex] = @testNDC(nationalDestinationCode, countryObj, withoutCountryCode)
					break if foundNDC is true

		if foundNDC
			withoutNDC = withoutCountryCode.replace(ndcRegex, "")

			phoneNumber = countryObj.specialRules(originalNumber, withoutCountryCode,
												withoutNDC, nationalDestinationCode)

