//Get data
var stringResult;
function postCodeSuburbs(searchFieldName,searchForm,searchedText)
{

//changing ' to readable character
 searchedText = escape(searchedText);
 stringResult = "";

$("#txtLocationHidden").val('');
	//getData
	$.ajax({
		type: "get",
		data: "",
		url: "ajaxsearch.asp?q="+searchedText,
		success: function(data)
			{
				var dataToSearch = new Array();
				dataToSearch = data;
								
				$('#' + searchFieldName).focus();
				callAutoComplete(dataToSearch,searchFieldName,searchForm);
				//We don't need to make the ajax call again so we need to let the system know
				dontCallAjaxAgain = 1;
			}
		});
}



function prePostCodeList(fieldName,formName,textSearched)
{
	//We check if last character is a comma then we make our ajax call
	var lengthOfString = textSearched.length;
	var lastCharacter = textSearched.charAt(lengthOfString-1);
	
		if(lastCharacter == "," || lengthOfString < 3)
		{
			dontCallAjaxAgain = 0;
		}
			
		if ( dontCallAjaxAgain == 0 )
		{
			//Let's split the string and grab the last bit of text if we have to
			var splitText = textSearched.split(",");
			
			for(var i=0; i<splitText.length; i++)
			{
				
				if(i == splitText.length-1)
				{
					
					var splittedText = splitText[ i ].replace(/^\s+|\s+$/g, '');
					
					
					
					if(splittedText.length >= 3)
					{
						textSearched = splittedText;
						
						//Call function to fecth Postcodes and Suburbs
						
						postCodeSuburbs(fieldName,formName,textSearched);
					}	
				}	
			}
		}	
}	


function callAutoComplete(stringDataToSearch,searchFieldName,searchForm)
{
	var dataToSearch = stringDataToSearch.split(",");
	var showMoreOpt = true;
	stringResult = "";
	stringResult = stringDataToSearch;
	//The results by default will display the add more button as well as the search button.
	//If We are in the admin section adding or editing properties then we don't show these options
	if(searchForm == 'frmAddProperty')
	{
		showMoreOpt = false;
		//Remove More options div
		$("#theOptions").css('display','none');
	}	
	
	$('#' + searchFieldName).autocomplete(dataToSearch);
	
	$('input#' + searchFieldName).setOptions({
	data:dataToSearch,
	isCheckBox:true,
	multiple:true,
	formatItem: formatItem,
	formName:searchForm,
	searchField:searchFieldName,
	showMoreOptions:showMoreOpt,
	minChars:1,
	cacheLength:10,
	width:220,
	extraParams: { active : $('input[name=CSS]').is(':checked')}				
	});

	//Hack so that if we type in 3 first characters, it will still show list of suburbs
	$('#' + searchFieldName).keydown();
	
	$('#' + searchFieldName).keyup(function(e) {
		if(e.keyCode == 13) {
			$("#"+searchForm).submit();
		}	
	});
}	


