// JavaScript Document

var surrounding;
var markerList = [];

function initialize() {
	geocoder = new google.maps.Geocoder();
	
	var myOptions = {
		zoom: 10,
		center: new google.maps.LatLng(-33.9, 151.2),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		navigationControl: true,
		mapTypeControl: false,
		scaleControl: true
	};

	map = new google.maps.Map(document.getElementById("map"),myOptions);
	
	setMarkers(map, beaches);

}

function codeAddress() {
	if(currentMarker)
		currentMarker.setMap(null);
	
	var address = document.getElementById("input-postcode").value;
	 getSurrounding(beaches, address);
	/**
	if (geocoder) {
	  geocoder.geocode( { 'address': address+" Australia", 'region':'AU'}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
		  map.setCenter(results[0].geometry.location);
		  //map.setZoom(zoom);
		  currentMarker = new google.maps.Marker({
			  map: map, 
			  position: results[0].geometry.location
			  
		  });
		  
		 
		  
		} else {
		  alert("Geocode was not successful for the following reason: " + status);
		}
		
		
		
		
	  });
	}
	//**/
}

function distanceCalculate (lat1,lon1,lat2,lon2) { 
	//var R = 6371; // km (change this constant to get miles) 
	//var R = 6371000; // meters 
	var R = 6371; // km 
	//var lat1 = this.lat(); 
//	var lon1 = this.lng(); 
//	var lat2 = newLatLng.lat(); 
//	var lon2 = newLatLng.lng(); 
	
	var dLat = (parseFloat(lat2)-parseFloat(lat1)) * Math.PI / 180;
//	console.log(dLat);
	var dLon = (parseFloat(lon2)-parseFloat(lon1)) * Math.PI / 180; 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) 	* Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c; 
	return d; 
}


