/*
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Title : surroudingSuburbs
Author : Robert Prib

Description : Script for allowing surrounding suburbs to be searchable

Created :
Modified : Prabhath Perera, Oliver Gassman

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
//GLOBALS
var ssData = null;
//@UPDATE: these URLS will change
//This url contains the file of the Surrounding Suburbs JSON data
var URLSSdata = "http://www.skills.vic.gov.au/__data/assets/js_file/0011/349616/suburbsData.js";

//This url contrains the file of an array of all suburbs
var URLSuburbsList = "http://www.skills.vic.gov.au/__data/assets/js_file/0003/349617/suburbsList.js";

var relatedSuburbString = "";
var totalIntialPages = 0;
var currentPage = 0;
var resultsOnPage =0;
var totalFilteredResults = 0;
var suburb = null;
var suburbArray = [];
var postcodeSuburbArray = [];
var sSuburbsArray = [];
var ssActualResultsArray = [];
var postcode = null;
var inputLocation = null;
var totalResults = null;

//things to run onload
$(function(){
		
	//check chkSurroundSuburbs checkbox is ticked or not
	if (querySt("chkSurroundSuburbs")!= ""){
		$("#chkSurroundSuburbs").attr("checked","checked");
	}else if( querySt("queries_provider_location_query") != "" || querySt("queries_learning_category_query") != "" ){
			$("#chkSurroundSuburbs").removeAttr("checked");
	}else{
		$("#chkSurroundSuburbs").attr("checked","checked");
	}

	if($(".acfe #provider_search_no_results_content").size() > 0){
		$("#chkSurroundSuburbs").attr("checked","checked");
	}

	$(".acfe #searchFormResults, .acfe #searchForm").submit(function(e){
		e.preventDefault();
		//get alias suburbs
		$.getJSON(URLSSdata, getAliasSuburbs);

	});

	//check we are on results page
	if($(".acfe #searchFormResults").size() > 0 && querySt("chkSurroundSuburbs") !=  "" && querySt("SurroundingsOnly") == ""){
		//get Location input field text <- This the location just searched
		inputLocation = jQuery.trim($("#txtLocation").val().toLowerCase());
		if(inputLocation != ""){
			//get Number of Results on Page
			resultsOnPage = parseInt($("#searchResults .result").size());

			//getTotalPages
			totalIntialPages = parseInt($(".pagination a[class!=next]").eq(0).text());

			//getCurrentPage
			currentPage = parseInt(querySt("current_result_page"));
			if(isNaN(currentPage)){
				currentPage =1;
			}

			//set a loading class if we are last page or greater
			if(currentPage >= totalIntialPages){
				$("body").addClass("search-loading");
			}

			$.getJSON(URLSSdata, ssDataPostBack);

		}
	}
	else if($(".acfe #searchFormResults").size() > 0){
		//crate google map results for standard results
		createResultsMap();
	}
	
	//redirect if searching only surrounding suburbs
	if($(".acfe #noProviderSearchFormResults").size() > 0 && querySt("chkSurroundSuburbs") !=  "" && querySt("SurroundingsOnly") == ""){
		inputLocation = jQuery.trim($("#txtLocation").val().toLowerCase());
		$.getJSON(URLSSdata, ssDataPostBack);
	}
	
	//hide pagination if there is only one result on standard search
	if($(".acfe #searchFormResults").size() > 0 && querySt("chkSurroundSuburbs") ==  "" && querySt("SurroundingsOnly") == ""){
		var countTotPagination = 0;
		$(".acfe .pagination a").each(function(i){
			countTotPagination++;
		});
			
		if(countTotPagination<=1){
			$(".acfe .pagination").hide();
		}	
	}
	
	//just show the search results message on the first results page
	if($('#searchResults #standard_results_msg_box').size() > 0 && querySt("current_result_page") > 1){
		$('#searchResults #standard_results_msg_box').hide();
	}	
	

});

/*
 * Summary:   	This is a postback of the suburbList JSON Data
 * Parameters:
 * Return:
 */
function suburbsListPostBack(data){
	//get the Suburb being searched
	getSuburb(data);

	//if no suburb is found get the postcode that is being searched
	if(suburb == null){
		//check if we already have data
		if(ssData != null){
			surroundingPostBack(ssData);
		}else{
			$.getJSON(URLSSdata, surroundingPostBack);
		}
	}else{
		/*$("#txtLocation").val(suburb);*//*set input to search only suburb*/
		//once we are done sumbit the page
		$(".acfe #searchFormResults, .acfe #searchForm").unbind();
		$(".acfe #searchFormResults, .acfe #searchForm").submit();
	}

}

