var home_currentHeroTab=1;
var home_currentNewsXpos=0;
var home_currentSearchTab=1;
var home_maxNewsXpos=0;
var home_tabSwitchTimeout;
var home_newsScrollTimeout;
var home_pageLoaded=0;
var tod_IEVersion = -1; 
var tod_FF = false;
var appName = navigator.appName.toLowerCase();
var appVersion = navigator.appVersion.toLowerCase();
var ua = navigator.userAgent.toLowerCase();
var searchBarBrowser = 'unknown';

/**********
UTILITY FUNCTIONS
**********/

function isBlank(s) {
	for (i=0;i<s.length;i++ ) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}
function createCookie(name,value,days) {
	var days = 3650;
	var expires;
	if (days) {
		var date = new Date();
	  	date.setTime(date.getTime()+(days*24*60*60*1000));
	  	expires = "; expires="+date.toGMTString();
	} else {
		expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/;domain=.orange.co.uk";
}

function readCookie(name) {
	var nameSG = name + "=";
	var nuller = '';
	if (document.cookie.indexOf(nameSG) == -1)	{
		return nuller;
	}

   	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ')c = c.substring(1,c.length);
			if (c.indexOf(nameSG) == 0) return c.substring(nameSG.length,c.length); 
  	}
	return null; 
}

function eraseCookie(name) {
	createCookie(name,"",3650); 
}

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';
}

/**********
END OF UTILITY FUNCTIONS
**********/

function home_init() {
	track_links();
	loadWeather();
	home_tabSwitchTimeout=setTimeout("home_automatedTabSwitch()",6000);
	home_newsScrollTimeout=setInterval("home_newsScroll()",25);
	var dupe;
	var width;
	var totalWidth=0;
	var firstChild=null;
	var el=document.getElementById("home_newstickerscroller");
	var childnodesLength=el.childNodes.length;
	for (var index=0; index<childnodesLength; index++) {
		child=el.childNodes[index];
		if (child.tagName=="LI") {
			dupe=child.cloneNode(true);
			el.appendChild(dupe);
			if (window.getComputedStyle) {
				width=parseInt(document.defaultView.getComputedStyle(child, null).getPropertyValue("width"))+17;
			} else {
				width=child.clientWidth;
			}
			totalWidth+=parseInt(width);
		}
	}

	document.getElementById("hometab1content").style.visibility="hidden";
	document.getElementById("hometab1content").style.visibility="visible";

	home_maxNewsXpos=totalWidth;

	home_pageLoaded=1;

}

function home_automatedTabSwitch() {
	home_activateHeroTab(home_currentHeroTab+1);
	home_tabSwitchTimeout=setTimeout("home_automatedTabSwitch()",8000);
}
function home_stopTabSwitching() {
	if (home_tabSwitchTimeout!=null) {
		clearTimeout(home_tabSwitchTimeout);
		home_tabSwitchTimeout=null;
	}
}
function home_newsScroll() {
	document.getElementById("home_newstickerscroller").style.clip="rect(0px "+(248+home_currentNewsXpos)+"px 23px "+(0+home_currentNewsXpos)+"px)";
	document.getElementById("home_newstickerscroller").style.left=(46-home_currentNewsXpos)+"px";
	home_currentNewsXpos++;
	if (home_currentNewsXpos>home_maxNewsXpos) {
		home_currentNewsXpos=0;
	}
}
function home_stopNewsScrolling() {
	if (home_pageLoaded) {
		if (home_newsScrollTimeout!=null) {
			clearInterval(home_newsScrollTimeout);
			home_tabSwitchTimeout=null;
		}
	}
}
function home_startNewsScrolling() {
	if (home_pageLoaded) {
		home_newsScrollTimeout=setInterval("home_newsScroll()",25);
	}
}
function var_dump(obj) {
   if(typeof obj == "object") {
      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
   } else {
      return "Type: "+typeof(obj)+"\nValue: "+obj;
   }
}
function home_activateHeroTab(tabIndex) {

	if (!document.getElementById("hometab"+tabIndex)) {
		tabIndex=1;
	}
	if (tabIndex!=home_currentHeroTab) {
		document.getElementById("hometab"+home_currentHeroTab).className="";
		document.getElementById("hometab"+home_currentHeroTab+"content").style.visibility="hidden";
		document.getElementById("hometab"+tabIndex).className="active";
		document.getElementById("hometab"+tabIndex+"content").style.visibility="visible";
		document.getElementById("hometab"+tabIndex+"content").style.zIndex="100";
		home_currentHeroTab=tabIndex;
	}
	return(false);
}