function getSurrounding(locations, postcode, zoom)
{
	/**
	var undefined;
	if(zoom == undefined) {
        zoom = 14;
    }
	
	var aZoomRatios = [591657527.591555,295828763.795777,147914381.897889,73957190.948944,36978595.474472,18489297.737236,9244648.868618,4622324.434309,2311162.217155,1155581.108577,577790.554289,288895.277144,144447.638572,72223.819286,36111.909643,18055.954822,9027.977411,4513.988705,2256.994353,1128.497176];
	var dist = 1.6; // starting distance
	
	if(zoom<14){
		ratio = (aZoomRatios[zoom]/aZoomRatios[14]);
		//alert(ratio);
		dist = ratio*dist;
		//alert(dist+"km");
	}
	
	
	
	var loc = locations;
	if(typeof(postcode) != 'undefined')
	{
		if(postcode == 4350)
		{
			console.log('hello');
			geocoder.geocode( { 'address': "254 South Street Toowoomba Australia", 'region':'AU'}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
			  map.setCenter(results[0].geometry.location);
			  map.setZoom(zoom);
			} 
		})
		}
		else if (geocoder) {
	  		geocoder.geocode( { 'address': postcode+" Australia", 'region':'AU'}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
			  map.setCenter(results[0].geometry.location);
			  map.setZoom(zoom);
			} 
	  });
	}
	}
	var mergedArray = [];
	for(i = 0; i < locations.length; i++)
	{
		var currentDistance = distanceCalculate(parseFloat(locations[i][1]), parseFloat(locations[i][2]), parseFloat(map.getCenter().lat()), parseFloat(map.getCenter().lng()));
		if(currentDistance < dist){
			locations[i].push(currentDistance);
			mergedArray.push(locations[i]);
		}
	}
	
	for(i=0;i<mergedArray.length;i++){
		if(parseFloat(mergedArray[i][9]) > 0){
			//alert(mergedArray[i][9]);
			if(zoom != parseFloat(mergedArray[i][9])){
				getSurrounding(loc, postcode, mergedArray[i][9]);
			}
		}
	}**/
	
	var undefined;
	var firstAddress;
	var centerLat;
	var centerLng;
	var storedZoom;
	var mergedArray = [];
	
	
	for(i = 0; i < locations.length; i++)
	{
		
		
		
		if(locations[i][5] == postcode)
		{
			if(centerLat == undefined)
			{
				centerLat = parseFloat(locations[i][1]);
				centerLng = parseFloat(locations[i][2]);
				firstAddress = locations[i][4]+" "+locations[i][7];
				storeZoom = locations[i][9];
				if(storeZoom == 0)
					storeZoom = 14;
			}
			
			if(postcode == 4000)
			{
				firstAddress = "4000 qld";
				
			}
			
			if(postcode == 4878)
			{
				firstAddress = "varley st 4878 qld";
				storeZoom = 12;
				
			}
			
			var currentDistance = distanceCalculate(parseFloat(locations[i][1]), parseFloat(locations[i][2]), centerLat, centerLng);
			locations[i].push(currentDistance);
			mergedArray.push(locations[i]);
		}
	}
	
	/**
	if(mergedArray.length == 0){
		zoom = zoom-1;
		if(zoom > 5){
			//alert(zoom);
			return getSurrounding(loc, postcode, zoom);
		}
		
		mergedArray = [['No Locations', -33.9, 151.2, 1, '', '', '', '', '', 0]];
	}
	else{
		
	//	alert(zoom);
		map.setZoom(zoom);
	}
	
	**/
	//console.log(storeZoom);
	if(mergedArray.length == 0){
		mergedArray = [['No Locations', -33.9, 151.2, 1, '', '', '', '', '', 0]];
		firstAddress = postcode;
	}
	
	geocoder.geocode( { 'address': firstAddress+" Australia", 'region':'AU'}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
		  map.setCenter(results[0].geometry.location);
		  map.setZoom(storeZoom);
		  /**currentMarker = new google.maps.Marker({
			  map: map, 
			  position: results[0].geometry.location
			  
		  });**/
		}
	});
	
	
	$('#map-form-name').hide('fast');
	$('#map-form-venus').hide('fast');
	$('#map-form-list').show('slow');
	var formListContent = "";
	for(lk = 0; lk < mergedArray.length;lk++)
	{
		var url = "";
		if(mergedArray[lk][8].search('http') == -1 && mergedArray[lk][8].search('www') != -1)
		{
			url = 'http://'+mergedArray[lk][8];
			if(mergedArray[lk][8] == 'none' || mergedArray[lk][8] == undefined)
				url = '';
			if(mergedArray[lk][8].search("@") != -1) 
				url	= 'mailto:'+mergedArray[lk][8];
		}
		var setContent = "<p class=\"bubble-header\">"+mergedArray[lk][0].replace('\'', ' ')+"</p><p class=\"bubble-address\">"+mergedArray[lk][4]+"<br />"+mergedArray[lk][7]+", "+mergedArray[lk][5]+"<br />"+mergedArray[lk][6]+" <br /><br /><a href=\""+url+"\" target=\"_blank\">"+url+"</a></p>";
		
		formListContent += "<li long='"+mergedArray[lk][2]+"' lat='"+mergedArray[lk][1]+"' id='l_"+lk+"' bubble='"+setContent+"'><span><strong>"+mergedArray[lk][0]+"</strong></span><br />"+mergedArray[lk][4]+" "+mergedArray[lk][7]+"<br />";
		if(mergedArray[lk][10] != '' && mergedArray[lk][0] != "No Locations")
			formListContent += Math.ceil(mergedArray[lk][10])+"km away";
		
		formListContent += "</li>";
	}
	$('#map-form-list ul').empty().append(formListContent).evtpaginate({perPage:3});
	$('#map-form-list #next').hide();	
	if(mergedArray.length > 3)
	{
		$('#map-form-list #next').show();	
	}
	
	
	
	return mergedArray;
}

