var BASE_AJAX_URL = "/FordUSCommApp";
var ACTION_LOCATE_DEALER_URL = "dealerSearch.do";

var dealerSearchResults = null;
var currentPage = 0;
var currentRecord = 1;
var criteriaCount = 1;
var totalRecordCount = 0;
var pageCount = -1;

function initializeDealerLocatorPage(){

	//Check for zip and 'refine'
	var refine = getParameter("refine");
	if( refine != "0" ){
		$("#criteriafilters").val( refine );
	}

	var zip = gup("zip");
	if(zip){
		if(!(zip.toLowerCase() ==  "zip") && isDigit(zip)){
			$("#criteriadealeraddresspostalCodepart1").val(zip);
			$("#zip").val(zip);
			locateDealerClick();
		}
	}

	if($("#dealerWindow").hasClass("jqmDealerOverlay")) {
		$("#dealerWindow").jqm({modal:true});
	}

}


function locateDealer(){

 	var url = BASE_AJAX_URL + "/" + ACTION_LOCATE_DEALER_URL;
	url += getLocateDealerURL();

	//Inactivate the button while performing the query
	$("#locateDealerLink").addClass("inactive");

	$.getJSON(url, function(json, textResponse){
		if( json ){
			dealerSearchResults = json;
			completeLocateDealer();
		}
	});
}

function locateDealerClick(){

	if( ! validateLocateDealer() ){
		//Show error dialog
		return false;
	}

	//If button is inactivated, don't perform the query
	if( $("#locateDealerLink").hasClass("inactive")){
		return;
	}

	$("#masterResultsContainer").html('<img src="images/spinner.gif" />');

	 currentPage = 0;
	 currentRecord = 1;
	 criteriaCount = 1;
	 totalRecordCount = 0;
	 pageCount = -1;

	 locateDealer();
}

function getPage(pageNumber){
	currentPage = pageNumber;
	currentRecord = (currentPage * criteriaCount)+1;

	locateDealer();
}

var searchType = "";
function validateLocateDealer(){

	var criteriadealername = $("#criteriadealername").val();

	var criteriadealeraddresscity = $("#criteriadealeraddresscity").val();
	var criteriadealeraddressregion = $("#criteriadealeraddressregion").val();
	var criteriadealeraddresspostalCodepart1 = $("#criteriadealeraddresspostalCodepart1").val();

	var criteriafilters = $("#criteriafilters").val();
	var criteriacount = $("#criteriacount").val();

	//Reset lat/lon hidden areas
	$("#criterialatitude").val('');
	$("#criterialongitude").val('');

	if( ! criteriadealername && !criteriadealeraddresscity && !criteriadealeraddressregion && ! criteriadealeraddresspostalCodepart1){
		$("#alertContent").html("Please enter at least one search criteria");
		$("#alertOverlay").jqmShow();
		return false;
	}
	if( criteriadealeraddresscity && !criteriadealeraddressregion ){
		$("#alertContent").html("Please select a State for City: '" + criteriadealeraddresscity + "'" );
		$("#alertOverlay").jqmShow();
		return false;
	}
	if( !criteriadealeraddresscity && criteriadealeraddressregion ){
		$("#alertContent").html("Please enter a City for State: '" + criteriadealeraddressregion + "'" );
		$("#alertOverlay").jqmShow();
		return false;
	}

	//Search Results for: Dealerships in the 64101 zip code
	if(criteriadealername){
		searchType = "Search Results for: Dealerships named '" + TextUtils.escapeHtml(criteriadealername) + "'";
	}else if(criteriadealeraddresscity){
		searchType = "Search Results for: Dealerships in the City of '" + TextUtils.escapeHtml(criteriadealeraddresscity) + "'";
	}else if(criteriadealeraddressregion){
		searchType = "Search Results for: Dealerships in the State of '" + TextUtils.escapeHtml(criteriadealeraddressregion) + "'";
	}else if(criteriadealeraddresspostalCodepart1){
		searchType = "Search Results for: Dealerships in the " + TextUtils.escapeHtml(criteriadealeraddresspostalCodepart1) + " zip code";
	}

	return true;
}

function handleError(errorCode, explanation) {
	html = "";
	html += '<div id="resultInfoContainer">';
	if (errorCode == 'MM_GEOCODE_MULTIPLE_MATCHES') {
        //processGeocodingErrors(response.recordSetOrError);
        html += '<div id="searchResults">Multiple locations found. ';
        html += "&nbsp;" + resolveMultipleMatches();
        html += "</div>";
    } else if (errorCode == 'MM_GEOCODE_NO_MATCHES') {
    	html += '<div id="searchResults">No matches found for your search criteria.</div>';
    } else {
    	//showError(errorCode, explanation != null ? explanation : "");
    }
    html += '</div>';

	$("#locateDealerLink").removeClass("inactive");
    $("#masterResultsContainer").html(html);


}