function home_activateSearchTabByTabIndex() {
	var tabIndex = "2";
	var query;
	
	query=document.getElementById("q"+home_currentSearchTab).value;
	document.getElementById("q"+home_currentSearchTab).value="";
	
	if (query!="") {
		document.getElementById("q"+tabIndex).value=query;
	} 
	
	if (tabIndex!=home_currentSearchTab) {
		document.getElementById("home_searchtab"+tabIndex).firstChild.className="active";
		document.getElementById("home_searchtab"+tabIndex).blur();
		document.getElementById("home_searchtab"+home_currentSearchTab).firstChild.className="";
		document.getElementById("home_searchform"+tabIndex).style.visibility="visible";
		document.getElementById("home_searchform"+home_currentSearchTab).style.visibility="hidden";
		home_currentSearchTab=tabIndex;
	}
	
	return(false);
}

function home_activateSearchTab(sourceObject) {

	tabIndex=parseInt(sourceObject.parentNode.id.substr(14));

	var tab;
	var query;
	if (home_currentSearchTab==3) {
		query=document.getElementById("what").value;
		document.getElementById("what").value="";
	} else {
		query=document.getElementById("q"+home_currentSearchTab).value;
		document.getElementById("q"+home_currentSearchTab).value="";
	}

	var changeTabs=false;
	if (query!="") {
		if (tabIndex==3) {
			document.getElementById("home_searchform"+tabIndex).elements.what.value=query;
		} else {
			document.getElementById("q"+tabIndex).value=query;
		}
		changeTabs=true;
	} else {
		changeTabs=true;
	}

	if (changeTabs) {
		if (tabIndex!=home_currentSearchTab) {
			document.getElementById("home_searchtab"+tabIndex).firstChild.className="active";
			document.getElementById("home_searchtab"+tabIndex).blur();
			document.getElementById("home_searchtab"+home_currentSearchTab).firstChild.className="";
			document.getElementById("home_searchform"+tabIndex).style.visibility="visible";
			document.getElementById("home_searchform"+home_currentSearchTab).style.visibility="hidden";
			home_currentSearchTab=tabIndex;
		}
	}

	return(false);
}
function home_pressSearchButton(f) {
	var pt;
	var tabId;
	switch(f.id) {
		case 'home_searchform1':
			tabId = 1;
			if (document.getElementById("home_searchform1").elements.org[0].checked) {
				pt="todayweb_hp"+hp;
				tab="allorg";
			} else {
				pt="todayuk_hp"+hp;
				tab="home";
			}
			document.getElementById("home_searchform1").elements.tab.value=tab;
			break;
		case 'home_searchform2':
			tabId = 2;
			pt="todaysite_hp"+hp;
			break;
		case 'home_searchform3':
			tabId = 3;		
			pt="todaylocal_hp"+hp;
			break;
		case 'home_searchform4':
			tabId = 4;
			pt="todaypics_hp"+hp;
			break;
		case 'home_searchform5':
			tabId = 5;
			pt="todayshop_hp"+hp;
			break;
		case 'home_searchform6':
			tabId = 6;
			pt="todayvid_hp"+hp;
			break;
	}
	document.getElementById(f.id).pt.value = pt;
	if(tabId==3) {
		if (isBlank(document.getElementById("what").value) && isBlank(document.getElementById("what").value)) {
			alert("Please type in a business/service or location before searching");
			return(false);
		}
	} else {
		if(isBlank(document.getElementById("q"+tabId).value))	{
			alert("Please type in one or more terms before searching");
			return(false);
		}
	}
	return(true);
}

