var geocoder;
var map;
var bounds;
var markersArray = [];
var infoWindow;
var address, searchType;
var initialized = 0;
var searchPostcode;
var unsuccessfulMBSearch = false;

function initialize() {
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: 4,
		center: new google.maps.LatLng(-28.1594, 135.6456),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById("mapviewer"), myOptions);
	address = document.getElementById("address");
	searchType = document.getElementById("searchType");
	
	google.maps.event.addListener(map, 'click', function() {
		infoWindow.close();
	});
	
	//initialise single info window to show only one at a time
	infoWindow = new google.maps.InfoWindow();
  //infoWindow.setOptions({maxWidth: 260});
  
  initialized = 1;
}

function addMarkerOverlay(location, title, infoBox, image) {
	var marker = new google.maps.Marker({
	position: location,
	map: map,
	icon: image
	});
	marker.setTitle(title);
	
	google.maps.event.addListener(marker, 'click', function() {
		 infoWindow.setContent(infoBox);
		 infoWindow.open(map, marker);
	});
	
	markersArray.push(marker);
}
 
function deleteAllMarkers() {
	if (markersArray) {
		for (i in markersArray) {
			markersArray[i].setMap(null);
		}
		markersArray.length = 0;
	}
}

function searchAroundMe() {
	deleteAllMarkers();
	
	if (address.value == "") {
		searchAgain(); 
	}
	
	bounds = new google.maps.LatLngBounds();
	
	geocoder.geocode( { 'address': address.value+',AU'}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var searchLatitude = results[0].geometry.location.lat();
			var searchLongitude = results[0].geometry.location.lng();
			
			if (searchType.value == 'mobile') {
				searchPostcode = address.value.match(/\d{4}/)[0];
				//for (var i = 0; i < results[0].address_components.length; i++) {
				//	if (results[0].address_components[i].types[0] == "postal_code") {
				//		searchPostcode = results[0].address_components[i].short_name;
				//	}
				//}
			}
			
			//custom marker to mark initial search location
			var image = new google.maps.MarkerImage('../Map_Assets/CUA/images/search_location.png',
				// This marker is 32 pixels wide by 32 pixels tall.
				new google.maps.Size(32, 32),
				// The origin for this image is 0,0.
				new google.maps.Point(0,0),
				// The anchor for this image is the center of the red circle at 16,16.
				new google.maps.Point(16, 16)
			);
			
			addMarkerOverlay(results[0].geometry.location, 'search spot', 'search initiated from here', image);
			bounds.extend(results[0].geometry.location);
			
			freeHound = new FreeHound( 'showLocs' );
			search = new FH_Search(); 
			
			if (searchType.value == 'branch') {
				search.count = 10; //number of locations to be returned in the result set
				search.filters = new Array();
				search.filters.push( new FH_SearchFilter('cat_id', 'eq', '37') );
			} else if (searchType.value == 'mobile') {
				search.count = 10; //number of locations to be returned in the result set
				search.filters = new Array();
				search.filters.push( new FH_SearchFilter('cat_id', 'eq', '38') );
				search.logic = new Array();
				search.logic.push('AND');
				search.filters.push( new FH_SearchFilter('custom_value_2', 'like', searchPostcode) );
			} else {
				search.count = 50; //number of locations to be returned in the result set
				search.filters = new Array();
				search.filters.push( new FH_SearchFilter('cat_id', 'eq', '224') );
				search.filters.push( new FH_SearchFilter('extra', 'eq', 'rediatm') );
			}
			
			search.max_distance = 0; //distance limit for proximity search in km, 0 for unlimited
			//search from a specific point using latitude and longitude of that point
			search.point = new FH_Location( new FH_LatLon( searchLatitude,searchLongitude ) );

			search.create_log = true;
			freeHound.proximitySearch( search );
		} else {
			if (status == 'ZERO_RESULTS') {
				alert("Sorry, your search location could not be found. Please check and try again.");
			} else {
				alert("Geocode was not successful for the following reason: " + status);
			}
		}
	});
}

