var xmlDataSet = "";

$(document).ready(function(){
	
	var rand=Math.floor(Math.random()*999999999999999999999);
	
	$("#regions").attr("disabled",true);
	
	$('body').css("cursor", "progress");
	
	$.ajax({
		type: "GET",
		url: "static/viprawards.xml",
		data: "r=" + rand,
		dataType: "xml",
		success: function(xmlData){
			xmlDataSet = xmlData;
			getRegions();
			searchAgSetup();
			searchContractorSetup();
			$(".loading").remove();
			$("#regions").attr("disabled",false);
			$('body').css("cursor","auto");
		}
	})
	
	
	$('#getpff').click(function(){
		var f = $('#agreementsList option:selected');
		if(f.val() != ""){
			window.open("static/awarded_equipment_reports/" + f.val());	
		}
	})
	
	$('.step2').change(function(){
		if($("#unitlist").val() != '' || $("#dispatchlist").val() != ""){
			runFilters(resources = true);
		} else {
			$("#agsearch3 select").attr("disabled", true);
			$('#resourcelist').empty();
			$("#resourcelist").append("<option value=''>Select a Resource Category</option>");
			$('#resultlist').empty();
		}
	})
	
	$('#agsearch3 select').change(function(){
		runFilters(resources = false);
	})
});

function sortAlpha(a,b){  
    return a.innerHTML > b.innerHTML ? 1 : -1;  
};

function getRegions(){
	$("#regions").change(function(){
			if($("#regions").val() != ""){
				$("#units select").attr("disabled", false);
				$('#dispatchcenter select').attr("disabled", false);
				$("#unitlist").empty();
				$('#dispatchlist').empty();
				$("#unitlist").append("<option value=''>Select a Unit</option>");
				$("#dispatchlist").append("<option value=''>Select a Dispatch Center</option>");
				$("#agreementsList").empty();
				$("#agreementsList").append("<option value=''>Select an Agreement</option>");
				$('#resultlist').empty();
				$("#agsearch3 select").attr("disabled", true);				
				reg = $('#regions').val();				
				getUnits(reg);
				getCenters(reg);
			} else {
				$("#units select").attr("disabled", true);
				$('#dispatchcenter select').attr("disabled", true);
				$("#unitlist").empty();
				$('#dispatchlist').empty();
				$("#unitlist").append("<option value=''>Select a Unit</option>");
				$("#dispatchlist").append("<option value=''>Select a Dispatch Center</option>");
				$("#agreements select").attr("disabled", true);
				$("#agreementsList").empty();
				$("#agreementsList").append("<option value=''>Select an Agreement</option>");
				$('#resultlist').empty();
				$("#agsearch3 select").attr("disabled", true);
			}
		});
}

function getUnits(region){
	$.get("../infra/vipragreements/units/"+ region + ".php",function(data){
			$("#unitlist").append(data);			
		});

	if($("#dispatchlist").val() == ''){
		getSecondedOffices(region);
	}
		
	
	// get the select
	var $dd = $('#unitlist');
	if ($dd.length > 0) { // make sure we found the select we were looking for
	
	    // save the selected value
	    var selectedVal = $dd.val();
	
	    // get the options and loop through them
	    var $options = $('option', $dd);
	    var arrVals = [];
	    $options.each(function(){
	        // push each option value and text into an array
	        arrVals.push({
	            val: $(this).val(),
	            text: $(this).text()
	        });
	    });
	
	    // sort the array by the value (change val to text to sort by text instead)
	    arrVals.sort(function(a, b){
		    if(a.val>b.val){
		        return 1;
		    }
		    else if (a.val==b.val){
		        return 0;
		    }
		    else {
		        return -1;
		    }
		});

	
	    // loop through the sorted array and set the text/values to the options
	    for (var i = 0, l = arrVals.length; i < l; i++) {
	        $($options[i]).val(arrVals[i].val).text(arrVals[i].text);
	    }
	
	    // set the selected value back
	    $dd.val(selectedVal);
	}

	
	
	
	
	//$('#unitlist').sortOptions();
	$('#unitlist option[value=""]').remove();
	$("#unitlist").prepend("<option value=''>Select a Unit</option>");
	$('#unitlist option[value=""]').attr("selected", "selected");
}