function home_openSetAsHomepage(dest) {
	window.open (dest,"setashomepage","menubar=0,resizable=1,width=500,height=400,scrollbars=1"); 
	return(false);
}

/* *****************
ONE THIRD EMAIL FUNCTIONS
***************** */
function random(x){
	// random number between 0 and x-1
	y=Math.floor(Math.random()*x);
	return(y==x)?x-1:y;
}
function toMem(a) {
    createCookie('otelEmail', document.getElementById('otelEmail').value);     // add a new cookie as shown at left for every
    createCookie('otelPswd', document.getElementById('otelPswd').value);   // field you wish to have the script remember
}

function delMem(a) {
  eraseCookie('otelEmail');   // make sure to add the eraseCookie function for every field
  eraseCookie('otelPswd');
}
function pirateMemory(a) {
	if (document.getElementById('emailChecker').checked) {
		toMem(a);
	}
	else {
		delMem(a);
	}
}
function chkOneThirdEmailLogin(id) {
	var sCalledFrom = document.location.href;
	var rpStr = "https://web.orange.co.uk/r/login/?rm=checkform";
	var submitURL = "webmail";
	var str = document.getElementById("otelEmail").value;
	var num = random(3)+1;
       var wStr = "http://fsmail0" + num + ".orange.co.uk/webmail/en_GB/connexion_multi_domains_submit.html";
	var myre = /07[0-9]{9}/;
	var myre2 = /^[-_a-zA-Z0-9]+(\.?[-_a-zA-Z0-9])*@orange\.net/;
	var myre3 = /^[-_a-zA-Z0-9]+(\.?[-_a-zA-Z0-9])*@fsmail\.net/;
   	if (str.match(myre)) { submitURL = "orange"; }
       if (str.match(myre2)) { submitURL = "orange"; }
       if (str.match(myre3)) { submitURL = "fsmail"; }
	switch (submitURL) {
		case "orange":
			document.getElementById(id).setAttribute("action", "https://services.orange.co.uk/sam/loginintercept");
			break;
		case "webmail":
			document.getElementById(id).setAttribute("action", rpStr);
			break;
		case "fsmail":
			document.getElementById(id).setAttribute("action", wStr);
			break;
		default:
			document.getElementById(id).setAttribute("action", rpStr);
	}
		//Check for values in the fields
	if (isBlank(document.getElementById("otelEmail").value) || isBlank(document.getElementById("otelPswd").value))	{
		if(isBlank(document.getElementById("otelEmail").value))	{
			alert('Please enter your username');
		}
		if(isBlank(document.getElementById("otelPswd").value))	{
			alert('Please enter your password');
		}
		return false;
	}
	else	{
		todTrackPopUnder('FSMail','today');
		document.forms[id].submit();
	}
}
// Pop-under tracking script
function todTrackPopUnder(str_trackInfo,str_whereFrom){
	var str_newLocation = '/popup/popTrack/default.htm?linkto=' + str_trackInfo + '&linkfrom=' + str_whereFrom;
	str_features = 'width=127,height=40';
	window2 = window.open(str_newLocation,'todayPopUnder',str_features);
	window2.blur()
	window.focus()
}
	
/*
LINK TRACKING FUNCTIONS
*/
/*
    Filename: 	linktrack_funcs.js 
	Purpose:  	clientside tracking functionality. Reads flattened SED CMS html pages and transforms
				all links within the page with tracking data by replacing CMS created placeholders with channel / page info. 
				Also contains a method for tracking form submitions. All code is based on orginally cminclude.js file
				within the wanadooo portal.
	Author:		Phil Darley
	Date:		15.12.2005
*/

//URL for html tracking page must add ? @ end for parameters
var trackURL = "/pagebuilder/admin/tools/tool_track.htm?";

