/* $Id$ */


$(document).ready(function() {


	/*-------- global variables --------*/
	var gotoMapPage = {};
	var updateMapImage = {};
	var updateMapOverlays = {};
	var updateMapTypes = {};
	var onAnimPlayClick = 1;

	var animReload = 0;

	var overlaysOnMap = new Array;
	overlaysOnMap['ovrHighlightus'] = 'us';
	overlaysOnMap['ovrCounties'] = 'c';
	overlaysOnMap['ovrRivers'] = 'r';
	overlaysOnMap['ovrInterstates'] = 'i,is';
	overlaysOnMap['ovrWarnings'] = 'wrn';
	overlaysOnMap['ovrStationmodels'] = 'station_models';
	overlaysOnMap['ovrFronts'] = 'fronts';
	overlaysOnMap['ovrStormreports'] = 'sels';
	overlaysOnMap['ovrRadsum'] = 'radsum';
	overlaysOnMap['ovrCities'] = 'cities';

	var underlaysOnMap = new Array;
	underlaysOnMap = overlaysOnMap;

	var mapTypes = new Array;
	mapTypes['typeAll'] = 'sp';
	mapTypes['typeSp'] = 'sp';
	mapTypes['typeSevere'] = 'severe';
	mapTypes['typeWintry'] = 'wintry';
	mapTypes['typeFlood'] = 'flood';
	mapTypes['typeWind'] = 'winds';
	mapTypes['typeFire'] = 'fire';
	mapTypes['typeFrostFreeze'] = 'frostfreeze';
	mapTypes['typeHWO'] = 'hwo';
	mapTypes['typeSPS'] = 'sps';
	mapTypes['typeNOW'] = 'now';




	/*-------- global functions --------*/

	gotoMapPage = function (useState) {
		var tState = (useState) ? useState : mapState;
		if (tState.substr(0,2) != 'us' && !tState.match(/^(trop|tropw|gulf|crb|nwatl|watl|aus|afr|can|crb|eur|mx|mide|nam|sam|nas|sas|world)$/) ) tState = 'us' + tState;

		var zurl = mapPageURLTemplate.replace('[typedir]', mapTypeDir);
		zurl = zurl.replace('[type]', mapType);
		zurl = zurl.replace('[region]', tState);
		zurl = zurl.replace('[interval]', mapInt);
		if ('undefined' !== typeof mapMTypes) zurl = zurl.replace('[mtypes]', mapMTypes);
		if ('undefined' !== typeof mapBase) zurl = zurl.replace('[base]', mapBase);
		if ('undefined' !== typeof mapSize) zurl = zurl.replace('[size]', mapSize);

		top.location = zurl;
	};

	updateMapImage = function () {
		if ('undefined' === typeof mapImgURLTemplate) gotoMapPage();
		else {
			var imgUrl = mapImgURLTemplate.replace('[typedir]', mapTypeDir);

			imgUrl = imgUrl.replace('[type]', mapType);
			imgUrl = imgUrl.replace('[region]', mapState);
			imgUrl = imgUrl.replace('[interval]', mapInt);
			imgUrl = imgUrl.replace('[points]', mapPoints);
			if ('undefined' !== typeof mapI) imgUrl = imgUrl.replace('[msg]', mapI);
			if ('undefined' !== typeof mapOverlays) imgUrl = imgUrl.replace('[overlays]', mapOverlays);
			if ('undefined' !== typeof mapUnderlays) imgUrl = imgUrl.replace('[underlays]', mapUnderlays);
			if ('undefined' !== typeof mapBase) imgUrl = imgUrl.replace('[base]', mapBase);
			if ('undefined' !== typeof mapMTypes) imgUrl = imgUrl.replace('[mtypes]', mapMTypes);
			if ('undefined' !== typeof mapSize) imgUrl = imgUrl.replace('[size]', mapSize);
			if ('undefined' !== typeof mapBase && mapType == 'preciptype') {
				if (mapBase == 'flat') imgUrl.replace('.jpg', '.png');
			}
			$('#contourMap').attr('src', imgUrl);
		}
	};

	updateMapOverlays = function () {
		var tOverlay = '';
		var tUnderlay = '';
		for ( var oType in overlaysOnMap ) {
			if (oType.substr(0,3) == 'ovr') {
				var cleanType =  oType.substr(3).toLowerCase();
				if ( $('#wxm-switch-overlays > li  #overlayOnMap-' + cleanType + '-link').hasClass('on') ) {
					tOverlay = tOverlay + overlaysOnMap[oType] + ',';
				}
				else if ($('#wxm-switch-overlays > li  #underlayOnMap-' + cleanType + '-link').hasClass('on') ) {
					tUnderlay = tUnderlay + overlaysOnMap[oType] + ',';
				}
			}
		}
		mapOverlays = tOverlay;
		mapUnderlays = tUnderlay;
		//updateMapImage();
		updateMapTypes();

		if ($('#anim-radar').is('*') && animReload) animPreload()
	};

	updateMapTypes = function () {
		if ('undefined' !== typeof mapTypes) {
			var tTypes = '';
			for ( var oType in mapTypes ) {
				if (oType.substr(0,4) == 'type') {
					var cleanType =  oType.substr(4).toLowerCase();

					if ( $('#wxm-switch-types > li  #type-' + cleanType + '-link').hasClass('on') ) {
						tTypes = tTypes + mapTypes[oType] + ',';
					}
				}
			}
		}
		mapMTypes = tTypes;
		updateMapImage();
	};




	/*-------- global processes --------*/

	// setup wxmap navbar stuff
	$('li.wxm-nav-el').mouseover(function(){
		var snav = $(this).children('div').get();
		$(snav).show();
	});
	$('li.wxm-nav-el').mouseout(function(){
		var snav = $(this).children('div').get();
		$(snav).hide();
	});

	// add regional menu clicks
	$('.wxm-snav-el > li > a').click(function(e){
		var ref = $(this).attr('id').replace(/mnu-(\w+)-link/, "$1");
 		gotoMapPage(ref.toLowerCase());
 		return false;
 	});

	// add imagemap clicks
	$('.optImageMap').click(function(e){
		var ref = $(this).attr('meta');
 		gotoMapPage(ref.toLowerCase());
 		return false;
 	});

	// contour type clicks
	$('#wxm-switch-contour > li > a').click(function(e){
		var ref = $(this).attr('id').replace(/^contour-(\w+)-link$/, "$1");

 		 mapInt = ref;
 		 updateMapImage();

 		$('#wxm-switch-contour > li > a').removeClass('on');
		$('#contour-' +ref + '-link').addClass('on');


 		return false;
 	});

	// contour type clicks
	$('#wxm-switch-data > li > a').click(function(e){
		var ref = $(this).attr('id').replace(/^data-(\w+)-link$/, "$1");
		var tRef =  (ref == 'NONE') ? '' : ref;

 		 mapPoints = tRef;
 		 updateMapImage();

 		$('#wxm-switch-data > li > a').removeClass('on');
		$('#data-' +ref + '-link').addClass('on');


 		return false;
 	});

	// date clicks
	$('#wxm-switch-dates > li > a').click(function(e){
		var ref = $(this).attr('id').replace(/^date-(\w+)-link$/, "$1");

 		 mapI = ref;
 		 updateMapImage();

 		$('#wxm-switch-dates > li > a').removeClass('on');
		$('#date-' +ref + '-link').addClass('on');

		if ('undefined' !== typeof dateOnClick) dateOnClick(this);


 		return false;
 	});

	// interval clicks
	$('#wxm-switch-intervals > li > a').click(function(e){
		var ref = $(this).attr('id').replace(/^interval-(\w+)-link$/, "$1");

 		 mapInt = ref;
 		 gotoMapPage();

 		return false;
 	});

 	// add overlay clicks
	$('#wxm-switch-overlays > li > a').click(function(e){
		if ( $(this).attr('id').match(/overlay-(\w+)-link/) ) {
			var ref = $(this).attr('id').replace(/(\w+)-link/, "$1");
	 		if ($('#' +ref).css('display') == 'none') {
	 			$('#' +ref).show();
	 			$('#' +ref + '-link').addClass('on');

	 			$.cookie($(this).attr('id'), 1,{path: '/'} );
	 		}
	 		else {
	 			$('#' +ref).hide();
	 			$('#' +ref + '-link').removeClass('on');
	 			$.cookie($(this).attr('id'), 0,{path: '/'});
	 		}
	 	}
	 	else if ( $(this).attr('id').match(/overlayOnMap-(\w+)-link/) ) {
	 		var ref = $(this).attr('id').replace(/overlayOnMap-(\w+)-link/, "$1");

	 		if ($('#overlayOnMap-' +ref + '-link').hasClass('on')) {
	 			$('#overlayOnMap-' +ref + '-link').removeClass('on');
	 			$.cookie($(this).attr('id'), 0,{path: '/'});
	 			$('#legend-' + ref).hide();
	 		}
	 		else {
	 			$('#overlayOnMap-' +ref + '-link').addClass('on');
	 			$.cookie($(this).attr('id'), 1,{path: '/'});
	 			$('#legend-' + ref).show();
	 		}
			updateMapOverlays();

		}
	 	else if ( $(this).attr('id').match(/underlayOnMap-(\w+)-link/) ) {
	 		var ref = $(this).attr('id').replace(/underlayOnMap-(\w+)-link/, "$1");

	 		if ($('#underlayOnMap-' +ref + '-link').hasClass('on')) {
	 			$('#underlayOnMap-' +ref + '-link').removeClass('on');
	 			$.cookie($(this).attr('id'), 0,{path: '/'});
	 			$('#legend-' + ref).hide();
	 		}
	 		else {
	 			$('#underlayOnMap-' +ref + '-link').addClass('on');
	 			$.cookie($(this).attr('id'), 1,{path: '/'});
	 			$('#legend-' + ref).show();
	 		}
			updateMapOverlays();
		}
 		return false;
 	});

 	// preset overlays
 	$('#wxm-switch-overlays > li > a').each(function(e){
 		if ( $(this).attr('id').match(/^(overlay|underlay)/) ) {
 			if ($.cookie( $(this).attr('id') ) == 1) $(this).click();
 		}

 		animReload = 1;
 	});

 	// add base sizes
	$('#wxm-switch-sizes > li > a').click(function(e){
		var ref = $(this).attr('id').replace(/^size-(\w+)-link$/, "$1");
 		mapSize = ref;
		gotoMapPage();

 		return false;
 	});

 	// add base clicks
	$('#wxm-switch-bases > li > a').click(function(e){
		var ref = $(this).attr('id').replace(/^base-(\w+)-link$/, "$1");
 		mapBase = ref;
		$.cookie($(this).attr('id'), 1,{path: '/'});

 		 if ('undefined' !== typeof mapBasePageRefresh && !mapBasePageRefresh) {
 		 	updateMapImage();
 		 	$('#wxm-switch-bases > li > a').removeClass('on');
			$('#base-' +ref + '-link').addClass('on');
		}
		else {
			gotoMapPage();
		}

 		return false;
 	});

 	// preset base only if we do not refresh on base
 	if ('undefined' !== typeof mapBasePageRefresh && !mapBasePageRefresh) {
	 	$('#wxm-switch-bases > li > a').each(function(e){
	 		if ( $(this).attr('id').match(/^base/) ) {
	 			if ($.cookie( $(this).attr('id') )) $(this).click();
	 		}
	 	});
	}

 	// animation stuff
	 function animEnded  () {
		$('#animctrl-stop-link').click();
	}
    function onAnimBefore(curr, next, opts) {
		if ('undefined' !== typeof mapAnimonBefore) mapAnimonBefore(curr, next, opts);
    };

 	$('#wxm-switch-animctrls > li > a').click(function(e){
 		var ref = $(this).attr('id').replace(/animctrl-(\w+)-link/, "$1");
 		if (ref == 'play') {
 			if ( !$(this).hasClass('on') ) {

 			    if (('undefined' !== typeof mapAnimAutoStart && !mapAnimAutoStart)) {
                    animPreload();
 			    }
 			    else {
    				var goPlay = (typeof onAnimPlayClick == 'function') ? onAnimPlayClick() : onAnimPlayClick;
     				if (goPlay) {
    	 				var paused = $('#animctrl-pause-link').hasClass('on');
    	 				$('#wxm-switch-animctrls > li > a').removeClass('on');
    	 				$(this).addClass('on');
    	 				if ( paused ) {
    	 					$('.anim-images').cycle('resume');
    	 				}
    	 				else {
    	 				    var thisAnimDelay= ('undefined' !== typeof mapAnimDelay) ? mapAnimDelay : 250;

    						$('.anim-images').cycle({
    					        timeout: thisAnimDelay,
    					        delay: 1000,
    					        speed: 1,
    					        pause: 0,
    					        autostopCount: 240,
    					        autostop: 1,
    					        end: animEnded,
    					        fastOnEvent: 1,
    					        prev: '#animctrl-prev-link',
    					        next: '#animctrl-next-link',
    					        before: onAnimBefore
    					    });
    					}
    				}
    			}
			}
		}
		else if (ref == 'stop') {
			if ( !$(this).hasClass('on') ) {
				$('#wxm-switch-animctrls > li > a').removeClass('on');
 				$(this).addClass('on');
 				$('.anim-images').cycle('stop');
 			}
 		}
		else if (ref == 'pause') {
			if ( !$('#animctrl-stop-link').hasClass('on') ) {
				if ( !$(this).hasClass('on') ) {
					$('#wxm-switch-animctrls > li > a').removeClass('on');
	 				$(this).addClass('on');
	 				$('.anim-images').cycle('pause');
	 			}
	 			else {
	 				$(this).removeClass('on');
	 				$('#animctrl-play-link').addClass('on');
	 				$('.anim-images').cycle('resume');
	 			}
	 		}
 		}

 		return false;
 	});

	if ( $('#anim-radar').is('*')) {
	    if ('undefined' === typeof mapAnimAutoStart || mapAnimAutoStart) {
		    animPreload();
		}
		else {
		    $('#wxm-switch-animctrls > li > a#animctrl-stop-link').click();
		}

	}

	function animPreloadRequest (data) {
		var now = data.done +1;
		var txt = 'Loading ' + now+ ' of ' + data.total;
		$('#mapLoadingStatusText').text(txt);

	}

	function animPreloadFinish() {
		$('#contourMapContainer').hide();
        $('#mapLoadingStatus').hide();
		$('#anim-radar').show();
		mapAnimAutoStart = 1;
		$('#animctrl-play-link').click();
	}


	function animPreload () {
		$('#mapLoadingStatus').show();
		// preload animations
		$.preload( '#anim-radar img', {
         		find:/o=[\w,\[\]]*/,
         		replace:'o=' + mapOverlays,
				onRequest: animPreloadRequest,
				onFinish: animPreloadFinish,
				threshold:1
			});
	}


 	// multiple map types (adv for now & soon others)
	$('#wxm-switch-types > li > a').click(function(e){
		 if ( $(this).attr('id').match(/type-(\w+)-link/) ) {
	 		var ref = $(this).attr('id').replace(/type-(\w+)-link/, "$1");

	 		if ($(this).hasClass('on')) {
	 			$('#type-' +ref + '-link').removeClass('on');

	 		}
	 		else {
	 			if (ref == 'all') $('#wxm-switch-types > li > a').removeClass('on');
	 			else $('#type-all-link').removeClass('on');
	 			$(this).addClass('on');
	 		}
			updateMapTypes();
		}

 		return false;
 	});


 	// simple types
	$('#wxm-switch-simpletypes > li > a').click(function(e){
		 if ( $(this).attr('id').match(/type-(\w+)-link/) ) {
	 		var ref = $(this).attr('id').replace(/type-(\w+)-link/, "$1");

	 		if (!$(this).hasClass('on')) {
	 			$('#wxm-switch-simpletypes > li > a').removeClass('on');
	 			$(this).addClass('on');
	 			mapType = ref;

	 			if ('undefined' !== typeof mapTypePageRefresh && mapTypePageRefresh) gotoMapPage();
	 			else updateMapImage();
	 		}
		}

 		return false;
 	});

});