function showLocs(response) {
	if ( response.error_code ) {
		if (searchType.value == 'mobile') {
			searchType.options[1].selected = true;
			unsuccessfulMBSearch = true;
			validateForm();
		} else {
			document.getElementById('resultSet').innerHTML = '';
			alert('Sorry, there are no locations within 100km of your address.');
		}
	}
	
	if ( response.record_set ) {
		if (searchType.value == 'mobile') {
			document.getElementById('message').innerHTML = 'Your Mobile Banker for postcode '+searchPostcode+' is:';
			
			for (var record_count = 0, rl = response.record_set.length; record_count < rl; record_count++ ) {
				var record = response.record_set[record_count];
				
				var resultsTable = '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="shadeGradient" summary="">';
				resultsTable += '<tr><td class="field">';
				if (record.custom_info.custom_value_3 != '') {
					resultsTable += '<img src="../../docs/userFileUploads/files_186/'+record.custom_info.custom_value_3+'" alt="'+record.details.contact_name+'" style="float:left;margin:10px 20px 10px 10px;" />';
				}
				resultsTable += '<div style="float:left;margin: 10px 0;width: 390px;">';
				resultsTable += '<h2 style="margin:0;">'+record.details.contact_name+'</h2>';
				if (record.custom_info.custom_value_4 != '') {
					resultsTable += '<p>'+record.custom_info.custom_value_4+'</p>';
				}
				if (record.details.phone != '') {
					resultsTable += '<p>Phone: '+record.details.phone+'</p>';
				}
				resultsTable += '</div>';
				resultsTable += '<div style="margin:10px 0;clear:both;">';
				if (record.details.contact_email != '') {
					resultsTable += '<a href="mailto:'+record.details.contact_email+'"><img src="../Map_Assets/CUA/images/btn-email.png" border="0"></a>&nbsp;&nbsp;&nbsp;';
				}
				resultsTable += '<a href="#" onclick="smsDetails(\'id'+record.loc_id+'\', \'3\'); return false;" title="send to my mobile"><img src="../Map_Assets/CUA/images/btn-sms.png" border="0"></a>';
				resultsTable += '</div>';
				resultsTable += '</td></tr>';
				resultsTable += '<\/table>';
			}
			
			var resultSet = document.getElementById('resultSet');
			resultSet.innerHTML = resultsTable;
		} else {
			//show results in a table
			var resultsTable = '<table width="100%" border="0" cellspacing="0" cellpadding="0" class="shadeGradient2" summary="">';
			resultsTable += '<tr>';
			resultsTable += '<th class="topLeft">&nbsp;</th>';
			if (searchType.value == 'branch') {
				resultsTable += '<th>Branch&nbsp;Manager</th>';
			}
			resultsTable += '<th>Address</th>';
			if (searchType.value == 'branch') {
				resultsTable += '<th>Phone</th>';
			}
			if (searchType.value == 'atm') {
				resultsTable += '<th>Access Hours</th>';
			}
			resultsTable += '<th>Distance</th>';
			resultsTable += '<th class="topRight">Send</th>';
			resultsTable += '<\/tr>';
			
			if (unsuccessfulMBSearch == true) {
				unsuccessfulMBSearch = false;
				document.getElementById('message').innerHTML = "Unfortunately there isn't a mobile banker in your area, but we have located your nearest branches:";
			} else {
				unsuccessfulMBSearch = false;
				document.getElementById('message').innerHTML = "Here are the top "+response.record_set.length+" closest locations to your address:";
			}
			
			var z = 1;
			for (var record_count = 0, rl = response.record_set.length; record_count < rl; record_count++ ) {
				var record = response.record_set[record_count];
	
				//add info box for each marker
				if (searchType.value == 'branch') {
					var title = 'Branch';
					var infoBoxContent = '<h2>Branch<\/h2>';
				} else {
					if (record.custom_info.custom_value_11 == 'Yes') {
						var title = 'Restricted Access rediATM';
						var infoBoxContent = '<h2>Restricted Access rediATM<\/h2>';
					} else {
						var title = 'rediATM';
						var infoBoxContent = '<h2>rediATM<\/h2>';
					}
				}
				
				infoBoxContent += '<p>';
				if (record.address.shop_unit) {
					infoBoxContent += record.address.shop_unit+'<br \/>';
				}
				infoBoxContent += record.address.street_address+'<br \/>'+record.address.town+' '+record.address.state+' '+record.address.postal_code;
				if (searchType.value == 'atm' && record.custom_info.custom_value_6 != '') {
					infoBoxContent += '<br />'+record.custom_info.custom_value_6;
				}
				if (record.details.phone != '') {
					infoBoxContent += '<br \/>Ph: '+formatPhoneNumber(record.details.phone);
				}
				infoBoxContent += '<\/p>';
				infoBoxContent += '<p class="dist">';
				if (record.distance.km >= 1) {
					infoBoxContent += 'Distance: '+record.distance.km+'km';
				} else {
					infoBoxContent += 'Distance: '+(record.distance.km*1000)+'m';
				}
				infoBoxContent += '<\/p>';
				infoBoxContent += '<a href="#" onclick="smsDetails(\'id'+record.loc_id+'\', \'\'); return false;" title="send to my mobile">Send to my mobile<\/a>';
				
				//custom markers
				if (searchType.value == 'branch') {
					var image = new google.maps.MarkerImage('../Map_Assets/CUA/images/CUA_Branch.png',
						// This marker is 46 pixels wide by 66 pixels tall.
						new google.maps.Size(34, 40),
						// The origin for this image is 0,0.
						new google.maps.Point(0,0),
						// The anchor for this image is the center bottom
						new google.maps.Point(17, 40)
					);
				} else {
					if (record.custom_info.custom_value_11 == 'Yes') {
						var image = new google.maps.MarkerImage('../Map_Assets/CUA/images/iconLock.png',
							// This marker is 46 pixels wide by 66 pixels tall.
							new google.maps.Size(19, 42),
							// The origin for this image is 0,0.
							new google.maps.Point(0,0),
							// The anchor for this image is the center bottom
							new google.maps.Point(9, 42)
						);
					} else {
						var image = new google.maps.MarkerImage('../Map_Assets/CUA/images/iconRedi.png',
							// This marker is 46 pixels wide by 66 pixels tall.
							new google.maps.Size(19, 42),
							// The origin for this image is 0,0.
							new google.maps.Point(0,0),
							// The anchor for this image is the center bottom
							new google.maps.Point(10, 42)
						);
					}
				}
				
				addMarkerOverlay(new google.maps.LatLng(record.latitude, record.longitude), title, infoBoxContent, image);
				
				if (record_count < 2) {
					bounds.extend(new google.maps.LatLng(record.latitude, record.longitude));
				}
				
				if (z < 11) {
					if (searchType.value == 'branch') {
						resultsTable += '<tr id="resultRow'+record.loc_id+'" class="rowNormal" onmouseover="highlightRow(\''+record.loc_id+'\');" onmouseout="removeHighlight(\''+record.loc_id+'\');" onclick="openInfo(\''+record.loc_id+'\', \''+searchType.value+'\');map.setCenter(new google.maps.LatLng('+record.latitude+', '+record.longitude+')); map.setZoom(17); google.maps.event.trigger(markersArray['+z+'], \'click\');">';
					} else {
						resultsTable += '<tr id="resultRow'+record.loc_id+'" class="rowNormal" onmouseover="highlightRow(\''+record.loc_id+'\');" onmouseout="removeHighlight(\''+record.loc_id+'\');" onclick="map.setCenter(new google.maps.LatLng('+record.latitude+', '+record.longitude+')); map.setZoom(17); google.maps.event.trigger(markersArray['+z+'], \'click\');">';
					}
					
					resultsTable += '<td class="highlightArrow">&nbsp;</td>';
					if (searchType.value == 'branch') {
						resultsTable += '<td class="branchManager">'+record.details.contact_name+'</td>';
					}
					resultsTable += '<td class="mapLinkCell">';
					resultsTable += '<a href="#" onclick="map.setCenter(new google.maps.LatLng('+record.latitude+', '+record.longitude+')); map.setZoom(17); google.maps.event.trigger(markersArray['+z+'], \'click\'); scroll(0,0); return false;">';
					resultsTable += record.address.street_address+', '+record.address.town+' '+record.address.postal_code;
					resultsTable += '</a>';
					if (searchType.value == 'atm' && record.custom_info.custom_value_6 != '') {
						resultsTable += '<br />'+record.custom_info.custom_value_6;
					}
					if (searchType.value == 'branch') {
						//if (record.custom_info.custom_value_1 != '') {
						//	resultsTable += '<br />'+record.custom_info.custom_value_1;
						//}
						if (record.opening_hours.abbr_opening_hours != '') {
							resultsTable += '<div id="link'+record.loc_id+'" style="color:#7D4369;font-family:Arial;font-size:10px;font-weight:bold;margin-top:8px;">show opening hours, etc</div>';
							resultsTable += '<div id="resultRowExtra'+record.loc_id+'" class="openingHours">';
							resultsTable += '<strong>Opening Hours</strong><br />';
							resultsTable += record.opening_hours.abbr_opening_hours;
							resultsTable += '</div>';
						}
					}
					if (searchType.value == 'atm') {
						if (record.custom_info.custom_value_5 == 'NAB') {
							resultsTable += '<div>this ATM is operated by NAB</div>';
						} else if (record.custom_info.custom_value_5 == 'BOQ') {
							resultsTable += '<div>this ATM is operated by Bank of Queensland</div>';
						} else {
							resultsTable += '<div>this ATM is operated by rediATM</div>';
						}
					}
					resultsTable += '</td>';
					if (searchType.value == 'branch') {
						resultsTable += '<td class="phone">'+formatPhoneNumber(record.details.phone)+'</td>';
					}
					if (searchType.value == 'atm') {
						resultsTable += '<td>';
						if (record.opening_hours.abbr_opening_hours != '') {
							resultsTable += record.opening_hours.abbr_opening_hours.replace(/; /gi,";<br />");
						}
						resultsTable += '</td>';
					}
					resultsTable += '<td>';
					if (record.distance.km > 1) {
						resultsTable += record.distance.km+"km";
					} else {
						resultsTable += (record.distance.km*1000)+"m";
					}
					resultsTable += '<\/td>';
					resultsTable += '<td class="send"><a href="#" onclick="smsDetails(\'id'+record.loc_id+'\', \'\'); return false;" title="send to my mobile"><img src="http://www.ehoundplatform.com/images/icon-mobile-1.png" style="border: none;" alt="send these details to your mobile" /></a></td>';
					resultsTable += '<\/tr>';
				}
				
				z++;
			}
			
			map.fitBounds(bounds);
			
			resultsTable += '<\/table>';
	
			var resultSet = document.getElementById('resultSet');
			resultSet.innerHTML = resultsTable;
		}
	}
	
	iframeResizePipe();
}