function getSecondedOffices(region){
	$('region_name',xmlDataSet).each(function(y){
		if($(this).text() == region){  // find the matching region entry
			$(this).siblings().each(function(d){ //look at the sibling 'region_offices'
					$(this).find('seconded_office').each(function(p){
							$(this).find("office_name").each(function(){
								ofn = $(this).text();
								ofncode = ofn.split(" - ");
								if(ofn != ''){
									$("#unitlist").prepend("<option value='" + ofncode[0] + "'>" + ofn + "</option>");	
								}
							})								
					})
			});
		} 
	});
}

function getCenters(region){
	/*$('region_name',xmlDataSet).each(function(y){
			if($(this).text() == region){  // find the matching region entry
				$(this).siblings().each(function(d){ //look at the sibling 'region_offices'
					$(this).children().each(function(y){
						$(this).find("centername").each(function(c){
							cn = $(this).text();
							if(cn != ''){
								found = false;
								$('#dispatchlist option').each(function(v){
									if($(this).val() == cn){
										found = true;
									}
								})
								if(!found){
									$("#dispatchlist").append("<option value='"+ cn +"'>" + cn + "</option>");
								}										
								
								found = false;
							}
						})
							
					})
	
				});
			}
	});*/
	
	$.get("../infra/vipragreements/centers/"+ region + ".php",function(data){
			$("#dispatchlist").append(data);
		});
	
	
	// get the select
	var $dd = $('#dispatchlist');
	if ($dd.length > 0) { // make sure we found the select we were looking for
	
	    // save the selected value
	    var selectedVal = $dd.val();
	
	    // get the options and loop through them
	    var $options = $('option', $dd);
	    var arrVals = [];
	    $options.each(function(){
	        // push each option value and text into an array
	        arrVals.push({
	            val: $(this).val(),
	            text: $(this).text()
	        });
	    });
	
	    // sort the array by the value (change val to text to sort by text instead)
	    arrVals.sort(function(a, b){
		    if(a.val>b.val){
		        return 1;
		    }
		    else if (a.val==b.val){
		        return 0;
		    }
		    else {
		        return -1;
		    }
		});

	
	    // loop through the sorted array and set the text/values to the options
	    for (var i = 0, l = arrVals.length; i < l; i++) {
	        $($options[i]).val(arrVals[i].val).text(arrVals[i].text);
	    }
	
	    // set the selected value back
	    $dd.val(selectedVal);
	}
	
	
	//$('#dispatchlist').sortOptions();
	$('#dispatchlist option[value=""]').remove();
	$("#dispatchlist").prepend("<option value=''>Select a Dispatch Center</option>");
	$('#dispatchlist option[value=""]').attr("selected", "selected");
}