var CAT_SERVICE = "1703,";
var CUMMINS_SERVICE = "4444,5555,666";

function completeLocateDealer(){

	$("#zip").val( "ZIP" );

	var actionErrorCode = dealerSearchResults.recordSetOrError[0].actionErrorCode;
	var error = dealerSearchResults.recordSetOrError[0].error;
	if (actionErrorCode || error) {
		if (actionErrorCode)
        	handleError(actionErrorCode, "");
		else if (error)
        	handleError(error.errorCode, error.explanation);
		return;
	}

	var html = "";

	html += '<div id="resultInfoContainer">';
    html += '<div id="searchResults">'+ searchType +'</div>';

	//Get total number of records
	totalRecordCount = dealerSearchResults.recordSetOrError[0].totalRecordCount;

	//Get total number of records to show PER PAGE
	criteriaCount = $("#criteriacount").val();

	//Get total number of pages for all recordss
	pageCount = (totalRecordCount/criteriaCount);

	//Get current record, which is the first row on the page
	currentRecord = (currentPage * criteriaCount)+1;

	var bc = "";
	//Show current page with NO link
	bc += (currentPage + 1) + "&nbsp;";

	count = 0;
	//Show next pages
	for(var j= currentPage+1; count < 5 && j < pageCount; j++){
		bc += "<a href='javascript:;' onclick='getPage("+j+")'>" + (j+1) + "</a>&nbsp;";
		count++;
	}

	rArrows = "";
 	if( currentRecord != 0 && ((totalRecordCount-currentRecord) > criteriaCount)  ){
		rArrows = '<a href="javascript:;" onclick="getPage('+ (currentPage+1) +')">&raquo;</a>';
	}

	//Create page links and arrows
    if(currentPage == 0){
    	html += '<div id="multiPageNav">Page: ' + bc + rArrows + '</div>';
    }else{
    	html += '<div id="multiPageNav">Page: <a href="javascript:;" onclick="getPage('+(currentPage-1)+')">&laquo;</a>&nbsp;' + bc + rArrows + '</div>';
    }
    html += '<div class="clear"></div>';
    html += '</div>';

	//Get criteria filter value to examine for CAT/CUMMINS refinement
	var criteriaFilter = $("#criteriafilters").val();
	var catCumminsTotals = 0;

    html += "<div id='dealerResultsContainerHolder'>"


	for(var i = 0; i < dealerSearchResults.recordSetOrError[0].record.length; i++) {
		var dealer = dealerSearchResults.recordSetOrError[0].record[i];

		var attribute = findFieldValue(dealer.fields.field, "bpnsls");
		var pnacode = findFieldValue(dealer.fields.field, "id");

		/*
		//If searching for cat/cummins dealer - check the cat/cummins accept file
		//Track how many records are added to recalculate the pagination.
		if( criteriaFilter == "CAT" ){
			if( CAT_SERVICE.indexOf( pnacode ) == -1){
				continue;
			}else{
				catCumminsTotals++;
			}
		}
		if( criteriaFilter == "CUMMINS" ){
			if( CUMMINS_SERVICE.indexOf( pnacode ) == -1){
				continue;
			}else{
				catCumminsTotals++;
			}
		}
		*/
		if (attribute == "1"){
			html += '<div class="dealerResultsContainer businessPreferred">';
		}else{
			html += '<div class="dealerResultsContainer">';
		}
    	html += '<div id="dealerRownumber">' + (currentRecord++) + '</div>';
    	html += '<div id="dealerLeft">';
        html +=	'<div id="dealerTitle"><a href="' + findFieldValue(dealer.fields.field, "url") + '" target="top"> '+findFieldValue(dealer.fields.field, "busname")+'</a><span class="dealerDistance">(Distance: '+dealer.distance[0].miles+' miles)</span></div>';
		html += '<div class="dealerAddress">' + findFieldValue(dealer.fields.field, "addr1") + '<br />'+findFieldValue(dealer.fields.field, "city")+ ", " + findFieldValue(dealer.fields.field, "state")+ " " + findFieldValue(dealer.fields.field, "zip") + '<br />Tel: '+findFieldValue(dealer.fields.field, "phone")+'   |   Fax: '+findFieldValue(dealer.fields.field, "fax")+'</div>';
        html += '<div class="dealerLinks">';
       // html += '<a href="">Set as My Ford Dealer</a>&nbsp;|&nbsp;';
       // html += '<a href="mailto:'+ findFieldValue(dealer.fields.field, "email") +'">Send to a Dealer</a>&nbsp;|&nbsp;';

       var lat = dealer.point.lat;
       var lon = dealer.point.lon;
       var id = findFieldValue(dealer.fields.field, "id");
       var dlrpa = findFieldValue(dealer.fields.field, "dlrpa");
       var zip = findFieldValue(dealer.fields.field, "zip");
       var dlrnm = findFieldValue(dealer.fields.field, "busname");

       html += '<input type="button" value="Select Dealer" onclick="DealerSelection.select(\'' + dlrpa + '\', \'' + zip + '\', \'' + TextUtils.escapeJson(dlrnm) + '\')" class="selectDealerButton" />';
        html += '<a href="javascript:showMap('+lat + ',' +lon +','+ id +')">Map &amp; Directions</a>';
       // html += '<a href="' + findFieldValue(dealer.fields.field, "url") + '"  target="top">Browse Inventory</a>';
        html += '</div>';
        html += '</div>';
      	html += '<div id="dealerRight">';
       	html += '<div id="dealerIcons">';

       	//Business Preferred Sales
		if (attribute == "1"){
			//TODO: Change this logo!
			html += '<img src="images/dealer/logos_dealer_bpn.jpg" alt="icon" class="dealerIcon" />';
		}else{
			html += '<img src="images/spacer.gif" width="75" height="35" alt="icon" class="dealerIcon" />';
		}



		attribute = findFieldValue(dealer.fields.field, "iapvd");
		//Internet Approved
		if (attribute == "1"){
			//TODO: Change this logo!
			html += '<img src="images/dealer/logos_dealer_intapprv.gif" alt="icon" class="dealerIcon" />';
		}else{
			html += '<img src="images/dealer/logos_dealer_intapprv_0.gif" alt="icon" class="dealerIcon" />';
		}

		/*
		attribute = findFieldValue(dealer.fields.field, "qcsc");
		//Quality Care Service Center
		//TODO: Change this logo!
		if (attribute == "1"){
			html += '<img src="images/dealer/logos_dealer_intapprv.gif" alt="icon" class="dealerIcon" />';
		}else{
			html += '<img src="images/dealer/logos_dealer_intapprv_0.gif" alt="icon" class="dealerIcon" />';
		}
		*/


		//Blue Oval Certified
		attribute = findFieldValue(dealer.fields.field, "boc");
		if (attribute == "1"){
			html += '<img src="images/dealer/logos_dealer_boc.gif" class="dealerIcon"/>';
		}else{
			html += '<img src="images/dealer/logos_dealer_boc_0.gif" alt="icon" class="dealerIcon" />';
		}


		html += '</div>';
		html += '</div>';

        html += '<div class="clear"></div>';

    	html += '</div>';



	}

	html += '</div>';

	//Return the button to the active state
	$("#locateDealerLink").removeClass("inactive");

	//Show the results
	$("#masterResultsContainer").html(html);

	//If there were any cat/cummins records, redraw the page links
	//Since they won't be acurately reflected from the real page count.
	if( catCumminsTotals > 0 ){
    	redrawPagination( catCumminsTotals );
    }


    if( currentRecord == 1 ){
    	 $("#multiPageNav").html( "" );
    }

}


