
function redirectRoute(isTo, a, c, sp, pc, country){
	var url = "http://www.mapquest.com/directions/main.adp?go=1";

	if(isTo){
		url += "http://www.mapquest.com/directions/main.adp?go=1&1a=" + document.getElementById("hdAddress").value + "&1c=" + document.getElementById("hdCity").value + "&1s=" + document.getElementById("hdStateProvince").value + "&1z=" + document.getElementById("hdPostalCode").value + "&2a=" + a + "&2c=" + c + "&2s=" + sp + "&2z=" + pc + "&r=f&cat=gas+stations";
	}
	else {
		url += "http://www.mapquest.com/directions/main.adp?go=1&1a=" + a + "&1c=" + c + "&1s=" + sp + "&1z=" + pc + "&2a=" + document.getElementById("hdAddress").value + "&2c=" + document.getElementById("hdCity").value + "&2s=" + document.getElementById("hdStateProvince").value + "&2z=" + document.getElementById("hdPostalCode").value + "&r=f&cat=gas+stations";					
	}
	//alert(url);
	self.location.href = url;
}


function redirectLocation(id){
	var lat = document.getElementById("hdLatitude").value;
	var lng = document.getElementById("hdLongitude").value;
	var sGasPriceType = getValue("hdGasPriceType");
	var sAddress = getValue("hdAddress");
	var sCity = getValue("hdCity");
	var sStateProvince = getValue("hdStateProvince");
	var sPostalCode = getValue("hdPostalCode");
	var sBrand = getValue("hdBrand");
	self.location.href= "station.jsp?StationId=" + id + "&latitude=" + lat + "&longitude=" + lng + "&address="+sAddress+"&city="+sCity+"&stateProvince="+sStateProvince+"&postalCode="+sPostalCode+"&gasPriceType="+sGasPriceType+"&brand="+sBrand;
}


function GasPrice(id, name, price, timestamp){
	this.id = id;
	this.name = name;
	this.price = price;
	if(timestamp)
		this.timestamp = timestamp;
	else
		this.timestamp = new Date();
}

GasPrice.prototype.getId = function(){
	return this.id;
}

GasPrice.prototype.getName = function(){
	return this.name;
}

GasPrice.prototype.getPrice = function(){
	return this.price;
}

GasPrice.prototype.getTimeStamp = function(){
	return this.timestamp;
}

GasPrice.prototype.getTimeStampFormated = function(){
	var sTimeStamp;
	sTimeStamp = (this.timestamp.getMonth()+1) + "/" + this.timestamp.getDate() + "/" + this.timestamp.getFullYear();
	//var hours = this.timestamp.getHours();
	//var minutes = this.timestamp.getMinutes();
	//if(minutes < 10){
	//	minutes = "0" + minutes;
	//}
	//sTimeStamp += " - ";
	//if(hours == 0 || hours == 12)
	//	sTimeStamp += "12:" + minutes	
	//else
	//	sTimeStamp += (hours % 12) + ":" + minutes
	//if(hours > 12){
	//	sTimeStamp += "pm";
	//}
	//else {
	//	sTimeStamp += "am";
	//}
	return sTimeStamp;
}


//*************************************************************************************
// StationCollection
//*************************************************************************************

function Station(id, name, address, city, stateProvince, postalCode, country, brand, phone, website, distance, gasPrices, mqLL, mqMapIcon){	
	this.base = MQPoi;
	this.base(mqLL, mqMapIcon);
	
	
	this.setKey(id);
	if(!(distance >= 0 )){
		distance = -1;
	}
	
	this.name = name;
	this.address = address;
	this.city = city;
	this.stateProvince = stateProvince;
	this.postalCode = postalCode;
	this.country = country;
	this.brand = brand;
	this.phone = phone;
	this.website = website;
	this.distance = distance;
	this.gasPrices = gasPrices;
}
Station.prototype = new MQPoi(new MQLatLng(0,0));


Station.prototype.getId = function(){ return this.getKey()};
Station.prototype.getName = function(){ return this.name};
Station.prototype.getAddress = function(){ return this.address};
Station.prototype.getCity = function(){ return this.city};
Station.prototype.getStateProvince = function(){ return this.stateProvince};
Station.prototype.getPostalCode = function(){ return this.postalCode};
Station.prototype.getCountry = function(){ return this.country};
Station.prototype.getBrand = function(){ return this.brand};
Station.prototype.getPhone = function(){ return this.phone};
Station.prototype.getWebsite = function(){ return this.website};
Station.prototype.getDistance = function(){ return this.distance};
Station.prototype.getGasPrices = function(){ return this.gasPrices};