function formatPhoneNumber(text) {
	if (text != '' && text != null) {
		text = text.replace(" ", "");
		var tmpText = "";
		if (text.length == 10) {
			tmpText += "("+text.substr(0, 2)+")";
			tmpText += " ";
			tmpText += text.substr(2, 4);
			tmpText += " ";
			tmpText += text.substr(6, 4);
			return tmpText;
		} else {
			return text;
		}
	} else {
		return text;
	}
}

function highlightRow(rowID) {
	if (document.getElementById('resultRow'+rowID).className != 'rowHighlightStay') {
		document.getElementById('resultRow'+rowID).className = 'rowHighlight';
	}
}

function removeHighlight(rowID) {
	if (document.getElementById('resultRow'+rowID).className != 'rowHighlightStay') {
		document.getElementById('resultRow'+rowID).className = 'rowNormal';
	}
}

function openInfo(rowID, type) {
	if (document.getElementById('resultRowExtra'+rowID).className == 'openingHoursOpen') {
		document.getElementById('resultRowExtra'+rowID).className = 'openingHours';
		if (type == 'branch') {
			document.getElementById('link'+rowID).innerHTML = 'show opening hours, etc';
		} else {
			document.getElementById('link'+rowID).innerHTML = 'show more info';
		}
		document.getElementById('resultRow'+rowID).className = 'rowNormal';
	} else {
		document.getElementById('resultRowExtra'+rowID).className = 'openingHoursOpen';
		if (type == 'branch') {
			document.getElementById('link'+rowID).innerHTML = 'hide opening hours, etc';
		} else {
			document.getElementById('link'+rowID).innerHTML = 'hide more info';
		}
		document.getElementById('resultRow'+rowID).className = 'rowHighlightStay';
	}
	
	iframeResizePipe();
}