function findLocation(locations, name, zoom)
{
	if(typeof(zoom) == 'undefined') {
        var zoom = 14;
    }
	
	loc = locations;
	var mergedArray = [];
	var counter = 0;
	for(i = 0; i < locations.length; i++)
	{
		var stringFound = locations[i][0].toLowerCase().indexOf(name.toLowerCase().replace("'", '&#39;'));
		var currentDitance;
		if(stringFound >= 0)
		{
			if(counter == 0)
			{
				var clicked = new google.maps.LatLng(parseFloat(locations[i][1]), parseFloat(locations[i][2]));
				map.setZoom(zoom);
				map.setCenter(clicked);
			}
			currentDistance = distanceCalculate(parseFloat(locations[i][1]), parseFloat(locations[i][2]), parseFloat(map.getCenter().lat()), parseFloat(map.getCenter().lng()));
			locations[i].push(currentDistance);

			mergedArray.push(locations[i]);
			counter++;
		}
	}
	if(mergedArray.length == 0){
		//zoom = zoom-1;
		//return findLocation(loc, name, zoom);
		mergedArray = [['No Locations', -33.9, 151.2, 1, '', '', '', '', '', 0]];
	}
	/**
	else{
		// hack the zoom level
		if(parseFloat(locations[i][9]) > 0){
			zoom = parseFloat(locations[i][9]);
		}
		//alert('a'+zoom);
		map.setZoom(zoom);
	} // **/
	
	$('#map-form-postcode').hide('fast');
	$('#map-form-venus').hide('fast');
	$('#map-form-list').show('slow');
	var formListContent = "";
	for(lk = 0; lk < mergedArray.length;lk++)
	{
		var url = "";
		if(mergedArray[lk][8].search('http') == -1 && mergedArray[lk][8].search('www') != -1)
		{
			url = 'http://'+mergedArray[lk][8];
			if(mergedArray[lk][8] == 'none' || mergedArray[lk][8] == undefined)
				url = '';
			if(mergedArray[lk][8].search("@") != -1) 
				url	= 'mailto:'+mergedArray[lk][8];
		}
		var setContent = "<p class=\"bubble-header\">"+mergedArray[lk][0].replace('\'', ' ').replace('\\\'',' ')+"</p><p class=\"bubble-address\">"+mergedArray[lk][4]+"<br />"+mergedArray[lk][7]+", "+mergedArray[lk][5]+"<br />"+mergedArray[lk][6]+" <br /><br /><a href=\""+url+"\" target=\"_blank\">"+url+"</a></p>";
		
		formListContent += "<li long='"+mergedArray[lk][2]+"' lat='"+mergedArray[lk][1]+"' id='l_"+lk+"' bubble='"+setContent+"'><span><strong>"+mergedArray[lk][0]+"</strong></span><br />"+mergedArray[lk][4]+" "+mergedArray[lk][7]+"<br />";
		if(mergedArray[lk][10] != '' && mergedArray[lk][0] != "No Locations")
			formListContent += Math.ceil(mergedArray[lk][10])+"km away";
		
		formListContent += "</li>";
	}
	$('#map-form-list ul').empty().append(formListContent).evtpaginate({perPage:3});
	$('#map-form-list #next').hide();
	if(mergedArray.length > 3)
	{
		$('#map-form-list #next').show();	
	}
	
	
	
	return mergedArray;
}

function clearOverlays() {
  if (markerList) {
    for (i in markerList) {
      markerList[i].close(null);
    }
	markerList.length = 0;

  }
}