function runFilters(resources){
	region = $('#regions').val();
	$("#agsearch3 select").attr("disabled", false);
	unit = $("#unitlist").val();
	center = $("#dispatchlist").val();
	resourceval = $('#resourcelist').val();
	if(unit != "" ){
		if(resources == true){
			resourceval = '';
			$('#resourcelist').empty();
			$('#resourcelist').append("<option value=''>Select a Resource Category</option>");
			$('office_name',xmlDataSet).each(function(y){
				if($(this).parent().parent().siblings().text() == region){	
					if($(this).text().indexOf(unit) != -1){  // find the matching unit entry code in 'office_name'
						$(this).siblings().each(function(d){ //look at the sibling 'office_awards'
							$(this).children().each(function(y){
								$(this).find("resource_center").each(function(c){  // populate the resource category drop down.
									rc = $(this).text();
									if(rc != ''){
										found = false;
										$('#resourcelist option').each(function(v){
											if($(this).val() == rc){
												found = true;
											}
										})
										if(!found){
											$("#resourcelist").append("<option value='"+ rc +"'>" + rc + "</option>");
										}										
										
										found = false;
									}
								})
									
							})
							
						});
					}
				};
			})
	}
		if(unit != "" && center != ""){
			getAgreementsByBoth(region,unit,center);
		} else {
			getAgreementsByUnit(unit);	
		}
	}
	
	if(center != ""){
		if($('#resourcelist').val() == ''){
			$('#resourcelist').empty();
			$('#resourcelist').append("<option value=''>Select a Resource Category</option>");
			$('centername',xmlDataSet).each(function(y){
				if($(this).parent().parent().parent().parent().parent().siblings().text() == region){
					
					if($(this).text().indexOf(center) != -1){  // find the matching unit entry 'centername'
						$(this).siblings().each(function(d){ //look at the sibling 'resource_center'						
							rc = $(this).text();
							if(rc != ''){
								found = false;
								$('#resourcelist option').each(function(v){
									if($(this).val() == rc){
										found = true;
									}
								})
								if(!found){
									$("#resourcelist").append("<option value='"+ rc +"'>" + rc + "</option>");
								}										
								
								found = false;
							}
						});
					}
				}
			})
	}
		if(unit != "" && center != ""){
			getAgreementsByBoth(unit,center);
		} else {
			getAgreementsByCenter(center);	
		}
		if(unit != "" && center != ""){
			getAgreementsByBoth(region,unit,center);
		} else {
			getAgreementsByCenter(center);	
		}
	}
	



	// get the select
	var $dd = $('#resourcelist');
	if ($dd.length > 0) { // make sure we found the select we were looking for
	
	    // save the selected value
	    var selectedVal = $dd.val();
	
	    // get the options and loop through them
	    var $options = $('option', $dd);
	    var arrVals = [];
	    $options.each(function(){
	        // push each option value and text into an array
	        arrVals.push({
	            val: $(this).val(),
	            text: $(this).text()
	        });
	    });
	
	    // sort the array by the value (change val to text to sort by text instead)
	    arrVals.sort(function(a, b){
		    if(a.val>b.val){
		        return 1;
		    }
		    else if (a.val==b.val){
		        return 0;
		    }
		    else {
		        return -1;
		    }
		});

	
	    // loop through the sorted array and set the text/values to the options
	    for (var i = 0, l = arrVals.length; i < l; i++) {
	        $($options[i]).val(arrVals[i].val).text(arrVals[i].text);
	    }
	
	    // set the selected value back
	    $dd.val(selectedVal);
	}
	
	
	$('#resourcelist option[value=""]').remove();
	$("#resourcelist").prepend("<option value=''>Select a Resource Category</option>");
	if(resourceval == ''){
		$('#resourcelist option[value=""]').attr("selected", "selected");
	} else {
		$('#resourcelist option[value="'+resourceval+'"]').attr("selected", "selected");
	}
}

function getAgreementsByUnit(unit){
	//check the year and status filters
	var yearfilter = $('#yearlist').val();
	var statusfilter = $('#statuslist').val();
	var resourcefilter = $('#resourcelist').val();
	var region = $('#regions').val();
	var records = new Array();
	$('ul#resultlist').empty();
	$('office_name',xmlDataSet).each(function(y){
		if($(this).parent().parent().siblings().text() == region){	
			if($(this).text().indexOf(unit) != -1){
				$(this).siblings('office_awards').each(function(a){
					
					$(this).find("award_file").each(function(e){
						var af = $(this).text();
						var display = 1;
						if(yearfilter != '' && $(this).siblings('year').text() != yearfilter){
							display = 0;
						}
						if(statusfilter != '' && $(this).siblings('status').text() != statusfilter){
							display = 0;
						}
						if(resourcefilter != ''){
							found = 0
							$(this).siblings('dispatch_center').children('resource_center').each(function(e){			
								if($(this).text() == resourcefilter){
									found++;
								}											
							})
							
							if(found == 0){
								display = 0;
							}
							
						}
						if(display == 1){
							records.push(af.split('-'));
							
						}
						
					});
										
				});
				
			}
		}	
	});
	if(records.length === 0){
		$('#resultlist').append("<li class='noag'>No Agreements Found (unit)</li>");
	} else {
		if( records.length > 0 ){
			records.sort(multisort);
			
			var len = records.length;
			for (var i=0; i<len; i++){
				var n = records[i][0]+'-'+records[i][1]+'-'+records[i][2]+'-'+records[i][3]+'-'+records[i][4];
				$("#resultlist").append("<li><a href='static/awarded_equipment_reports/" + n + "'>" + n + "</a></li>");
			}
		}
	}
	
}

