/* Copyright 2009 Palm, Inc.  All rights reserved. */

var Address = Class.create({
  initialize: function(address) {
		if(address){
	  	address = address;
			this.freeformAddress= address.freeformAddress || "";
			this.streetAddress = address.streetAddress || "";
			this.city = address.city || "";
			this.state = address.state || "";
			this.zipCode = address.zipCode || "";
		}
		this.isAddress = true;
  },

  isAddress: function() {
    return true;
  },

  getOneLine: function() {
    var addressToReturn = "";
		if(this.freeformAddress){
			return this.freeformAddress;
		}
    if (this.streetAddress) {
      addressToReturn = this.streetAddress;
    }

    if (this.city || this.state || this.zipCode) {
      addressToReturn += "\n";

      if (this.city) {
        addressToReturn += this.city;
        if (this.state) {
          addressToReturn += ", ";
        } else {
          addressToReturn += " ";
        }
      }

      if (this.state) {
        addressToReturn += this.state + " ";
      }

      if (this.zipCode) {
        addressToReturn += this.zipCode;
      }

      addressToReturn.strip();
    }

    if (this.country) {
      if (addressToReturn) {
        addressToReturn += "\n" + this.country;
      } else {
        addressToReturn = this.country;
      }
    }
    return addressToReturn;
  },

  parseAddress: function(address) {
    if (!address) {
		return;
	}
	address = address.strip();
    if (!this.pattern) {
      this.pattern = new RegExp();
      this.pattern.compile(Address.pattern);
    }
	var result = this.pattern.exec(address);
	if(result === null){
		this.streetAddress = address;
		this.city = "";
		this.state = "";
		this.zipCode = "";
		this.country = "";
		return;
	}
    //var result = address.strip().exec(this.pattern);
	for(var i = 0; i < 7; i++){

		if(result[i]){
			if(result[i].charAt(result[i].length -1) == ","){
				result[i] = result[i].substring(0, result[i].length -1);
			}
			result[i] = result[i].strip();
		}
	}

    this.streetAddress = result[1] || "";
    this.city = result[2] || "";
    this.state = result[3] ||  "";
	this.zipCode = result[4] ||   "";
	this.country = result[6] || "";
  },

	getHashKey: function(){
		this.freeformAddress = this.freeformAddress || this.getOneLine();
		return this.freeformAddress + "-LABEL:" + this.label;
	}
});

Address.pattern = "([\\s\\S]*?)" +
			"([A-Za-z \\.]+),?" + // city
			"(\\s+[A-Za-z]{2})[\\s]?" + // state
			"([0-9]{5}(-[0-9]{4})?)?" +  // zip and optional zip+4
			"(\\s+[A-Za-z \\.]+)?$"; // country