function setValue(id, value) {
	if (document.getElementById(id).value == value) {
		document.getElementById(id).value = '';
	}
}
function unsetValue(id, value) {
	if (document.getElementById(id).value == '') {
		document.getElementById(id).value = value;
	}
}

function smsDetails(locationID, category) {
	document.getElementById('locationID').value = locationID;
	document.getElementById('category').value = category;
	document.getElementById('innerContent').style.display = 'block';
	document.getElementById('success').style.display = 'none';
	popup('popUpContainer');
}

function validateNumber(formData, jqForm, options) {
	mobileNumber = formData[0]['value'];
	mobileNumber = mobileNumber.split(' ').join('');
	if (isNaN(mobileNumber) || mobileNumber.length!=10 || mobileNumber.substr(0,2)!='04'){ 
	document.getElementById('errorMessage').innerHTML = 'Invalid mobile number';
	return false;
	} else {
	document.getElementById('errorMessage').innerHTML = '';
	}
}

function showResponse(responseText)  {
	document.getElementById('successMessage').innerHTML = '<p>'+responseText.msg+'<\/p>';
	document.getElementById('innerContent').style.display = 'none';
	document.getElementById('success').style.display = 'block';
}

$(function() {
	$( "#address" ).autocomplete({
		source: "/ajax/suburbLookup.php",
		minLength: 3,
		autoFocus: true
	});
});