Station.prototype.createInfoTitle = function(page, number){ 
	var sTitle = this.name;
	if(page && number){
		switch(page){
			case "index":
				sTitle = "#" + number + " " + this.name;
				break;
			default:
				sTitle = number + ". " + this.name;
				if(this.getBrand() != "null" && this.getBrand() != '')
					sTitle += " - " + this.getBrand();	
				break;
		}
	}

	this.setInfoTitleHTML(sTitle);
}

function getValue(elementName) {
	var element = document.getElementById(elementName);
	if (element != null) {
		return element.value;
	}
	return "";
	
}

Station.prototype.createInfoContentHTML = function(page){
	var sContent = "";

	
	switch(page){
		case "index":
			sContent = this.getLowPrice() + "<br/>";
			sContent += this.city + ", " + this.stateProvince;
			break;
		default:
			if(page == "resultlist")
				sContent = "<table width='100%' border='0' align='center' cellpadding='0' cellspacing='2' class='tbl'>";
			else 
				sContent = "<table width='215' border='0' align='center' cellpadding='0' cellspacing='2' class='tbl'>";

				sContent += "<tr style='color:#242451;' class='trPopupShaded'>";
					sContent += "<td colspan=2>";
					var gPrice, sPrice;
					for(var j = 0; j < this.gasPrices.length; j++){
						gPrice = this.gasPrices[j];
						
						if(j > 0)
							sContent += "<br>";
							
						sContent += "<font class='popupgastype'>" + gPrice.getName() + ":</font>&nbsp;";
						
						sPrice = StringFunctions.formatCurrency(gPrice.getPrice());
						if(sPrice == "$0.00"){
							sContent += "Available";
						}
						else {
							sContent += sPrice;
						}
						sContent += "&nbsp;<i class='timestampsm'>(" + gPrice.getTimeStampFormated() + ")</i>";
					}
					sContent += "</td>";
				sContent += "</tr>";
				sContent += "<tr>";
					sContent += "<td colspan='2' class='popup'>" + this.address + ", " + this.city + ", " + this.stateProvince;
					if(this.distance >= 0){
						sContent += "<br>(" + this.distance.toPrecision(2) + " miles away)";
					}
					if(this.phone){
						sContent += "<br>" + this.phone;
					}
					sContent += "</td>";
				sContent += "</tr>";
				sContent += "<tr>";
					sContent += "<td height='16' colspan='2' class='dir' >";
					if(page != "details"){
						sContent += "<a href='javascript:redirectLocation(" + this.getId() + ");'";
						sContent += "' class='popupLink'>Map</a> | ";
					}
					sContent += "<a href='http://www.mapquest.com/maps/map.adp?address=" + this.address + "&city=" + this.city + "&state=" + this.stateProvince + "&zipcode=" + this.postalCode + "&country=US&cat=*' class='popupLink'>Places Nearby</a>";
					if(this.website != "" && this.website != null && this.website != "null"){
						sContent += " | <a href='" + this.website + "' target='new' class='popupLink'>Website</a>";
					}
					sContent += "<br/><a href='javascript:redirectRoute(true, \"" + this.address + "\", \"" + this.city + "\", \"" + this.stateProvince + "\", \"" + this.postalCode + "\", \"" + this.country + "\")' class='popupLink'>Directions To</a>";
					sContent += " | <a href='javascript:redirectRoute(false, \"" + this.address + "\", \"" + this.city + "\", \"" + this.stateProvince + "\", \"" + this.postalCode + "\", \"" + this.country + "\")' class='popupLink'>Directions From</a>";
					sContent += "<br/></td>";
				sContent += "</tr>";					  
			sContent += "</table>";	
			break;
	}
	return sContent;
}

Station.prototype.createInfoContent = function(page){
	this.setInfoContentHTML(this.createInfoContentHTML(page));
}

Station.prototype.getLowPrice = function(){
	var dLowPrice = 1000000;
	for(var i=0; i < this.gasPrices.length; i++){
		if(dLowPrice > this.gasPrices[i].getPrice()){
			dLowPrice = this.gasPrices[i].getPrice();
		}
	}
	if(dLowPrice < 1000000){
		return StringFunctions.formatCurrency(dLowPrice);
	}
	else {
		return "";
	}

}

//*************************************************************************************
// StationCollection
//*************************************************************************************

