function getRequestParameter(name, url) {
	  url = url || location.href;
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp(regexS);
      var results = regex.exec(url);
      if( results == null )
            return null;
      else
            return results[1];
}

/**
 * setTheForecast(com.corporatevoice.claritin.model.forecast.WeatherPollenForecast o)
 */
window.setTheForecast = function(o){
	function pollenHTML(pVal){
		return '<img src="/img/manage/forecast/pollen-icons/'+pVal+'.gif"><span class="pollen-icon">'+pVal+'</span>';
	}
	
	function weatherHTML(day,night, icon, desc, nightOnly){
		if(nightOnly){
			return '<span class="lowTemp">'+night+'&deg;F</span><img src="/img/manage/forecast/weather-icons/'+icon+'-trans.png"><br /><br /><span class="weatherDescr">'+desc+'</span>';
		}else{			
			return '<span class="lowTemp">'+night+'&deg;F</span>/'+day+'&deg;F<img src="/img/manage/forecast/weather-icons/'+icon+'-trans.png"><br /><br /><span class="weatherDescr">'+desc+'</span>';
		}
	}
	$(document).ready( function() {
		var evening = new Date().getHours() >= 14;
		
		// Set the title
		$('.forecastContainer H2:first').html(o.city+', '+o.state+' '+o.zip);
		
		$('#forecastTable TR.day TD:eq(1)').html(evening?'Tonight':'Today');
		$('#forecastTable TR.day TD:eq(2)').html(o.days[1]);
		$('#forecastTable TR.day TD:eq(3)').html(o.days[2]);
		$('#forecastTable TR.day TD:eq(4)').html(o.days[3]);
		
		$('#forecastTable TR.pollen TD:eq(1)').html(pollenHTML(o.pollens[0]));
		$('#forecastTable TR.pollen TD:eq(2)').html(pollenHTML(o.pollens[1]));
		$('#forecastTable TR.pollen TD:eq(3)').html(pollenHTML(o.pollens[2]));
		$('#forecastTable TR.pollen TD:eq(4)').html(pollenHTML(o.pollens[3]));
		
		$('#forecastTable TR.pollen-details TD:eq(1)').html('Predominant Pollen:<br /> '+o.pollenPP);
		
		$('#forecastTable TR.weather TD:eq(1)').html(weatherHTML(o.weatherForecast.forecast[0].highF,o.weatherForecast.forecast[0].lowF,o.weatherForecast.forecast[0].skyDay,o.weatherForecast.forecast[0].phraseDay || o.weatherForecast.forecast[0].phraseNight, evening));
		$('#forecastTable TR.weather TD:eq(2)').html(weatherHTML(o.weatherForecast.forecast[1].highF,o.weatherForecast.forecast[1].lowF,o.weatherForecast.forecast[1].skyDay,o.weatherForecast.forecast[1].phraseDay, false));
		$('#forecastTable TR.weather TD:eq(3)').html(weatherHTML(o.weatherForecast.forecast[2].highF,o.weatherForecast.forecast[2].lowF,o.weatherForecast.forecast[2].skyDay,o.weatherForecast.forecast[2].phraseDay, false));
		$('#forecastTable TR.weather TD:eq(4)').html(weatherHTML(o.weatherForecast.forecast[3].highF,o.weatherForecast.forecast[3].lowF,o.weatherForecast.forecast[3].skyDay,o.weatherForecast.forecast[3].phraseDay, false));
		
		$('#link_hbh').attr('href','http://www.weather.com/weather/hourbyhour/'+o.zip).show();
		$('#link_10d').attr('href','http://www.weather.com/weather/tenday/'+o.zip).show();
		$('#link_i').attr('href','http://www.weather.com/weather/map/interactive/'+o.zip).show();
		
		$('#tipsContainerId .tipText:eq(0)').html(o.tips[0].text+'?').truncate(160);
		$('#tipsContainerId .tipText:eq(1)').html(o.tips[1].text+'?').truncate(160);
		
		$('#tipsContainerId').show();
		
		$('INPUT#forecastFormZip').val(o.zip);
		$('INPUT#forecastFormCity').val(o.city);
		$('SELECT#forecastFormState').styledDropDown({select:o.state});
		
		$._trackEvent("Forecast","ZIP", o.zip);
		$._trackEvent("Forecast","City", o.city);
		$._trackEvent("Forecast","State", o.state);
	});
};

window.clearForecast = function(message){
	$(document).ready( function() {
	var evening = new Date().getHours() >= 14;
	
	$('.forecastContainer H2:first').html(message);
	
	$('#forecastTable TR.day TD:eq(1)').html(evening?'Tonight':'Today');
	$('#forecastTable TR.day TD:eq(2)').html('Tomorrow');
	$('#forecastTable TR.day TD:eq(3)').html('&nbsp;');
	$('#forecastTable TR.day TD:eq(4)').html('&nbsp;');
	
	$('#forecastTable TR.pollen TD:gt(0)').html("--");
	
	$('#forecastTable TR.pollen-details TD:eq(1)').html("&nbsp;");
	
	$('#forecastTable TR.weather TD:gt(0)').html("--/--");
	
	$('#link_hbh').hide();
	$('#link_10d').hide();
	$('#link_i').hide();
	
	$('#tipsContainerId').hide();
	
	$('INPUT#forecastFormZip').val('ENTER ZIP CODE');
	$('INPUT#forecastFormCity').val('CITY');
	$('SELECT#forecastFormState').styledDropDown({select:''});	
	});
};

