var fs;
var City; //City
var combo; // State
var Zip;
var isDirty;
var partnerSite;
var YourName;
var CompanyName;
var PhoneNumber;
var EmailAddress;
var CallBackTime;
var OtherPhoneNumber;
var aObj;
var zObjCity;
var aObjCityZip;
var hiddenSite;

var phoneRegEx = /^(\d{3}[-]?){1,2}(\d{4})$/;
var phoneMask = /[\d-]/;
var phoneText = 'Not a valid phone number.  Must be numeric only in the format of 5551113333';

var zipIsDirty;
var cityIsDirty;

document.write("        <div id='leadForm' style='width:100%;'>");
document.write("        </div>");

Ext.onReady(function(){

    Ext.QuickTips.init();
   
    var states=[['AL','Alabama'],['AK','Alaska'],['AZ','Arizona'],['AR','Arkansas'],['CA','California'],['CO','Colorado'],['CT','Connecticut'],['DE','Delaware'],['DC','District of Columbia'],['FL','Florida'],['GA','Georgia'],['HI','Hawaii'],['ID','Idaho'],['IL','Illinois'],['IN','Indiana'],['IA','Iowa'],['KS','Kansas'],['KY','Kentucky'],['LA','Louisiana'],['ME','Maine'],['MD','Maryland'],['MA','Massachusetts'],['MI','Michigan'],['MN','Minnesota'],['MS','Mississippi'],['MO','Missouri'],['MT','Montana'],['NE','Nebraska'],['NV','Nevada'],['NH','New Hampshire'],['NJ','New Jersey'],['NM','New Mexico'],['NY','New York'],['NC','North Carolina'],['ND','North Dakota'],['OH','Ohio'],['OK','Oklahoma'],['OR','Oregon'],['PA','Pennsylvania'],['PR','Puerto Rico'],['RH','Rhode Island'],['SC','South Carolina'],['SD','South Dakota'],['TN','Tennessee'],['TX','Texas'],['UT','Utah'],['VT','Vermont'],['VA','Virginia'],['WA','Washington'],['WV','West Virginia'],['WI','Wisconsin'],['WY','Wyoming']    ];

    partnerSite = window.location.hostname;

    fs = new Ext.form.Form({
        labelAlign: 'top',
        labelWidth: 90,
        buttonAlign:'left',
        url:'contact_large.asp',
        name:'ContactForm',
        id:'ContactForm'
    });

    Zip = new Ext.form.TextField({
		fieldLabel: 'Zip Code',
        name: 'zip',
        width:80,
        maxlength: 80,
        maskRe: /[0-9]/
    });
    
    Zip.on('change',function(el){
    
		var val = new String();
		val = el.getRawValue();
		
		if(val){

			if(isZip(val)){
				// get the first 5 of the zipcode
				if(val.length>5){
					val = val.substr(0, 5);
				}
			
				Ext.get('leadForm').mask('Loading City & State...');
			
				var request = 'http://www.leads.com/TrackerForms/ZipValidator.ashx?action=getCityState&zip='+val + '&output=json&callback=getLocal';
				
				// Create a new script object
				aObj = new JSONscriptRequest(request);
				// Build the script tag
				aObj.buildScriptTag();
				// Execute (add) the script tag
				aObj.addScriptTag();
				
				//var rec = ds;
			}
		}
    });
    
    YourName = new Ext.form.TextField({
        fieldLabel: 'Name',
        name: 'YourName',
        width:160,
        maskRe: /[^,'"]/
    });
    
    CompanyName = new Ext.form.TextField({
        fieldLabel: 'Company Name',
        name: 'BusinessName',
        width:160,
        maskRe: /[^,'"]/
    });
    
    PhoneNumber = new Ext.form.TextField({
        fieldLabel: 'Phone Number',
        name: 'PhoneNumber',
        width:160,
        regex: phoneRegEx,
        regexText: phoneText,
        maskRe: /[0-9]/
    });
    
    EmailAddress = new Ext.form.TextField({
        fieldLabel: 'Email Address',
        name: 'from',
        width:160,
        vtype:'email'
    });
    
    CallBackTime = new Ext.form.TextArea({
        fieldLabel: 'Best Call Back Times',
        name: 'CallBack',
        grow: true,
        preventScrollbars:false,
        width: 160,
        maskRe: /[^,'"]/
    });
            
    fs.add(
		YourName,
		CompanyName,
		PhoneNumber,
		EmailAddress,
	    Zip,
	    CallBackTime
	);

	var btnSubmit = fs.addButton('Submit');
		
		btnSubmit.on('click', function(){
			
			if(Zip.getRawValue() == ""){
				//if(City.getRawValue == "" || combo.getValue() == ""){
					Ext.MessageBox.alert('Incorrect Values', 'Please enter a zip code');
				//}
				return;
			}else{
				if(YourName.getValue() == "" || CompanyName.getValue() == "" || PhoneNumber.getValue() == "" || Zip.getRawValue() == ""){
					Ext.MessageBox.alert("Incorrect Values","Please enter Your Name, Company Name, Phone Number, Zip Code");
					return;
				}else{
			
				YourName.setValue(String.escape(YourName.getValue().replace(/'/g, "")));
				EmailAddress.setValue(String.escape(EmailAddress.getValue().replace(/'/g, "")));
				CompanyName.setValue(String.escape(CompanyName.getValue().replace(/'/g, "")));
				PhoneNumber.setValue(String.escape(PhoneNumber.getValue().replace(/'/g, "")));
				document.getElementById("OtherPhoneNumber").value="";
				Zip,
				CallBackTime.setValue(String.escape(CallBackTime.getValue().replace(/'/g, "")));
				
				document.forms['ContactForm'].action = 'contact_large.asp';
				document.forms['ContactForm'].submit();
				
				}
				
			}
			
		});
		
		fs.render('leadForm');
		
		// add hidden fields
		// we do it this way because using Ext.form.Field before render method causes labelSeparator : to appear on the page
        hiddenSite = fs.el.createChild({tag: 'input',type: 'hidden',id:'Site',name: 'Site',value: partnerSite});
        combo = fs.el.createChild({tag: 'input',type: 'hidden',id:'State',name: 'State',value: ''});
        City = fs.el.createChild({tag: 'input',type: 'hidden',id:'City',name: 'City',value: ''});
        OtherPhoneNumber = fs.el.createChild({tag:'input', type:'hidden',id:'OtherPhoneNumber',name:'OtherPhoneNumber', value: ''});


    
});

function isZip(s) 
{
 
     // Check for correct zip code
     reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
 
     if (!reZip.test(s)) {
          Ext.Msg.alert("Zipcode Error", "Zip Code Is Not Valid");
          return false;
     }
 
	return true;
};

function myCallback(response,object){
	
	var xmlObject;
	var retCity;
	var retState;
	
	if(Ext.isIE || Ext.isIE7){
		//retCity = xmlObject.childNodes[1].text;
		//retState = xmlObject.childNodes[2].text;
	}else{
		//retCity = xmlObject.childNodes[1].textContent;
		//retState = xmlObject.childNodes[2].textContent;
	}
	
    //City.setValue(retCity);
    //combo.setValue(retState);
	
	Ext.get('leadForm').unmask();
	
};

function _serverResponseHandler(sData){
	alert(sData);
};

function JSONscriptRequest(fullUrl) {
  // REST request path
  this.fullUrl = fullUrl; 
  // Keep IE from caching requests
  this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
  // Get the DOM location to put the script tag
  this.headLoc = document.getElementsByTagName("head").item(0);
  // Generate a unique script tag id
  this.scriptId = 'ZipValidator' + JSONscriptRequest.scriptCounter++;
};

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
JSONscriptRequest.prototype.buildScriptTag = function () {
  // Create the script tag
  this.scriptObj = document.createElement("script");

  // Add script object attributes
  this.scriptObj.setAttribute("type", "text/javascript");
  this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
  this.scriptObj.setAttribute("id", this.scriptId);
};

// removeScriptTag method
JSONscriptRequest.prototype.removeScriptTag = function () {
  // Destroy the script tag
  this.headLoc.removeChild(this.scriptObj); 
};

// addScriptTag method
JSONscriptRequest.prototype.addScriptTag = function () {
  // Create the script tag
  this.headLoc.appendChild(this.scriptObj);
};

function getLocal(json){
	
	var city = json.zipInfo.zipcode[0].city;
	var state = json.zipInfo.zipcode[0].state;
	
    document.getElementById("City").value = city;
    document.getElementById("State").value = state;
	
	aObj.removeScriptTag();
	
	Ext.get('leadForm').unmask();
};

function getZipCode(json){

	var l = json.zipInfo.length;
	
	if(l){
		if(l>0){
		
			var city = json.zipInfo[0].city;
			var state = json.zipInfo[0].state;
			var zip = json.zipInfo[0].zipcode;
			
			document.getElementById("City").value = (city);
			document.getElementById("State").value = (state);
			
			if(zip != "00000"){
				Zip.setValue(zip);
			}
			
		}
	}
   	
   	zObjCity.removeScriptTag();
   	   	
	Ext.get('leadForm').unmask();

};

function getCityZip(json){

	var l = json.zipInfo.length;
	
	if(l){
		if(l>0){
		
			var city = json.zipInfo[0].city;
			var state = json.zipInfo[0].state;
			var zip = json.zipInfo[0].zipcode;
			
			//City.setValue(city);
			//combo.setValue(state);
			if(zip != "00000"){
				Zip.setValue(zip);
			}
		}
	}
   	
   	aObjCityZip.removeScriptTag();
   	   	
	Ext.get('leadForm').unmask();

};