function redrawPagination( totalRecords ){

	var html = "";
	//Get total number of records
	totalRecordCount = totalRecords;

	//Get total number of records to show PER PAGE
	criteriaCount = $("#criteriacount").val();

	//Get total number of pages for all recordss
	pageCount = (totalRecordCount/criteriaCount);

	//Get current record, which is the first row on the page
	currentRecord = (currentPage * criteriaCount)+1;

	var bc = "";
	//Show current page with NO link
	bc += (currentPage + 1) + "&nbsp;";

	count = 0;
	//Show next pages
	for(var j= currentPage+1; count < 5 && j < pageCount; j++){
		bc += "<a href='javascript:;' onclick='getPage("+j+")'>" + (j+1) + "</a>&nbsp;";
		count++;
	}

	rArrows = "";
 	if( currentRecord != 0 && ((totalRecordCount-currentRecord) > criteriaCount)  ){
		rArrows = '<a href="javascript:;" onclick="getPage('+ (currentPage+1) +')">&raquo;</a>';
	}

	//Create page links and arrows
    if(currentPage == 0){
    	html += 'Page: ' + bc + rArrows;
    }else{
    	html += 'Page: <a href="javascript:;" onclick="getPage('+(currentPage-1)+')">&laquo;</a>&nbsp;' + bc + rArrows;
    }

   $("#multiPageNav").html( html );


}

