$(document).ready(function() {
    function countryLog(str, str2) {
        if ( console && console.log )
            console.log(str, str2);
    }
    countryLog('started');
        var hostMap = {
        'www.funtosee.com' : {country: ['US','CA'], text: 'USA / Canada'},
        'www.funtosee.co.uk' : {country: ['GB'], text: 'Europe / Rest of World'}
};
// if we are allowing the user to switch domains, clear any cookie that has been set
if ( document.location.hash.match(/clearCookie/) )
	$.cookie('selectedDomain', null, -1);

            var chosenCookie = $.cookie('selectedDomain');
        countryLog('ChosenCookie is ', chosenCookie);
    if ( chosenCookie && chosenCookie == document.location.host ) {
        // rewrite the cookie with 1 days expiry from now
        $.cookie('selectedDomain', chosenCookie, 30);
        // already chosen this domain
        return false;
    }
    if ( chosenCookie && chosenCookie != document.location.href ) {
	// user has chosen a location we dont agree with, but let them pass without interupting them
        $.cookie('selectedDomain', chosenCookie, 30);
	document.location.href = 'http://'+chosenCookie;
	return false;
    }
var title = 'Please select your location';
countryLog(document.location);
for ( domain in hostMap ) {
	if ( $.inArray(detectedCountry.code, hostMap[domain].country) !== -1 ) {
		if ( domain == document.location.host )
			return false;
		return showDialog(title, domain);
	}
}
/*
if we got to here then the country didnt match a defined country, therefore its a "europe" or "rest of world" situation
only show the popup if we are not on the .co.uk (catchall) site
*/
if ( document.location.host != 'www.funtosee.co.uk' )
	showDialog(title, 'www.funtosee.co.uk');

function showDialog(title, domain) {
	var buttons = {};
	if ( title == 'Please select your location' )
		buttons["Change Site"] = function() {
			$(this).dialog('close');
			document.location.host=domain;
			return false;
		}
	buttons['Cancel'] = function() {
		$(this).dialog('close');
	}
        var s = $('<ul />');
for ( domain in hostMap )
        s.append($('<li/>', { class: hostMap[domain].country[0], text: hostMap[domain].text}).click(function(d){
                     return function() {
                    //selectedDomain = d;
                    $.cookie('selectedDomain', d, {expires: 30});
countryLog($.cookie('selectedDomain'));
                    if ( d == document.location.host ) {
                        // if this is the chosen domain just close the dialog
                        $('#domainDialog').dialog('close');
                        return false;
                    }
        document.location = 'http://'+d;
                    }
                }(domain)));
$('<div />', {
'id': 'domainDialog',
'title': title
}).append(
s
).dialog({
modal: true,
position: ['center', 'top'],
width: 454,
hide: 'explode',
buttons: buttons
});
return false;
}
}); 

