$(function() {
        //un-check radio buttons based on click if they are already checked.
        //this only works because there is a div surrounding the family of
        //radios.
        $('input:radio').click(function(){
            if ($(this).hasClass('bogus')){
                $(this).removeAttr('checked');
                $(this).removeClass('bogus');
            } else {
                $(this).addClass('bogus');
                $(this).siblings().each(function(){
                    $(this).removeClass('bogus');
                });
            }
        });

        //apply the bogus class to any radio that is selected on load.
        $('input:radio').each(function(){
            if ($(this).attr('checked'))
                $(this).addClass('bogus');
        });

		//labelify / over-label
		$(".labelify").labelify({text: "label"});
		
        $('.datepicker').datepicker({
            dateFormat: 'dd-mm-yy',
            yearRange: '-100:+10',
            changeMonth: true,
            changeYear: true
        }).focus(function() {
            $('#ui-datepicker-div').css('top', $(this).offset().top + $(this).height());
        });
		
		// Collapsable sections
		$('form.collapse fieldset legend').nextAll('.container').hide();
		//$('form.collapse fieldset legend.active').nextAll('.container').show();
		$('.open').show();
		
		/* check if preferred_mode_of_contact exists and update the form */		
		if($('#preferred_mode_of_contact')){
			preferredModeOfContact($('#preferred_mode_of_contact'));
		}
		
		//enlarge the gmap if necessary
		elem = $("#map-legend");
		if (elem.is (".active")) {
			$('#resultsMap').css("height",586);
		} else {
			$('#resultsMap').css("height",200);
		}
		
		//Expand / contract gmap along with fieldset
		/*$("#map-legend").click(
			function () {
				if ($(this).is(".active"))
					$('#resultsMap').css("height",200);
				else
					$('#resultsMap').css("height",586);
			}
		);*/

		$('form.collapse fieldset legend').click(
			function () {
				$(this).toggleClass('active');
				$('form.collapse fieldset legend').nextAll('.container').hide();
				$('form.collapse fieldset legend.active').nextAll('.container').show();
			}
		);

		// Other fields expanding on checkbox click
		
		// hide all other fields
		$("label:contains('Other')").parents('.ctrl-holder').next('.ctrl-holder').css('display','none');
		
		// show other fields that have already been slected
        $('input:checked').next("label:contains('Other')").parent().next('.ctrl-holder').css('display','block');

        //At the time of writing this, there are no radio options that have a
        //text-input other that is related so show the next element.
        $(".radio-input-label").parents('.ctrl-holder').next('.ctrl-holder').css('display','block');

		$("label:contains('Other')").prev().change(function() {
			if ($(this).attr('checked') && $(this).attr('type') != "radio") {
				$(this).parents('.ctrl-holder').next('.ctrl-holder').slideDown('slow');
			} else if (!$(this).attr('checked') && $(this).attr('type') != "radio") {
				$(this).parents('.ctrl-holder').next('.ctrl-holder').slideUp('slow');
			}
		});
		
		// Other fields expanding on select box
		
		//hide all other fields
		$("select:contains('Other')").parents('.ctrl-holder').next('.ctrl-holder').css('display','none');
		
		//show other fields that have already been selected
		$("select").children("option:selected:contains('Other')").parents('.ctrl-holder').next('.ctrl-holder').css('display','block');
		
		$("select").change( function() {
			if ($(this).children('option:last').text() == "Other") {
				if ($(this).children("option:selected").text() == "Other") {
					$(this).parents('.ctrl-holder').next('.ctrl-holder').slideDown('slow');
				} else {
					$(this).parents('.ctrl-holder').next('.ctrl-holder').slideUp('slow');
				}		
			}
		});
		
		// The same as residential checkbox on the my details page copies text from the
		
		$('#same_as_residential').change( function() {
			if ($(this).attr("checked") == true) {
				$('#postal_address').val($('#residential_address').val());
				$('#postal_suburb').val($('#residential_suburb').val());
				$('#postal_state').val($('#residential_state').val());
				$('#postal_postcode').val($('#residential_postcode').val());
			}	
		});
				
		// Draw rounded corners
		$('.rounded-box').wrapInner('<div class="rbg1"><div class="rbg2"><div class="rbg3"><div class="rbg4"></div></div></div></div>');
		$('#secondary-nav').wrapInner('<div class="rbg1"><div class="rbg2"><div class="rbg3"><div class="rbg4"></div></div></div></div>');
		
		// Mega dropdown

		function addMega(){
			$(this).addClass("hovering");
		}

		function removeMega(){
			$(this).removeClass("hovering");
		}

		var megaConfig = {
			interval: 200,
			sensitivity: 4,
			over: addMega,
			timeout: 500,
			out: removeMega
		};
		
		$("li.mega").hoverIntent(megaConfig)
});

	/*
	Ultimate Age calculator script- By JavaScript Kit (http://www.javascriptkit.com)
	Over 200+ free scripts here!
	Credit must stay intact for use
	*/

	var one_day=1000*60*60*24
	var one_month=1000*60*60*24*30
	var one_year=1000*60*60*24*30*12

	function calAge(yr, mon, day, unit, decimal, round){
		today=new Date()
		var pastdate=new Date(yr, mon-1, day)
		
		var countunit=unit
		var decimals=decimal
		var rounding=round
		
		finalunit=(countunit=="days")? one_day : (countunit=="months")? one_month : one_year
		decimals=(decimals<=0)? 1 : decimals*10
	
		if (unit!="years"){
			if (rounding=="rounddown")
				return (Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals)
			else
				return (Math.ceil((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals)
		} else {
				yearspast=today.getFullYear()-yr-1
				tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0
				pastdate.setFullYear(today.getFullYear())
				pastdate2=new Date(today.getFullYear()-1, mon-1, day)
				tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals
				return (yearspast+tail)
		}
	}


	/* field to update is a select field */
	function update_age_range(date_field, field_to_update){
		var selectedDate;
		if($(date_field)){
			selectedDate = $(date_field).val().split('-');
						
			if(selectedDate.length == 3){
				var getYear = new Date().getFullYear();
				var birthDay = selectedDate[0];
				var birthMonth = selectedDate[1];
				var birthYear = selectedDate[2];
								
				/* workout the age */ 
		
				var set_age = calAge(birthYear, birthMonth, birthDay, "years", 0, "rounddown") //getYear - birth_year;
				
				if(set_age < 20){
					$(field_to_update).attr('value', 2);
				} else if(set_age >= 20 && set_age <= 29){
					$(field_to_update).attr('value', 3);
				} else if(set_age >= 30 && set_age <= 39){
					$(field_to_update).attr('value', 4);
				} else if(set_age >= 40 && set_age <= 49){
					$(field_to_update).attr('value', 5);
				} else if(set_age >= 50 && set_age <= 59){
					$(field_to_update).attr('value', 6);
				} else if(set_age >= 60 && set_age <= 69){
					$(field_to_update).attr('value', 7);
				} else if(set_age >= 70){
					$(field_to_update).attr('value', 8);
				}	
			}
		}
	}
	
	/* check that the CDE select status field is not 'none' */
	function updateCDE_credential(selectField, field_to_update, check_for_value){
					
		if($('#' + ($(selectField).attr('id') + ' :selected')).text().toLowerCase() != 'none'){
			updateFieldCurrentDate($('#' + field_to_update), check_for_value);	
		}
	}
	
	/* set the current date to the field passed to dd-mm-yyyy*/
	function updateFieldCurrentDate(field_name, check_for_value){
		var currentDate=new Date();
		var update_field = false;
				
		if ($(field_name)) {
																
			if(check_for_value == 1 && $(field_name).val() == ''){
				update_field = true;
			} else if(check_for_value = 0) {
				update_field = true;
			}
						
			if(update_field){
				var getDate = '' + currentDate.getDate();
				
				/* Jan is 0, so adding 1 is required */
				var getMonth = '' + (currentDate.getMonth() + 1);
				
				
				if(getDate.length == 1){
					getDate	 = '0' + getDate;	
				}
				
				if(getMonth.length == 1){
					getMonth = '0' + getMonth;
				}
				
				$(field_name).attr("value", getDate + '-' + getMonth + '-' + currentDate.getFullYear());
			}
		}
	}
	
	/* add a star next to the field which is required */	
	function preferredModeOfContact(select_field){
		if($(select_field)){			
			var val = $(select_field).val();			
			var field = new Array('phone_work', 'phone_home', 'phone_mobile');
			
			var email = 22
			var work_phone = 23;
			var home_phone = 24;
			var mobile_phone = 25;
			var post = 26;
			
			// remove any of the <em>*</em> which have been set before
			for(var i=0; i < field.length; i++){
				
				if($('#label_' + field[i]).find('span').length){
					$('#label_' + field[i]).find('span').remove();
				}
			}
						
			if(val == work_phone){
				//is there a better way of adding "<span class="mand">*</span>" in front of text in the label
				$('#label_' + field[0]).html('<span class="mand">*</span>' + $('#label_' + field[0]).html());
			} else if(val == home_phone){
				$('#label_' + field[1]).html('<span class="mand">*</span>' + $('#label_' + field[1]).html());
			} else if(val == mobile_phone)
				$('#label_' + field[2]).html('<span class="mand">*</span>' + $('#label_' + field[2]).html());	
		}		
	}

    /**
     * adds an asterixs to the appropriate field
     */
    function clinicContactDetails (obj) {
        var mandObj;
        var objArray = new Array($("#label_clinic_email"),$("#label_clinic_landline"),$("#label_clinic_mobile"),$("#label_clinic_fax"));

        for (var i=0;i<objArray.length;i++){
            if(objArray[i].find('span').length){
                objArray[i].find('span').remove();
            }
        }

        switch(obj.value){
            case '208': //email
                mandObj = $("#label_clinic_email");
                break;
            case '209': //landline
                mandObj = $("#label_clinic_landline");
                break;
            case '210': //mobile
                mandObj = $("#label_clinic_mobile");
                break;
            case '211': //fax
                mandObj = $("#label_clinic_fax");
                break;
        }

        mandObj.html('<span class="mand">*</span>'+mandObj.html());
    }

