﻿dojo.addOnLoad(function(){

if(dojo.byId("search-text")){
dojo.byId("search-text").onkeypress=function(event){
				if(!event){
					event=window.event;
					}
				return event.keyCode!=13;
			}

dojo.connect(dojo.byId("search-text"),"onkeyup",function(e){
				e.preventDefault();
				if(e.keyCode == dojo.keys.ENTER){
					searchSubmit();
				}	
			});
dojo.connect(dojo.byId("search-btn"),"onclick",function(e){
				e.preventDefault();
				searchSubmit();
			});
}
});

function searchSubmit() {
	var searchText=dojo.query("#form-search-submit #search-text")[0].value;
	if(isTrackingNumber(searchText)){
		if(typeof homePageSearchBeaconDoer == 'function') {
			homePageSearchBeaconDoer();
		}			
		window.top.location="https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1="+searchText;
	}else{
		if(dojo.byId("search-text").value==""||dojo.byId("search-text").value=="Search") {
			alert("Please enter a word or phrase to search for.");
		} else {
			if(typeof homePageSearchBeaconDoer == 'function') {
				homePageSearchBeaconDoer();
			}
			window.top.location="http://about.usps.com/search.htm?q="+searchText;
		}
	}
}

function isTrackingNumber(searchText){
	var regex=new RegExp(/^\d{20}/);
	var result=regex.exec(searchText.split(' ').join(''));
	if(result){
	return true;
	}
	regex=new RegExp(/^[a-zA-Z]{2}\d{9}[a-zA-Z]{2}/);
	result=regex.exec(searchText.split(' ').join(''));
	if(result){
	return true;
	}	

	regex=new RegExp(/^[a-zA-Z]{2}\d{9}/);
	result=regex.exec(searchText.split(' ').join(''));
	if(result){
	return true;
	}

	regex=new RegExp(/^\d{10}/);
	result=regex.exec(searchText.split(' ').join(''));
	if(result){
	return true;
	}

	regex=new RegExp(/^\d{22}/);
	result=regex.exec(searchText.split(' ').join(''));
	if(result){
	return true;
	}

	regex=new RegExp(/^\d{30}/);
	result=regex.exec(searchText.split(' ').join(''));
	if(result){
	return true;
	}
return false;
}