function multisort(a,b){
	var o1 = a[1].toLowerCase();
	var o2 = b[1].toLowerCase();
	
	var p1 = a[3].toLowerCase();
	var p2 = b[3].toLowerCase();
	
	var q1 = a[4].toLowerCase();
	var q2 = b[4].toLowerCase();
	
	if (o1 != o2) {
		if (o1 < o2) return -1;
		if (o1 > o2) return 1;
		return 0;
	}
	if (p1 != p2){
		if (p1 < p2) return -1;
		if (p1 > p2) return 1;
		return 0;
	}
	if (q1 < q2) return -1;
	if (q1 > q2) return 1;
	return 0;
}

function getAgreementsByCenter(center){
	//check the year and status filters
	yearfilter = $('#yearlist').val();
	statusfilter = $('#statuslist').val();
	resourcefilter = $('#resourcelist').val();
	records = new Array();
	$('#resultlist').empty();
	$('award',xmlDataSet).each(function(y){
		$(this).children('dispatch_center').each(function(a){
			if($(this).children('centername').text().indexOf(center) != -1){
				var af = $(this).siblings('award_file').text();
				var display = 1;
				if(yearfilter != '' && $(this).siblings('year').text() != yearfilter){
					display = 0;
				}
				if(statusfilter != '' && $(this).siblings('status').text() != statusfilter){
					display = 0;
				}
				if(resourcefilter != ''){
					found = 0
					$(this).children('resource_center').each(function(e){			
						if($(this).text() == resourcefilter){
							found++;
						}											
					})
					
					if(found == 0){
						display = 0;
					}
					
				}
			
				if(display == 1){
					records.push(af.split('-'));	
				}						
			}
						
		});
		
	});
	if(records.length === 0){
		$('#resultlist').append("<li class='noag'>No Agreements Found (unit)</li>");
	} else {
		if( records.length > 0 ){
			records.sort(multisort);
			
			var len = records.length;
			for (var i=0; i<len; i++){
				var n = records[i][0]+'-'+records[i][1]+'-'+records[i][2]+'-'+records[i][3]+'-'+records[i][4];
				$("#resultlist").append("<li><a href='static/awarded_equipment_reports/" + n + "'>" + n + "</a></li>");
			}
		}
	}

}

