jQuery().ready(function(){

	$("#email22, #email23").hide(); // simple s p a m  protection
    
    $('#header_nav_map_lawyers, #header_nav_map_public, #choose_your_state, .select_state').click(function(){
        // Reset session state selection...
        $.get(foolkit_root+"/foolkit.ajax.php", {ajax:'reset_session_id', id:'current_state'}, function(group){
            $.cookie('foolkit_state', null, {path:'/'});
            window.location.href = foolkit_root + '/';
        });
        return false;
    });
    $("#state").change(function() {
		var cookie_state = 'foolkit_state',
            cookie_group = 'foolkit_group',
            state = $(this).val();
        
        // Reset session state selection...
        $.get(foolkit_root+"/foolkit.ajax.php", {ajax:'reset_session_id', id:'current_state'}, function(group){
            if (state=='') {
                $.cookie(cookie_state, null, {path:'/'});
                group = '';
            }
            else {
                $.cookie(cookie_state, state, {path:'/',expires:30});
                $.cookie(cookie_group, group, {path:'/',expires:30});
                group = '/'+group;
            }
            window.location.href = foolkit_root + '/' + state + group;
        });
    });

    $('.list5:not("#student-unis")').accordion({
		header: 'dt',
		active: false,
		alwaysOpen: false,
		animated: false,
		autoheight: false
    });

    $('#flt').accordion({
		header: 'div#flt-switch',
		active: false,
		alwaysOpen: false,
		animated: false,
		autoheight: false
	});


    $('.mainpage #flt').activate(0);
    $('.mainpage #flt-switch').toggleClass("flt-switch-up");
	$('.flt-sec').css('display', 'block');
	$('#flt-switch').click(function(){
		$(this).toggleClass("flt-switch-up");
	});
	// Melbourne Cup Hack
    $('.sitepage #flt').activate(0);
    $('.sitepage #flt-switch').toggleClass("flt-switch-up");


	$("#leg-form-flt").find('.select-act-state').hide();
	$("#leg-form-flt input[name='leg-type']").click(function() {
		var leg_type = $("#leg-form-flt input[name='leg-type']:checked").val();
		switch (leg_type) {
			case "federal": 
                $("#leg-form-flt").find('.select-act-state').hide();
				$("#leg-form-flt").find('.select-act-federal').show();
				break;
			case "state":
				$("#leg-form-flt").find('.select-act-federal').hide();
				$("#leg-form-flt").find('.select-act-state').show();
				break;
		}
	});
    
	$('#leg-form-flt, #leg-form-state, #leg-form-federal, #reg-form-state, #reg-form-federal').submit(function() {

		var url = "",
		    id = "",
		    sec = $.trim($(this).find('.input-sec').val().toLowerCase()),
		    sch = $.trim($(this).find('.input-sch').val().toLowerCase()),
            form_id = $(this).attr('id');
		
		if (form_id == 'leg-form-flt') {
            switch ($("#leg-form-flt input[name='leg-type']:checked").val()) {
			    case "federal":   id = $(this).find('.select-act-federal').val(); break;
			    case "state": id = $(this).find('.select-act-state').val(); break
		    }
        }
        else if (form_id == 'leg-form-state') id = $(this).find('.select-act-state').val();
        else if (form_id == 'leg-form-federal') id = $(this).find('.select-act-federal').val();
        else if (form_id == 'reg-form-state') id = $(this).find('.select-reg-state').val();
        else if (form_id == 'reg-form-federal') id = $(this).find('.select-reg-federal').val();
        
        if (!id) alert('Please make a selection first...');
        else {
            // get URL from DB based on snippet name
            $.get(foolkit_root+"/foolkit.ajax.php", {ajax:'get_austlii_url', id:id}, function(url){
                if (sec) url += "s"+sec+".html";
                else if (sch)  url += "sch"+sch+".html";

                //alert(url);
                //window.location.href = url;
                //var newwin = open(url, "legislation");
                var newwin = window.open(url, "legislation", 'width=1000,height=600,toolbar=yes, location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes, resizable=yes');
                if (window.focus) newwin.focus();
            });
        }
                        
		return false;
	});
	
	
	$('#calculator').click(function(){
		var calc = window.open($(this).attr('href'), "calculator", 'width=200,height=360,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no, resizable=yes');
		if (window.focus) calc.focus();
		return false;
	});
	
	$('#foolkit-intro').click(function(){
		var newwin = window.open($(this).attr('href'), "foolkittour", 'width='+screen.width+',height='+screen.height+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no, resizable=yes');
		if (window.focus) newwin.focus();
		return false;
	});
	
	$('#digplayer').click(function(){
		var calc = window.open($(this).attr('href'), "digplayer", 'width=600,height=260,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no, resizable=no');
		if (window.focus) calc.focus();
		return false;
	});
	
	var options = { 
        target:			'#contactus-response',
        beforeSubmit:	emailValidate,
        resetForm:		true
    }; 
    $('#contactus-form').ajaxForm(options);
	
	var thoughts = $('#thoughts-form');
	if (thoughts.length) {
		var options = { 
	        target:			'#thoughts-response',
	        beforeSubmit:	emailValidate,
	        resetForm:		true
	    }; 
	    thoughts.ajaxForm(options); 
	
	    $('#screen-size').val(screen.width+'x'+screen.height);
	    $('#window-size').val($(window).width() +'x'+ $(window).height());
	}

        var newsletter = $('#newsletter-form');
	if (newsletter.length) {
		var options = {
	        beforeSubmit:	emailValidate,
	        resetForm:		true,
                success:    function() {
                    alert('Thanks for subscribing');
                }
	    };
	    newsletter.ajaxForm(options);

	    $('#screen-size').val(screen.width+'x'+screen.height);
	    $('#window-size').val($(window).width() +'x'+ $(window).height());
	}
	
	/*/ On every page:
	var vSearch  = "Search Foolkit";
	$('#sq').val(vSearch);
    $('#sq').click(function () {if ($(this).val()==vSearch) $(this).val("").css({ color:"#000000" });});
    $('#sq').blur(function () {if ($(this).val()=="") $(this).val(vSearch).css({ color:"#666666" });});
    $('#ss').click(function () {if ($('#sq').val()==vSearch) $('#sq').val("");});
    */
   $('#search-form').submit(function () {
		$('#sq').val(addslashes($('#sq').val()));
		return true;
	});
	
	$("a[href^='http://']").attr('target', '_blank');

	// Create the index box. Make sure this is done after the above call to set target=_blank, otherwise in IE index links also get the _blank treatment...
	var otpl = $('#onthispage-links');
	if (otpl.length) {
		var h2s = [];
		var id = '';
		$(".subpage div[class ^= 'sec'] h2[id != 'improve']").each(function (i) {
			id = 'h2'+i;
			h2s[i] = [$(this).html(), id];
			$(this).before("<a id='"+id+"' class='onthispagelink' name='"+id+"'></a>");
		});
		h2s.sort();
		var txt = '';
		for (var i = 0; i < h2s.length; i++) {
			if (h2s[i][0].indexOf('egislation')>=0) txt = '<strong>'+h2s[i][0]+'</strong>';
			else txt = h2s[i][0];
			id = h2s[i][1];

                        if (i==0) {
                            $('#onthispage-links').append(' <a id="a'+id+'" class="onthispage-first" href="#'+id+'">'+ txt +'</a>');
                        }
                        else {
                            $('#onthispage-links').append(' &bull; <a id="a'+id+'" href="#'+id+'">'+ txt +'</a>');
                        }

			
                        $('#a'+id).click(function(){
                            $('html, body').animate({
                                scrollTop: $('#'+this.id.substr(1)+' + h2').offset().top
                            },1000);

                            //$('#'+this.id.substr(1)+' + h2').fadeTo(500, 1).animate({opacity: 0.2}, 1000).animate({opacity: 1}, 1000);

                            $('#'+this.id.substr(1)+' + h2').fadeTo(500, 1).animate({opacity: 0.2, fontSize:"18px"}, 1000).animate({opacity: 1, fontSize:"16px"}, 1000);
                        });
		}
	}
	
	$("a[href^='http://legislation.sa.gov.au']").addClass("tip").attr('title', 'South Australian Legislation');
	$("a[href^='http://www.courts.sa.gov.au']").addClass("tip").attr('title', 'Courts Administration Authority of South Australia');

	toolTip.init();
	
	$('#makehomepage').click(function(){
		var oBtn = document.getElementById("makehomepage");
		if(oBtn.addBehavior) {
			oBtn.style.behavior='url(#default#homepage)';
			//oBtn.setHomePage('http://www.foolkit.com.au/sa/lawyers');
			oBtn.setHomePage(location.href);
			return false;
		}
		return true;
	});
	
	showLocalTime();
	setInterval("showLocalTime()", 60000);
    
    if ($.isFunction($.fn.nifty)) $('#tooltips').nifty("bottom");
    $('#tooltips').bind("mouseenter",function(){
        $(this).addClass('hover');
    }).bind("mouseleave",function(){
        $(this).removeClass('hover');
    });
    
    // Slideshow code... only run if there are 'slidecontent' on the page:
    if ($('.slidecontent').length) {
        var slideW = 620,
            timeout = 15000, // 15 secs
            tid = 0; // timeout id

        $("#slideshow div.slide").each(function (i) {
            this.style.left = i*slideW+'px';
            //$(this).css({left:i*slideW+'px'});
        });
              
        currentSlide = 0;
        numberSlides = $('#slideshow div.slide').length;
        
        numberSlides--; // making the numbers work!
        
        function slideTo(slideNumber) {
            currentSlide = slideNumber;
            animeDur = 1000; // 1 sec
            if(currentSlide>numberSlides) {
                currentSlide = 0;
                slideNumber = 0;
                //TBD $('#slideshow div.slidecontent').animate({opacity: 0, filter: 'alpha(opacity=0)'},1000).css({left:'0px'}).animate({opacity: 1, filter: 'alpha(opacity=100)'},{duration:500,complete:bannerLoop});
                
                //  Uncomment this to make the slide jump instead of slide back...
                //animeDur = 0;
            }
            $('#slideshow div.slidecontent').animate({left: '-'+(slideNumber*slideW)+'px'},{duration:animeDur,complete:bannerLoop} );
        }
        
        holdIt = false;
        slideIt = false;
        $('#slideshow').click(function(e){
            var a = $(e.target).parents('a');
            if(a.length == 0) { // skip to next slide only if a link wasn't clicked
                slideIt = true;
                bannerLoop2();
            }
        }).bind("mouseenter",function(){
            holdIt = true;
        }).bind("mouseleave",function(){
            holdIt = false;
            if (slideIt) bannerLoop2();
        });
        
        function bannerLoop() {
            clearTimeout(tid);
            tid = setTimeout(bannerLoop2, timeout);
        }
        function bannerLoop2() {
            if (holdIt && !slideIt) slideIt = true;
            else {
                slideTo(currentSlide+1);
                slideIt = false;
            }
        }
        slideTo(0);
        $("#slideshow div.slide").show();
    }
	
	//searchTextOpt('sv','Enter words, numbers or address ...');
        $.fn.replaceholder({
            focusColor:'#000',
            blurColor:'#999'
        });
	
	//add a scroll to top link to every h2 element.
	$("#wrapper h2, *[class^=sec] h2").after("<span class='tothetop'><a>Top</a></span>");
	$('span.tothetop').click(function() {
		if($(window).scrollTop() > 0) {
			$("html, body").animate({scrollTop:"0px"},1000);
		}
	});
    
});

function addslashes (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Oskar Larsson Högfeldt (http://oskar-lh.name/)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
 
    return (str+'').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

function hideDisclaimer2() {
    $('p#disclaimer, p#disclaimer2').hide();
if ($("#col2").height() > $("#homepage-lawyers").height()) {
    $('p#disclaimer').show();
}

else {
        $('p#disclaimer2').show();
}
alert('ran');
}

function hideDisclaimer3() {
    $('#legalspacer').css('height', 0);
    spacer = $("#col2").height() - $("#homepage-lawyers").height() - $("#disclaimer").height() - 40;
    $('#disclaimer p').css('margin-bottom', 0);
    if (spacer < 0) {
        $('#disclaimer p').css('margin-bottom', 10);
    }
    //alert(spacer);
    $('#legalspacer').css('height', spacer);
    $('#disclaimer').show();
}


function showLocalTime() {
	var currentTime = new Date();
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();
    var ampm = 'am';
	var t = '';
	if (minutes < 10) minutes = "0" + minutes;
    if(hours > 11) ampm = 'pm';
    if(hours > 12) hours = hours - 12;
	if(hours == 0) hours = 12;
    t = hours + ":" + minutes + ampm;
	$("#local-time").text(t+' - ');
};

function updatePageTitle(str) {
	$(".title").html(str);
};

function emailValidate(formData, jqForm, options) { 
    //$('#thoughts-text').val($.param(formData));
    var form = jqForm[0]; 
    var emailfilter = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
    var validemail = emailfilter.test(form.email.value);
    if (validemail == false) {
        alert("Please enter a valid email address.");
        return false;
    }
    return true; 
};

function showLinks() {
    /* ver 1
    loc=location.href;
    x=document.getElementById("container").getElementsByTagName('A');
    y=window.open();
    y.document.write('<html><head><title>Links!<title></head><body><h3>Links from '+loc+'</h3>');
    for(n=0;n<x.length;n++){
        if(x[n].href!="") 
            y.document.write('<p>Text: '+x[n].text+'<br>\nURL: '+x[n].href+' <a href="'+x[n].href+'">Go!</a></p>\n');
    }
    y.document.write('</body></html>');
    y.document.close();
    */
    
    /* ver 2
    loc=location.href;
    x=document.getElementById("container").getElementsByTagName("A");
    y=window.open();
    y.document.write("<html><head><title>Links<title></head><body>\n<h3>Links from "+loc+"</h3>\n");
    for(n=0;n<x.length;n++){
        if(x[n].href!="") {
            y.document.write("<p>"+(n+1)+". ");
            if(x[n].text.replace(/\s+/,"").length<1) {
                for(j=0;j<x[n].childNodes.length;j++) {
                    if(x[n].childNodes[j].nodeName=="IMG"){
                        y.document.write("<img src=\""+x[n].childNodes[j].src+"\" alt=\""+x[n].childNodes[j].alt+"\">"); 
                        break;
                    }
                }
            }
            else y.document.write(x[n].text);
            
            y.document.write(" - "+x[n].href+" <a href=\""+x[n].href+"\">&raquo;</a></p>\n");
        }
    }
    y.document.write("</body></html>");
    y.document.close();
    return false;
    */
    
    var id;
    $("a.auto").each(function (i) {
        id = $(this).attr("rel");
        if (id) $(this).before('<a target="links" class="link-id" href="?links='+id+'">&nbsp;'+id+'&nbsp;</a>&nbsp;');
    });
    
};

//auto fill and clear text from the FLT search
function searchTextOpt(inField,inText) {
	var searchBox = $("input[name="+inField+"]");
	var searchText = inText;
	searchBox.focus(function(){
		if ($(this).val() == searchText) $(this).val('');
	});
	searchBox.blur(function(){
		if($(this).val() == "") $(this).val(searchText);
	});
};

$.fn.replaceholder = function(options) {

		var $placeholder;

		(this.length > 0) ? $this = $(this) : $this = $('input[placeholder]');

		return $this.each(function() {

			settings = jQuery.extend({
				focusColor: '#000',
				blurColor: '#aaa'
			}, options);

			var $placeholder = $(this);

			if ($placeholder.length > 0) {

				var attrPh = $placeholder.attr('placeholder');

				$placeholder.attr('value', attrPh).css('color',settings.blurColor)
				  .bind('focus', function() {

					var $this = $(this);

					if($this.val() === attrPh)
						$this.val('').css('color',settings.focusColor);

				}).bind('blur', function() {

					var $this = $(this);

					if($this.val() === '')
						$this.val(attrPh).css('color',settings.blurColor);

				});

			}

		});

	};
        

// To prevent issues when Firebug is not installed...
if(typeof console === "undefined") {
    console = { log: function() { } };
}