function formatItem(value,q) 
{		
	//alert(stringResult);
	var resultMax = 50;
	var newConvertedString = new String(value);	
	//alert(value);
	//var newConvertedString =stringResult;
	
	var stringLength = newConvertedString.length;
	var data = newConvertedString.split(",");
	//alert(value);
	var returnedString  = "";
				
				
	for(var i=0; i<data.length; i++)
	{
		 var re = /.*?\(([^\)]*)/;
		 var oldData = re.exec(data[i])[1];
		 var newData = oldData.split("--");
		 
		 for(var j=0; j<newData.length; j++){
		 	 	var suburbArr = newData[0];
		 	 	var poscodeArrPre = newData[1];
				
				
		 	 } // End of loop
	 	     
	 	     
	 	     var newDataPcodeID = poscodeArrPre.split("**");
	 	     //Now we will split post code and post code id
	 	     for(var m=0; m<newDataPcodeID.length; m++)
	 	     {
		 	 	var poscodeArr = newDataPcodeID[0];
		 	 	
		 	 	if ( poscodeArr.length < 4)
		 	 	{
		 	 		poscodeArr = "0" + poscodeArr;
		 	 	}
		 	 	
		 	 	var poscodeIdPre = newDataPcodeID[1];
				
				
		 	 } // End of loop
		 	 
		 	 //Now we need to split the post code id and the state
		 	 var newDataState = poscodeIdPre.split("##");
		 	 for(var n=0; n<newDataState.length; n++)
	 	     {
		 	 	var poscodeId = newDataState[0];
		 	 	var countryState = newDataState[1];
		 	 } // End of loop
		 	 
	 	  
			 
	 	 	 returnedString = returnedString + "<input type='checkbox' name='selector' id='" + poscodeId + "' onClick=manipulateSearchBox(\'" + poscodeArr + "\',\'"+poscodeId+"\',\'" + countryState + "\'); class='searchRlts' value='"+ poscodeArr +"' title='"+escape(suburbArr)+"'/> <label for='" + poscodeId + "'>" + suburbArr + ", " + countryState + " (" + poscodeArr + ")</label>"; 
			//alert(returnedString)
	}
	
	return returnedString;
}

//function to close window
function closeMe()
{
	if ( !isIE7 )
	{
		$(".ac_results").slideUp("slow");
	}
	else
	{
		$(".ac_results").hide();
	}
	dontCallAjaxAgain = 1;
}

function searchNow(formName)
{
	if ( !isIE7 )
	{
		$(".ac_results").slideUp("slow");
	}
	else
	{
		$(".ac_results").hide();
	}
	
	if(formName.name == "fSearch")
	{
		SubmitForm('-1');
	}
	else
	{
		$("#" + formName.name).submit();
	}	
}

//function to add more parameters to the search
function addMore(fieldName)
{
	dontCallAjaxAgain = 0;
	//close result box
	if ( !isIE7 )
	{
		$(".ac_results").slideUp("slow");
	}
	else
	{
		$(".ac_results").hide();
	}
	
	
	
	isAddMore = isAddMore + 1;
			
	
	
	//Get actual value of the search box
	var actualText = $("#" + fieldName).val();
	
	//Let's check if last character is already a comma
	
	
	var stringLength = actualText.length;
	
	if(stringLength > 1)
	{
		stringLength = stringLength -1;
	}
	
	//We could have gone (-1,1) to get last character but starting with negative value won't work in IE
	commaText = actualText.substr(stringLength,1);
					
	if(actualText != "" && commaText != ",")
	{
		actualText = actualText + ", ";
	}
			
	$("#" + fieldName).val(actualText);
	
	//Get latest length of actual text
	var stringLength = actualText.length;


	$("#" + fieldName).focus();
	getFocus();
}

function getFocus()
{
	//Function to force the cursor to be position at the end of the input field
	$('input[type="text"]').bind('focus',function() {
	  window.o=this;
	  if (o.setSelectionRange)     /* DOM */
	   setTimeout('o.setSelectionRange(o.value.length,o.value.length)',2);
	  else if (o.createTextRange)     /* IE */
	  {
	   var r=o.createTextRange();
	   r.moveStart('character',o.value.length);
	   r.select();
	  }
	 }); 
}

tempSearchText = "";
//Function to clear or add text to the search box based on the checked boxes
//Fieldname is set in the page itself. could not find another best way to do it.
var currentSearchField = fieldNameAutocomplete;


//This function helps to check if a Checkbox is checked or unchecked
function checkIfChecked(checkId)
{
	isChecked = 0;
	$('input:checkbox[name=selector]:checked').each(function() {
		//Get attribute id
		  var actualId = $(this).attr('id');
		  var checkIdReloaded = checkId;
		
		//For debugging
		//alert(actualId + "--" + " the one clicked" + checkIdReloaded);
		//Based on id we can know if that checkbox is actually checked or unchecked
		  if( checkIdReloaded == actualId)
		  {
			isChecked = 1;
		  }
	});
	return isChecked;
}