// only write the tool tracking iframe for http pages
function drawTrackFrame(){	
	
	

	if (document.URL.substring(0,5) != 'https' && typeof document.getElementById("tooltrack")!= null ) 	{
		document.write('<div id="div_tooltrack" style="display:none;"><iframe id="tooltrack" name="tooltrack" width="0" height="0" src="about:blank"></iframe></div>');
		var iframe_loaded = "no";	
	}
}

function appendTrackFrame(){
	if (document.URL.substring(0,5) != 'https' && typeof document.getElementById("tooltrack")!= null ){
		var newIFrame = document.createElement("iFrame");
		
		newIFrame.setAttribute("id","tooltrack");
		newIFrame.setAttribute("name","tooltrack");
		newIFrame.setAttribute("src","about:blank");
		
		newIFrame.setAttribute("style","display:none;");
		newIFrame.setAttribute("height","0");
		newIFrame.setAttribute("width","0");
	
		document.body.appendChild(newIFrame);
	}
}

//function to get name of the current page
function getPageName()
{
	var s_str1 = new String();
	var s_str2 = new String();
	if (document.location.pathname == "/"){
		s_thisPagename = 'hp' + hp;
	}
	else{
		var thePathnameShort = document.location.pathname;
		s_str1 = thePathnameShort.substring(1,thePathnameShort.length);
		var s_thisPagename = "";
		for (var h=0; h<s_str1.length; h++){
			if (s_str1.charAt(h) == "/")
				{s_thisPagename = s_thisPagename + "_";}
			else
				{s_thisPagename = s_thisPagename + s_str1.charAt(h);}
		}
	}
	
	if(s_thisPagename == "default.htm" || s_thisPagename == "default1.htm" || 
			s_thisPagename == "default2.htm" || s_thisPagename == "default3.htm" || s_thisPagename == "default4.htm"){
			s_thisPagename = 'hp' + hp;
	}
	return s_thisPagename;
}

//function to return channel name, if we are in a channel
function getChannelName(){
	var theChannelName = "";
	document.location.pathname.split("/").length > 1? 
			theChannelName = document.location.pathname.split("/")[1] : theChannelName = "";
	return theChannelName;
	
}

//function to track all links within the DOM for the current page
function track_links(){

	var i_articlelinkno = 1;
	var reFileExt = /\..*/;
	var s_thisPagename = getPageName().replace(reFileExt,""); //gives us the replacement value for the bp_trackingPage value
	var re = /[^_a-zA-Z0-9\.]/g; //Regex for removing special characters
	var a_doclinks = document.links; //create an array of all link objects in the page
	var s_temp; //temp var to hold the replacement strings
	var s_thisChannel = getChannelName().replace(re,""); //replacement value for the bp_trackingChannel

	//Loop over all the links within the page replacing the placeholders
	for (var i_doclinks=0; i_doclinks<a_doclinks.length; i_doclinks++){
		
		s_temp = new String (unescape(a_doclinks[i_doclinks].href));
		s_temp = s_temp.replace("<!--linkfromvariable-->", s_thisPagename);
		s_temp = s_temp.replace("<!--channelnamevariable-->", s_thisChannel);
		if (s_temp.indexOf("%bp_archiveLinkNo%") != 0)	{
			s_temp = s_temp.replace("%bp_archiveLinkNo%", i_articlelinkno);
			i_articlelinkno++;
		}
		
		//Extra code to strip // from TP external links 
		if (s_temp.indexOf("//redirect") != -1)	{	
			s_temp = s_temp.replace("//redirect", "/redirect");	
		}
		
		document.links[i_doclinks].href = s_temp;
	}
}



