var geocoder;
var map;
var marker = null;

function initializeMap() {
	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(-28.397, 134.644);
	var myOptions = {
		zoom: 14,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: false
	}
	if (document.getElementById("map_canvas") !== null) {
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);		
	}
}

function codeAddress(address) {
	if (geocoder) {
	    address = address.replace(/\n/g,' ');
		geocoder.geocode( { 'address': address }, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);
				if (marker != null) {
					marker.setMap(null);
				}
				marker = new google.maps.Marker({
					map: map, 
					position: results[0].geometry.location
				});
			} else {
				alert("Geocode was not successful for the following reason: " + status);
			}
		});
	}
}

$.extend({
    getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function(name){
        return $.getUrlVars()[name];
    }
});

var staying_in_site = false;

$(document).ready(function(){

	initializeMap();

	// Lightbox
	$("a#setCookie").fancybox({
		'hideOnContentClick': false,
		'autoDimensions': false,
		'overlayOpacity': 0.9,
		'overlayColor': '#000',
		'width': 742,
		'height': 700,
		'padding': 0,
		'scrolling': 'yes'
	});

	$('a.closeOverlay').click(function(event) {
	    event.preventDefault();
		$.fancybox.close();
	});
	
	$('a.proceed').click(function(event) {
	    event.preventDefault();
        window.location = '/';
	});
	
	$('.setCookie').live('click', function() {
		var expiry = new Date();
		// set expiry to 30 minutes
		expiry.setTime(expiry.getTime() + (30 * 60 * 1000));
		$.cookie("overlay", "hide", { expires: expiry });
		$('.content-overlay').hide();
		$('.contentBox').show();
		if (!$(this).hasClass('in-queensland')) {
			$('#quote').css('background-image','url("/public/themes/cmclawyers/images/logo_quote.jpg")');
		};
	});

	$('.noCookie').click(function() {
		$.cookie("overlay", null);
		window.location.reload();
	});

	$('#our_locations_list li ul').hide();

	var showLoc = $.getUrlVar('loc');
	if (showLoc) {
		$('.' + showLoc).show('fast').parent().addClass('active');
		var address = $('.' + showLoc).html().replace(/<\S[^>]*>/g,"");
		codeAddress(address);
	}

	$('#our_locations_list li').click(function(){
		if($(this).find('ul').is(':hidden')) {
			$('#our_locations_list li ul').hide();
			$(this).addClass('active').find('ul').show('fast');
			var address = $(this).find('ul').html().replace(/<\S[^>]*>/g,"");
			codeAddress(address);
		} else {
			$(this).removeClass('active').find('ul').hide('fast');
		}
	});

    // #submission form validation
	var errorContainer = $('.enquiries_form span.error');
	
	$('#pollform').submit(function(){
		errorContainer.show();
        if ($('#pollform #phone').val() == '' || $('#pollform #email').val() == '') {
            errorContainer.text('Please enter your phone and your email address.');
        } else {
            
            var valid = false;
            
            $("#pollform #phone").val($("#pollform #phone").val().replace(/[\(\)\.\-\s,]/g, ""));

			if ($("#pollform #phone-input").val() == "") {
				errorContainer.text('Please enter a phone number.');
			} else if (!isNumeric($("#pollform #phone").val())) {
				errorContainer.text('Please enter a valid phone number (digits only).');
			} else if ($("#pollform #phone").val().length !== 8 && $("#pollform #phone").val().length !== 10) {
				errorContainer.text('Phone number must be 8 or 10 digits long.');
			} else if ($("#pollform #email").val() == "") {
				errorContainer.text('Please enter an email.');
			} else if (!isEmail($("#pollform #email").val())) {
				errorContainer.text('Please enter a valid email.');						
			} else {
				errorContainer.hide();
				return true;
			}
        }

		return false;
	});

    $('a').click(function(){
		staying_in_site = true;
	});

});


function isEmail(value) {
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value)
}

function isNumeric(value) {
	return /^\d+$/.test(value);
}

function clearCookies() {
	if (staying_in_site !== true) {
		$.cookie("overlay", null);
		$.cookie("in-queensland", null);
	}
}