function StationCollection(){
	this.base = MQPoiCollection;
	this.base();
	this.brands = new Array();
	this.totalCount = 0;
}
StationCollection.prototype = new MQPoiCollection();

StationCollection.prototype.getBrands = function(){
	return this.brands;
}

StationCollection.prototype.setBrands = function(brds){
	this.brands = brds;
}

StationCollection.prototype.getTotalCount = function(){
	return this.totalCount;
}

StationCollection.prototype.loadFromXML = function(xmlDoc){
	this.removeAll();

	var xmlParser = new XMLParser(xmlDoc);	
	var nStationCollection = xmlParser.getNode("stationCollection");
	var nlStationCollectionChildren = nStationCollection.childNodes;
	var stationCount = 1;
	for(var i=0; i < nlStationCollectionChildren.length; i++){
		if(nlStationCollectionChildren[i].nodeName.toLowerCase() == "brands"){
			this.handleBrandsXML(nlStationCollectionChildren[i]);
		}
		else if(nlStationCollectionChildren[i].nodeName.toLowerCase() == "station"){
			this.handleStationXML(nlStationCollectionChildren[i], stationCount);
			stationCount++;
		}
	}
	// set total count size
	var nTotalCount = xmlParser.getNode("totalCount");
	this.totalCount = this.getNodeValue(xmlParser.getNode("totalCount"));
}

StationCollection.prototype.getNodeValue = function(node){
	var val = "";
	if(node.firstChild){
		val = node.firstChild.nodeValue;
	}
	return val;
}

StationCollection.prototype.handleStationXML = function(nStation, num){
	var mqMapIcon = new MQMapIcon();
	if(num >= 100){
		mqMapIcon.setImage("images/06_14_07/3digit_icon.png", 29, 31, true, true);
	}
	else {
		mqMapIcon.setImage("images/06_14_07/2digit_icon.png", 26, 29, true, true);
	}
	
	var mqLatLng = null;
	var id, name, address, city, stateProvince, postalCode, country, brand = "", phone = "", website = "", distance = -1;
	var gasPrices = new Array();
	
	var nlStationChildren = nStation.childNodes;
	for(var i=0; i < nlStationChildren.length; i++){
		switch(nlStationChildren[i].nodeName.toLowerCase()){
			case "id":
				id = parseInt(this.getNodeValue(nlStationChildren[i]));
				break;
			case "name":
				name = this.getNodeValue(nlStationChildren[i]);
				break;
			case "address":
				address = this.getNodeValue(nlStationChildren[i]);
				break;
			case "city":
				city = this.getNodeValue(nlStationChildren[i]);
				break;
			case "stateprovince":
				stateProvince = this.getNodeValue(nlStationChildren[i]);
				break;
			case "postalcode":
				postalCode = this.getNodeValue(nlStationChildren[i]);
				break;
			case "country":
				country = this.getNodeValue(nlStationChildren[i]);
				break;
			case "brand":
				brand = this.getNodeValue(nlStationChildren[i]);
				break;
			case "phone":
				phone = this.getNodeValue(nlStationChildren[i]);
				break;
			case "website":
				website = this.getNodeValue(nlStationChildren[i]);
				break;
			case "distance":
				distance = parseFloat(this.getNodeValue(nlStationChildren[i]));
				break;
			case "latlng":
				mqLatLng = this.getMQLatLngFromXML(nlStationChildren[i]);
				break;
			case "pricecollection":
				var nlGasPriceChildren = nlStationChildren[i].childNodes;
				for(var j=0; j< nlGasPriceChildren.length; j++){
					if(nlGasPriceChildren[j].nodeName.toLowerCase() == "gasprice"){
						gasPrices.push(this.handleGasPrice(nlGasPriceChildren[j]));
					}
				}
				break;
		}
	}
	if(mqLatLng != null){
		var station = new Station(id, name, address, city, stateProvince, postalCode, country, brand, phone, website, distance, gasPrices, mqLatLng, mqMapIcon);
		station.setLabel(num + 1, "numbericon");
		station.setLabelVisible(true);
		station.createInfoTitle("searchresults", num);
		station.createInfoContent("searchresults");
		
		MQEventManager.addListener(station, "mouseover", mqPoiSwapIcon);
		MQEventManager.addListener(station, "mouseout", mqPoiSwapIcon);
		MQEventManager.addListener(station, "infowindowopen", mqPoiSwapIcon);
		MQEventManager.addListener(station, "infowindowclose", mqPoiSwapIcon);
		MQEventManager.addListener(station, "rolloveropen", showInfoWindow);
		this.add(station);
	}

	
}