function getAgreementsByBoth(region,unit,center){
	//check the year and status filters
	yearfilter = $('#yearlist').val();
	statusfilter = $('#statuslist').val();
	resourcefilter = $('#resourcelist').val();
	bothrecords = new Array();
	bothrecords.length = 0;
	$('#resultlist').empty();

	/*$('office_name',xmlDataSet).each(function(y){
		if($(this).text().indexOf(unit) != -1){
			$(this).siblings('office_awards').each(function(a){
				$(this).children('award').each(function(a){
					$(this).children('dispatch_center').each(function(a){						
						if($(this).children('centername').text().indexOf(center) != -1){
							
							var af = $(this).siblings('award_file').text();
							var display = 1;
							if(yearfilter != '' && $(this).siblings('year').text() != yearfilter){
								display = 0;
							}
							if(statusfilter != '' && $(this).siblings('status').text() != statusfilter){
								display = 0;
							}
							if(resourcefilter != ''){
								found = 0
								$(this).children('resource_center').each(function(e){			
									if($(this).text() == resourcefilter){
										found++;
									}											
								})
								
								if(found == 0){
									display = 0;
								}
								
							}
						
							if(display == 1){
								bothrecords.push(af.split('-'));
								af = '';
							}
							
						}
									
					});
				});
			});
		}
	});*/
	$('region_name',xmlDataSet).each(function(y){
		if($(this).text().indexOf(region) != -1){
			$(this).siblings('region_offices').each(function(a){
				$(this).children('office,seconded_office').each(function(a){
					$(this).children('office_name').each(function(a){
						if($(this).text().indexOf(unit) != -1){
							$(this).siblings('office_awards').each(function(a){
								$(this).children('award').each(function(a){
									$(this).children('dispatch_center').each(function(a){
										if($(this).children('centername').text().indexOf(center) != -1){
											var af = $(this).siblings('award_file').text();
											var display = 1;
											if(yearfilter != '' && $(this).siblings('year').text() != yearfilter){
												display = 0;
											}
											if(statusfilter != '' && $(this).siblings('status').text() != statusfilter){
												display = 0;
											}
											if(resourcefilter != ''){
												found = 0
												$(this).children('resource_center').each(function(e){			
													if($(this).text() == resourcefilter){
														found++;
													}											
												})
												
												if(found == 0){
													display = 0;
												}
												
											}
										
											if(display == 1){
												
												bothrecords.push(af.split('-'));
											}					
										}
													
									});
								});
							});
						}
					})		
				})
			})
		}
		
	});

	if(bothrecords.length === 0){
		$('#resultlist').append("<li class='noag'>No Agreements Found (unit)</li>");
	} else {
		if( bothrecords.length > 0 ){
			bothrecords.sort(multisort);
			// Searching for both center and unit can return results from multiple regions due to seconded offices showing up.  This removes duplicates from the list so we're just getting single results.
			
			
			var len = bothrecords.length;
			for (var i=0; i<len; i++){
				var n = bothrecords[i][0]+'-'+bothrecords[i][1]+'-'+bothrecords[i][2]+'-'+bothrecords[i][3]+'-'+bothrecords[i][4]				
				$("#resultlist").append("<li><a href='static/awarded_equipment_reports/" + n + "'>" + n + "</a></li>");
			}
		}
	}
}




function searchAgSetup(){
	$('#agreementNumber').focus(function(){
		if($(this).val() == "AG-xxxx-X-##-####"){
			$(this).val("");
			$(this).removeClass("defaulttext");	
		}	
	});
	$('#agreementNumber').blur(function(){
		if($(this).val() == ""){
			$(this).val("AG-xxxx-X-##-####");
			$(this).addClass("defaulttext");
		}
	})
	$('#agNumLookup').submit(function(){
		AgSearch();
		return false;	
	})

}

function searchContractorSetup(){
	$('#contName').focus(function(){
		if($(this).val() == 'Contractor Name'){
			$(this).val("");
			$(this).removeClass("defaulttext");
		}
	});
	$("#contName").blur(function(){
		if($(this).val() == ""){
			$(this).val("Contractor Name");
			$(this).addClass("defaulttext");
		}
	})
	$('#contractorLookup').submit(function(){
		contSearch();
		return false;	
	})
}

function AgSearch(){
	if($("#agreementNumber").val() == "AG-XXXX-X-##-####" || $("#agreementNumber").val() == "") {
		alert("Please enter an Agreement Number to search for.");
		return false;
	} else {
		if(checkAgFormat($('#agreementNumber').val())){
			getAgreement($('#agreementNumber').val());
			return false;
		} else {
			alert("Sorry, the agreement number format is incorrect.  Please reenter the number and try again.  Remember, the format needs to match the example show above the search box.");
			return false;
		}
		
	}
}

// matches given string to reg expression to confirm format.
function checkAgFormat(agString){
	if(agString.match(/AG\-[0-9a-zA-Z]{4}\-[a-zA-Z]\-[0-9]{2}\-[0-9]{4}/)){
		return true;
	} else {
		return false;
	}
}

