var fs;
var City;
var combo;
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 style='width:345px;'>");
document.write("    <div class='x-box-tl'><div class='x-box-tr'><div class='x-box-tc'></div></div></div>");
document.write("    <div class='x-box-ml'><div class='x-box-mr'><div class='x-box-mc'>");
document.write("");
document.write("        <div id='leadForm'>");
document.write("			<input type='hidden' name='Site' id='Site' value=''/> ");
document.write("        </div>");
document.write("    </div></div></div>");
document.write("    <div class='x-box-bl'><div class='x-box-br'><div class='x-box-bc'></div></div></div>");
document.write("</div>");
*/

document.write("        <div id='leadForm' style='width:345px;'>");
//document.write("			<input type='hidden' name='Site' id='Site' value=''/> ");
document.write("        </div>");

Ext.onReady(function(){

   Ext.QuickTips.init();
   
   partnerSite = window.location.hostname;
   //document.getElementById('Site').value = partnerSite;
   
	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']
    ];


   
hiddenSite = new Ext.form.Field({
	autoCreate: {
		tag: 'input',
		type: 'hidden',
		name: 'Site',
		value: partnerSite
	}
});

    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;
				}
		}
    });
    
    var store = new Ext.data.SimpleStore({
        fields: ['abbr', 'state'],
        data : states // from states.js
    });
    combo = new Ext.form.ComboBox({
        store: store,
        fieldLabel: 'State',
        displayField:'abbr',
        name: 'state',
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText:'',
        selectOnFocus:true,
        resizable:true,
        allowBlank:false
    });
   
	combo.on('select', function(cbo, rec, id){
	
		if(City.getRawValue()!="" || (City.getRawValue()!="" && Zip.getRawValue()=="")){
			var val = new String();
			val = cbo.getValue();
			
			if(val){
			
				Ext.get('leadForm').mask('Loading City & Zipcode...');
			
				var request = 'http://www.leads.com/TrackerForms/ZipValidator.ashx?action=getCityZip&city=' + City.getRawValue() + '&State=' + combo.getRawValue() + '&output=json&callback=getCityZip';
				
				// Create a new script object
				aObjCityZip = new JSONscriptRequest(request);
				// Build the script tag
				aObjCityZip.buildScriptTag();
				// Execute (add) the script tag
				aObjCityZip.addScriptTag();
			}
		}
	
	});
   
    fs = new Ext.form.Form({
        labelAlign: 'right',
        labelWidth: 90,
        url:'contact_large.asp',
        name:'ContactForm',
        id:'ContactForm'
    });
    
    City = new Ext.form.TextField({
            fieldLabel: 'City',
            name: 'City',
            width:190,
            allowBlank:false,
            blankText: 'A City is required. Enter a valid zip code and the city and state will be populated for you',
            maskRe: /[^,'"]/
    });
    
    City.on("change", function(el){
    
		var val = new String();
		val = el.getRawValue();
	
		if(Zip.getRawValue()==""){
			
			Ext.get('leadForm').mask('Locating zipcode ...');
		
			var request = 'http://www.leads.com/TrackerForms/ZipValidator.ashx?action=GetStateZip&city=' + val + '&output=json&callback=getZipCode';
			
			// Create a new script object
			zObjCity = new JSONscriptRequest(request);
			// Build the script tag
			zObjCity.buildScriptTag();
			// Execute (add) the script tag
			zObjCity.addScriptTag();
		}
    
    });

    YourName = new Ext.form.TextField({
        fieldLabel: 'Name',
        name: 'YourName',
        width:190,
        maskRe: /[^,'"]/
    });
    
    CompanyName = new Ext.form.TextField({
        fieldLabel: 'Company Name',
        name: 'BusinessName',
        width:190,
        maskRe: /[^,'"]/
    });
    
    PhoneNumber = new Ext.form.TextField({
        fieldLabel: 'Phone Number',
        name: 'PhoneNumber',
        width:190,
        regex: phoneRegEx,
        regexText: phoneText,
        maskRe: /[0-9]/
    });
    EmailAddress = new Ext.form.TextField({
        fieldLabel: 'Email Address',
        name: 'from',
        width:190,
        vtype:'email'
    });
    
    CallBackTime = new Ext.form.TextArea({
        fieldLabel: 'Best Call Back Times',
        name: 'CallBack',
        grow: true,
        preventScrollbars:false,
        width: 190,
        maskRe: /[^,'"]/
    });
    
    OtherPhoneNumber = new Ext.form.TextField({
        fieldLabel: 'Other Phone Number',
        name: 'OtherPhoneNumber',
        width:190,
        regex: phoneRegEx,
        regexText: phoneText,
        maskRe: /[0-9]/
    });


        
    fs.fieldset(
		{legend:'Contact Information',labelSeparator:''},
		YourName,
		CompanyName,
		PhoneNumber,
		OtherPhoneNumber,
		EmailAddress,
	Zip,
        City,
        combo,
	CallBackTime,
	hiddenSite
	);

//fs.add(hiddenSite);
//document.write("			<input type='hidden' name='Site' id='Site' value='" + partnerSite + "'/> ");

	var btnSubmit = fs.addButton('Start Getting Local Leads');
		
		btnSubmit.on('click', function(){
			//fs.submit({params:{'partner': partnerSite}})			
			//fs.el.dom.submit();
			
			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() == "" || City.getValue() == "" || City.getRawValue == "" || combo.getValue() == "" || Zip.getRawValue() == ""){
					Ext.MessageBox.alert("Incorrect Values","Please enter Your Name, City, State, Zip Code, Company Name and Phone Number");
					return;
				}else{
			
				YourName.setValue(String.escape(YourName.getValue()));
				CompanyName.setValue(String.escape(CompanyName.getValue()));
				PhoneNumber.setValue(String.escape(PhoneNumber.getValue()));
				OtherPhoneNumber.setValue(String.escape(OtherPhoneNumber.getValue()));
				Zip,
				City.setValue(String.escape(City.getValue()));
				CallBackTime.setValue(String.escape(CallBackTime.getValue()));
				
				document.forms['ContactForm'].action = 'contact_large.asp';
				document.forms['ContactForm'].submit();
				}
				
			}
			
		});
		
		fs.render('leadForm');
		
		
    
});

function isZip(s) 
{
 
     // Check for correct zip code
     reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);
 
     if (!reZip.test(s)) {
          alert("Zip Code Is Not Valid");
          return false;
     }
 
	return true;
};

function handleMe(rec,arg,suc){

	alert(rec);

};

function myCallback(response,object){
	
	var xmlObject;
	var retCity;
	var retState;
	
	alert(response.responseText);
	
	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;
	
    City.setValue(city);
    combo.setValue(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;
			
			City.setValue(city);
			combo.setValue(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();

};