StationCollection.prototype.handleGasPrice = function(nGasPrice){
	var id, name, price;
	var timestamp = new Date();
	
	var nlGasPriceChildren = nGasPrice.childNodes;
	for(var i=0; i < nlGasPriceChildren.length; i++){
		switch(nlGasPriceChildren[i].nodeName.toLowerCase()){
			case "typeid":
				id = this.getNodeValue(nlGasPriceChildren[i]);
				break;
			case "type":
				name = this.getNodeValue(nlGasPriceChildren[i]);
				break;
			case "price":
				price = parseFloat(this.getNodeValue(nlGasPriceChildren[i]));
				break;
			case "lastupdatedate":
				timestamp = new Date(this.getNodeValue(nlGasPriceChildren[i]));
				break;

		}
	}
	return new GasPrice(id, name, price, timestamp);
	
}

StationCollection.prototype.getMQLatLngFromXML = function(nLatLng){
	var lat= -90, lng = -190;
	
	var nlLatLngChildren = nLatLng.childNodes;
	for(var i=0; i < nlLatLngChildren.length; i++){
		switch(nlLatLngChildren[i].nodeName.toLowerCase()){
			case "latitude":
				lat = parseFloat(this.getNodeValue(nlLatLngChildren[i]));
				break;
			case "longitude":
				lng = parseFloat(this.getNodeValue(nlLatLngChildren[i]));
				break;
		}
	}
	
	return new MQLatLng(lat, lng);
	
}



StationCollection.prototype.handleBrandsXML = function(nBrands){
	var nlBrandsChildren = nBrands.childNodes;
	var nBrand;
	this.brands = new Array();
	for(var i=0; i < nlBrandsChildren.length; i++){
		nBrand = nlBrandsChildren[i];
		if(nBrand.nodeName.toLowerCase() == "brand"){
			this.brands.push(nBrand.firstChild.nodeValue);
		}
	}
}



//*************************************************************************************
// Gas Price Locator
//*************************************************************************************
function GasPriceLocator(){
	this.sRequestUrl = GAS_PRICE_URL;
	this.errorMessage = "";
	this.status = 1;
}

GasPriceLocator.prototype.sendRequest = function(qstring){
		var url = this.sRequestUrl;

		xmlDoc =  XMLFunctions.getHTTPRequest();
		xmlDoc.open("POST", url , false);
		xmlDoc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
		xmlDoc.send(qstring);
		//window.open(url + "?" + qstring);
		
		var xmlParser = new XMLParser(xmlDoc);
		var statusNode = xmlParser.getNode("/gasPriceLocation/status");
		if(statusNode){
			this.status = parseInt(statusNode.firstChild.nodeValue);
			if(this.status == 0){
				return xmlDoc
			}
			else {
				try{
					this.errorMessage = xmlParser.getNode("/gasPriceLocation/errorMessage").firstChild.nodeValue;
					throw this.errorMessage;
				}catch(exc){
					this.errorMessage = "Gas Price Locator Error: No Page Data";
					throw this.errorMessage;
				}
			}
		}
		else {
			this.status = 1;
			this.errorMessage = "Gas Price Locator Error: No Page Data";
			throw this.errorMessage;

		}
}

GasPriceLocator.prototype.getRadiusSearch = function(dRadius, dLat, dLng, sGasPriceTypeId, sSortOrder, sGasPriceTypeSort, sBrand, trys, pgNum){
		if(!trys)
			trys = 3;

		var data ="ST=RE";
		data += "&R=" + dRadius;
		data += "&CLL=" + dLat + "," + dLng;
		if(sGasPriceTypeId != "")
			data += "&GPT=" + sGasPriceTypeId;
		data += "&OB=" + sSortOrder;
		data += "&OBPT=" + sGasPriceTypeSort;
		
		if(sBrand != ""){
			data += "&BD=" + sBrand;
		}
		
		if (pgNum != null) {
			data += "&PS=10&PN=" + pgNum;
		} else {
			data += "&PS=10&PN=0";
		}
		
		var xmlDoc = this.sendRequest(data);
		if(this.status != 0){
			if(trys > 0){
				return this.getRadiusSearch(dRadius, dLat, dLng, sGasPriceTypeId, sSortOrder, sGasPriceTypeSort, sBrand, trys-1, pgNum);
			}
			else {
				throw this.errorMessage;
			}
		}
		else {
			var sCollection = new StationCollection();
			sCollection.loadFromXML(xmlDoc);
			
			return sCollection;			
		}
}


