// JavaScript Document//onload js
var suburbsData = "";
var suggestionText = "";
var allOrgNames ="";

$(function() {
//remove current onload script
onloaded =true;

//auto check sei items 
$(".check-item-Yes").click();

    // fix search forms (temporary function - WS)
    //fixSearchFormFileds();
    //check if CSS is disabled
    if ($("#css-check").css("z-index") == 1578 || $.browser.webkit) {
        //add js loading class
        /*$("body").addClass("js-loading").removeClass("no-js");*/
        //add code to external links
        //$("#middle a[href^='http:']").not("[href*='"+location.hostname+"']").attr('target','_blank').attr("rel","External Link - Opens in new window");

       //insert print button for opportunity tools
       $("#opportunity-tools .email-opp").after('<a class="print" href="#">Print</a>');
       $("#opportunity-tools .print").click(function(e){e.preventDefault();window.print();})

        //home asterisk disco ball
        $(".home .asterisk").append('<div></div><div class="pink"></div><div class="green"></div><div class="orange"></div><div class="purple"></div>')
                    .cycle({fx: 'fade'});

        $('.navigation ul li:last').addClass('last');
        $("body").append("<div id='absolute-saviour'></div>");

		// Add quote marks in IE for q tags
		if ($.browser.msie &&$.browser.version < 7) {
			$('q').each(function(){
				$(this).parents('q').length > 0 ? $(this).prepend('&lsquo;').append('&rsquo;') : $(this).prepend('&ldquo;').append('&rdquo;');
			});
		}

		// Login error message styling helper
		if($.trim($('div.error-msg-blank').text()) != ''){
			$('div.error-msg-blank').removeClass('error-msg-blank').addClass('error-msg');
		}


		//insert back to search button for opportunities detail pages
		if ($(".opp-result").size() > 0) {
			var referrerURL = document.referrer;
			if (referrerURL.search("find-a-volunteer-opportunity") != -1) {
				$(".opp-result").eq(0).before('<div class="section back-to-search"><a href="' + referrerURL + '" class="back-to-search">back to search results</a></div>');
			}
		}
        //fix for wysiwgy sei -> Opportunity Benefits
        $("#metadata_field_wysiwyg_415_default").addClass("default").hide();
        $("#metadata_field_wysiwyg_415_default").next("label").hide();


		//add in select all for timecommitment
		$("#time-commitment table").after("<div class=\"check-all\"><input type=\"checkbox\" id=\"tc_Check_all\" name=\"tc_Check_all\" value=\Check all\"><label for=\"tc_Check_all\"><strong>Select all/Clear all</strong></label></div>");

        //custom form elements
		var createSelect = function(select) {
			if($(select).is(":visible")){
				if($(select).attr("multiple")){
					return false;
				} else {
					$(select).customInput();
					$(select).selectmenu({
						style: "dropdown",
												  maxHeight: 300
					});
				}
			} else {
				var selectCheck = setTimeout(function() {
					createSelect(select);
				}, 2000);
			}
	   }

        $('input:not(.default)').customInput();
		$('select').each(function(){
			createSelect(this);
		});


		if($('.help').size() > 0){
			$("#absolute-saviour").append("<div id='tooltip' class='help-tooltip'></div>");
		}
		$(".help").tooltip({
			effect: 'fade',
			position: 'bottom center',
			tip: '#tooltip',
			onBeforeShow: function() {
				var tipText = this.getTrigger().text();
				this.getTip().text(tipText);
			}
		});
        
        
        // Change error message on reg as emergency vol form
        $('#page_asset_builder_49224 .errors li, #page_asset_builder_85088 .errors li').each(function(i,val){
            if($(this).text().indexOf('SYS0251') > -1){
                $(this).text('Unable to create this account as the email address is already in use. You may already be on the Emergency Volunteer Register or you have used this email for your Organisation account.');
                $(this).closest('div.errors').removeClass('hide');
            };
        });


		// Javascript date fixes for 'Readable' dates to convert them to DD/MM/YYYY formats for
		// metadata date field editing
		$('input.date').each(function(){
		    var val = $(this).val();
		    // If the date format contains a comma it's likely to be the incorrect format
		    if (val.indexOf(',') !== -1) {
		        var newVal = convertDateString(val);
		        // Defaults to '' empty if the date could not be reformatted
		        $(this).val((newVal !== null) ? newVal : '');
		    }// End if
			if($(this).val()=="01/01/1970" || $(this).val()=="01/01/2010" || $(this).val()=="1/1/2010"){
				$(this).val("");
			};
		});

		//split date up into three fields
		$(".form-date input.date, .form-date input.date-adv").addClass("date-cal").css({"height":"1px","width":"1px","visibility":"hidden","left": "1px","top":"46px","position":"absolute"});
		$(".form-date").css({"position":"relative"});

		$(".form-date .custom-text").prepend("<input class='day-cal date-adv' type='text' /><input class='month-cal date-adv' type='text' /><input class='year-cal date-adv' type='text' />");

		$("input.day-cal").each(function() {
			createDefaultText($(this), "day");
		});
		$("input.month-cal").each(function() {
			createDefaultText($(this), "month");
		});
		$("input.year-cal").each(function() {
			createDefaultText($(this), "year");
		});

		//set date on fields update
		$("input.day-cal, input.month-cal, input.year-cal").bind("change blur", function(){
			current = $(this);
			hiddenDate = current.parent(".custom-text").find("input[type=text]:last");

			if(isFinite(current.val())){
				var leadingZero2 = function(number){
					number = parseFloat(number);
					if(number<10 && number>-1 ){
						return "0"+String(number)
					}
					
					return number;
				}
				//day-cal
				if(hiddenDate.val() == "") hiddenDate.val("DD/MM/YYYY");
				if(current.hasClass("day-cal")){
					if (current.val().length == 2) {
						hiddenDate.val(hiddenDate.val().replace(/^[0-9D]+\//,leadingZero2(current.val()) +"/"));
					} else {
						hiddenDate.val(hiddenDate.val().replace(/^[0-9D]+\//, "DD/"));
					}
				} //month-cal
				else if (current.hasClass("month-cal")){
					if (current.val().length == 2) {
						hiddenDate.val(hiddenDate.val().replace(/\/[0-9M]+\//,"/"+leadingZero2(current.val())+"/"));
					} else {
						hiddenDate.val(hiddenDate.val().replace(/\/[0-9M]+\//, "/MM/"));
					}
				} //year-cal
				else if (current.hasClass("year-cal")){
					if (current.val().length == 4) {
						hiddenDate.val(hiddenDate.val().replace(/[0-9Y]+$/, current.val()));
					}
					else {
						hiddenDate.val(hiddenDate.val().replace(/[0-9Y]+$/, "YYYY"));
					}
				}
				//set date of calendar widget
				if(hiddenDate.val().match(/[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/)){
					$("input.date").datepicker("setDate", hiddenDate.val());
				}
				//if date empty set empty
				if(hiddenDate.val() == "DD/MM/YYYY") hiddenDate.val("");

			}
		});


        $("input.date").datepicker({
            showOn: 'button',
            buttonText: 'Pick a date',
            dateFormat: "dd/mm/yy",
            onClose: function(dateText, inst) {
                if (dateText != null) {
                    $(this).removeClass("blank");
                }
				var date = dateText.split("/");
				$(inst.input).prevAll(".day-cal").val(date[0]);
				$(inst.input).prevAll(".month-cal").val(date[1]);
				$(inst.input).prevAll(".year-cal").val(date[2]).trigger("focus");

            }
        });
        $(".hasDatepicker").each(function(){
        	var dateOrg = $(this);
        	if(dateOrg.val()!="") {
        		var dateSplit = dateOrg.val().replace("-","/").split("/");
        		if(dateSplit.length == 3){
        			dateOrg.prevAll(".day-cal").val(dateSplit[0]);
					dateOrg.prevAll(".month-cal").val(dateSplit[1]);
					dateOrg.prevAll(".year-cal").val(dateSplit[2]);
        		}
        	}
        });
        $("#ui-datepicker-div").hide();

        //overwrite focusEditor function
        /*if ($("#page_asset_builder_34166_type_news_item").length > 0 || $("#page_asset_builder_2469").length > 0 || $("#sei_upload_logo_div").length > 0 || $(".form-step-2").length > 0){*/
        if (typeof(HTMLArea) !== "undefined"){
            HTMLArea.prototype.focusEditor = function() {
            if (HTMLArea.is_gecko) {
                this._iframe.contentWindow.focus();
            } else if (HTMLArea.is_ie) {
                //this._docContent.focus();
            }
            return this._docContent;
            };
        }


       $('.banner .pagination li').remove();
        $('.banner .images').cycle({
            pager: '.banner .pagination',
            pause: 1,
            pagerAnchorBuilder: function(idx, slide) {
                var color = "";
                switch (idx) {
                case 0:
                    color = "blue";
                    break;
                case 1:
                    /*color = "yellow";*/
		                color = "blue";
                    break;
                case 2:
                    /*color = "pink";*/
		                color = "blue";
                    break;
                }
                return '<li><a href="#" class="' + color + '">View Image ' + (idx + 1) + ':' + $(slide).attr("alt") + '" </a></li>';
            }
        });
        //remove link from current page on a-z listing
		var currentLetter = $("#current-letter").text();
		if (currentLetter != "") {
			$(".section.listing a:contains(" + currentLetter + ")").before(currentLetter).remove();
		}
		if(currentLetter == "@"){
			$(".section.listing a:contains([ther])").before("[Other]").remove();
		}
        //results page map
        $(".results-map #map").append('<div class="gmap-btn hide-map"><a href="#">Hide Map</a></div>');
        $(".results-map .hide-map").click(function(e) {
            e.preventDefault();
            $(this).toggleClass("map-close");
            if ($(this).hasClass("map-close")) {
                $("#map").slideUp();
                $("a",this).text("Show Map")
				$(this).css({"width":"7em","position":"static"});
            } else {
                $("#map").slideDown();
                $("a", this).text("Hide Map");
				$(this).css({"width":"5em","position":"absolute"});
            }
        });

        $(".banner .pagination").after('<a href="#" class="pause">Pause Gallery</a>');

        $('.banner .pause').click(function(e) {
            e.preventDefault();
            if ($(this).hasClass('play')) {
                $('.banner .images').cycle('resume');
                $(this).text("Pause Gallery");
            } else {
                $('.banner .images').cycle('pause');
                $(this).text("Resume Gallery");
            }
            $(this).toggleClass("play");
            return false;
        });

        //hover change banner for hotspots
        $(".hotspots div h2 a").bind('focus mouseover',
        function() {
            if (!$(".banner .pause").hasClass('play')) {
                $(".banner .pause").trigger('click');
            }
            switch ($(this).parents(".spot-1, .spot-2, .spot-3").attr('class')) {
            case "spot-1":
                $(".banner .pagination a:eq(0)").trigger('click');
                break;
            case "spot-2":
                $(".banner .pagination a:eq(1)").trigger('click');
                break;
            case "spot-3":


                $(".banner .pagination a:eq(2)").trigger('click');
                break;
            }
        });


        //AddThis
        //$("div.social-links").html('<div class="addthis_toolbox addthis_default_style"><a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=xa-4ca17c05057c0b59" style="float:left;padding-top:2px;"><img src="http://s7.addthis.com/static/btn/sm-share-en.gif" width="83" height="16" alt="Bookmark and Share" style="border:0;"/></a><a class="addthis_button_facebook_like" style="padding-top:2px;margin-right:-25px;"></a></div><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4ca17c05057c0b59"></script>');


        $("#content-tools").append('<ul><li><a href="#" id="small-font-size"><abbr title="Small text size">A</abbr></a></li><li><a href="#" id="medium-font-size"><abbr title="Medium text size">A</abbr></a></li><li><a href="#" id="large-font-size"><abbr title="Large text size">A</abbr></a></li></ul>');

        $("#small-font-size, #medium-font-size, #large-font-size").click(function() {
            $("body").removeClass("small-font-size");
            $("body").removeClass("medium-font-size");
            $("body").removeClass("large-font-size");
            $("body").addClass($(this).attr("id"));
            redrawCyclePlugin($(".share-your-story .items"));
            redrawCyclePlugin($(".photo-gallery .items"));
            setBestPracticeToolkitBoxHeights();
        });


        createCheckboxDropDown($("fieldset#Interests, fieldset#Skills, fieldset#avaiblitiyLocations, .createCheckboxDropDown"));

        //Run this only on find oppurtunieis form
        if ($("form#find-opportunities").size() > 0) {
			// Autocomplete for search location fields
			if ($('input#Location').size() > 0) {
				suburbs();
				suburbsData = suburbsData.split(", ");
				$('input#Location').autocomplete(suburbsData);
			};

            //default value for text fields
            createDefaultText($("form#find-opportunities input#Location"), "Enter suburb or postcode");
            createDefaultText($("#start-date"), "DD / MM / YYYY");

			 checkboxSelectAll($("#time-commitment .check-all input"), $("#time-commitment table input[type=checkbox]"));
            // Hide advanced options on page load and provide buttons to switch between adv and simple modes
            $("#find-btn .advanced-search a").click(function(e) {




                var thisEle = this;
				e.preventDefault();
				  if ($.browser.msie && $.browser.version < 7) {
					  	$(this).parents("form").eq(0).toggleClass("search-form-advanced");
						$(this).parents("form").eq(0).toggleClass("search-form-lite");
				  }else{
					$(this).parents("div.form-container").eq(0).fadeOut("slow",
					function() {
						$("form", this).eq(0).toggleClass("search-form-advanced");
						$("form", this).eq(0).toggleClass("search-form-lite");
						$(this).fadeIn("slow");
					});
				 }
            });

			// Autocomplete for opportunity location fields
			if ($('input#metadata_field_text_390_value').size() > 0) {
			suburbs();
                suburbsData = suburbsData.split(", ");
                $('input#metadata_field_text_390_value').autocomplete(suburbsData);
			};

            $("#location-online-home").click(function(){
               if($(this).attr("checked")){
                  $("#Location").val("").hide();
                  $(".surr_sub").hide();
               }else {
                  $("#Location").show();
                  $(".surr_sub").show();
               }
            });
        };



        if ($.browser.msie && $.browser.version < 7) {

			$("input, .save-btn, .my-account-btn, .preview-btn, .draft-btn, .back-btn").bind('mouseover mouseout',
            function() {
				if($(this).hasClass('save-btn')){
					$(this).toggleClass('save-btn-hover');
				}else if($(this).hasClass('my-account-btn')){
					$(this).toggleClass('my-account-btn-hover');
				}else if($(this).hasClass('preview-btn')){
					$(this).toggleClass('preview-btn-hover');
				}else if($(this).hasClass('draft-btn')){
					$(this).toggleClass('draft-btn-hover');
				}else if($(this).hasClass('back-btn')){
					$(this).toggleClass('back-btn-hover');
				}else{
					$(this).toggleClass('hover');
				}

            });

        }



        /* Flag Inappropriate Form Stuff */
        if($('#form_email_51907').length){
            $('#form_email_51907').attr('action',$('#form_email_51907').attr('action')+'&flag-inappropriate=true');
            $('#form_email_51907').validate({
                rules:{
                    "q51907:q4":{
                        required: true
                    }
                }
            });
        };



		/* Multiple locations search result format hide/show locations*/
		if($("ul.multi-map-location").length){
			$("ul.multi-map-location").hide();
			$(".search-result h4 a:contains('Multiple Locations +')").click(function(e){
				e.preventDefault();
				$(this).parents(".search-result").eq(0).find("ul.multi-map-location").eq(0).slideToggle();
			});
		}

        // Accessible Map
        var mapDiv = $("#map");
        if (mapDiv.length > 0) {
            var mapLocation = mapDiv.attr("class");
            var title = $("#body-copy h1:first");
            var contents = $(".contact-details dl");
            var address = $("address");
            var searchResults = $(".search-result");
			var multipleLoc = $(".multiple-loc .map-location")

			//resize map to be larger
			if (multipleLoc.size() > 5) {
				var heightMulti = (parseFloat(multipleLoc.size()) * 50) + 50
				mapDiv.css("height",heightMulti);
			}

            if (searchResults.length > 0) {
                title = null;
                contents = null;
            } else if (address.length > 0) {
				//replace the first <br /> with a % so we can split title from address
                address = address.html().replace(/<br \/>/i, "<br>").replace(/<br>/i, "%","i");

                if(address.indexOf("%") != -1){
					contents = address.substring(address.indexOf("%") + 1);
                	title = address.substring(0, address.indexOf("%"));
				}else{
					title = address;
					contents = "";
				}
            } else {
                title = title.html();
                if (contents.length == 0) {
                    contents = "";
                } else {
                    contents = "<dl>" + contents.html().replace(/\<br \/>/gi, ", ").replace(/<br>/gi, ", ") + "</dl>";
                }
            }

            if (mapLocation.indexOf(",") != -1) {
                var locationParts = mapLocation.split(",");
                if (locationParts.length == 2) {


					 // Initialise the map (if this is the search results page pass the title and contents as null as pins will be added later from the search results)
					//for ie6 workaround for map sometime cutting up due to floats being used. Add and remove float
					if($.browser.msie && $.browser.version < 7 && mapDiv.css("float")!="none"){
						mapDivFloat = mapDiv.css("float");
						mapDiv.css("float","none");
						ACCESSIBLE_GMAP.initMap("map", locationParts[0], locationParts[1], title, contents);
						mapDiv.css("float",mapDivFloat);
					}else{
						 // Initialise the map (if this is the search results page pass the title and contents as null as pins will be added later from the search results)
						ACCESSIBLE_GMAP.initMap("map", locationParts[0], locationParts[1], title, contents);
					}


                    // Add Markers for each search result
                    searchResults.each(function() {
						 var title = $("h3", this);

						//single location
						if($("ul.multi-map-location",this).length < 1){
	                        var pin = $(".map-location .map-pin", this);
	                        var contents = $(".map-location span", this);
	                        if (pin.length > 0 && title.length > 0 && contents.length > 0) {
	                            mapLocation = pin.find("abbr").attr("class");
	                            if (mapLocation.indexOf(",") != -1) {
	                                locationParts = mapLocation.split(",");
	                                if (locationParts.length == 2) {
	                                    ACCESSIBLE_GMAP.addMarker(pin.text(), locationParts[0], locationParts[1], title.html().replace(/<\/a> -/i, "</a><br />"), contents.text(), pin);
	                                }
	                            }
	                        }
						}else {
							//multiple location
							$("ul.multi-map-location li",this).each(function(){
								var pin = $(".map-pin", this);
		                        var contents = $("span", this);
		                        if (pin.length > 0 && title.length > 0 && contents.length > 0) {
		                            mapLocation = pin.find("abbr").attr("class");
		                            if (mapLocation.indexOf(",") != -1) {
		                                locationParts = mapLocation.split(",");
		                                if (locationParts.length == 2) {
		                                    ACCESSIBLE_GMAP.addMarker(pin.text(), locationParts[0], locationParts[1], title.html().replace(/<\/a> -/i, "</a><br />"), contents.text(), pin);
		                                }
		                            }
		                        }
							});
						}


                    });

					//Add markers for multiple locations

					multipleLoc.each(function() {
						var pin = $(".map-pin", this);
						var title = $("h1.result-heading");
						var contents = $("address", this);

						if($(".step3").length){
							title = $(".detail-title").next("div.opp-data").eq(0);
						}else if(title == ""){
							title = "Opportunity Location";
						}

						if (pin.length > 0 && title.length > 0 && contents.length > 0) {
							mapLocation = pin.find("abbr").attr("class");
							if (mapLocation.indexOf(",") != -1) {
								locationParts = mapLocation.split(",");
								if (locationParts.length == 2) {
									ACCESSIBLE_GMAP.addMarker($.trim(pin.text()), locationParts[0], locationParts[1], title.text(), contents.text(), pin);

								}
							}
						}
					});

                }
            }

            //add map-foot for opp-details page map
            $(".opp-result #map, .results-map #map ").before("<p class='map-tools x-small align-r'></p>");

            //== GET DIRECTIONS for google maps ===
            //do all html building here and page insertion here and send elements into funciton

            //insertion and html build for search page results map
            //create get directions link
            var gdLink = '<a href="#" id="get-directions">Get Directions</a>';

            //insert button
            $(".map-tools").prepend(gdLink);

            //create build directions panel
            var gdPanel = '<div id="gd-panel" class="section">' +
            '<form action="#">' +
            '<fieldset><legend>Get Directions</legend>' +
            '<div class="form-item">' +
            '<label for="from">From:</label>' +
            '<div class="custom-text"><input type="text" name="from" value="" class="d-from" /></div>' +
            '</div>' +
            '<div class="form-item">' +
            '<label for="to">To:</label>' +
            '<div class="dt-to"></div><input type="hidden" name="to" value="" class="d-to" />' +
            '</div>' +
            '<input type="button" name="submit-Directions" class="submit btn get-dir-btn" value="Get directions" />' +
            '<input type="button" name="clear-Directions" class="clear btn clear-btn" value="Clear" /></fieldset>' +
            '</form><p><a href="http://www.volunteer.vic.gov.au/help/get-directions-guide" target="_blank">Help</a></p>' +
            '<div id="directions-info"></div>'
            '</div>';
            //insert gdPanel
            $(".content-main > .col.one").append(gdPanel);

            useGetDirectionsOnMap({
                map: ACCESSIBLE_GMAP.map,
                gdLink: $("#get-directions"),
                gdPanel: $("#gd-panel"),
                to: $("#gd-panel .d-to"),
                from: $("#gd-panel .d-from"),
                submit: $("#gd-panel .submit"),
                clear: $("#gd-panel .clear"),
                gdInstr: document.getElementById("directions-info")//$("#gd-panel .directions-info")
            });

            //connect the pins

            //map pins outeside of google map to auto fill directions into to field

            //for search results page
            if($("#results-wrapper").length){
                var SRpins = $(".search-result");

                //default to first pin
                var toLoc = "";
                if ($.trim($(".map-location span", SRpins).eq(0).text()) !== "") {
                    toLoc = " in " + $(".map-location span", SRpins).eq(0).text();
                }
                $("#gd-panel .dt-to").text($("h3", SRpins).eq(0).text() + toLoc);
                $("#gd-panel .d-to").val($(".map-location a abbr", SRpins).attr("class"));

                if (SRpins !== null && SRpins.length) {
                    $(".map-location a.map-pin", SRpins).click(function(){
                        //get address
                        var toLoc = "";
                        if ($.trim($(this).next("span").eq(0).text()) !== "") {
                            toLoc = " in " + $(this).next("span").eq(0).text();
                        }
                        $("#gd-panel .dt-to").text($(this).parents(".search-result").eq(0).find("h3").text() + toLoc);
                        $("#gd-panel .d-to").val($(this).find("abbr").attr("class"));

                        //clear directions
                        $("#gd-panel .clear").trigger("click");
                    });
                }
            }

            if ($(".opp-result").length) {
                //for opp details page

                //single location
                if ($.trim($(".address-details address").eq(0).text()) !== "") {
                    toLoc = $(".address-details address").eq(0).text();
                }else if($(".multiple-loc").length){
                //multiple locations
                    toLoc = $(".map-location address").eq(0).text();
                }
                $("#gd-panel .dt-to").text(toLoc);
                $("#gd-panel .d-to").val($("#map").attr("class"));

                var ODpins = $(".multiple-loc .map-location");
                //multiple locations
                if (ODpins !== null && ODpins.length) {
                    $("a.map-pin", ODpins).click(function(){
                        //get address
                        var toLoc = "";
                        if ($.trim($(this).next("address").eq(0).text()) !== "") {
                            toLoc = $(this).next("address").eq(0).text();
                        }
                        $("#gd-panel .dt-to").text(toLoc);
                        $("#gd-panel .d-to").val($(this).find("abbr").attr("class"));

                        //clear directions
                        $("#gd-panel .clear").trigger("click");
                    });
                }
            }

            $('#directions-info').hyphenate();

            //auto moving get directions
            var navHeight = $(".col.one .navigation:first").offset().top + $(".col.one .navigation:first").height() - 10;
            var $scrollingDiv = $("#gd-panel");
            var scrollUpDown = $(window).scrollTop();

            $(window).scroll(function(){
                var footerTouch = $(".footer .asterisk:first").offset().top - 100;

                var docBottom = $(window).scrollTop() + $(window).height();
                var elemBottom = $scrollingDiv.offset().top + $scrollingDiv.outerHeight();

                if ((elemBottom < docBottom && footerTouch > elemBottom) || (scrollUpDown > $(window).scrollTop() && $scrollingDiv.offset().top > $(window).scrollTop()) ) {
                    $scrollingDiv.stop();

                    $scrollingDiv.animate({
                        "marginTop": Math.max(0, $(window).scrollTop() - navHeight) + "px"
                    }, "slow");
                }

                scrollUpDown = $(window).scrollTop();
            });

        } else {
            $("#results-wrapper .results-map").eq(0).hide();
        }


        // Rounded Corners on images
        /*$(".image.rounded").each(function(i) {
			var imgContainer = $(this);
			imgContainer.children("img").each(function() {
				var img = $(this);

				if (this.complete && img.width() > 0 && img.height() > 0) {
					imgContainer.css("background-image", "url(" + img.attr("src") + ")").css("width", img.width() + "px").css("height", img.height() + "px").css("padding",0);
					img.hide();
				} else {
					img.load(function() {
					imgContainer.css("background-image", "url(" + img.attr("src") + ")").css("width", img.width() + "px").css("height", img.height() + "px").css("padding",0);;
					img.hide();
				});
				}
			});
		});*/


        //Load the cylcle plugins once all images are loaded
        /*var images = $("img");
		var imagesLoaded = 0;
		var updateImagesLoaded = function() {
			imagesLoaded++;
			if (imagesLoaded == images.length) {*/
         	//Gallery for Information for Volunteers and Also Org Web Presence
			 $(".volunteer-stories-wrapper .items").cycle({
			            pager: '.volunteer-stories-wrapper .pagination .pages',
			            timeout: 0,
			            prev: '.volunteer-stories-wrapper .pagination .prev',
			            next: '.volunteer-stories-wrapper .pagination .next',
			            slideExpr: "> div"
			 });

        $(".photo-gallery .items").cycle({
            pager: '.photo-gallery .pagination .pages',
            timeout: 0,
            prev: '.photo-gallery .pagination .prev',
            next: '.photo-gallery .pagination .next',
            pagerAnchorBuilder: function(idx, slide) {
                return '.photo-gallery .pagination .pages a:eq(' + idx + ')';
            },
            slideExpr: "> div"
        });
        /*
			}
		}
		images.each(function(i) {
			if (this.complete) {
				updateImagesLoaded();
			} else {
				$(this).load(updateImagesLoaded).error(updateImagesLoaded);
			}
		});*/


        // Make the columns in the best practice toolkit the same height
        setBestPracticeToolkitBoxHeights();


		// Featured Organisation portlet truncation
		if($('.featured-org-overview').size() > 0){
			truncateFeaturedOrgDesc();
		}

        if ($("#featured-organisation-details").length > 0) {
            function forceRedraw(obj) {
                obj = $(obj);

                // force IE to redraw the obj
                if (jQuery.browser.msie) {
                    obj.css("display", "none");
                    obj.css("display", "block");
                }
            };
            var featuredOrgCurrentDiv = '#' + $('#featured-organisation-details li:first-child').attr('id');
            var liHeight = $('li' + featuredOrgCurrentDiv).show().css("height", "auto").outerHeight(true);
            $('#featured-organisation-details').css('height', liHeight);
            forceRedraw('#featured-organisation-details');


            $('#featured-organisation-key-wrapper').serialScroll({
                items: 'a',
                prev: '#featured-organisation-key-scroll-wrapper a.previous',
                next: '#featured-organisation-key-scroll-wrapper a.next',
                offset: 0,
                start: 0,
                duration: 200,
                force: true,
                stop: true,
                lock: false,
                cycle: true,
                easing: null,
                jump: false
            });

            $('#featured-organisation-key li a').click(function() {
                var featuredOrgDivId = $(this).attr('href');
                $('li' + featuredOrgDivId).fadeIn('fast');
                liHeight = $('li' + featuredOrgDivId).show().css("height", "auto").outerHeight(true);
                $('#featured-organisation-details').css('height', liHeight);
                forceRedraw('#featured-organisation-details');
                if (featuredOrgCurrentDiv == "") {
                    featuredOrgCurrentDiv = '#' + $('#featured-organisation-details li:first-child').attr('id');
                }
                if (featuredOrgDivId != featuredOrgCurrentDiv) {
                    $('li' + featuredOrgCurrentDiv).fadeOut('fast');
                }
                featuredOrgCurrentDiv = featuredOrgDivId;
                return false;
            });

            if ($('#featured-organisation-key').find('li').size() < 3) {
                $('#featured-organisation-key-scroll-wrapper a.previous').hide();
                $('#featured-organisation-key-scroll-wrapper a.next').hide();
            };
            if ($('#featured-organisation-key').find('li').size() < 2) {
                $('#featured-organisation-key-scroll-wrapper').hide();
            };
        };

		// Replace \; in interested in last minute listings
		$('#last-minute-opportunities span.opp-interests').each(function(i,val){
			$(val).text($(val).text().replace(/\_/g,' '));
			$(val).text($(val).text().replace(/\\;/g,';'));
		});

        // Split semi-colon separated values from Opportunity.Time.Availability (transform into table)
        if ($('#opportunity_time_availability').length > 0) {
            var timeAvail = $.trim($('#opportunity_time_availability').text()).split('\\; ');
            //create table
			var timeAvailTable = $("<table id='time_availability_table'>"+
					"<thead>"+
					"<tr>"+
					"<th class='first'></th>"+
					"<th>Morning</th>"+
					"<th>Afternoon</th>"+
					"<th class='last'>Evening</th>"+
					"</tr>"+
					"</thead>"+
					"<tbody>"+
					"<tr class='monday'>"+
					"<th>Monday</th>"+
					"<td class='morning'></td>"+
					"<td class='afternoon'></td>"+
					"<td class='last evening'></td>"+
					"</tr>"+
					"<tr class='tuesday'>"+
					"<th>Tuesday</th>"+
					"<td class='morning'></td>"+
					"<td class='afternoon'></td>"+
					"<td class='last evening'></td>"+
					"</tr>"+
					"<tr class='wednesday'>"+
					"<th>Wednesday</th>"+
					"<td class='morning'></td>"+
					"<td class='afternoon'></td>"+
					"<td class='last evening'></td>"+
					"</tr>"+
					"<tr class='thursday'>"+
					"<th>Thursday</th>"+
					"<td class='morning'></td>"+
					"<td class='afternoon'></td>"+
					"<td class='last evening'></td>"+
					"</tr>"+
					"<tr class='friday'>"+
					"<th>Friday</th>"+
					"<td class='morning'></td>"+
					"<td class='afternoon'></td>"+
					"<td class='last evening'></td>"+
					"</tr>"+
					"<tr class='saturday'>"+
					"<th>Saturday</th>"+
					"<td class='morning'></td>"+
					"<td class='afternoon'></td>"+
					"<td class='last evening'></td>"+
					"</tr>"+
					"<tr class='sunday'>"+
					"<th>Sunday</th>"+
					"<td class='morning'></td>"+
					"<td class='afternoon'></td>"+
					"<td class='last evening'></td>"+
					"</tr>"+
					"</tbody>"+
					"</table>");
			$(timeAvail).each( function() {
				var vs = this.toLowerCase().split(" ");
				var tp = "."+vs[0] + " ." + vs[1];
				$(tp, timeAvailTable).append('<div class="tick">available</div>');
			});

			$('#opportunity_time_availability').after(timeAvailTable)
            $('#opportunity_time_availability').remove();

        };


        // Split Opportunity.Location.Details
        if ($('.address-details ul.location-details li').length > 0) {
            var addressDetails = $('.address-details ul.location-details li').text();
            addressDetails = jQuery.trim(addressDetails);
            var objAddr = new Array();
            objAddr = addressDetails.split(';');

            $('.address-details ul.location-details li').hide();
            jQuery.each(objAddr,
            function() {
                $(".address-details ul.location-details").append('<li>' + this + '</li>');
            });
        };

        //split values for opportunties design
        splitMatrixValues($('p#opp-interests'));
        splitMatrixValues($('p#opp-skills'));
        splitMatrixValues($('p.audience-list'));
        splitMatrixValues($("#opp-audience"));
        splitMatrixValues($("#opp-age-range"));

        //onsubmit of Register a volunteer form
        $('form#page_asset_builder_49224 input[type=submit], form#page_asset_builder_85088 input[type=submit]').click(function(){
        	globalPopulateDate($("#metadata_field_text_85150_value"));
        });
        // Populate the email field when registering as a volunteer
		if($('form#page_asset_builder_2667 input, form#page_asset_builder_46242 input').size() > 0 || $('form#page_asset_builder_4867').size() > 0 || $('form#page_asset_builder_49224, form#page_asset_builder_85088').size() > 0){
			$("label[for='metadata_field_select_2027_SMS'").click(subscriptionSms);
			$("input#metadata_field_select_2027_SMS").click(subscriptionSms);
			$("label[for='metadata_field_select_2027_Email'").click(subscriptionEmail);
			$("input#metadata_field_select_2027_Email").click(subscriptionEmail);
			$("input#simple_edit_user_0_373").change(subscriptionEmail);
			$("input#simple_edit_user_0_373").blur(subscriptionEmail);
			//Remove this line when we add SMS
			$("label[for=email_subscription_options_281]").click(subscriptionEmail);
			$("label[for=email_subscription_options_282]").click(subscriptionEmail);
			$("label[for=email_subscription_options_283]").click(subscriptionEmail);
			$("input#email_subscription_options_281").click(subscriptionEmail);
			$("input#email_subscription_options_282").click(subscriptionEmail);
			$("input#email_subscription_options_283").click(subscriptionEmail);
		}else{
			$("input#simple_edit_user_0_367").change(setorgUsername);
			$("#sq_commit_button").click(setorgUsername);
		};

        // Add confirm password label to volunteer registration form
		if($('form#page_asset_builder_46242 input').size() > 0 || $('form#page_asset_builder_4867').size() > 0){
			if ($('input#simple_edit_user_0_371_two').parent('div.custom-text')) {
				$('input#simple_edit_user_0_371_two').parent('div.custom-text').before("<label for='simple_edit_user_0_371_two'>Confirm Password</label>");
			} else {
				$('input#simple_edit_user_0_371_two').before("<label for='simple_edit_user_0_371_two'>Confirm Password</label>");
			};
		};

        // Add confirm password label to add user account form
        /*if ($('input#simple_edit_user_0_371_two').parent('div.custom-text')) {
            $('input#simple_edit_user_0_371_two').parent('div.custom-text').before("<label for='simple_edit_user_0_371_two'>Confirm Password</label>");
        } else {
            $('input#simple_edit_user_0_371_two').before("<label for='simple_edit_user_0_371_two'>Confirm Password</label>");
        };*/

        // Link emergency checkboxs on volunteer registration form
        $('form#page_asset_builder_46242 input').change(function() {
            if ($(this).is('#metadata_field_select_5811_Emergency_and_Crisis:checked')) {
                $('#check-emergencies').attr('checked', true).trigger('updateState');
            } else if ($(this).is('#check-emergencies:checked')) {
                $('#metadata_field_select_5811_Emergency_and_Crisis').attr('checked', true).trigger('updateState');
            } else if ($(this).is('#metadata_field_select_5811_Emergency_and_Crisis')) {
                $('#check-emergencies').attr('checked', false).trigger('updateState');
            } else if ($(this).is('#check-emergencies')) {
                $('#metadata_field_select_5811_Emergency_and_Crisis').attr('checked', false).trigger('updateState');
            };
        });
		// If emergency is checked on page load, check second box.
		if ($('#metadata_field_select_5811_Emergency_and_Crisis:checked').size() > 0) {
			$('#check-emergencies').attr('checked', true).trigger('updateState');
		}

        // Link emergency checkboxs on volunteer edit account form
        $('div#edit-volunteer-account input').change(function() {
            if ($(this).is('#metadata_field_select_5811_Emergency_and_Crisis:checked')) {
                $('#check-emergencies').attr('checked', true).trigger('updateState');
            } else if ($(this).is('#check-emergencies:checked')) {
                $('#metadata_field_select_5811_Emergency_and_Crisis').attr('checked', true).trigger('updateState');
            } else if ($(this).is('#metadata_field_select_5811_Emergency_and_Crisis')) {
                $('#check-emergencies').attr('checked', false).trigger('updateState');
            } else if ($(this).is('#check-emergencies')) {
                $('#metadata_field_select_5811_Emergency_and_Crisis').attr('checked', false).trigger('updateState');
            };
        });


        // jQuery Form Validation Calls
        if ($('form#page_asset_builder_97229, form#page_asset_builder_46242, form#page_asset_builder_48510, form#page_asset_builder_4867, form#page_asset_builder_49224, form#page_asset_builder_85088').size() > 0 ) {
            validateVolunteerRegistration();
            $('input#simple_edit_user_0_367').parents('div.reg-form-email').css({
                'position': 'absolute',
                'left': '-999em'
            });
        };

        //EVR Conditional Hide/Show
		if ($('#edit-volunteer-account #main_form, form#page_asset_builder_97229').length ){    
			//if Availablity is Short term show avaiblity date field
			radioHideShow({
				input : $("input[name=metadata_field_select_85063]"), 
				elements : $(".availShortTerm"),
				value : "ShortTerm" });
			//Police check is true show field to enter id
			radioHideShow({
				input : $("input[name=metadata_field_select_46041]"), 
				elements : $(".policeYes"),
				value : "yes" });
			//Children working check is true show field to enter id
			radioHideShow({
				input : $("input[name=metadata_field_select_46042]"), 
				elements : $(".childrenYes"),
				value : "yes" });
			
			//Skills
			checkboxSelectedShow({
				input : $("#SpecialistFlag"), 
				elements : $(".specialistSkills")});

			//Tradesperson
			checkboxSelectedShow({
				input : $("input[name^=metadata_field_select_85047]"), 
				elements : $(".tradesHS")});
			//Driver
			checkboxSelectedShow({
				input : $("input[name^=metadata_field_select_85050]"), 
				elements : $(".driverHS")});
			//Heavy Equipment
			checkboxSelectedShow({
				input : $("input[name^=metadata_field_select_85052]"), 
				elements : $(".heavyEquipHS")});
			//Health Professional
			checkboxSelectedShow({
				input : $("input[name^=metadata_field_select_85054]"), 
				elements : $(".healthProfHS")});
			//Language
			checkboxSelectedShow({
				input : $("input[name^=metadata_field_select_85056]"), 
				elements : $(".langHS")});

			$("input[name^=metadata_field_select_85056]").click(function(){
				$("#metadata_field_text_85057_value").trigger("blur");
			})
			//if other lanugaged entered	
			$("#metadata_field_text_85057_value").blur(function(){
				if($(this).val() != ""){
					$(".langHS").show();
				}else if(!$("input[name^=metadata_field_select_85056]:checked").length){
					$(".langHS").hide();	
				}
			});
			
			//Other Skills
			checkboxSelectedShow({
				input : $("input[name^=metadata_field_select_85059]"), 
				elements : $(".otherSkillHS")});
		}//end evr condtional section

		if ($('form#page_asset_builder_35190, form#page_asset_builder_48510').size() > 0) {
            $('input#simple_edit_user_0_373').parents('div.reg-form-email').css({
                'position': 'absolute',
                'left': '-999em'
            });
		};
		if ($('div#edit-volunteer-account').size() > 0) {
            $('div.reg-form-email').css({
                'position': 'absolute',
                'left': '-999em'
            });
		};

	if($('ul.opps-list').size() > 0){
		$('ul.opps-list li').each(function(i,val){
			if(i==9){
				$('ul.opps-list').nextAll('p.hide').removeClass('hide');
			};
		});
	};

	//autocomplete for finding existing organisations
	/*if ($('input#q2253_q5').size() > 0) {
		orgData();
		allOrgNames = suggestionText.split(", ");
		$('input#q2253_q5').autocomplete(allOrgNames);
	}*/

	//show more comments link for volunteer stories
	$('#comments-wrapper div.comment-even').each(function(i, val){
		if(i==4){
			$('p.comments-count a').removeClass('hide');
		}
	});

    };

    //add js class

      $("body").addClass("js").removeClass("js-loading");
	  if ($.browser.msie &&$.browser.version == 7) {
           //fix for ie7
           $("#cof").addClass("clearfix");

          }
	//clear search form on load
    $('#find-opportunities input').each(function() {
    $(this).attr('checked', false);
		switch(this.type) {
		   case 'password':
		   case 'select-multiple':
		   case 'select-one':
		   case 'text':
		   case 'textarea':
			   $(this).val('');
			   break;
		   case 'checkbox':
		   case 'radio':
			  this.checked = false;
		}
	});

	$('#find-opportunities label').each(function() {
		$(this).removeClass('checked')
	});

	$('#surrounding-suburbs').attr('checked', true);
	$('#surrounding-suburbs').next("label").addClass("checked");


	if ($('.map-holder').size() > 0){
		if ($.browser.msie && $.browser.version < 9 ) {

			showAddress();

		}
	}


    // Blur the autopopulate fields after the spinner is gone so they populate correctly
    $('input.blank').blur();

});

// Redraw a cycle plugin on font resize
function redrawCyclePlugin(cycleElement) {
    var maxHeight = 0;
    var maxHeightInner = 0;

    if (cycleElement != undefined && cycleElement.length > 0) {
        var currSlide = cycleElement.children(":visible");
        cycleElement.children().each(function() {
            var thisHeight = $(this).show().css("height", "auto").outerHeight(true);
            if (thisHeight > maxHeight) {
                maxHeight = thisHeight;
                maxHeightInner = $(this).height();
            }
        });
        cycleElement.css("height", maxHeight + "px");
        cycleElement.children().each(function() {
            $(this).css("height", maxHeightInner + "px").hide();
            this.cycleH = maxHeightInner;
        });
        currSlide.show();
    }
}

function setBestPracticeToolkitBoxHeights() {
    var maxHeight = 0;
    var boxes = $(".best-practice-toolkit .content-box");

    boxes.each(function() {
        var boxHeight = $(this).css("height", "auto").height();
        if (boxHeight > maxHeight) maxHeight = boxHeight;
    });
    boxes.each(function() {
        $(this).css("height", maxHeight + "px");
    });
}

/*
 * Summary:	 Creates a checkbox drop down list
 * Parameters:   takes jquery object elements to run on
 * Return:
 */
function createCheckboxDropDown(elements) {
    elements.each(function(f) {
        var currentElement = this;
        //hide the list of checkboxes
        if ($.browser.msie && $.browser.version < 7) {
            $(currentElement).find(".checkbox-options-box").css("display", "none");
        } else {
            $(currentElement).find(".checkbox-options-box").css({
                "opacity": 0,
                "display": "none"
            });
        }
        //append drop down under different circumstances
        if ($('#volunteer-reg-form').size() > 0 || $('#edit-volunteer-account').size() > 0) {
            if ($(currentElement).attr("id") == "Interests") {
                $("label#select-interests", this).after('<div class="drop-down" id="drop-down-interests">Select interest(s)</div>');
            } else if ($(currentElement).attr("id") == "Skills") {
                $("label#select-skills", this).after('<div class="drop-down" id="drop-down-skills">Select skill(s)</div>');
            } else {
                $("label#please-select, label.please-select", this).after('<div class="drop-down">Please Select</div>');
            }
        } else {
            if ($(currentElement).attr("id") == "Interests") {
                $("legend", this).after('<div class="drop-down" id="drop-down-interests">Select interest(s)</div>');
            } else if ($(currentElement).attr("id") == "Skills") {
                $("legend", this).after('<div class="drop-down" id="drop-down-skills">Select skill(s)</div>');
            } else {
                $("legend", this).after('<div class="drop-down">Please Select</div>');
            }
        }
        if(!$(currentElement).hasClass("noCheckAll")){
	        //add in tools for select all and ok button
	        $(".checkbox-options-box", currentElement).prepend('<div class="check-all"><input type="checkbox" value="Check all" name="IS_check_all'+f+'_name" id="IS_check_all'+f+'"/><label for="IS_check_all'+f+'"><strong>Select all/Clear all</strong></label></div>');
	        $('.check-all input',currentElement).customInput();
	        checkboxSelectAll($(".check-all input", currentElement), $(".checkbox-options-box input", currentElement));
	    }

		$(".checkbox-options-box", currentElement).append('<a href="#" class="ok-btn btn">Select</a>');
        //close box on clicking ok button
        $(".ok-btn", currentElement).click(function(e) {
            e.preventDefault();
            $(".drop-down", currentElement).trigger("click");
        });

        var clickTimer = 0;
        //open and close on drop down click
        $(".drop-down", currentElement).click(function() {
            var box = $(this);

            //delay click event to stop people breaking with rapidClick
           var runDropDownClick = function() {

				$(currentElement).removeClass("dropDownIsOpen");

                //get a reference to any currently open boxes
                var currentOpen = $(".dropDownIsOpen");
                //set this base element to open or closed as reference tool

                //close all other drop down boxes on page
                if (currentOpen.size() > 0) {
                    currentOpen.removeClass("dropDownIsOpen");
                    //find the current box that is open
                    openCloseDropDown(currentOpen.find(".drop-down"), $(""), currentOpen);
                }

                //set this box as tob opened or closed
                var dropdown = $(".checkbox-options-box", currentElement);
                openCloseDropDown(box, dropdown, currentElement);

				//make sure options are checked for ie6
				 if ($.browser.msie && $.browser.version < 7) {
					 $("label.checked").prev("input").attr("checked","checked");
				 }

           }
           clearTimeout(clickTimer);
           clickTimer = setTimeout(runDropDownClick, 200);
        });
		 if ($.browser.msie) {
		 }else{
		//close if user clicks outside of page
		var all= $("*").not(".checkbox-options-box, .drop-down, #absolute-saviour");
		var remove= $("*", ".checkbox-options-box");

		all = all.not(remove);
		all.click(function(){

			//get a reference to any currently open boxes
                var currentOpen = $(".dropDownIsOpen");
                //set this base element to open or closed as reference tool

                //close all other drop down boxes on page
                if (currentOpen.size() > 0) {
                    currentOpen.removeClass("dropDownIsOpen");
                    //find the current box that is open
                    openCloseDropDown(currentOpen.find(".drop-down"), $(""), currentOpen);
                }
		});

		$("#absolute-saviour, .drop-down").click(function(e){
			e.stopPropagation();
		});
		}

        $(window).resize(function(e) {
            var box = $(".drop-down", currentElement);
            //offset to position
            $("#absolute-saviour .checkbox-options-box").css("left", box.offset().left);
            $("#absolute-saviour .checkbox-options-box").css("top", box.offset().top + 26);
        });


        $(currentElement).parents("form").submit(function(e) {
            if ($(".checkbox-options-box", currentElement).size() < 1) {
                e.preventDefault();
                $(".drop-down", currentElement).trigger("click");
                function checkDropDownExist() {
					$("label.checked").prev("input").attr("checked","checked");
                    if ($(".checkbox-options-box", currentElement).size() > 0) {
                        $(currentElement).parents("form").submit();
                    } else {
                        setTimeout(checkDropDownExist, 100);
                    }
                }
                checkDropDownExist();
            }else{
		$("label.checked").prev("input").attr("checked","checked");
	    }
        });

    });

}
/**
 *
 * @param {Object} input: Input for checking all/clearing all checkboxes
 * @param {Object} elements: Checkbox elements to check/uncheck
 */
function checkboxSelectAll(input,elements){
	input.click(function(){
		if(input.is(":checked")){
			elements.attr("checked", "checked");
			elements.trigger('updateState');
		}else {
			elements.removeAttr("checked");
			elements.trigger('updateState');
		}
	});
}

/*
 * Summary:	 Creates a default value for text fields
 * Parameters:   element: jquery object elements to run on, text: the default text to be used
 */
function createDefaultText(element, text) {
	$(element).val(text);
    //clear default value if still default
    $(element).focus(function() {
        if ($(this).val() == text || $(this).val() == "") {
            $(this).val("").removeClass("blank");
        }
    });
    //put default value back in if left blank
    $(element).blur(function() {
        if ($(this).val() == "") {
            $(this).val(text).addClass("blank");
        }
    });

    $(element).parents("form").eq(0).submit(function() {
        if ($(element).val() == text) {
            $(element).val("").removeClass("blank");
        }
    });
    if ($(element).val() == text) {
		$(element).addClass("blank");
	}else{
		$(element).removeClass("blank");

	}
}

/*
 * Summary:	 moves toolip out of page before show
 * Parameters:
 */
function ttBeforeShow() {
    this.getTooltip().appendTo("#absolute-saviour");
}

// Volunteer registration subscription type
function subscriptionSms() {
    var smsSubscription = $('input#metadata_field_text_2026_value').attr("value") + "@sms.messagemedia.com.au";
    $('input#simple_edit_user_0_367').attr('value', smsSubscription);
};
function subscriptionEmail() {
    var emailSubscription = $('input#simple_edit_user_0_373').attr("value");
    $('input#simple_edit_user_0_367').attr('value', emailSubscription);
};

//Set username as email - Organisation Form Step 1
function setorgUsername() {
    var orgEmail = $('input#simple_edit_user_0_367').attr("value");
    $('input#simple_edit_user_0_373').attr('value', orgEmail);
};


/*
 * Summary:	 popluates the drop down box if text from inputs or back to defaults
 * Parameters:
 */
function populateInterestsField(currentElement) {
    var dropLabelText = "";

    $("#absolute-saviour li input:checked").each(function() {
        dropLabelText += $(this).next("label").text() + ", ";

		var reginald = /^\,\ /
        if (dropLabelText.length > 18) {
            dropLabelText = dropLabelText.substr(0, 18) + "...";
			if(dropLabelText.match(reginald)){
				dropLabelText = dropLabelText.substr(2, 21);
			}
            return false;
        }

    });

    if (dropLabelText.length < 1) {
        if ($(currentElement).attr("id") == "Interests") {
            dropLabelText = "Select interest(s)";
            $('fieldset#Interests span.error').show();
        } else if ($(currentElement).attr("id") == "Skills") {
            dropLabelText = "Select skill(s)";
            $('fieldset#Skills span.error').show();
        }
    }else{
        if ($(currentElement).attr("id") == "Interests") {
            $('fieldset#Interests span.error').hide();
        } else if ($(currentElement).attr("id") == "Skills") {
            $('fieldset#Skills span.error').hide();
        }

	}

    $(currentElement).find(".drop-down").html(dropLabelText);
}

/*
 * Summary:	 opens and closes the drop down box
 * Parameters:
 */
function openCloseDropDown(box, dropdown, currentElement) {
    //dropdown.toggleClass("openThis");

    //open and close box
    if (dropdown.size() >0) {
       $(currentElement).addClass("dropDownIsOpen");

	   //move this to aboslute saviour box
	 	box.nextAll(".checkbox-options-box").appendTo("#absolute-saviour");


        dropdown.css("display", "block");

        //position next to drop down div
        dropdown.css("left", box.offset().left);
        dropdown.css("top", box.offset().top + 26);

        if ($.browser.msie && $.browser.version < 7) {
            } else {
            dropdown.stop(true, false);
            dropdown.animate({
                opacity: 1
            },
            'slow');
        }

    } else {
		var dropdown =$("#absolute-saviour .checkbox-options-box");
        populateInterestsField(currentElement);
        if ($.browser.msie && $.browser.version < 7) {
			dropdown.hide();

			box.after(dropdown);
        } else {
            dropdown.stop(true, false);
            dropdown.animate({
                opacity: 0
            },
            'slow',
            function() {
                dropdown.css("display", "none");
                box.after(dropdown);
            });
        }
    }
}

/*
 * Summary:	 counts words in featured organisations description and truncates if necessary
 * Parameters:
 */
function truncateFeaturedOrgDesc(){
	$('.featured-org-overview').each(function(ind,val){
		var $counter = new Array;
		$counter = $(this).text().split(" ");
		$(this).after("<span class='featured-org-truncated' id='featDesc"+ind+"'></span>");
		$.each($counter,function(index,value){
			if(index < 50){
				$("#featDesc"+ind).append(value+" ");
			}
		});
		$("#featDesc"+ind).append("...");
		$(this).hide();
	})
}

/*
 * Summary:	 split checkbox matrix values
 * Parameters:	takes a jquery object containing the string to split and restyle
 */
function splitMatrixValues(element){
	var string = jQuery.trim(element.text().replace(/\\\;/g,"</li><li>"));
       	element.hide();
	element.after("<ul><li>"+string+"</li></ul>");
        element.remove();
}

/*
 * Used fo creating the get directions boxes and map get directions on map
 * @param {Object} options
 */
function useGetDirectionsOnMap(options){
	var settings = {
		map		:	null,//map div
		gdLink	: 	null,//anchor that show/hides get directions box
		gdPanel	: 	null,//the get directions box
		to		: 	null,//to directions form field
		from	: 	null,//from directions form field
		submit	: 	null,//submit input for firing the get directions to google
		clear	: 	null,//submit input for clearing the directions on map
		gdInstr	: 	null//Div to insert map textual directions. Needs to be document.getElementById("id") does not take a jquery object
	}

	if ( options ) {
		$.extend( settings, options );
	}

	if (settings.map !== null && settings.gdLink !== null && settings.gdLink.length && settings.gdPanel !== null && settings.gdPanel.length && settings.submit !== null) {
		//on click of get directions link hide/show directions panel
		settings.gdPanel.hide();
		settings.gdLink.click(function(e){
			e.preventDefault();
			settings.gdPanel.slideToggle();
		});

		var directions = new GDirections(settings.map, settings.gdInstr);

		// === Array for decoding the failure codes ===
		var reasons=[];
		reasons[G_GEO_SUCCESS]				= "Success";
		reasons[G_GEO_MISSING_ADDRESS]		= "Missing Address: The address was either missing or had no value.";
		reasons[G_GEO_UNKNOWN_ADDRESS]		= "please try again with more details in the from field. Entering a postcode will deliver the most accurate results";//Unknown Address:  No corresponding geographic location could be found for the specified address.
		reasons[G_GEO_UNAVAILABLE_ADDRESS]	= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
		reasons[G_GEO_BAD_KEY]				= "Get directions serice is currently down";//Bad Key: The API key is either invalid or does not match the domain for which it was given
		reasons[G_GEO_TOO_MANY_QUERIES]		= "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
		reasons[G_GEO_SERVER_ERROR]			= "Server error: The geocoding request could not be successfully processed.";
		reasons[G_GEO_BAD_REQUEST]			= "A directions request could not be successfully parsed.";
		reasons[G_GEO_MISSING_QUERY]		= "No query was specified in the input.";
		reasons[G_GEO_UNKNOWN_DIRECTIONS]	= "Cannot not compute directions between the points provided.";

		// === catch Directions errors ===
		GEvent.addListener(directions, "error", function() {
			var code = directions.getStatus().code;
			var reason="Code "+code;
			if (reasons[code]) {
				reason = reasons[code]
			}
			settings.gdPanel.prepend("<div class='errors'>Failed to obtain directions, "+reason+"</div>");
		});

		//fix to what google prints out in the directions summary so it does not display unknown road
		GEvent.addListener(directions, "addoverlay", function() {
			$("#gd-panel td:contains('Unknown road')").html(settings.to.prev("div.dt-to").text());
		});

		//display directions after click of btn
		settings.submit.click(function(){
			//get directions from and to && load directions on map
			var from = settings.from.val();

			//confined directions to only within australia
			if(from.search(/australia|aus|au/i) < 0){
				from += ", Australia";
			}

			if(settings.to !== null && settings.to.length && settings.from !== null && settings.from.length){
				directions.load("from: " + from +" to: " + settings.to.val());

			}else{
				directions.clear();
			}
			$(".errors", settings.gdPanel).remove();


		});

		//clear get directions on click of btn
		if(settings.clear !== null && settings.clear.length){
			settings.clear.click(function(){
				directions.clear();
				$(".errors", settings.gdPanel).remove();
			});
		}

		//block from submit from ever happening
		settings.gdPanel.find("form:first").submit(function(e){
			e.preventDefault();
		});

	}
}

/*for putting date fields ready for matrix metadata date fields, takes a jquery object of the input as param*/ 
function globalPopulateDate(element){
	 var parent = element.parents('div.form-item, fieldset.form-item').eq(0);  
     if(element.val() != null){ 
		if(element.val() != ""){
			  var date = element.val().split("/"); 
			  parent.find("input:hidden").eq(1).val(date[0]); 
			  parent.find("input:hidden").eq(2).val(date[1]); 
			  parent.find("input:hidden").eq(3).val(date[2]); 
		 } else {
			  parent.find("input:hidden").eq(1).val("01"); 
			  parent.find("input:hidden").eq(2).val("01"); 
			  parent.find("input:hidden").eq(3).val("1970"); 
		 }
	 }
}

//Hides/Shows content depending whether a checkbox value is selected within a group
	//inputs - jquery elment of all checkbox inputs with the same name
	//elements - jquery element of all objects to hide/show
	//value - string to check for to hide/show
	var checkboxSelectedShow = function(options){
		
		var check = function(input){
			if(input.length){
				options.elements.show();
			}else {
				options.elements.hide();
			}
		}

		check(options.input.filter(":checked"));

		options.input.click(function(){
			check(options.input.filter(":checked"));
		});	
	}

//Hides/shows content depending on radio value selected
	//inputs - jquery elment of all checkbox inputs with the same name
	//elements - jquery element of all objects to hide/show
	//value - string to check for to hide/show
	var radioHideShow = function(options){
		
		var check = function(input){
			if(input.val() == options.value ){
				options.elements.show();
			}else {
				options.elements.hide();
			}
		}

		check(options.input.filter(":checked"));

		options.input.click(function(){
			check($(this));
		});	
	}

