/**
 * wkw.js
 * javascript functions used in the HTML interface for culturalcartography.net
 * @author Peter Edwards <tech@e-2.org>
 * @version 2.0
 * @requires jQuery 1.3
 */
/**
 * make sure the page doesn't load in a frame (i.e. when a link is followed from an SVG in an iframe)
 */
if (self.location != top.location) top.location = self.location;
/**
 * function to redirect to the SVG interface - place to check browser/platform/version info
 */
var viewSVG = function(nameStr)
{
    if ((navigator.userAgent.indexOf('Firefox') > -1 && parseInt(navigator.userAgent.charAt(navigator.userAgent.indexOf('Firefox') + 8)) >= 2)
         || (window.opera && parseInt(navigator.appVersion) >= 9)
         || (navigator.userAgent.indexOf('AppleWebKit') > -1 && parseInt(navigator.appVersion) >= 3)) {
            window.location.href = '/wkw/'+nameStr;
    } else {
        if (confirm("The SVG interface has only been tested in:\n* Firefox 2\n* Opera 9\n* Safari 3\n\nIt is known *NOT* to work in earlier versions of these\nbrowsers, or with any version of Adobe SVG Viewer.\n\nIf you want to try it anyway, click OK")) {
            window.location.href = '/wkw/'+nameStr;
        }
    }
}
/**
 * do stuff when DOM ready
 */
$(function(){
	$('#content a').each(function(){
		if ($(this).hasClass("external")) {
			$(this).attr("target", "_blank");
		}
	});
	if ($('#getNamesList_result').length){
		getNamesList();
	}
});
/**
 * searchName
 */
var searchName = function()
{
	var querytxt = $.trim(document.forms.searchform.search.value);
    if (querytxt === "") {
        window.location.href = '/wiki/index.php?title=Special:Random';
    } else {
    	$('#searchGo').html("loading&hellip;");
        var qUrl = mediawikiAPI + '?action=query&generator=search&gsrwhat=title&prop=info&format=xml&gsrsearch='+querytxt;
        $.get(qUrl,null,function(data, textStatus){
        	var names = $('page', data);
        	if (names.length === 0) {
        		alert("Sorry, no matches found for "+querytext);
        	} else if (names.length == 1) {
        		window.location.href = wikiURL + escape(names[0].getAttribute('title'));
        	} else {
        		var nameslist = '';
        		names.each(function(){
        			nameslist += '<li><a href="'+wikiURL+escape($(this).attr('title'))+'">'+$(this).attr('title')+'</a></li>';
        		})
        		$('#search_results').empty().append('<p>Your search for <strong>'+querytxt+'</strong> returned <strong>'+names.length+'</strong> results:</p><ul>'+nameslist+'</ul>').show();
        	}
        	$('#searchGo').html("go");
        },'xml');
    }
};
var clearSearchResults = function()
{
    $('#search_results').empty();
    $('#search_results').hide();
}
/**
 * getNamesList
 * gets the first 5000 names from MediaWiki in the 0 namespace (WKW)
 */
var currentLetter = false;
var getNamesList = function()
{
    /* variables needed to get a list of names from the MediaWiki API */
    var qUrl = mediawikiAPI + '?action=query&list=categorymembers&cmtitle=Category:WKW&cmlimit=max&cmprop=ids|title|sortkey&format=xml';
    /* first argument is the name to start at */
    if (arguments.length) {
        fromName = arguments[0];
        qUrl += '&cmcontinue='+fromName;
    }
    /* now we have a query for the API */
    $.get(qUrl, null, function(data, textStatus){
    	var names = $('cm', data);
    	if (names.length) {
            var letterKey = 1;
            var currentLetter = false;
    		names.each(function(){
    			var sortLetter = $(this).attr('sortkey').substr(0,1).toUpperCase();
                if (currentLetter === false || currentLetter != sortLetter) {
                    currentLetter = sortLetter;
                    letterKey = 1;
                }
    		    $('#getNamesList_result').append('<li><a href="'+wikiURL+escape($(this).attr('title'))+'" id="'+sortLetter+letterKey+'">'+$(this).attr('title')+'</a></li>');
    		});
    		var continueName = $('query-continue categorymembers', data);
    		if (continueName.length){
    			getNamesList($('query-continue categorymembers', data).attr('cmcontinue'));
        }
    	}
    }, 'xml');
}
var scrollToLetter = function(letterID) {
    if (!document.getElementById(letterID)) {
        alert("Sorry, no names begin with "+letterID.substr(0, 1));
    } else {
        if (document.getElementById("scrollpane")) {
            document.getElementById("scrollpane").scrollTop = document.getElementById(letterID).offsetTop - 2;
        }
    }
}
var submitContactForm = function()
{
    var f = document.forms['contactus'];
    var errorMsg = '';
    if (f.email.value == "") {
        errorMsg += "- please provide an email address\n";
    } else {
        var emailRegex = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
        if( !emailRegex.test(f.email.value)) {
            errorMsg += "- your email address appears to be invalid\n";
        }
    }
    if (f.fullname.value == "") {
        errorMsg += "- please provide your name\n";
    }
    if (f.message.value == "") {
        errorMsg += "- please fill in your message\n";
    }
    if (errorMsg) {
        alert("Sorry, but you need to correct the following errors\n"+errorMsg);
    } else {
        /* submit form via AJAX */
        var data = {"fullname":encodeURIComponent(f.fullname.value),"email":encodeURIComponent(f.email.value),"message":encodeURIComponent(f.message.value)};
        $('contactform').empty().load(formURL, data);
    }
}
