$(document).ready(function() {
    insertNewWindowLinks();
    tab_init();
});




/* Tabs ------------------------------------------------ */

var tabSections;

function tab_init() {
	//Hide the sections, set the height, overflow:scroll and hide their h1s
	tabSections = $('.jstabs .panel');
		
	//Show the tab controls
	tabControls = $('.jstabs .tabcontrols');
	 
	tabAs = $('li a', tabControls);

	tabAs.each(function(element) {
		$(this).attr("href", "javascript:void(0);");
	});
	
	/* Go gadget Tabs! */
	tabAs.click(function(element) {
		//Hide all the tabs
		tabSections.each(function(element) {
			$(this).css('display', 'none');
		});
		
		tabAs.each(function(element) {
			$(this).removeClass("highlight");
		});
		
		$(this).addClass("highlight");

		//Show the relevant one
		this.myTitle = $(this).attr('name');
		this.theDiv = $('#'+this.myTitle);
		this.theDiv.css('display', 'block');
		
	});
	
	//Start with the 1st one
	$(tabAs[0]).trigger('click');
}




/* External links ------------------------------------------------ */

//Tests whether 'link' begins with http://(www.)domain. Needn't pass the www., or the .com or .org (though these will narrow the match down).
function linkIsToDomain(link, domain) {
	var re = new RegExp("^http://((www.)|(dev.)|)"+domain, "i"); //i=case insensitive
	return re.test(link);
}

//Add the openInNewWindow function, and an icon to the onclick event of external links
function insertNewWindowLinks() {
// Check that the browser is DOM compliant and not home page
	if (document.getElementById && document.createElement && document.appendChild && typeof(homepage) == 'undefined') {
		// Find all links
		var links = $('a');
		links.each(function() {
			this.link = $(this);
			this.l_href = this.link.attr("href");
			if (linkIsToDomain(this.l_href, "") && //tests that the link is absolute
				!linkIsToDomain(this.l_href, "ifacca") &&
				!linkIsToDomain(this.l_href, "media.ifacca") &&
                !$(this).hasClass('external-ignore')
			) {

				// Create an img element containing the new window warning text and insert it after the link text
 				this.link.addClass("external");
				this.link.attr("title", 
					(this.link.attr("title")?this.link.attr("title")+" ":"")
					 + "(new window)");
				this.link.attr("target", "_blank");
			}
		});
	}
}





/* Ajaxy selection of organisations -------------------------------- */
function manage_messages() {
    $("#id_organisation").hide();
    $("#org_message").hide();
	
    if ($("#id_country")[0].selectedIndex==0) { // No country selected
        $("#id_organisation").hide();
        $("#org_message").html('&lt; Please select a country first &gt;');
        $("#org_message").show();
    }
    else {
        var country_name = $("#id_country")[0].options[$("#id_country")[0].selectedIndex].text;
        if ($("#id_organisation")[0].options.length == 0) { // If no organisation found for that country
            $("#id_organisation").hide();
            $("#org_message").html('No organisation found in ' + country_name + '. Please type your organisation\'s name in "Other" below.');
            $("#org_message").show();
        }
        else {
            $("#id_organisation").show();
            $("#org_message").html('If your organisation is not in the list above please select "Not Known/not applicable" and then type its name in "Other" below.');
            $("#org_message").show();
        }
    }
}
	
function ajaxy_organisation_select(){
    $("#id_country").css({
        width: "240px"
    });
    $("#id_organisation").css({
        width: "240px"
    });
    
    
    $("#id_organisation").after('<div class="message" id="org_message"></div>');
    manage_messages();
    
    $("#id_country").change(function(){
        if (this.selectedIndex == 0) { // If no country selected
            $("#id_organisation").html('');
            manage_messages();
        }
        else {
            var selected_country = this.options[this.selectedIndex];
            var country_pk = selected_country.value;
            var country_name = selected_country.text;
            
            $("#id_organisation").hide();
            $("#org_message").html('<img src="http://media.ifacca.org/navimages/loading.gif" /> Loading organisations for ' + country_name);
            $("#org_message").show();
            $.getJSON('/ajax/orgs_by_country/', {
                country_pk: country_pk
            }, function(json){
                if (json.length > 0) {
                    options_html = '';
                    for (i = 0; i < json.length; i++) {
                        options_html += '<option value="' + json[i][0] + '">' + json[i][1] + '</option>';
                    }
                    $("#id_organisation").html(options_html);
                    $("#id_organisation")[0].selectedIndex = 0;
                }
                else {
                    $("#id_organisation").html('');
                }
                manage_messages();
            });
        }
    });
}

