var isIE;

$(document).ready( function() {

	// Are we Internet Explorer? 
	isIE = $.browser.msie;
	
	// Navbar hover - show submenu
	// (IE fadeIn effect is clunky, so use a plain old 'show' instead)
	$('li.has-dropdown').hover(
		function () {
			if ( isIE ) {
				if ( parseInt($.browser.version) >= 7 ) {
					$(this).children("ul").show();
				}
			} else {
				$(this).children("ul").fadeIn('fast');
			}
		},
		function () {
			if ( isIE ) {
				if ( parseInt($.browser.version) >= 7 ) {
					$(this).children("ul").hide();
				}
			} else {
				$(this).children("ul").fadeOut('fast');
			}
		}
	);
	
	// on the homepage? load the slideshow
	if ($('#slideshow').length > 0 ) {
		slideshow_load();
		$('#slideshow-controls a').live('click', function(event) {
			event.preventDefault();
			clearTimeout(slideshowTimer);
			slide_display( $(this).attr('id').replace('btn-', '') );
		});
	}
	
	// on the homepage? jump to the appropriate page when the "I want to" select is changed.
	$('#quick-jump').change( function() {
		if ( $(this).val() != '' ) {
			window.location = $(this).val();
		}
	});

	// on the compare regions page? load data
	if ($('#compare-regions').length > 0 ) { regional_data_init(); }
	
	// compare page, catch dataset change
	$('#stat-sets').change( function() {
		if (isNaN( $(this).val() ) ) { return } else { regional_dataset_change( $(this).val() ); }
	});
	
	// catch regional dropdown change
	$('.region-select').change( function() {
		if (isNaN( $(this).val() ) ) {
			return false; 
		} else {
			var intSet = $(this).attr('id').replace('stat-region-', '');
			regional_data_update_region( intSet, $(this).val(), true );
		}
	});	
});

// initialise regional data 
function regional_data_init() {

	// javascript enabled, let's enable the wrapper (otherwise we're showing noscript content)
	$('.compare-regions-cols-wrapper').show();
	
	// remove the placeholders
	$('#data-output tr, .region-select option').remove();

	// initialize our HTML
	var strHTML = '';
	
	// loop over regions, making them options in our dropdown
	for ( i in arrRegions ) {
		var strOption = ( i == 0 ) ? "Select a region" : arrRegions[i];
		intIndex = parseInt(i) - 1;
		strHTML += '<option value="' + intIndex + '">' + strOption + '</option>';
	}
	for (var i=0;i<=2;i++) {
		$('#stat-region-' + i).append(strHTML);
		if ( !isIE || ( isIE && parseInt($.browser.version) >= 7 ) ) {
			$('#stat-region-' + i).selectmenu({style:'dropdown', width: 232 });
		}
	}
	
	// set up our stat sets
	strHTML = '<option value="">Select statistical set</option>';
	for ( j in arrDataset ) {
		strHTML += '<option value="' + j + '">' + arrDataset[j].key + '</option>';
	}
	
	// add our options to the stats dropdown, and apply selectmenu magic
	$('#stat-sets').html(strHTML);
	if ( !isIE || ( isIE && parseInt($.browser.version) >= 7 ) ) {
		$('#stat-sets').selectmenu({style:'dropdown', width: 232 });
	}
}


/*
 * Change what dataset is being shown
 * @intSet: the key of the dataset being requested
 */
function regional_dataset_change( intSet ) {
	var objData = arrDataset[intSet].data;
	var strHTML = '';
	var zebra = 'even';
	var first = '';
	for ( var i in objData) {
		zebra = ( zebra == 'odd' ) ? 'even' : 'odd';
		first = ( i == 0 ) ? ' first' : '';
		strHTML += '<tr id="data-row-'+ i +'" class="'+ zebra + first + '">';
		strHTML += '<th>' + objData[i].key + '</th>';
		strHTML += '<td></td><td></td><td class="last"></td></tr>';
	}
	$('#data-output').html(strHTML);
	for ( var j=0;j<3;j++) {
		var intRegion = $("#stat-region-"+j).val();
		regional_data_update_region( j, intRegion, false );
	}
}

/*
 * Update the data for the given region
 * @intCol: which column are we dealing with (0, 1 or 2)
 * @intRegion: the key of the region dataset being requested
 * @booLoadImage: do we need to reload the image? 
 */