function manipulateSearchBox(searchText,suburbABSID,ozzyState)
{ 
	dontCallAjaxAgain = 0;	
	//Pre-loaded text
	var preLoadedText = "";
	var firstAction = 1;
	var searchedText = "";
	var activateLastString = 1;
	searchedText = $("#txtLocationHidden").val();
	//alert(searchedText);
	
	
	//Checks if the checkbox selected is actually unchecked but still in the search box
	var isCheckBoxChecked = checkIfChecked(suburbABSID);
	// debugging :: alert(isCheckBoxChecked);
		
	//Determine what is the search field name being used.
	if(currentSearchField == undefined)
	{
		fieldNameAutocomplete = "txtLocation";
	}
	else
	{
		fieldNameAutocomplete = currentSearchField;
	}
	
	//Before manipulating the string from the text box, we keep a copy of it
	var currentSearchString = $("#" + fieldNameAutocomplete).val();
	
	//Preloaded Text
	preLoadedText = currentSearchString;
	
	
	/*
		If we are in the admin section adding or editing property,
		then we only allow one post code to be added to the search box
	*/
	
	if(currentSearchField == "txtpostcode")
	{
		$("#" + currentSearchField).val(searchText);
		$(".ac_results").slideUp("slow");
		//$(".ac_results").css('display','none');
		$("#" + currentSearchField).focus();
		$("#txtpostcodeHidden").val(suburbABSID);
		$("#suburbName").html($("#" + suburbABSID).attr('title'));
	}
	else
	{
			var postCodeList = new Array();
			if(isAddMore > 0)
			{
					if(isAddMore >= 1)
					{
						
						var actualValueText = $("#" + fieldNameAutocomplete).val();
						//Add newly checked checkboxes
						
						//Also worked with $("#mainUl :checked")
						//$('#mainUl input:checkbox:checked')
						$('input:checkbox[name=selector]:checked').each(function() {
							  //Suburb Name
							  var suburbName = $(this).attr('title');
							 
							  postCodeList.push(suburbName + " " + $(this).val());
					 	});
						
						
					 	//Converting preloaded text and preparing for action
						if(preLoadedText != "")
					 	{
							var preLoadedArray = new Array();
							preLoadedArray = preLoadedText.split(",");
							
							for (j=0;j<preLoadedArray.length;j++)
							{
								postCodeList.push($.trim(preLoadedArray[j]));
							}
						}	
						
					}	
			}
			//Beginning of our search :: step one
			else
			{
				var actualValueText = $("#" + fieldNameAutocomplete).val();
				//alert(actualValueText);
				//Suburb Name
				//Also worked with $('input:checkbox:checked')
				
					$('input:checkbox[name=selector]:checked').each(function() {	
							//Now we remove space at beginning of string if any
							var suburbName = $(this).attr('title');
							postCodeList.push(unescape(suburbName) + " " + $(this).val());
				 	});	
					
				//Converting preloaded text and preparing for action
				
				//************************************************************
				//If we comment this section, it actually cause a problem as follows.
				//type in perth in the search box,
				//click on perth, this will populate the search box with perth and pcode.
				//then search for bentley, choose from list, it then removes perth from the select box
				/**/
				if(preLoadedText != "")
			 	{				
					var preLoadedArray = new Array();
					preLoadedArray = preLoadedText.split(",");
					for (j=0;j<preLoadedArray.length;j++)
					{
						postCodeList.push(unescape( $.trim(preLoadedArray[j])));
					}
				}
				
				//alert(postCodeList);
				
				//************************************************************
			}
		
			populateBox(fieldNameAutocomplete,postCodeList,isCheckBoxChecked);	
			actualValueText = $("#" + fieldNameAutocomplete).val();
			
			/*
				Check first character of the string. If it is a comma, then remove it.
			*/
			var firstCharacter = actualValueText.charAt(0);
			
			if(firstCharacter == ",")
			{
				actualValueText = actualValueText.replace(actualValueText.charAt(0),"");
				actualValueText = $.trim(actualValueText);
			}
			
			
			//If the checkbox is not checked, then we want to make sure to remove the suburb code from the search box
			if( isCheckBoxChecked == 0)
			{
				//Lookup for suburb -- code that we need to remove from the list
				var suburbCode = $('#'+ suburbABSID).attr('title') + " " + $("#"+suburbABSID).val();
				
				//Replace the value text string
				//alert("Actual Text " + actualValueText + " suburbCode " + unescape(suburbCode));
				actualValueText = actualValueText.replace(unescape(suburbCode),"");
				//alert("We are here " + actualValueText);
			}
			
			//Let's check if last character is a comma ,
			/*
			var lastCharIsComma = 0;
			if(actualValueText.indexOf(",")!=-1)
			{
				lastCharIsComma = 1;
			}
			else
			{
				lastCharIsComma = 0;
			}
			*/
			
			//recheck again for first characterSet
			var anotherFirstCharacter = actualValueText.charAt(0);
			
			
			if(anotherFirstCharacter == ",")
			{
				actualValueText = actualValueText.replace(",","");
				actualValueText = $.trim(actualValueText);
			}
			
			if (actualValueText != "") 
			{
				actualValueText += ",";
				//alert(actualValueText);
				//Quick check if the string does not contain duplicate ,,
				actualValueText = actualValueText.replace(", ,",",");
				//alert(actualValueText);
				
				$("#" + fieldNameAutocomplete).val(actualValueText);
			}
			
			
			
			
			$("#" + fieldNameAutocomplete).focus();
			//alert($('#'+ suburbABSID).attr('title') + "--" + $("#"+suburbABSID).val());
	}//End of function if we are not in the admin section
	
	// Function to get word for abbreviation
	function getAbbreviationSuburb(abbr)
	{
		switch (abbr.toLowerCase())
		{
		case 'mt':
		  completeName = 'Mount';
		  break;
		case 'e':
		  completeName = 'East';
		  break;  
		case 'w':
		   completeName = 'West';
		  break;
		case 'n':
		   completeName = 'North';
		  break;  
		case 's':
			completeName = 'South';
		  break;
		case 'h':
			completeName = 'High';
		  break;  
		case 'mid':
		   completeName = 'Middle';
		  break;
		case 'st':
		   completeName = 'Saint';
		  break;  
		case 'lr':
			completeName = 'Lower';
		  break;
		case 'up':
			completeName = 'Upper';
		  break;  
		case 'ctrl':
		   completeName = 'Central';
		  break;
		case 'bsn':
			completeName = 'Basin';
		  break;  
		case 'b':
			completeName = 'Bay';
		  break;
		case 'bch':
			completeName = 'Beach';
		  break;		
		case 'ch':
		   completeName = 'Chase';
		  break;
		case 'ck':
		   completeName = 'Creek';
		  break;  
		case 'csg':
			completeName = 'Crossing';
		  break;
		case 'dn':
			completeName = 'Down';
		  break;  
		case 'frst':
		   completeName = 'Forest';
		  break;
		case 'gdn':
			completeName = 'Gardens';
		  break;  
		case 'gr':
			completeName = 'Grove';
		  break;
		case 'gly':
			completeName = 'Gully';
		  break;  
		case 'hd':
		   completeName = 'Heads';
		  break;
		case 'ht':
		   completeName = 'Heights';
		  break;  
		case 'hl':
			completeName = 'Hill';
		  break;	
		case 'jctn':
		   completeName = 'Junction';
		  break;  
		case 'lgn':
		   completeName = 'Lagoon';
		  break;
		case 'l':
		   completeName = 'Lakes';
		  break;  
		case 'mdw':
			completeName = 'Meadows';
		  break;
		case 'mls':
			completeName = 'Mills';
		  break;  
		case 'pk':
		   completeName = 'Park';
		  break;
		case 'rdg':
		   completeName = 'Ridge';
		  break;  
		case 'rks':
			completeName = 'Rocks';
		  break;
		case 'spri':
			completeName = 'Springs';
		  break;	
		case 'va':
		   completeName = 'Vale';
		  break;
		case 'vy':
		   completeName = 'Valley';
		  break;  
		case 'wts':
			completeName = 'Waters';
		  break;	  		
		default:
			completeName = '';
		 break
		}
		
		return completeName;
	}
	
	function populateBox(fieldNameAutocomplete,postCodeList,isCheckBoxChecked)
	{
			/*
				Building our list of postcode before we display in box
			*/
			
			//Create new array to store our details
			var newArray = new Array();
			//alert("Post Code List " + postCodeList);
			for (i=0;i<postCodeList.length;i++)
			{
				var valueToPush;

				valueToPush = $.trim(postCodeList[i]);
				newArray.push(valueToPush);
			}
			
			//Sort the array
			newArray.sort();
			
			//Reinitialising postcodelist
			var postCodeListFinal = new Array();
			
			//Get length of checkboxes
			sizeCheckBoxes = $('#mainUl > li').size();
			
						
			isChecked = 0;
			if(sizeCheckBoxes == 1)
			{
					//Initially it is unchecked
					$('input:checkbox[name=selector]:checked').each(function() {	
								isChecked = 1;
					});	
			}
			
			//alert(isCheckBoxChecked);
			
			//Removing duplicates
			for (i=0;i<newArray.length;i++)
			{
				var found = 0;
				//While we are here, we check if user has unchecked then we also remove
				
					if(sizeCheckBoxes == 1)
					{
						
						if( isChecked == 0)
							{
								var suburbName = $('#'+ suburbABSID).attr('title') + " " + searchText;
								if(suburbName == newArray[i])
								{
									found = 1;
								}
							}
					}
					else
					{
							
							checkBoxChecked = false;
							$('input:checkbox[name=selector]:checked').each(function() {	
								//Based on id, we can know if the checkbox is actually selected or not
								if( $('#'+ suburbABSID).attr("id") == suburbABSID)
								{
									checkBoxChecked = true;
								}
								else
								{
									checkBoxChecked = false;
								}
								
							});	
							
							
							if( checkBoxChecked == false)
							{
								var subTitle = unescape($('#'+ suburbABSID).attr('title'));
								var suburbName = subTitle + " " + searchText;
								
								if(suburbName == newArray[i])
								{
									found = 1;
								}
							}
					}
				
					
					var testSearc = new Array();
					var loopText = newArray[i].toLowerCase();
					
					loopText = unescape(loopText);
					initialAbbreValue = '';
					
					caseAbbrv = 0;
					
					testSearc = loopText.split(" ");
																				
					for (m=0;m<testSearc.length;m++)
					{
						
						if(testSearc.length > 1)
						{
							loopText = testSearc[0];
							
							textFromAbbFunction = getAbbreviationSuburb(loopText);
							initialAbbreValue = testSearc[0] + " " + testSearc[1];
							if(textFromAbbFunction != '')
							{
								//Get the related abbreviation link
								loopText = getAbbreviationSuburb(loopText) + " " + testSearc[1];
								caseAbbrv = 1;
							}
							else
							{
								loopText = testSearc[0] + " " + testSearc[1];
							}
						}
						
					}
				
					var loopText = newArray[i].toLowerCase();
					
					if(searchedText == loopText || ( caseAbbrv == 1 && loopText == initialAbbreValue) )
					{
						found = 1;
					}
				//Re-Building array
				//if(( newArray[i] != newArray[i-1] && found != 1))
				//alert( newArray[i] + " " + newArray[i-1]);
				if(( unescape(newArray[i]) != unescape(newArray[i-1]) && found != 1))
				{
						postCodeListFinal.push(" " + unescape(newArray[i]));
				}
			}
			
			postCodeList = postCodeListFinal;
			
			//Before we display the result, we should add a space just after the comma	
			$("#" + fieldNameAutocomplete).val(postCodeList);
			//Get latest value and trim left if any
			latestValue = $.trim($("#" + fieldNameAutocomplete).val());
			latestValue = unescape(latestValue);
			//Reassigning value
			$("#" + fieldNameAutocomplete).val(latestValue);
		}	
	
}