function showMap(lat, lon, dlrid){

	javascript:popUpSizeWindow('http://www.multimap.com/clients/browse.cgi?client=ctruck&lat='+lat+'&lon='+lon+'&count=1&ovtype=2&f_busid='+dlrid+'&rt=1dealer','450','650');

}

function popUpSizeWindow(newHref,height,width){
 //used thru the whole site for opening a fixed size page in a new window
	window.open(newHref,'externalFleet',"left=10,top=10,toolbar=0,scrollbars=1,resizable=1,height=" + height + ",width=" + width);
}


function resolveMultipleMatchesSelect( coordinates ){

	if( coordinates == -1 ){
		return;
	}

	//Reset the rest of the form
	$("#criteriadealername").val('')
	$("#criteriadealeraddresscity").val('')
	$("#criteriadealeraddressregion").val('')
	$("#criteriadealeraddresspostalCodepart1").val('')

	coord = coordinates.split(":");
	$("#criterialatitude").val(coord[0].trim());
	$("#criterialongitude").val(coord[1].trim());

	/*
	var url = BASE_AJAX_URL + "/" + ACTION_LOCATE_DEALER_URL;
	url += getLocateDealerURL();
	url += "?";
	url += "&criteria.latitude=" + coord[0].trim();
	url += "&criteria.longitude=" + coord[1].trim();
	url += "&criteria.filters=" + $("#criteriafilters").val();
	url += "&criteria.count=" + $("#criteriacount").val();
	url += "&criteria.start=" + (currentRecord);

	$.getJSON(url, function(json, textResponse){
		if( json ){
			dealerSearchResults = json;
			completeLocateDealer();
		}
	});
	*/

	locateDealer();

}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
function resolveMultipleMatches(){
	mm = "<select onchange='resolveMultipleMatchesSelect(this.value)'>";
	mm += "<option value='-1'>(Please refine your search)</option>";
	for(var i = 0; i < dealerSearchResults.recordSetOrError[0].locations.location.length; i++) {
		mm += "<option value='";
		mm += dealerSearchResults.recordSetOrError[0].locations.location[i].point.lat;
		mm += " : ";
		mm += dealerSearchResults.recordSetOrError[0].locations.location[i].point.lon;
		mm += "'>";
		mm += dealerSearchResults.recordSetOrError[0].locations.location[i].address.displayName;
		mm += "</option>";
	}
	mm += "</select>";
	return mm;
}

function getLocateDealerURL(){
	var u = "?";
	u += "&criteria.organization.name=" + $("#criteriadealername").val();
	u += "&criteria.organization.address.city=" + $("#criteriadealeraddresscity").val();
	u += "&criteria.organization.address.region=" + $("#criteriadealeraddressregion").val();
	u += "&criteria.organization.address.postalCode.part1=" + $("#criteriadealeraddresspostalCodepart1").val();
	u += "&criteria.longitude=" + $("#criterialongitude").val();
	u += "&criteria.latitude=" + $("#criterialatitude").val();

	var criteria = $("#criteriafilters").val();
	u += "&criteria.filters=" + $("#criteriafilters").val();
	// FIXME: Change the values to what it's called in the dropdown - adds CAT/CUMMINS support
	/*
	if( criteria != "CAT" && criteria != "CUMMINS" ){
		u += "&criteria.filters=" + $("#criteriafilters").val();
	}
	*/
	u += "&criteria.count=" + $("#criteriacount").val();
	u += "&criteria.start=" + (currentRecord);

	return u;
}

function findFieldValue(fieldArray, name) {
	var field = findField(fieldArray, name);
	return field == null ? "" : field.value;
}

function findField(fieldArray, name) {
	for(var i=0;i < fieldArray.length; i++) {
		if (fieldArray[i].name == name)
			return fieldArray[i];
	}
	return null;
}

var DealerSelection = {
	listeners: [],
	register: function(listener) {
		this.listeners[this.listeners.length] = listener;
	},
	select: function(dlrPa, dlrZip, dlrNm) {
		for(var i=0; i<this.listeners.length; i++) {
			this.listeners[i].apply(window, [dlrPa, dlrZip, dlrNm]);
		}
	}
};