/**
 * get URL parameter value
 * @param a - parameter name
 * @return paramenter value
 */
var gup=function(a){a=a.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");var b="[\\?&]"+a+"=([^&#]*)";var c=new RegExp(b);var d=c.exec(window.location.href);if(d==null)return"";else return d[1]};

/**
 * Asynchronously attaches forecast
 * @param zip
 * @param city
 * @param state
 * @param callback
 */
function attachForecast(zip, city, state, callbackName){
	//document.write(unescape("%3Cscript src='./../data/forecast.json?zip="+zip+"&city="+city+"&state="+state+"&jsCallback="+callback+"' type='text/javascript'%3E%3C/script%3E"));
	attachScript("./../data/forecast.json?zip="+zip+"&city="+city+"&state="+state+"&jsCallback="+callbackName);
}

function getForecast(zip, city, state, callback){
	/*var forecastCallbackName = 'forecastcallback'+Math.round(new Date().getTime());
	window[forecastCallbackName] = callback;
	attachForecast(zip,city,state,"window."+forecastCallbackName);*/
	$.ajax({
		url:"./../data/forecast.json?zip="+zip+"&city="+city+"&state="+state,
		dataType: 'json',
		success: callback
	});
}

/**
 * Asynchronously attach script
 * @param src
 */
function attachScript(src){
	var head= document.getElementsByTagName('head')[0];
	var script= document.createElement('script');
	script.type= 'text/javascript';
	script.src= src;
	head.appendChild(script);
}

// If "zip" or "city" & "state" are set, fetch forecast for that location
if(gup('zip')||(gup('city')&&gup('state'))){
	window.dontUseCurrentLocation = true;
	getForecast(gup('zip'),gup('city'),gup('state'),function(obj){
		if(!obj.result){
			try{
				console.log('forecast failed: '+obj.reason);
				clearForecast(obj.reason);
			}catch(e){}
			return;
		}
		window.setTheForecast(obj.objects);
	});
}

// Meanwhile, get user forecast
window.googleApiCallback = function(){
	getForecast('',google.loader.ClientLocation.address.city,google.loader.ClientLocation.address.region,function(obj){
		if(!obj.result){
			try{
				console.log('currentLocationForecast failed: '+obj.reason);
			}catch(e){}
			return;
		}
		window.currentLocationForecast = obj.objects;
		if(!window.dontUseCurrentLocation){
			window.setTheForecast(window.currentLocationForecast);
		}
	});
};

// Based on user current location from google apis
var gaJsHost = (("https:" == document.location.protocol) ? "https://" : "http://");
//document.write(unescape("%3Cscript src='" + gaJsHost + "www.google.com/jsapi?callback=window.googleApiCallback' type='text/javascript'%3E%3C/script%3E"));
attachScript(gaJsHost + "www.google.com/jsapi?callback=window.googleApiCallback");



$(document).ready( function() {
    $.attachAtlas('cbnctn_AllergyForecast_1');
	//$.attachSpotlightTag('1608566','manag537','aller034');
	
	/*zipResult && $('INPUT#forecastFormZip').val(zipResult);
	stateResult && $('SELECT#forecastFormState').val(stateResult);
	cityResult && $('INPUT#forecastFormCity').val(cityResult);*/
	
	$('SELECT#forecastFormState').styledDropDown();
	
	
	$("FORM#forecastForm").submit(function(){
		$(".error",this).removeClass("error");
		//$("#getForecast").attr('disabled',true);
		var isZipValid = /^\d{5}$|^\d{5}-\d{4}$/.test($("#forecastFormZip").val());
		var isCityValid = /^.+$/.test($("#forecastFormCity").val()) && $("#forecastFormCity").val()!="CITY";
		var stateSelect = $("SELECT#forecastFormState")[0];
		var stateValue = stateSelect.options[stateSelect.selectedIndex].value;
		var isStateValid = /^.+$/.test(stateValue);
		
		if(isZipValid){
			// Async forecast request using zip
			$("#forecastFormCity,#forecastFormState",this).val("");
			getForecast($("#forecastFormZip").val(),'','',function(obj){
				if(!obj.result){
					try{
						console.log('forecast failed: '+obj.reason);
						clearForecast(obj.reason);
					}catch(e){}
					return;
				}
				window.setTheForecast(obj.objects);
			});
		}else{
			if(isCityValid && isStateValid){
				$("#forecastFormZip",this).val("");
				// Async forecast request using city,state
				getForecast('',$("#forecastFormCity").val(),$("#forecastFormState").val(),function(obj){
					if(!obj.result){
						try{
							console.log('forecast failed: '+obj.reason);
							clearForecast(obj.reason);
						}catch(e){}
						return;
					}
					window.setTheForecast(obj.objects);
				});
				return false;
			}else{
				$("#forecastFormZip").addClass("error");
				if(!isCityValid)
					$("#forecastFormCity",this).addClass("error");
				if(!isStateValid)
					$("DIV.stateDropdownContainer",this).addClass("error");
			}
		}
		//$("#getForecast").attr('disabled',false);
		return false;
	});
	
	//$(".tipsContainer P").truncate(160);
	
});