/*
 * Summary:   	This id postback of the suurroundingSuburbs JSON Data
 * Parameters:
 * Return:
 */
function surroundingPostBack(data){
	getPostcodeSuburb(data);

	if(postcode == null){
	//if we are here this means we are unable to search surrounding suburbs, so switch off surrounding suburbs search
	}else{$("#txtLocation").val(postcode);/*set input to search only postcode*/}

	//once we are done sumbit the page
	$(".acfe #searchFormResults, .acfe #searchForm").unbind();
	$(".acfe #searchFormResults, .acfe #searchForm").submit();
}


/*
 * Summary:   	This is for retreiving the suburb that is being searched
 * Parameters:  data: This takes the JSON data that contains all the suburb names
 * Return:
 */
function getSuburb(data){
	var temp = null;
	var i=0;

	//check for a suburb match in the json data within the location input string
	for (var key in data.suburbs) {
	  if (data.suburbs.hasOwnProperty(key)) {
			temp = inputLocation.match(key,"i");
			if(temp != null){
				suburbArray[i] = temp;
				temp = null;
				i++;
			}
	  }
	}

	//get longest matched suburb string from the json data (longest match == closest match)
	for(var x in suburbArray){
		if(x == 0){
			suburb = suburbArray[x];
		}
		else if(suburbArray[x].length > suburbArray[x].length[x-1])
		{
			suburb = suburbArray[x];
		}
	}

}

/*
 * Summary:   	This is for retreiving the postcode that is being searched
 * Parameters:  data: This takes the JSON data that contains all the suburb names
 * Return:
 */
function getPostcodeSuburb(data){
	postcode = $("#txtLocation").val().match(/\d{4}/g);
	var i=0;

	//UPDATE NOTE: This possible will need to change with dav imp
	if(postcode != null){
		//if the postcode is not within correct range
		if(parseInt(postcode) < 3002 || parseInt(postcode) > 3996)
		{
			postcode = null;
		}else{
			//get all the suburbs name related to the postcode
			for (var key in data.suburbs) {
				if (data.suburbs.hasOwnProperty(key)) {
					 if(data.suburbs[key].postcode == postcode){
						postcodeSuburbArray[i] = key;
						i++;
					}
				}
			}
		}
	}

}

/*
 * Summary:   	This is the first AJAX postback function run on search results page
 * Parameters:  Data is the JSON of all surrounding suburbs and their relations
 * Return:
 */
function ssDataPostBack(data){
	//save loaded data somewhere
	ssData = data;
	postcode = $("#txtLocation").val().match(/\d{4}/g);
	var sSuburbsArrayCount = 0;

	//ignore if the related suburbs containes the inputLocation as it already outputs in the normal search
	ssRegMatch = new RegExp("\\b"+inputLocation+"\\b","gi");

	if(postcode != null){
		//get a string of related subrubs for this postcode
		getPostcodeSuburb(data);
		for(var y in postcodeSuburbArray){
			for(var x in data.suburbs[postcodeSuburbArray[y]].relations){
				var isRelation = false;
				if(data.suburbs[postcodeSuburbArray[y]].relations[x]!==undefined){
					var tempSuburb = data.suburbs[postcodeSuburbArray[y]].relations[x];
				}
				for(var y in postcodeSuburbArray){
					isRelation = true;
					if(tempSuburb == postcodeSuburbArray[y]){
						isRelation = false;
						break;
					}
				}
				if(isRelation){
					if(jQuery.inArray(tempSuburb, sSuburbsArray)<0 && ssRegMatch.test(tempSuburb) !== true){
						relatedSuburbString += '"'+tempSuburb +'"+';
						sSuburbsArray[sSuburbsArrayCount] = tempSuburb;
						sSuburbsArrayCount++;
					}
				}
			}
		}
	}else{
		if(typeof(data.suburbs[inputLocation]) != "undefined"){
			//Get a string of related suburbs to send to Surrounding Suburbs JSON data search
			for(var x in data.suburbs[inputLocation].relations){
				if(jQuery.inArray(data.suburbs[inputLocation].relations[x], sSuburbsArray)<0  && ssRegMatch.test(data.suburbs[inputLocation].relations[x]) !== true){
					relatedSuburbString += '"'+data.suburbs[inputLocation].relations[x]+'"+';
					sSuburbsArray[sSuburbsArrayCount] = data.suburbs[inputLocation].relations[x];
					sSuburbsArrayCount++;
				}
			}
		}
	}
	
	//if there are no surrounding suburbs, relatedSuburbString = inputLocation
	if(sSuburbsArray.length<1){
		relatedSuburbString += '"'+inputLocation+'"+';
		sSuburbsArray[0] = inputLocation;
	}

	//if there are no standard results, then redirect to the search page with surrounding suburbs.
	if(resultsOnPage<=0){
		$(".acfe #provider_search_no_results_content").hide();
		var redirectSearchURL = "./find-a-course-provider-in-surrounding-suburbs" + location.search + "&SurroundingsOnly=on&current_result_page=1&queries_surrounding_suburb_query=" + relatedSuburbString;

		window.location = redirectSearchURL;
	}
	

	//need to find out which page we need
	var neededResultsPage = currentPage - totalIntialPages;
	//delete items on this page
	if(totalIntialPages < currentPage){
		$("#searchResults .result").remove();
	}

	if(neededResultsPage < 0 && resultsOnPage >9){
		//get the number of results and create pagination
		$.getJSON("./surroundingresults.js"+location.search+ "&current_result_page=1&results_per_page=1&queries_surrounding_suburb_query=" + relatedSuburbString, ssActualPagination);
	}else{
		var URLSSResults = "./surroundingresults.js"+location.search+ "&results_per_page=0&current_result_page=1&queries_surrounding_suburb_query=" + relatedSuburbString;
		
		$("#searchResults").append('<div id="result-set1"></div><div id="result-set2"></div>');
		$.getJSON(URLSSResults, ssActualResults);

	}

}

