$(document).ready(function(){
	//client login form - top nav 
	if ($('form[name=aspnetForm]').length>0){
		$('#login #aspnetForm input[name=username]').example('Account Name');
		$('#login #aspnetForm input[name=password]').example('Password');
		$('#login #aspnetForm input[name=clientcode]').example('Client Code');
	}
	/*$('form[name=client_login]').submit(function(){
		//TODO form validation
		if ($('#clientcode').val()==""){
			$(this).attr('action','claimnetpluslogin');
		}else{
			$(this).attr('action','claimnetlogin');
		}
		return true;
	});*/

	

	//stay-in-touch RHS
	if ($('form[name=stay-in-touch]').length>0){
		$('#ohkdiy-ohkdiy').example('Email Address');
	}	
	
    $("#stay-in-touch button").click(function() {
        // First, disable the form from submitting
        $('form#stay-in-touch').submit(function() { return false; });
        // Grab form action
        var formAction = $("form#stay-in-touch").attr("action");
        // Hacking together id for email field
        // Replace the xxxxx below:
        // If your form action were http://mysiteaddress.createsend.com/t/r/s/abcde/, then you'd enter "abcde" below
        var id = "ohkdiy";
        var emailId = id + "-" + id;
        // Validate email address with regex
        if (!checkEmail($("#"+emailId).val())) {
          alert("Please enter a valid email address");
          return;
        }
        // Serialize form values to be submitted with POST
        var str = $("form#stay-in-touch").serialize();

        // Add form action to end of serialized data
        // CDATA is used to avoid validation errors
        //<![CDATA[
        var serialized = str + "&action=" + formAction;
        // ]]>
        // Submit the form via ajax
        $.ajax({
          url: "proxy.php",
          type: "POST",
          data: serialized,
          success: function(data){
            // Server-side validation
            if (data.search(/invalid/i) != -1) {
              alert('The email address you supplied is invalid and needs to be fixed before you can subscribe to this list.');
              
            }
            else
            {
              $("#stay-in-touch").hide(); // If successfully submitted hides the form
              $("#confirmation").slideDown("slow");  // Shows "Thanks for subscribing" div
              $("#confirmation").tabIndex = -1;
              $("#confirmation").focus(); // For screen reader accessibility
              // Fire off Google Analytics fake pageview
              //var pageTracker = _gat._getTracker("UA-XXXXX-X");
              //pageTracker._trackPageview("/newsletter_signup");
            }
          }
        });
      });
	//stay-connected RHS - deactivate links
	$('.social a[href="#"]').attr('target','');	
	
	//index.php and RHS	
	if (!$.browser.opera) {
		// select element styling
	$('.locator select').each(function(){
		var title = $(this).attr('title');
		if( $('option:selected', this).val() != 'Select State'  ) title = $('option:selected',this).text();
		$(this)
			.css({'z-index':10,'opacity':0,'-khtml-appearance':'none'})
			.after('<span class="select">' + title + '</span>')
			.change(function(){
				val = $('option:selected',this).text();
					$(this).next().text(val);
					})
		});
	
	};
	$('#office_locator_rhs select').change(function (){
		$('#office_locator_rhs').submit();
	});

	$('form[name=office_locator_db] #search_term').keyup(function (){
		officeLocatorAutocomplete();
	});
	$('form[name=office_locator_db] #id_state').change(function (){
		officeLocatorAutocomplete();
	});

	//about-us and subpages
	if ($('ul.collapse').length>0){
		//$('ul.collapse').quickTree();
		$('ul.collapse li ul').hide();
		//$('ul.collapse li ul').children().hide();
	}
	thisPage=getFileName();
	//thisPage = location.href.substring((location.href.lastIndexOf("/"))+1);
	//thisPage = thisPage.substring(0,thisPage.firstIndexOf("#"))+1);
	//get the page filename from the URL
	$('ul.collapse li a[href="'+thisPage+'"]').each(function() {
	//for each list item that has a link to this page's URL:
		//$(this).addClass('current');
		$(this).parent('li').css('display','block');
		$(this).parent('li').children().css('display','block');
		//$(this).parent('li').children('ul:first').css('display','block');
		//add class="current"
		$(this).parents('ul').css('display','block');
		//display the parent element as block
		//$(this).css('color','#ea6e23');
		//change the color
	});
	
	//contact-us page defaults
	if ($('form[name=contact-us]').length>0){
		$('#first_name').example('First Name');
		$('#last_name').example('Last Name');
		$('#email_address').example('Email Address');
		$('#phone_number').example('Phone Number');
		$('#feedback').example('Your Feedback');
	}	
	//contact-us page validation
	$('form[name=contact-us]').submit(function() {
		errors=0;
		$('form[name=contact-us] fieldset input,textarea').each(function() {
			var label=$(this).prev().html();
			if ($(this).val()==""){
				$(this).addClass('error');
				$(this).example('Please Enter '+label);
				errors=errors+1;
			}
		});
		var email_address=$('#email_address').val();
		if (email_address!="Please Enter Email Address"){
			var email_valid=checkEmail(email_address);
			if (email_valid==false){
				$('#email_address').val('');
				$('#email_address').example('Please Enter Valid Email Address');
				$('#email_address').addClass('error');
				errors=errors+1;
			}
		}
		if (errors>0){
			return false;
		}
	});	
	$('form[name=contact-us] fieldset input,textarea').keyup(function(){
		$(this).removeClass('error');
	});	
	//office-locator.php
	if ($('#map_canvas').length>0){
		initializeGoogleMap();
	}
	if ($('form[name=office_locator]').length>0){
		$('#search_term').example('Search');
	}
	$('#id_state').change(function() {
		if ($('#id_office').length>0){
			var id_state=$(this).val();
			updateOffices(id_state);
			$('#id_office').next().html("Select Office");
		}
	    return false;
	});	
	$('#id_office').change(function() {
		if ($(this).val()!=""){
			$('#search_term').val('');
		}
	    return false;
	});		
	
});
//client login
function OnSubmitForm()
{
  if(document.aspnetForm.clientcode.value != '' && document.aspnetForm.clientcode.value != 'Client Code')
  {
   //alert("Claim net.");
   document.aspnetForm.action ="https://extranet.freemans.com.au/servlet/au.com.icconsulting.freemans.servlet.UserAuthenticationServlet";
   return true;
  }
  else
  {
	//alert("Claimnet +");
	document.aspnetForm.ctl00$ContentPlaceHolder1$_txtUsername.value = document.aspnetForm.username.value;
	document.aspnetForm.ctl00$ContentPlaceHolder1$_txtPassword.value = document.aspnetForm.password.value;
	document.aspnetForm.ctl00_ContentPlaceHolder1__txtTimezoneOffset.value = (new Date().getTimezoneOffset()) * (-1);
	//document.aspnetForm.id="aspnetForm";
	document.aspnetForm.action ="https://claimnet.freemans.com.au/ClaimnetPlus/Login.aspx?ReturnUrl=%2fclaimnetplus%2fdefault.aspx";
  }
 
}

