function trim(str) {
	return str.replace(/^\s*|\s*$/g,"");

}

function findDealer() {

	var country = document.customForm.country.value;
	var city = "";
	var postal = document.customForm.postalCode.value;
	var state = "";
	
	getDealer(country, state, city, postal);

}

function getDealer(country, state, city, postal) {

	var url='http://dealerlocator.cat.com/dealerlocator/jsonService/V1/mainstore';
	url=url+"/";
	url=url+ country;
	url=url+"/";
	url=url+"1/en";
	url=url+"/";
	url=url+state;
	url=url+"/";
	url=url+city;
	url=url+"/";
	url=url+postal;

	jsonpRequest(url);
	
}

function jsonpRequest(url,callback) {

	var script = document.createElement("script");
	script.setAttribute("src", url);
	script.setAttribute("type", "text/javascript");
	document.body.appendChild(script);

}

function dlLoaded() {

	var errCode = "n6t+xAQEqP6Ku/zn7H9+dA==";
	var postal = document.customForm.postalCode.value;

	if (dealerList.error) {
		alert("An error has occurred, please verify your postal code and try again.");
	} else {

		var key = getKey();

		if (errCode == key) {

			if (validateZipCode(postal)) {
				openInFullWindow(getURL(key));
			} else {
				alert("Invalid Postal Code.");
			}


		} else {
			processURL(key);
		}

	}

}

function processURL(key) {

	var url = getURL(key);

	if (url != "nonPartStore") {
		
		openInFullWindow(url);			

	} else {

		var msg = document.getElementById("message");

		msg.innerHTML = buildErrorMsg();

	}

}

function buildErrorMsg() {

	var dlrName = trim(dealerList["dealerlocation-array"][0].name);
	var dlrUrls = dealerList["dealerlocation-array"][0]["urls"];
	var phone = dealerList["dealerlocation-array"][0]["phoneNumbers"];
	var url;

	var errMsg = "<b>Your local Caterpillar dealer is ";
	errMsg = errMsg + dlrName;
	errMsg = errMsg + "<br/>";
	errMsg = errMsg + "This dealer does not currently use PartStore.<br/>";
	errMsg = errMsg + "Please vist their website at: <br/>";

	for (var c = 0; c < dlrUrls.length; c++) {

		url = trim(dlrUrls[c]);

		errMsg = errMsg + "<a href=\"http://";
		errMsg = errMsg + url;
		errMsg = errMsg + "\" target = _blank>";
		errMsg = errMsg + url;
		errMsg = errMsg + "</a><br/>";

	}
	
	errMsg = errMsg + "Or contact them at: <br/>";

	for (var i = 0; i < phone.length; i++) {

		errMsg = errMsg + phone[i] + "<br/>";

	}

	errMsg = errMsg + "</b>";

	return errMsg;

}

function getKey() {

	var key = "";

	if (dealerList) {

		key = trim(dealerList["dealerlocation-array"][0].dealerCode);

	}

	return key;		

}

function getIntId() {

	var intId = "";

	if (dealerList) {

		intId = trim(dealerList["dealerlocation-array"][0].intId);

	}

	return intId;

}

function getURL(key) {

	var url = "http://www.cat.com/cda/layout?m=37400&x=7&id=1408022&mode=blank";
	var dlrName = getDealerId(key);
	var intId = getIntId();

	if (dlrName != "nonPartStore") {
		return url + "&dealer=" + dlrName + "&intid=" + intId;
	} else {
		return dlrName;
	}

}