function track_ttlinks(IframeId)	{

	//alert(IframeId);

	var reFileExt = /\..*/;
	var s_thisPagename = getPageName().replace(reFileExt,""); //gives us the replacement value for the bp_trackingPage value
	var re = /[^_a-zA-Z0-9]/g; //Regex for removing special characters
	var s_thisChannel = getChannelName().replace(re,""); //replacement value for the bp_trackingChannel
	var s_temp; //temp var to hold the replacement strings
	var a_tablinks = "";
	var browsertype="";
	
	//track links in tabbed tools
	try {
	if (typeof document.getElementById(IframeId) !='undefined')	
	{
	
		if (typeof document.getElementById(IframeId).contentDocument != 'undefined')	{
			if (typeof document.getElementById(IframeId).contentDocument.links != 'undefined')	{
				a_tablinks =  document.getElementById(IframeId).contentDocument.links;
				browsertype="moz";
			}
		}
		
		if (typeof document.frames != 'undefined')	{
			if (typeof document.frames[IframeId].document != 'undefined')	{	
				if (typeof document.frames[IframeId].document.links != 'undefined')	{
					a_tablinks = document.frames[IframeId].document.links;
					browsertype="ie";		
				}		
			}
		}
						
		if (browsertype != "")	{
		
			for (i_tablinks=0; i_tablinks<a_tablinks.length; i_tablinks++)	{
				
				i_articlelinkno = 1;
		
				if (browsertype == "moz") s_temp = new String (unescape(a_tablinks[i_tablinks].href));
				if (browsertype == "ie") s_temp = new String (unescape(a_tablinks[i_tablinks]));
				
				s_temp = s_temp.replace("<!--linkfromvariable-->", s_thisPagename);
				s_temp = s_temp.replace("<!--channelnamevariable-->", s_thisChannel);
			
				if (s_temp.indexOf("%bp_archiveLinkNo%") != 0)	{
					s_temp = s_temp.replace("%bp_archiveLinkNo%", i_articlelinkno);
					i_articlelinkno++;
				}
				
				//Extra code to strip // from TP external links 
				if (s_temp.indexOf("//") != 0)	{
					s_temp = s_temp.replace("//redirect", "/redirect");
				}
				if (browsertype == "moz") {document.getElementById(IframeId).contentDocument.links[i_tablinks].href = s_temp;}
				if (browsertype == "ie")  {document.frames[IframeId].document.links[i_tablinks].setAttribute('href',s_temp);}
			
			}
		}
	}
	} catch (e) {  }
}

//Function to track dropdown links
function track_dropdown_links(linkToTrack)	{

	var reFileExt = /\..*/;
	var s_thisPagename = getPageName().replace(reFileExt,""); //gives us the replacement value for the bp_trackingPage value
	var re = /[^_a-zA-Z0-9]/g; //Regex for removing special characters
	var s_thisChannel = getChannelName().replace(re,""); //replacement value for the bp_trackingChannel
	var s_temp; //temp var to hold the replacement strings
	var i_articlelinkno = 1;
	s_temp = new String (unescape(linkToTrack));
	s_temp = s_temp.replace("<!--linkfromvariable-->", s_thisPagename);
	s_temp = s_temp.replace("<!--channelnamevariable-->", s_thisChannel);
	if (s_temp.indexOf("%bp_archiveLinkNo%") != 0)	{
		s_temp = s_temp.replace("%bp_archiveLinkNo%", i_articlelinkno);
		i_articlelinkno++;
	}
	
	//Extra code to strip // from TP external links 
	if (s_temp.indexOf("//") != 0)	{
		
		s_temp = s_temp.replace("//redirect", "/redirect");
		
	}
	
	return s_temp;
}

//function to track form submissions
function track(trackObj, s_link, s_act, partner_func){
		appendTrackFrame();
		try	{
			if (typeof partner_func != 'undefined'){	
				if (partner_func != true){
					return false;
				}
			}
			var rnd;
			rnd = Math.random();
			
			var s_act_nohttp = new String(s_act);
			if (s_act_nohttp.substring(0,7) == 'http://'){
				s_act_nohttp = s_act_nohttp.substring(7,s_act_nohttp.length);
			}
			var tracking_string = trackURL + "linkfrom="+ getPageName()+"&article="+trackObj+"&link="+s_link+"&linkto="+s_act_nohttp+"&rnd="+rnd;
			document.getElementById("tooltrack").src = tracking_string;
		}
		catch (e)	{
			//alert(e);
			return false;
		}
		return true;
}