function GetClientTimeZoneOffset() {
    var o = document.getElementById('ctl00_ContentPlaceHolder1__txtTimezoneOffset');
    var tzo = (new Date().getTimezoneOffset()) * (-1);  //  / 60) * (-1)
    o.setAttribute("value", tzo);
}	

//index.php

function officeLocatorAutocomplete(){
	var id_state=$('#id_state').val();
	var search_term=$("#search_term").val();
	if (search_term.length>2 || id_state){
		 $.getJSON('ajax.php?action=officeLocator&id_state='+id_state+'&search_term='+search_term, function(locator) {
			 $('#office_list').hide();
			 if (locator.num_results>0){
				 $('#office_list ul').remove();
				 $('#office_list').append('<ul></ul>');
				 $.each(locator.results, function(i,office)
						 {   
					 		$('#office_list ul').append('<li><a href="office_locator_grey.php?id_office='+office.id_office+'">'+office.office_name+', '+office.state.label+'</a></li>');
						 });
				 $('#office_list').show();
			 }
		 });	
	}else{
		$('#office_list').hide();
	}	
	
}
//global string helper
function getFileName() {
	//this gets the full url
	var url = document.location.href;
	//this removes the anchor at the end, if there is one
	url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
	//this removes the query after the file name, if there is one
	url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
	//this removes everything before the last slash in the path
	url = url.substring(url.lastIndexOf("/") + 1, url.length);
	//return
	return url;
}