$(document).ready(function() {

	$('.dob-day, .dob-month, .dob-year').focus(function() {
		$(this).attr('value', '');												
	});
	$('.dob-day, .dob-month, .dob-year').autotab_magic().autotab_filter('numeric');

	var curpage;
	var maxpage;
	
	$('#leaderboard-content-restaurant').jScrollPane({showArrows:true, scrollbarWidth: 13});
	$('#leaderboard-content-pubs').jScrollPane({showArrows:true, scrollbarWidth: 13});
	$('#leaderboard-content-clubs').jScrollPane({showArrows:true, scrollbarWidth: 13});
	$('#battle-highlights-content').jScrollPane({showArrows:true, scrollbarWidth: 13});
	$('.scrolley').jScrollPane({showArrows:true, scrollbarWidth: 13,animateTo:true, animateInterval:50, animateStep:5, dragMinHeight:60});
	$('#venue-anchor li a').bind('click', function()
					{
						
						$this = $(this);
						var destinationSelector = $(this).attr('rel');
						$('.scrolley', $this.parent().parent().parent()).each(
							function()
							{
								this.scrollTo(destinationSelector);
							}
						);
						return false;
					}
	);

	//$('#pane1').jScrollPane();
	
	$('#input-postcode').keypress( function(e) {
		if(e.keyCode == 13) {
			e.preventDefault();
			codeAddress();
	    }						
	});
	
	$('#input-postcode-home').keypress( function(e) {
		
		if(e.keyCode == 13) {
			e.preventDefault();
			window.location = '?venue-locator&postcode='+$(this).val();
	    }						
	});
	
	$('#age-form input-postcode-home').keypress( function(e) {
		
		if(e.keyCode == 13) {
			e.preventDefault();
			$('#age-form').submit();
	    }						
	});
	
	$('#psuedo-botton').click( function() {
		$(this).attr('href', '?venue-locator&postcode='+$('#input-postcode-home').val());
	});
	
	$('#input-postcode-home').change(function() {
		$('#psuedo-botton').attr('href', '?venue-locator&postcode='+$(this).val());				  
	});
	
	$('#psuedo-botton').attr('href', '?venue-locator&postcode='+$('#input-postcode-home').val());
	
	$('#input-location-name').keypress( function(e) {
		if(e.keyCode == 13) {
			e.preventDefault();
			findLocation(beaches, $('#input-location-name').val());
	    }						
	});
	
	
	
	$('#map-form-list #next').bind('click', function() {
		$('#map-form-list ul').trigger('next.evtpaginate');
		$('#map-form-list #prev').show();
		$(this).show();
		if(curpage == maxpage)
		{
			$(this).hide();	
		}
	});
	
	$('#map-form-list #prev').bind('click', function() {
		$('#map-form-list ul').trigger('prev.evtpaginate');
		$('#map-form-list #next').show();
		$(this).show();
		if(curpage == 1)
		{
			$(this).hide();	
		}
	});
	
	$('#map-form-list').bind( 'initialized.evtpaginate', function(e, startnum, totalnum ){
		maxpage = totalnum;
	});
	
	$('#map-form-list').bind( 'finished.evtpaginate', function(e, num, isFirst, isLast ){ 
		curpage = num;
	}); 

	
	$("#button-location-name").click(function() {
		findLocation(beaches, $('#input-location-name').val());
	});
	
	$('#button-postcode-nosubmit').click(function() {
		codeAddress();
	});
	
	$('#button-postcode').click(function() {
		window.location = 'http://www.google.com';
	
	});
	
	
	$('#map-form-list ul li').live('click', function() {
		var clicked = new google.maps.LatLng($(this).attr('lat'), $(this).attr('long'));
		map.panTo(clicked);
		map.setZoom(15);
		var setContent = $(this).attr('bubble');
		
		var image = new google.maps.MarkerImage('images/icon.png',
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(36, 56),
		// The origin for this image is 0,0.
		new google.maps.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(7, 54));
		var shape = {
		  coord: [1, 1, 1, 15, 55, 15, 1 , 53],
		  type: 'poly'
		};
		
		var infowindow = new google.maps.InfoWindow({
    	    content: setContent
	    });
		clearOverlays();
		
			
		var marker = new google.maps.Marker({
			position: clicked,
			map: map,
			icon: image
		});
		
		infowindow.open(map,marker);
		markerList.push(infowindow);
		//GEvent.trigger(marker, 'click');

		//var openMe = $(this).children('strong').text();
		//$("area[title='"+openMe+"']").parent().parent().children("img").click();
		//GEvent.trigger(marker, 'click');
		//alert($("area[title='"+openMe+"']").parent().parent().children("img").attr("usemap"));
	 });
	
	
	
	$("#contact-us-form").validate({			   
		errorContainer: $("div.errorDiv"),
		errorLabelContainer:  $("div.errorDiv"),
		wrapper: 'li',
		meta: "validate",
		errorPlacement: function(error, element) {
				error.appendTo( element.parent("li").next("a") );
		},
		rules: {
			
			first_name: "required",
			last_name: "required",
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			first_name: "Please enter your first name",
			last_name: "Please enter your last name",
			email: "Please enter a valid email address",
			comment: "An enquiry comment is required",
			phone: "Please enter a valid phone number"
		}
		
	});
	
	
	$('#leaderboard-links li a').click(function() {
		$('#leaderboard-links li a').removeClass('active');
		$(this).addClass('active');
		$('.leader-hider').hide();
		var type = $(this).attr('title');
		$('#default-'+type.toLowerCase()).show();
	});
	
		$('input').focus(function() {
			$(this).css('color', '#971b2c');				  
		});
		
		$('li#navigation-comp-details').hover(
			
			function() { $('#comp-dropdown').css('display', 'block'); },
			function() { $('#comp-dropdown').css('display', 'none'); }
		);
		
		
		$('#comp-dropdown').hover(
			function() { $('#navigation-comp-details-a').addClass('dropdown'); },
			function() { $('#navigation-comp-details-a').removeClass('dropdown'); }
		);
		
		
		$(".front-button a img").hover(function() {
			$(this).attr("src","images/button-find-out-how-ovr.png");
				}, function() {
			$(this).attr("src","images/button-find-out-how.png");
		});
		
		$(".button a.howitworks").hover(function() {
		$(this).attr("src","images/btn-howitworks-ovr.png");
			}, function() {
		$(this).attr("src","images/btn-howitworks.png");
		});
		
		$('#map-form-venus a img').hover(function() {
		$(this).attr("src","images/btn-venues-ovr.png");
			}, function() {
		$(this).attr("src","images/btn-venues.png");
		});
		
		$('#our-wine-button a img').hover(function() {
		$(this).attr("src","images/btn-visit-ovr.png");
			}, function() {
		$(this).attr("src","images/btn-visit.png");
		});
		
		$('#psuedo-botton img').hover(function() {
		$(this).attr("src","images/button-postcode-ovr.png");
			}, function() {
		$(this).attr("src","images/button-postcode.png");
		});
		
		$('#button-postcode-nosubmit').hover(function() {
		$(this).css("background-image","url(images/button-postcode-ovr.png)");
			}, function() {
		$(this).css("background-image","url(images/button-postcode.png)");
		});
		
		$('#button-location-name').hover(function() {
		$(this).css("background-image","url(images/button-postcode-ovr.png)");
			}, function() {
		$(this).css("background-image","url(images/button-postcode.png)");
		});
		
		$('.button a.rankingsystem').hover(function() {
		$(this).css("background-image","url(images/btn-ranking-ovr.png)");
			}, function() {
		$(this).css("background-image","url(images/btn-ranking.png)");
		});
		
		$('#span-postcode-button input').hover(function() {
		$(this).attr("src","images/button-postcode-ovr.png");
			}, function() {
		$(this).attr("src","images/button-postcode.png");
		});
		
		$('.button a.viewprizes').hover(function() {
		$(this).css("background-image","url(images/btn-view-prizes-ovr.png)");
			}, function() {
		$(this).css("background-image","url(images/btn-view-prizes.png)");
		});
		
		$('.button a.howitworks').hover(function() {
		$(this).css("background-image","url(images/btn-howitworks-ovr.png)");
			}, function() {
		$(this).css("background-image","url(images/btn-howitworks.png)");
		});
		
		$('#li_submit #form_submit').hover(function() {
		$(this).attr("src","images/submit_btn_ovr.png");
			}, function() {
		$(this).attr("src","images/submit_btn.png");
		});

});


// GOOGLE MAPS STUFF

var geocoder;
var map;
var currentMarker;
var infowindow = new google.maps.InfoWindow();

function setMarkers(map, locations) {
  // Add markers to the map

  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.

  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.
  var image = new google.maps.MarkerImage('images/icon.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(36, 56),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(7, 54));
  var shape = {
      coord: [1, 1, 1, 15, 55, 15, 1 , 53],
      type: 'poly'
  };
  
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
	createMarkers(map, beach, image, shape, i);
    
  }
  
};
var undefined;
var markerList = [ ];
function createMarkers(map, beach, image, shape, id) {
	var url = beach[8];
	if(beach[8].search('http') == -1 && beach[8].search('www') != -1)
	{
		url = 'http://'+beach[8];
		if(beach[8] == 'none' || beach[8] == undefined)
			url = '';
		if(beach[8].search("@") != -1) 
			url	= 'mailto:'+beach[8];
	}
		
	var setContent = "<p class=\"bubble-header\">"+beach[0]+"</p><p class=\"bubble-address\">"+beach[4]+"<br />"+beach[7]+", "+beach[5]+"<br />"+beach[6]+" <br /><br /><a href=\""+url+"\" target=\"_blank\">"+url+"</a></p>";
	var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image,
        title: beach[0],
        zIndex: beach[3]
    });
   
    /*$("li#l_"+id).bind("click", function(e) {
    	alert(0);
		//map.setCenter(marker.getPoint(), 12);
		GEvent.trigger(marker, 'click');
	});*/
    
	//markerList.push(marker);
	 google.maps.event.addListener(marker, 'click', function() {
        
        infowindow.setContent(setContent); 
        infowindow.open(map,marker);
		
        });
	
}

$.validator.addMethod(
    "australianDate",
    function(value, element) {
        var explode = value.split('/');
		
		if(explode.length != 3)
		{
			return false;	
		}
    },
    "Please enter a date in the format dd/mm/yyyy"
);

$.validator.addMethod(
	"notEight",
    function(value, element) {
        var explode = value.split('/');
		
		var d = new Date();
		var age = d.getFullYear() - explode[2];
		if(age < 18)
		{
			return false;
		}
    },
    "Sorry. You must be 18 years or over to partake in the battle."		  
);


function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
	}
}
function clickrecall(thisfield, defaulttext) {
	if (thisfield.value == "") {
		thisfield.value = defaulttext;
	}
}

initialize();