//HP Link tracking for HP.
function setHPLinkTracking(s){
	if(!s) return '';
	s = s.replace(/<!--linkfromvariable-->/gi,"hp" + hp);	
	return s;
}


//this part ensures links are tracked even when clicked before page is loaded.
var re = /(\<|\%3C)!--linkfromvariable--(\>|\%3E)/;

if (window.captureEvents){
	window.captureEvents(Event.ONMOUSEUP);
    window.onmouseup = function(e){
    	setAnchor(e);
	}
}else{
	document.onclick= function(e){
		var e=(typeof event!=='undefined')? event.srcElement : e.target;
		setAnchor(e);
  	}
}

function setAnchor(e){
/**
   	alert('setAnchor pagename = '+ getPageName());
	var o_anchor = (e.target) ? e.target: e;
	alert('tagName = ' + o_anchor.tagName);   
   	if((o_anchor.tagName == "A")|(o_anchor.parentNode.tagName == "A")){
   		//alert('detected');
		var o_anchorHref = (o_anchor.tagName == "A") ? o_anchor: o_anchor.parentNode;
		//alert('href before : ' + o_anchorHref.href);
		o_anchorHref.href = o_anchorHref.href.replace(re,getPageName());
		//alert('href after : ' + o_anchorHref.href);
   	}
*/
}
/* ***********************
	WEATHER FUNCTIONS
 *********************** */
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 = "Oops, we can't find a region for that search. Try a city name or UK postcode, like 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);
		appendDiv("dynamicOverviewDiv","WKdescription",o);
		bSave = false;
		
	}else{
		errorStr = null;
		bSave = true;
		if(typeof WK != 'undefined'){
			appendDocumentToDom("http://www.orange.co.uk/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.getElementById("location").value;
	
	for (i=0;i<postcodeStr.length;i++) {
		if (postcodeStr.charCodeAt(i)>47 && postcodeStr.charCodeAt(i)<59) {
			isPC = true;
		}
	}
	if (postcodeStr.length<2 || postcodeStr == "postcode/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("http://www.orange.co.uk/weather/weathersearch/sed_lookup_ajax.cfm?wk=" + postcodeStr,"CF_AJAX_LOOKUP");
		WK = postcodeStr;
		//If the savelocaton checkbox is checked then call the remember function
		if (document.getElementById("savelocation").checked)	{
			remember();
		}
		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 == "postcode/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="http://www.orange.co.uk/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.getElementById("wk").value = unescape(pstcd);
	}else{
	}
}

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.getElementById("location").value;
		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 check the 'save location' checkbox 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];
				
	}
	
	
	
	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","WKdescription",o);
	document.getElementById("weatherLocation").innerHTML = 'in <strong>'+city+'</strong>';
}

function renderForcast(forcast,ele){
	
	var o = '';

	o += '<div class="WKday">';
		o += '<h3>'+validateFeedData(forcast.dayname) + '</h3>';
	if(validateFeedData(forcast.dayicon) != 'n/a')	{
		o += '<img src="http://www.orange.co.uk/images/news/weather/icons/small/' + forcast.dayicon + '.gif" alt="' + forcast.dayphrase + '" />';
	}
	else	{
		o += '<img src="http://www.orange.co.uk/images/t.gif" alt="" />';
	}
		o += '<ul><li><strong>H:</strong> ' + validateFeedData(forcast.high) + 'C</li>';
		o += '<li><strong>L:</strong> ' + validateFeedData(forcast.low) + 'C</li></ul>';
	o += '</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("http://www.orange.co.uk/jsincludes/feeds/" + wCode + ".js","JS_WEATHER");
	}else{
		appendDocumentToDom("http://www.orange.co.uk/jsincludes/feeds/" + WK + ".js","JS_WEATHER");
	}
	
}