function regional_data_update_region( intCol, intRegion, booLoadImage ) {


	// do nothing if no value
	if ( intRegion < 0 ) return;
	
	// check for pic - don't need to if we're updating the dataset
	if ( booLoadImage ) {
		$.ajax(
		{
			url:'/compare-regions/_images/' + intRegion + '.jpg',
			type:'HEAD',
			error: function() {
				if ( isIE ) {
					$('#region-img-' + intCol).html('<img width="230" height="150" src="/compare-regions/_images/placeholder.jpg" alt="" />').hide().fadeIn();
				} else {
					var imageObj = new Image(); 
					$( imageObj ).attr( 'src', '/compare-regions/_images/placeholder.jpg' ).load( function() {
						$('#region-img-' + intCol).html(
							'<img width="230" height="150" src="' + imageObj.src + '" alt="" />'
						).fadeIn();
					});
				}
			},
			success: function() {
				if ( isIE ) {
					$('#region-img-' + intCol).html('<img width="230" height="150" src="/compare-regions/_images/' + intRegion + '.jpg" alt="" />').hide().fadeIn();
				} else {
					var imageObj = new Image(); 
					$( imageObj ).attr( 'src', '/compare-regions/_images/' + intRegion + '.jpg' ).load( function() {
						$('#region-img-' + intCol).html(
							'<img width="230" height="150" src="' + imageObj.src + '" alt="" />'
						).fadeIn();
					});
				}
			}
		});
	}
	
	
	// get current dataset key
	var intSet = $("#stat-sets").val();
		
	// do nothing if no active set
	if ( isNaN(intSet) || intSet == '' || intSet == 'undefined'	) {
		return;
	} 
	
	// get dataset object for this region
	var objRegionalData = arrDataset[intSet].data;
	
	// add data to our table! 
	for (var i in objRegionalData) {
		var strHTML = cleanCellData(objRegionalData[i].data[intRegion]);
		$('#data-output tr:eq('+i+') td:eq('+ intCol +')').html(strHTML).fadeIn();
	}
	
}

/*
 * Tidy up data from the spreadsheet
 * (text fields with commas or single quotes get wrapped in double quotes)
 * @strData: string to be cleaned
*/
function cleanCellData( strData ) {
	if ( typeof strData != 'string' ) return '-';
	if ( strData == '' ) { strData = strNoData; }
	if ( strData.indexOf('"') == 0 ) { strData = strData.substr(1); }
	if ( strData.charAt(strData.length-1) == '"' ) { strData = strData.substr(0, strData.length-1); }
	strData = strData.replace("'", "\'");
	return strData;
}



/*
 * SLIDESHOW FUNCTIONALITY
 */
var slideshowTimer;				// global timer variable
var slideshowPause = 5000;		// time to show each slide (in milliseconds: eg. 5000 = 5 seconds)

/*
 * Kick of the slideshow
 */
function slideshow_load() {
	for ( var i in arrSlides ) {
		var booLast = ( i == arrSlides.length-1 ) ? true : false;
		slideshow_load_slide( i, arrSlides[i], booLast );
	}
}
/*
 * Update the slide on display
 */
function slide_display( intSlide ) {
	var intActiveSlide = $('#slideshow-controls a.active').attr('id').replace('btn-', '');
	if ( intActiveSlide == intSlide ) return;
	$('#slide-' + intActiveSlide).fadeOut()
	$('#slideshow-controls a.active').removeClass('active');
	$('#slideshow-controls a#btn-'+ intSlide).addClass('active');
	$('#slide-' + intSlide).fadeIn('slow');
	
}

/*
 * Get a slide ready for display
 */
function slideshow_load_slide( intSlide, strFile, booLast ) {
	var filePath = "_images/homepage-slideshow/" + strFile;
	var imageObj = new Image(); 
	$( imageObj ).attr( 'src', filePath ).load( function() {
		var strHTML = '<div id="slide-' + intSlide + '" class="slide">';
		strHTML += '<img src="' + imageObj.src + '" width="710" height="146" alt="" />';
		strHTML += '</div>';
		$('#slideshow-wrapper').append(strHTML);
		if ( intSlide == 0 ) {
			$('#slideshow').removeClass('loading');
			$('#slide-0').show();
			$('#slideshow-placeholder').remove();
		}		
		if ( booLast ) {
			for ( var j = 0; j <= intSlide; j++ ) {
				var active = ( j == 0 ) ? ' active' : '';
				$('#slideshow-controls').append('<a id="btn-'+ j +'" href="#" class="slide-selector'+ active +'"><span>show slide '+ j +'</span></a>');
			}
			$('#slideshow-controls').fadeIn();
			slideshow_run();
		}
	}); 
	
}

/*
 * Run the homepage slideshow
 * Loops back on itself until stopped by a click on an image selector
 */
function slideshow_run() {
	// set our timer to loop over this until told otherwise
	slideshowTimer = setTimeout( function() {
		var intActiveSlide = $('#slideshow-controls a.active').attr('id').replace('btn-', '');
		var intNextSlide = parseInt(intActiveSlide)+1;
		if ( intNextSlide == arrSlides.length ) {
			intNextSlide = 0;
		}
		slide_display( intNextSlide );
		slideshow_run();
	}, slideshowPause );	
}