//load sms sending code
$(document).ready(function() { 
	var options = { 
		beforeSubmit: validateNumber,
		url: '/ajax/sendSMS.php',
		dataType: 'jsonp',
		crossDomain: true,
		success: showResponse
	};
	
	$('#smsForm').ajaxForm(options); 
});


jQuery(document).ready(function() {
    jQuery("#searchType").select_skin();
    jQuery("#state2").select_skin();
});

function validateForm() {
	var address = document.getElementById('address');
	var searchType = document.getElementById('searchType');
	
	if (address.value.length < 3 || address.value == "Address") {
		alert("Please enter suburb or postcode or street address.");
		address.focus();
		return false;
	}
	
	if (searchType.value == 'mobile' && address.value.match(/\d{4}/) == null) {
		alert("For mobile banker search please specify a postcode.");
		address.focus();
		return false;
	}
	
	var charpos = address.value.search("[^A-Za-z0-9 ]-"); 
	if(charpos >= 0) { 
		alert("Please use alphabetic or numeric characters only."); 
		address.focus();
		return false; 
	}
	
	if (initialized == 0) {
		initialize();
	}
	
	if (searchType.value == 'mobile') {
		//document.getElementById("mapviewer").style.display = 'none';
		document.getElementById("mapviewer").style.position = 'absolute';
    document.getElementById("mapviewer").style.left = '-4000px';
	} else {
		//document.getElementById("mapviewer").style.display = 'block';
		document.getElementById("mapviewer").style.position = 'relative';
    document.getElementById("mapviewer").style.left = '0px';
	}
	
	searchAroundMe();
	
	document.getElementById("cuaFindUs").style.display = 'none';
	document.getElementById("cuaResults").style.display = 'block';
	
	return false;
}

function validateStateForm() {
	var state = document.getElementById('state2');
	
	if(state.value == "") {
		alert("Please select a State.");
		state.focus();
		return false;
	}
	
	return true;
}

function searchAgain() {
	document.getElementById("cuaFindUs").style.display = 'block';
	document.getElementById("cuaResults").style.display = 'none';
	document.getElementById('resultSet').innerHTML = '';
	document.getElementById("address").value = '';
	document.getElementById("address").focus();
	document.getElementById('message').innerHTML = '';
}

function iframeResizePipe() { 
   var height = document.body.scrollHeight; 
   var helpframe = document.createElement('iframe'); 
   helpframe.id = 'helpframe'; 
   helpframe.src = 'http://www.cua.com.au/design/helpers-that-require-a-url/iframe-helper?height=' + height + '&cacheb=' + Math.random(); 
   helpframe.height = '0'; 
   helpframe.width = '0'; 
   helpframe.frameborder = '0'; 
   document.body.appendChild(helpframe); 
}