//contact-us form

function checkEmail(email) {
    var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return pattern.test(email);
  }


//office-locator.php

function updateOffices(id_state){
	 $('#id_office option').remove();
	 $.getJSON('ajax.php?action=getOffices&id_state='+id_state, function(data) {
		 addOptionsToSelect('#id_office',data);
	 });		
}

function addOptionsToSelect(select,options){
	 $.each(options, function(i,option)
			 {   
			      $(select).
			           append($("<option></option>").
			           attr("value",option.value).
			           text(option.text)); 
			 });
	 if (options.length==2){
		 jQuery(select+" option:last").attr("selected", "selected");
	 }	
}

var geocoder;
var map;
var bounds=null;
var markers=new Array();
var markerImage;
function initializeGoogleMap() {
    geocoder = new google.maps.Geocoder();
    bounds = new google.maps.LatLngBounds();
    var latlng = new google.maps.LatLng(-28.5, 133);
    var myOptions = {
      zoom: 4,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function officeLocator(id_office,id_state,search_term){
	 $.getJSON('ajax.php?action=officeLocator&id_office='+id_office+'&id_state='+id_state+'&search_term='+search_term, function(locator) {
		 putOfficesOnMap(locator);
	 });
}

function putOfficesOnMap(locator){
		
		 showWindow=false;
		 if (locator.num_results==1){
			showWindow=true;
		 }
		 $.each(locator.results, function(i,office)
				 {   
			 			addOfficeMarker(office,showWindow);
			 			
				 });
		 if (locator.num_results==1){
		 	 map.setCenter(bounds.getCenter());
			 map.setZoom(14);
			 showInfoWindow(locator.results[0].id_office);
			 //$("ul.results li a").trigger("click");
		 }else{
			 map.fitBounds(bounds);
		 }
		 //if only one office. zoom out.
		 
}

function hideAllInfoWindows(){
	$.each(markers, function(i,marker)
			 {   
					if (marker){
						marker.infowindow.close();
					}
			 });	
	
}

function showInfoWindow(id){
	 hideAllInfoWindows();
	 markers[id].infowindow.open(map,markers[id]);
}

function addOfficeMarker(office,showWindow) {
		var point = new google.maps.LatLng(office.latitude, office.longitude);
		//
        markers[office.id_office] = new google.maps.Marker({
            map: map,
            position: point,
            title: office.office_name,
            icon: 'images/bluemarker.png'
        });
        var contentHtml='<div class="infowindow"><h3>'+office.office_name+'</h3>\n';
        if (office.image){
        	contentHtml+='<img width="50" src="image.php?type=office&file=cms_images/'+office.image+'" />\n';
        }
        contentHtml+='<!--<p>This is a description\n'+
        'that can go here.</p>\n'+
        '\n-->'+
        '<p>'+office.address+'</br>\n'+
        ''+office.suburb+', '+office.state.label+', '+office.postcode+'</p>\n'+
        '\n'+
        '<p>Telephone: '+office.telephone+'</p>\n'+
        '<p>Fax: '+office.fax+'</p>\n';
        if (office.manager_name.length>0){
        	contentHtml+='<p>Manager: '+office.manager_name+'</p>\n';
        }
        if (office.manager_email.length>0){
        	contentHtml+='<p>Manager Email: <a href="mailto:'+office.manager_email+'">'+office.manager_email+'</a></p>\n';
        }        
        contentHtml+='<p>Email: <a href="mailto:'+office.email+'">'+office.email+'</a></p></div>'
        markers[office.id_office].infowindow = new google.maps.InfoWindow({
            //content: address
        	
        	content:contentHtml
        });
        if (showWindow){
        	markers[office.id_office].infowindow.open(map,markers[office.id_office]);	
        }
        google.maps.event.addListener(markers[office.id_office], 'click', function() {
        	hideAllInfoWindows();
        	markers[office.id_office].infowindow.open(map,markers[office.id_office]);
        });         
        bounds.extend(point);	
}






//TODO: once cerno google map is stable delete all of the following that are not being used.
//DELETE FROM HERE:
function setMapCenter(){		
	//map.setCenter(new GLatLng(lat, lng), 17);
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
}
function addMarker_old(latitude,longitude,address,index){
	
	var point=new GLatLng(latitude, longitude);
	createMarker(point,address,index)
}
function addLetterMarker(latitude,longitude,address,index){
	
	var point=new GLatLng(latitude, longitude);
	createLetterMarker(point,address,index)
}	
function createMarker(point,address,index){
		  map.setCenter(point, 17);
		  //map.setCenter(new GLatLng(-37.867837, 144.761479), 17);
		  map.addControl(new GSmallMapControl());
          map.addControl(new GMapTypeControl()); 
		  var baseIcon = new GIcon(G_DEFAULT_ICON);
		//baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		
		baseIcon.iconSize = new GSize(40, 55);
		baseIcon.shadowSize = new GSize(0, 0);
		baseIcon.iconAnchor = new GPoint(20, 50);
		baseIcon.infoWindowAnchor = new GPoint(9, 15);
		var letteredIcon = new GIcon(baseIcon);
		var letter = String.fromCharCode("A".charCodeAt(0) + index); 
		//letteredIcon.image = "http://www.google.com/mapfiles/marker"+letter+".png";
		letteredIcon.image="http://www.yournewsagent.com.au/images/ynaicon.png";
		//letteredIcon.image="http://www.yournewsagent.com.au/images/ynaiconglow.png";
		//letteredIcon.image="http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
		
		markerOptions = { icon:letteredIcon };

		  var marker = new GMarker(point, markerOptions); 
		  //var marker = new GMarker(point); 
          map.addOverlay(marker);
		  GEvent.addListener(marker, "click", function() {
          	marker.openInfoWindowHtml(address);
		  });
		  bounds.extend(point);
	return marker;
}
function createLetterMarker(point,address,index){
		  map.setCenter(point, 17);
		  //map.setCenter(new GLatLng(-37.867837, 144.761479), 17);
		  map.addControl(new GSmallMapControl());
          map.addControl(new GMapTypeControl()); 
		  var baseIcon = new GIcon(G_DEFAULT_ICON);
		//baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		
		/*baseIcon.iconSize = new GSize(40, 55);
		baseIcon.shadowSize = new GSize(0, 0);
		baseIcon.iconAnchor = new GPoint(20, 50);
		baseIcon.infoWindowAnchor = new GPoint(9, 15);*/
		var letteredIcon = new GIcon(baseIcon);
		var letter = String.fromCharCode("A".charCodeAt(0) + index); 
		letteredIcon.image = "http://www.google.com/mapfiles/marker"+letter+".png";						
		markerOptions = { icon:letteredIcon };

		  var marker = new GMarker(point, markerOptions); 
		  //var marker = new GMarker(point); 
          map.addOverlay(marker);
		  GEvent.addListener(marker, "click", function() {
          	marker.openInfoWindowHtml(address);
		  });
		  bounds.extend(point);
	return marker;
}	
//addMarker(-37.9254,145.035,'<div style="float:left;padding-right:10px;"><a href="http://www.yournewsagent.com.au/pattersonroadtattsnewsandpost" border="0"><img src="http://www.yournewsagent.com.au/gm_image.php?file=yna_photos/prtnp.jpg"></a></div><div style="float:left;"><a href="http://www.yournewsagent.com.au/pattersonroadtattsnewsandpost"><span style="color:red"><b>Patterson Road Tatts, News & Post</b></span></a><br>51 Patterson Road<br>Bentleigh,VIC, 3204</div>',1);

function showAddress(address,index) {
  var lat=null;
  var lng=null;
  map = new GMap2(document.getElementById("map_canvas"));
  geocoder = new GClientGeocoder();
  geocoder.getLatLng(
	address,
	function(point) {
	  if (!point) {
		alert(address + " not found");
	  } else {
		createMarker(point,address,index);
		
	  }
	  
	  lat=point.lat();		  
	  lng=point.lng();		  
	  
	}
  );
  
}
//DELETE TO HERE:
