var wCode = "UKXX0085"
var bp_trackingObject='weathertool';
var pstcd = ""
var URHere = document.location.search.toString();
var errMsg = "";
var debug = false;
var WK = null;
var bSave = true;
var iLoadCounter = 0;

function appendDocumentToDom(url,id,onLoadEvent){
	
	if(debug)
		alert("appendDocumentToDom called");

	if (document.createElement && document.body.appendChild){
		try {
			if(debug)
				alert("entered : if (document.createElement && document.body.appendChild)");
			
			if(id == null)
				var id = 'JS_WEATHER';
			
			var oldJs = document.getElementById(id);
			if (oldJs){
			
				if(debug)
					alert("tryin to remove : " + oldJs);
					
				document.body.removeChild(oldJs);
			}
			
			// add the element
			var e=document.createElement('SCRIPT');
			e.setAttribute('language','javascript');
			e.setAttribute('src',url);
			e.setAttribute('id',id);
			
			if(debug)
				alert("created element attempting to append to document");
		
			document.body.appendChild(e);
			
			if(debug)
				alert("appended element to document");
				
			iLoadCounter++;

		}
		catch (all){
			if(debug)
				alert(all);
		}
	} else {
		alert("Sorry your browser doesn't support the functionality required, please upgrade.");
	}
}



//look for stored cookie postcode
var strCookie = document.cookie;
strCookie = unescape(strCookie);
var cookiePos = strCookie.indexOf("OforecastAJAX");

if (cookiePos!=-1) {
	var weatherCode = strCookie.substring(cookiePos+14,cookiePos+22);
	if (weatherCode.indexOf(";")!=-1) {
		weatherCode = weatherCode.substring(0,weatherCode.indexOf(";"));
	}
	
	//var newLocation = "/weather/weathersearch/ajax_lookup.cfm?wk=" + weatherCode;
	//appendDocumentToDom(newLocation,'CF_AJAX_LOOKUP');
	WK = weatherCode;
	//alert(WK);
	
	
}



function updateTool(errorStr,WK){
	
	//alert("updateTool() called by CF script");
	
	if(typeof errorStr == 'undefined' && typeof WK == 'undefined'){
		if(debug)
			alert("AJAX error no js vars set by CF script");
		
		var errorStr = "505";
	}
	
	
	
	if(typeof errorStr != 'undefined' && errorStr !=null){
		switch(errorStr){
			case "404": 
				o = "Sorry, but we were unable to find a weather region matching your search. Please enter a valid " +
						" UK postcode or city e.g. Leeds or LS27 5JX.";
				break;
			default:
				o = "Sorry, an error occured when trying to find a weather region matching your search. Please try again."
				break;
		}
		errorStr = null;
		appendDiv("dynamicDescDiv","WKdescription",o);
		bSave = false;
		
	}else{
		errorStr = null;
		bSave = true;
		if(typeof WK != 'undefined'){
			appendDocumentToDom("/jsincludes/feeds/" + WK + ".js","JS_WEATHER");
		}
	}
		
	
}

function appendDiv(divId,targetDivId,innerHTML){
	
	if(debug)
		alert("appendDiv ("+divId+ ","+ targetDivId+","+innerHTML +")");
	
	try{
	
  	
	var oldDiv = document.getElementById(divId);
	
	
	newDiv = document.createElement("div");
	newDiv.setAttribute('id',divId);
  	newDiv.innerHTML = innerHTML;
	
	if(debug)
		alert("created new Div element and set innerHTML on the div");
	if (oldDiv){
		if(debug)
			alert("attempting to replaceChild");
		document.getElementById(targetDivId).replaceChild(newDiv,oldDiv);
	}else{
		if(debug)
			alert("attempting to appendChild");
			
		document.getElementById(targetDivId).appendChild(newDiv);
	}
	
  	}catch(err){
		if(debug)
			alert(err.description + ", id: " + targetDivId);
	}
}

function refreshDiv(id){
	var div = document.getElementById(id);
	div.style.display = 'all';
}

function go() {
	
	var isPC = false;
	var postcodeStr = document.forms["weatherForm"].elements["wk"].value.toString();
	for (i=0;i<postcodeStr.length;i++) {
		if (postcodeStr.charCodeAt(i)>47 && postcodeStr.charCodeAt(i)<59) {
			isPC = true;
		}
	}
	if (postcodeStr.length<2 || document.forms["weatherForm"].elements["wk"].value.toString() == "type in postcode or town") {
		alert ("You have not entered a valid postcode or town name");
		return false;
	}
	else if (isPC==true && postcodeStr.length>4 && postcodeStr.indexOf(" ")==-1) {
		alert("Please include a space in your postcode");
		return false;
	}
	else {
		//alert('go() appendDocumentToDom("/weather/weathersearch/ajax_lookup.cfm?wk="' + postcodeStr);
		//make ajax call to cf script
		appendDocumentToDom("/weather/weathersearch/sed_lookup_ajax.cfm?wk=" + postcodeStr,"CF_AJAX_LOOKUP");
		return false;
	}
}
function goExtended() {
	
	
	
	if(typeof WK == 'undefined'){
		if(typeof key != 'undefined')
			var WK = key;
		else
			var WK = wCode;
	}
	
	winExt = window.open("http://uk.weather.com/weather/10day-"+WK);

}
function clearTxt(input){
	if(input.value == "type in postcode or town") input.value = "";
}

/****code taken from existing weather.js file***********/

/*
* History:  JL 27.08.2002 - Updated large if() blocks with case blocks for speed.
*/
var nameMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December")
var decMonths = new Array("01","02","03","04","05","06","07","08","09","10","11","12")

function PageQuery(q) {


	
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) { /*try if not == null*/
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
			return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; } 
}

function queryString(thiskey){
	var page = new PageQuery(window.location.search);
	
	
		
	return unescape(page.getValue(thiskey));
}


function writeinclude(thiskey){
	document.write('<script language="JavaScript" src="/jsincludes/feeds/' + thiskey + '.js"></script>');
}



function fillItIn() {
	
	
		
	if(URHere.indexOf("originalquery")!=-1) {
		pstcd = URHere.substring(URHere.indexOf("originalquery")+14)
		pstcd = pstcd.substring(0,pstcd.indexOf("&"))
		document.forms["weatherForm"].elements["wk"].value = unescape(pstcd);
	}else{
		document.forms["weatherForm"].elements["wk"].value = "type in postcode or town";
	}
}

function remember() {

	if (WK == null)	{
		alert("Please click the search button first to look up your weather details.");
		return;
	}
	
	if(!bSave){
		alert("Your current location can not be stored as your location can not be found, please try a new search");
		
	}else{

	if (confirm("This information will be stored on your computer as a text file called a cookie. Do you wish to continue?")) {
		var expires = new Date();
		var input = document.forms["weatherForm"].elements["wk"].value.toString();
		expires.setTime(expires.getTime() + 24 * 60 * 60 * 1000 * 364);
		var cookieStr = "OforecastAJAX=" + WK + ";expires="+expires.toGMTString()+";";
		
		
		
		if (input.length > 1 && input != "no original query" && errMsg == "" && input != "type in postcode or town") {
			document.cookie = cookieStr;
			alert ("Your location has now been saved.\nNext time you access this page your local weather reports will be displayed.")
		}
		else {
			alert("Please enter a postcode into the input field, then click on the 'remember your location' link again.")
		}
	}
	
	}
}

//rendering methods
function getday(daynum){
	for (a=0;a<=forcasts.length;a+=1){
		if(forcasts[a].daycode==daynum){
			
			return forcasts[a];
		}
	}
	document.write('failed to return a forcast');
	return false;	
}
function getyear(forecast) {
	var strDate = '' + forecast.date;
	var year = strDate.substr(0,4);
	return year;
}
function getmonth(forecast) {
	var strDate = '' + forecast.date;
	var month = strDate.substr(4,2);
	for (i=0;i<decMonths.length;i++) {
		if (month == decMonths[i]) {
			month = nameMonths[i]
		}
	}
	return month;
}
function getdateday(forecast) {
	var strDate = '' + forecast.date;
	var dateday = strDate.substr(6,2);
	
	return dateday;
}
function gethour(forecast) {
	forcast = getday('hourly');
	var strTime = '' + forcast.time;
	var hour = strTime.substr(0,2);
	var amorpm = 'am';
	if (parseInt(hour)>11) {
		amorpm = 'pm';
	}
	if (parseInt(hour)>12) {
		hour = "" + parseInt(hour)-12;
	}
	var fulltime = hour + '' + amorpm;
	return fulltime;
}

function getWeatherDescription(id){

	//alert("getWeatherDescription called");
	var o = "";
	
	if( typeof forcasts != 'undefined'){
		forcast = forcasts[0];

		if(getdateday(forcast)!="*" && getdateday(forcast)!="" ){
			o ='Conditions reported at ' + city ;
			
			
			
	    	switch (country) {
	        case 'SCT' :
	            o+= " (Scotland) ";
	            break;
	        case 'ENG' :
	            o+=" (England) ";
	            break;
	        case 'WLS' :
	            o+=" (Wales) ";
	            break;
	        case 'NIR' :
	            o+=" (Northern Ireland) ";
	            break;
	   	 }
		if (orig()!= 'no original query') {
				o+=' (which is the nearest meteorological station to ' + orig() + ')';
			}
		
			o+=' on the ' + getdateday(forcast) + ' of ' + getmonth(forcast) + ' ' + getyear(forcast) + ' at ' + gethour() + '.'; 
		
		}else{
			o+= '<b>Sorry but the hourly forecast for your region is currently unavailable.</b>';
		}
	
	}
	
	
	
	appendDiv("dynamicDescDiv","WKdescription",o);
 }
 
 
function orig() {
	var orig = queryString("originalquery")
	if (orig != null && orig != "" && orig != "false") {
		return orig;
	}
	else {
		return "no original query";
	}
}


function outputWeatherOverview(){
	if(debug)
		alert("outputWeatherOverview() called");
		
	var o = '';
	o += renderForcast(forcasts[0],1);
	o += renderForcast(forcasts[1],2);
	
	//alert(o);	
	
	appendDiv("dynamicOverviewDiv","weatherOverview",o);
}

function renderForcast(forcast,ele){
	
	var o = '';

	o += '<div id="WKday' + ele +'">';
	
	if(validateFeedData(forcast.dayicon) != 'n/a')
		o += '<b style="font-size:11px;"><img style="margin-top:-5px;margin-right:2px;" src="/images/news/weather/icons/small/' + forcast.dayicon + '.gif" border="0" width="25" height="25" align="left" hspace="0">';
	else
		o += '<b style="font-size:11px;"><img src="/images/t.gif" border="0" width="25" height="25" align="left" style="margin-top:-5px;margin-right:2px;" hspace="0">';
	o += validateFeedData(forcast.dayname) + '</b>';
	o += '<p style="clear:both;margin-top:-3px;">High: ' + validateFeedData(forcast.high);
	o += '<br>Low: ' + validateFeedData(forcast.low);
	o += '<br>';
		if(validateFeedData(forcast.dayphrase)=='n/a')
			o += 'summary: n/a';
		else
			o += forcast.dayphrase;
	o += '</p></div>';
	
	return o;
}

function validateFeedData(feedData){
	
	//alert("validateFeedData");

	if(feedData == null || feedData == '' || feedData ==  '*')
		return 'n/a';
	else	
		return feedData;
}

//default get weather
function loadWeather(){
	
	

	if(typeof WK == 'undefined' || WK == null){
		appendDocumentToDom("/jsincludes/feeds/" + wCode + ".js","JS_WEATHER");
	}else{
		appendDocumentToDom("/jsincludes/feeds/" + WK + ".js","JS_WEATHER");
	}
}

var isIE = false;

if (navigator.appName=="Microsoft Internet Explorer") 
	isIE=true;