//searches xml file for matching Agreement Number.
function getAgreement(agString){
	var isAgMatch = false;
	$('award_number',xmlDataSet).each(function(y){
		if($(this).text() == agString){
			isAgMatch = true;
			filename = $(this).siblings("award_file").text();
			$('#agreementNumber').removeClass('formerror');
			window.open("static/awarded_equipment_reports/" + filename );	
			return false;		
		}
	})
	if(!isAgMatch){
		$('#agreementNumber').addClass('formerror');
		alert("Sorry, the agreement number you entered wasn't found in our database.  Please check the number you entered and try again.");
		return false;
	}
}


/*
 * Contractor search functions
 */


function contSearch(){
	if($("#contName").val() == "Contractor Name" || $("#contName").val() == "") {
		alert("Please enter a Contractor Name to search for.");
		return false;
	} else {		
		getContractor($('#contName').val());
	}
}

function getContractor(contString){
	myreg = contString.toLowerCase().replace(/^\s*|\s*$/g,'');  //change the string to all lowercase with no spaces.
	$(".contractors").remove();  // Remove any lists that preexist on the page
	var isMatch = false;  // shows if this was a match or not.
	var count = 1; // base for an incremented value to append to the lists so they have unique id's.
	var contFound = new Array;	//holds the name of the contractor that was found, to avoid listing duplicates
	$('contractor_name',xmlDataSet).each(function(y){  // for each item found in the XML file...
		xmlCont = $(this).text().toString().toLowerCase().replace(/^\s*|\s*$/g,''); //take the value from the xml, clean it up.
		if(xmlCont.search(myreg) != -1){  // if the search function returns a value, it means the string was found.
			if(searchFoundContractors($(this).text(),contFound) == '-1' && searchFoundContractors($(this).text(),contFound) != ''){  // run the contractor name against the tracking array to make sure we haven't see it before.  If '-1' comes back then it's new and hasn't be listed yet.
				$('#contractorLookup').after( //add an entry on the page for the contractor
					"<dl id='contractorList"+count+"' class='contractors'><dt>" + $(this).text() + "</dt></dl>"
				)
				showContractorAgreements($(this).text(), count);  //find and display all the agreements for this contractor
				count = count+1; //increment the count so we can still have unique list names
				isMatch = true; //show that we found a match so the error message won't get displayed.
				$('#contName').removeClass("formerror");  //if there was an error class on the textbox, remove it.
				contFound.push($(this).text()); //Add this contractor listing to the array of entries that have been searched.
			}			
		};			
	})
	if(!isMatch){
		$('#contName').addClass('formerror');  //if a contractor wasn't found, add the error class to the form text box.
		$("#contractorList").remove(); //if a list of contractors already exists from a previous search, remove it.
		alert("Sorry, the Contractor you entered wasn't found in our database.  Please check the name you entered and try again.");
	}
	return false;  // negate the submission of the form.
}

function showContractorAgreements(contName, count){
	$('contractor_name',xmlDataSet).each(function(i){  //loop through all the contractor names in the XML file.
		if($(this).text() == contName){  // if the name matches the value passed to this function...
			$(this).siblings().each(function(d){ //look at the siblings
					af = $(this).filter("award_file").text();  //only look at those that are the award file
					if(af != ''){  // if the value isn't empty append the award entry to the contractor name list on the page.
						$("#contractorList" + count).append("<dd><a href='static/awarded_equipment_reports/"+af+"'>" + af + "</a></dd>");	
					}
			});
		}	
	})
}

function searchFoundContractors(contName, contArray){
	y = '-1';  //default value is that we didn't find anything.
	for (var i = contArray.length - 1; i >= 0; i--){		// loop over the array of contractors 
		y = contArray[i].search(contName);  // should return -1 if not found, else will return a position index like '6'.
	};
	return y;  //send back the value we found.
}