/*
 * Summary:   	This gets the first set of 10 results
 * Parameters:
 * Return:
 */
function ssResultsPostBack(data){
	// get the number of search results
	//totalResults = parseInt(data.search.totalResults);
	totalResults = data.length-1;
	if(totalResults > 0){

		//Required Results on First Page == number of items on last page and minus 10
		var resultsNeededOnPage = 10- resultsOnPage;
		
		//get the amount of extra page required
		var numOfExtraPages = Math.ceil((totalResults-resultsNeededOnPage)/10);
		
		ssAddPagination(numOfExtraPages);				

		//if we are on last page
		if(totalIntialPages == currentPage){
			if(resultsNeededOnPage > 0){
				$("#searchResults #result-set1").prepend("<div class='box' id='ss-found'><div class='box_inner'>Providers found in surrounding area</div></div>");
				insertSSresults(1, Math.min(resultsNeededOnPage+1,totalResults+1), data);
			}
		}else if(totalIntialPages < currentPage){
			if(resultsNeededOnPage < 1){
				$("#searchResults #result-set1").prepend("<div class='box' id='ss-found'><div class='box_inner'>Providers found in surrounding area</div></div>");
			}

			//set current page pagination
			$(".pagination a").each(function(){
				if(parseInt($(this).text()) == currentPage){
					$(this).addClass("current");
					return true;
				}
			});

			resultDec = 10*((currentPage -1)- totalIntialPages);
			//this should start at where the offset from the first page was
			var rangeX = (resultsNeededOnPage+1) +resultDec;

			//this should be only the last item 10 or the last result
			var rangeY =  Math.min(12+resultDec, totalResults+1);
			insertSSresults(rangeX, rangeY, data);

		}
	}else{
		//if there are only standard results, then show the google map now
		createResultsMap();
	}
	$("body").removeClass("search-loading");
}

/*
 * Summary:   	This creates the pagination when no results are needed to be appended
 * Parameters:
 * Return:
 */
function ssCreatePagination(data){
	// get the number of search results
	totalResults = data.length-1;

	var resultsNeededOnPage = 10- (parseInt($("#result_count").val())/10);
	var numOfExtraPages = Math.ceil((totalResults-resultsNeededOnPage)/10);

	ssAddPagination(numOfExtraPages);
}

/*
 * Summary:   	appends the surrounding surbubs to pagination
 * Parameters:  numOfExtraPages: The number of extra pages to create
 * Return:
 */
function ssAddPagination(numOfExtraPages){
	var totalPages = totalIntialPages + 1;
	var href = location.href.replace(/&current_result_page=[0-9]*/,"");

	for(var i=0;numOfExtraPages>i;i++){
		$(".pagination a[class!=next]").eq(0).before('<a href="'+href+'&current_result_page='+ totalPages +'">'+totalPages+'</a>');
		totalPages++;
	}
	
	var countTotPagination = 0;
	$(".acfe .pagination a").each(function(i){
		countTotPagination++;
	});
		
	if(countTotPagination<=1){
		$(".acfe .pagination").hide();
	}
	
}

/*
 * Summary:   	This is inserting in Results from JSON file
 * Parameters:
 * Return:
 */