function getDealerId(key) {

	var defaultVal = "nonPartStore";
	var dlrs = new Array();

	//Alban - US - 21237
	dlrs["8oE2kCp8q+JGeH/Tv3JNZg=="] = "alban";

	//Altorfer - US - 52404
	dlrs["uIV93YDTV6dkE7dy92yxww=="] = "altorfer";

	//Atlantic - CA - B3B2B1
	dlrs["ZwUUY4znq+otSDVAYb0Q6g=="] = "atlantic";

	//Blanchard - US - 29203
	dlrs["rTQs6Bv4pOVfj+Fypa+4pQ=="] = "blanchard";

	//Butler - US - 58041
	dlrs["aYX8lxt4db/0S/QfrjCkOg=="] = "butler";

	//Carolina - US - 28269
	dlrs["x24ZzJKBd88MMQilR7e5pQ=="] = "carolinacat";

	//Carter - US - 23060
	dlrs["j6+ZLTH9BEHBwTTvIVayUw=="] = "cartermachinery";

	//Cashman - US - 89052
	dlrs["p141qFyG6AYmfACNRprW0Q=="] = "cashman";

	//Cleveland - US - 15668
	dlrs["gJiNVw0y9xevKUEsBAWYOA=="] = "clevelandbrothers";

	//Dean - US - 64132
	dlrs["tOtGu1NewhMgUaW1RDhiRQ=="] = "deanmachinery";

	//Empire - US - 86033
	dlrs["Ska1z+z3rUZeNC8yt2uRYQ=="] = "empire";

	//Fabco - US - 53225
	dlrs["0xAilnoYQ4jc7BN/Vd0iVg=="] = "fabco";

	//Fabick - US - 62294
	dlrs["9VjPfYZwfVY5DFiH9fH20Q=="] = "johnfabick";

	//Finning CA - CA - T5S 1C1
	dlrs["Ay1OTduha65Cfq107/OgeQ=="] = "finningca";

	//Foley Equipment - US - 67213
	dlrs["suy9l5xoQlUnpORTz56DQQ=="] = "foley";

	//Foley Inc - US - 08854
	dlrs["mJ232D0XFCArC0j+XS7bew=="] = "foleyinc";

	//Ransome - US - 19020
	dlrs["5T3EhCq9wwaqjc9aZlRksw=="] = "ransome";

	//Gregory Poole - US - 27606
	dlrs["clY6C498WMbZF+EPJIUxsw=="] = "gregorypoole";

	//Halton - US - 97218
	dlrs["2qVLM+3+y9eiBIg5gkP+ZA=="] = "haltonco";

	//Hawthorne - US - 92127
        dlrs["2jhpX4AqIwmcTc2A6NG6+A=="] = "hawthorne";

	//Hawthorne Pacific - US - 96732
	dlrs["n2aQTt6qx34j5U3BvFRYIg=="] = "hawthornepacific";

	//Hewitt - CA - G8Z 4H1
	dlrs["V73vm8Cn9941rA1GkxHGWw=="] = "hewitt";

	//HO Penn - US - 06111
	dlrs["+8HQcPQPbPHOpmAEGzBVVw=="] = "hopenn";

	//Holt Cat - US - 78045
	dlrs["68h9QwUBFoqsBNqMEZjyWw=="] = "holttexas";

	//Holt Californina - US - 95206
	dlrs["LdtA2/wQZUh0cNgP2J8oJg=="] = "holtca";

	//JA Riggs - US - 72601
	dlrs["NRQijb4snvl9BQn9syf0gg=="] = "jariggs";

	//Johnson Machinery - US - 92507
	dlrs["OSZdS/So1wOD7/HagTdsYg=="] = "johnsonmachinery";

	//Kelly Tractor - US - 33440
	dlrs["MbZyXckxLVBODqFWgIKP6Q=="] = "kellytractor";

	//Kramer - CA - S4P3A8
	dlrs["tyZiP7GXYiiLvUSkp3dYmA=="] = "kramer";

	//Louisiana - US - 71052
	dlrs["U6o2W5tg/z9Qp2rGaUmRfA=="] = "louisiana";

	//MacAllister - US - 46032
	dlrs["E0UG9GqaScjrmCRhXjB4Ew=="] = "macallister";

	//Martin Tractor - US - 66609
	dlrs["n6t+xAQEqP6Ku/zn7H9+dA=="] = "martintractor";

	//Michigan Cat - US - 48375
	dlrs["T1L4lAr5WYf+v3bQ2rt9gg=="] = "michigan";

	//Milton Cat - US - 01757
	dlrs["nc5/VlC5atL5bNO4LOzQWw=="] = "milton";

	//Mustang Cat - US - 77040
	dlrs["klhvndOFELNy902GCYpyMQ=="] = "mustang";

	//NC Machinery - US - 98424
	dlrs["fCxp6PGTsip3AVBxcyetOw=="] = "ncmachinery";

	//NMC - US - 68138
	dlrs["MPeFLWRPOqbrS4/YcIlHiQ=="] = "nebraskamachinery";

	//Ohio Cat - US - 43701
	dlrs["gwyGHWtu4QJr74eAHd9dYg=="] = "ohiomachinery";

	//Patten - US - 61348
	dlrs["H8mKEMFyYGXwW8C9nRRNXg=="] = "patten";

	//Peterson - US - 97459
	dlrs["fAkdcAXmQIbAtfZLjmdjlA=="] = "petersonmachineryco";

	//Peterson Tractor - US - 94577
	dlrs["sZf9j2VFlA3CmmeBWASp/A=="] = "petersontractor";

	//Puckett - US - 39204
	dlrs["DZORkit6lI/8poLtd9bTGg=="] = "puckett";

	//Quinn Company - US - 90601
	dlrs["Rm0M2SXH+++W0aR9gRXf8A=="] = "quinncompany";

	//Ring Power - US - 33578
	dlrs["vh+8kdoEkwhDuRB3lcFdiQ=="] = "ringpower";

	//Stowers Cat - US - 37924
	dlrs["tkU1LSGxsLa4mw9qYOu/2A=="] = "stowers";

	//Thompson Machinery - US - 37086
	dlrs["0EBoFGpT+rtuYyLU5ca5lA=="] = "thompsonmachinery";

	//Thompson Tractor - US - 35805
	dlrs["F3OhENWRyNiqVdzdltFLhg=="] = "thompsontractor";

	//Toromont Cat - CA - R2R2W3
	dlrs["ztR7F1PgalxXSmcOXjsXXQ=="] = "toromont";

	//Tractor and Equipment - US - 59101
	dlrs["doCQev+egYKTlD8eLcnmlw=="] = "tractorandequipment";

	//Wagner - US - 81505
	dlrs["YTvxg7iLXHgZVlNKH6McqA=="] = "wagnerequipment";

	//Walker - US - 25015
	dlrs["2MDkiOhsCFAvtff+fH3jFA=="] = "walker";

	//Warren Cat - US - 79118
	dlrs["eRaPzaMAs9jz/pOOxTkucw=="] = "warrencat";

	//Western States - US - 83642
	dlrs["nJbSGhYqH4YPAZVLXVupnw=="] = "westernstates";

	//Whayne - US - 47711
	dlrs["UYxzJD11Or+EsG0RHQ9AeQ=="] = "whayne";

	//Wheeler - US - 84737
	dlrs["MKbaD+QlrsdTrM3GA5sQ6g=="] = "wheelermachinery";

	//Wyoming - US - 82604
	dlrs["Oez0eZ7p6/Sh8bs7aLoxMw=="] = "wyoming";

	//Yancey Bros - US - 31909
	dlrs["eCA8vI2hbyOY/KZqbE/SdQ=="] = "yanceybros";

	//Ziegler - US - 55420
	dlrs["S+sTOuAS9VVvkd5Y0l/AYg=="] = "ziegler";
	
	//Mc Cormick MacNaughton - IE
      dlrs["OjLNzF14WNkvTqoIoh+6HQ=="] = "mccormickmacnaughton";

      //Finning UK - GB
      dlrs["/DY0smaf+eqmiSBHuHVJHw=="] = "finninguk";	

	//BM France - FR
	dlrs["f+dty8D9CU6atWl8bWOKXA=="] = "b-m";

	//BM Belgium - BE
	dlrs["6pbOhmMpM2RtTAg7qI8lGQ=="] = "bmbe";

	var dlr = dlrs[key];

	if (dlr == undefined ||
		dlr == null ||
		dlr == '') {
		return defaultVal;
	} else {
		return dlr;
	}

}

function openInFullWindow(url) {

	if (url != '') {

		params  = 'width='+screen.width;
		params += ', height='+screen.height;	
		params += ', top=0, left=0'
		//params += ', fullscreen=1';
		params += ', scrollbars=auto';
		params += ', resizable=1';
		params += ', status=1';
		params += ', directories=1';
		params += ', location=1';
		params += ', menubar=1';
		params += ', toolbar=1';

		window.open(url, '', params);

	}

}

function validateZipCode(zip) {

	/* 
		Zip code begins with 66 or 67
	*/

	if (zip != undefined &&
				zip != null) {

		if (zip.length >= 5) {

			var temp = zip.substring(0, 2);

			if (temp == '66' ||
				temp == '67') {

				return true;

			}

		}


	}

	return false;

}