function insertSSresults(rangeX, rangeY, data){
	var numSurroundingSuburbs = 0;
	var suburbRegMatch = new RegExp(inputLocation, 'i');
	for(rangeX;rangeX<rangeY;rangeX++){
			for(y=0;y<sSuburbsArray.length;y++){
				var findSSuburb = "<span class='sSuburbChk'>"+sSuburbsArray[y].toLowerCase()+"</span>";
				var suburbRegMatch = new RegExp(findSSuburb.toLowerCase(), 'i');

				if(suburbRegMatch.test(data[rangeX].toLowerCase()) == true){
					$("#searchResults #result-set1").append(data[rangeX].replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&amp;/gi,"&"));
					numSurroundingSuburbs ++;
				}
			}
	}

	//display learning category icons
	if($("#searchResults #result-set1 .result").size() > 0){

		$("#searchResults #result-set1 .result").each(function(i){

			var learning_categories = $(".learning_categories",this).text();
			var a_id = $(".category_icons",this).attr("id");
			displayLearningCategoryIcons(learning_categories, a_id);

			//Hide Email and Website if empty
			if($(".provider_email_link",this).is(":empty") == true){
				$(".s_provider_email",this).hide();
			}
			if($(".external-link",this).is(":empty") == true){
				$(".s_provider_website",this).hide();
			}

		});

	}

	//odd and even results
	$(".result:odd").addClass("alternate");

	//Hide #ss-found, if there are no surrounding suburb results.
	if(numSurroundingSuburbs <= 0){
		$('#ss-found').hide();
	}

	//create google map results for both standard results and surrounding suburb results
	createResultsMap();
}

/*
 * Summary:   Pass the filtered results to ssResultsPostBack
 * Parameters:   ji: Name of query
 */
function ssActualResults(data){
	ssActualResultsArray = processResults(data);
	ssResultsPostBack(ssActualResultsArray);
}

/*
 * Summary:   Pass the filtered results to ssActualPagination
 * Parameters:   ji: Name of query
 */
function ssActualPagination(data){
	ssActualResultsArray = processResults(data);
	ssCreatePagination(ssActualResultsArray);
}

/*
 * Summary:   This filters all the unwanted results and returns actual results
 * Parameters:   ji: Name of query
 * Return:       ssActualResultsArray
 */
function processResults(data){

	totalResults = parseInt(data.search.totalResults);
	var sSuburbName = null;
	var ssActualResultsCount = 1;

	for(x=0;x<totalResults;x++){
		if(data.results[x] !== undefined){
			for(y=0;y<sSuburbsArray.length;y++){
				var findSSuburb = "<span class='sSuburbChk'>"+sSuburbsArray[y].toLowerCase()+"</span>";				
				var suburbRegMatch = new RegExp(findSSuburb.toLowerCase(), 'i');
				
				var searchedSuburbRegMatch = new RegExp(jQuery.trim($("#txtLocation").val().toLowerCase()), 'i');
								
				if(suburbRegMatch.test(data.results[x].toLowerCase()) == true && searchedSuburbRegMatch.test(data.results[x].toLowerCase()) != true){
					ssActualResultsArray[ssActualResultsCount] = data.results[x];
					ssActualResultsCount++;
				}
			}
		}
	}
	return ssActualResultsArray;

}

/*
 * Summary:   This returns the answer to a url query of a chosen name
 * Parameters:   ji: Name of query
 * Return:       the query value
 */
function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
		for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
			if (ft[0] == ji) {
				return ft[1];
			}
		}
	return "";
}


/*
 * Summary:   This function finds alias suburbs
 * Parameters:
 * Return:
 */
function getAliasSuburbs(data){

    var aliasSuburb = "";
	var i=0;
	for (var key in data.suburbs){
		if (data.suburbs.hasOwnProperty(key)) {
			if( data.suburbs[key].aliases != "" ){
				for(var x in data.suburbs[key].aliases){
					if( data.suburbs[key].aliases[x] == jQuery.trim($("#txtLocation").val().toLowerCase()) ){
						aliasSuburb = key;
					}
				}
			}
		}
	}

	//if a suburb found for this alias
	if(aliasSuburb != ""){
			$("#txtLocation").val(aliasSuburb);
	}

	if($("#chkSurroundSuburbs:checked").size() > 0){

		//retrieve Location input field text before submission <-- This is the location that is about to be searched
		inputLocation = jQuery.trim($("#txtLocation").val());

		if(ssData == null){
			$.getJSON(URLSuburbsList, suburbsListPostBack);
		}else {
			suburbsListPostBack(ssData);
		}
	}else{
		$(".acfe #searchFormResults, .acfe #searchForm").unbind();
		$(".acfe #searchFormResults, .acfe #searchForm").submit();
	}

}
