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';
var dayNames=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var monthNames=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var today=new Date();

function displayDateSuffix(d) {
    var s='th';
    if(d===1 || d==21 || d==31) s='st';
    if(d===2 || d==22) s='nd';
    if(d===3 || d==23) s='rd';
    return s;
}

var displayDate=dayNames[today.getDay()]+" "+today.getDate()+displayDateSuffix(today.getDate())+" "+monthNames[today.getMonth()];


/**********
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);
	if (document.getElementById("home_pushdown")) {
		if (ouk_pushdown_open_automatically) {
			ouk_pushdown_obj.auto_expand();
		}
	}
	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 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_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;
		}

		var pt="";
		switch(tabIndex) {
			case 1:
				if (document.getElementById("home_searchform1").elements.weboruk[0].checked) {
					pt="todayweb_hp"+hp+"_link";
					tab="web";
				} else {
					pt="todayuk_hp"+hp+"_link";
					tab="home";
				}
				document.getElementById("home_searchform1").elements.tab.value=tab;
				break;
			case 2:
				pt="todaysite_hp"+hp+"_link";
				break;
			case 3:
				pt="todaylocal_hp"+hp+"_link";
				break;
			case 4:
				pt="todaypics_hp"+hp+"_link";
				break;
			case 5:
				pt="todayshop_hp"+hp+"_link";
				break;
			case 6:
				pt="todayvid_hp"+hp+"_link";
				break;
		}

		document.getElementById("home_searchform"+tabIndex).elements.pt.value=pt;
		if (tabIndex==3) {
			if (tabIndex==home_currentSearchTab) {
				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 {
					document.getElementById("home_searchform"+tabIndex).submit();
				}
			} else {
				changeTabs=true;
			}

		} else {
			if(isBlank(document.getElementById("q"+tabIndex).value))	{
				alert("Please type in one or more terms before searching");
				return(false);
			} else {
				document.getElementById("home_searchform"+tabIndex).submit();
			}
		}
		
	} else {
		// If local tab is clicked on and no search term has been entered then redirect user to the main local search page.
		if(tabIndex == 3) { document.location.href = "http://search.orange.co.uk/all?brand=ouk&tab=local&section=home "; }
		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;
			//If we're on the local tab we need a different focus
			if (tabIndex == 3)
			{
				document.getElementById("what").focus();
			}
			else	{
				document.getElementById("q"+tabIndex).focus();
			}
		}
	}

	return(false);
}
function home_pressSearchButton(f) {
	var pt;
	var tabId;
	switch(f.id) {
		case 'home_searchform1':
			tabId = 1;
			if (document.getElementById("home_searchform1").elements.weboruk[0].checked) {
				pt="todayweb_hp"+hp;
				tab="web";
			} 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) {

        el=document.getElementById("setashomepage");
        el.style.behavior='url(#default#homepage)';
        try {
            el.setHomePage('http://www.orange.co.uk');
        } catch (e) { 
            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");	
		}

		if (s_temp.indexOf(window.location.hostname+"/default.htm/redirect") != -1) {
			s_temp = s_temp.replace(window.location.hostname+"/default.htm/redirect",window.location.hostname+"/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 bError = false;
var iLoadCounter = 0;

function appendDocumentToDom(url,id,onLoadEvent){
	
	if(debug)
		alert("appendDocumentToDom("+url+" 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);
		
		setErrorMessage(o);
		bError = true;
		//alert('bError set to true.');
		bSave = false;
		
	}else{
		errorStr = null;
		bSave = true;
		bError = false;
		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() {
	// reset error flag.
	bError = false;
	bSave = true;
	var isPC = false;
	var postcodeStr = document.getElementById("weatherlocation").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");
		setErrorMessage("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");
		setErrorMessage("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)	{
			setTimeout('remember()', 500);
		//}
		if(debug) { alert('Should i close the modal window now?'); }
		if(!bError) {
		    //ouk_closeWeatherForm();
		    // Reset the error message (if any).
			if(document.getElementById('home_weatherlightboxerror').innerHTML) {
				setErrorMessage('');
			}
		}
		return false;
	}
}
function setErrorMessage(msg) {
	//alert('setErrorMessage(' + msg + ')');
	if(msg == '') {
	    document.getElementById('home_weatherlightboxerror').style.display = 'none';
		document.getElementById('home_weatherlightboxerror').innerHTML = msg;
	}
	else {
		document.getElementById('home_weatherlightboxerror').innerHTML = msg;
        document.getElementById('home_weatherlightboxerror').style.display = 'block';
	}
}
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() {

	//alert('in remember() ... if this has worked you should see another alert showing the cookie string');

	if (WK == null)	{
		//alert("Please click the search button first to look up your weather details.");
		//setErrorMessage("Please click the search button first to look up your weather details.");
		bError = true;
		return;
	}
	
	if(!bSave){
		//alert("Your current location can not be stored as your location can not be found, please try a new search");
		//setErrorMessage("Your current location can not be stored as your location can not be found, please try a new search");
		bError = true;
		
	}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("weatherlocation").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.\n\n"+cookieStr+"\n\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 = 'innermost <strong>'+city+'</strong>';
}

function renderForcast(forcast,ele){
    if (debug) {
        alert('in renderForecast('+forcast.city+')');
    }
    
    // Update city in the modal popup.
    document.getElementById('home_weatherlightboxcity').innerHTML = city;

    // If no day icon is supplied then show generic icon #28.
    var dayicon;
	if(validateFeedData(forcast.dayicon) != 'n/a')	{
        dayicon = 'http://www.orange.co.uk/images/news/weather/icons/small/' + forcast.dayicon + '.gif';
	}
	else {
        dayicon = 'http://www.orange.co.uk/images/news/weather/icons/small/28.gif';
	}
    
    var o  = ''
        o += '<div id="home_weathericonandtemp"><img src="' + dayicon + '" height="25" width="25" alt="' + forcast.dayphrase + '" />';
        o += '<h4><span>high:</span> '+validateFeedData(forcast.high)+'&deg; &nbsp; <span>low:</span> '+validateFeedData(forcast.low)+'&deg;</h4></div>';
        o += '<p>'+city+' <a href="javascript:ouk_openWeatherForm()">change</a><br/><a href="javascript:goExtended()">10-day forecast</a></p>';

    // close modal window.
    ouk_closeWeatherForm();

    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){
    	if(debug) { alert('wCode = ' + wCode); }
        appendDocumentToDom("http://www.orange.co.uk/jsincludes/feeds/" + wCode + ".js","JS_WEATHER");
    }else{
    	if(debug) { alert('WK = ' + WK); }
        appendDocumentToDom("http://www.orange.co.uk/jsincludes/feeds/" + WK + ".js","JS_WEATHER");
    }
}

function showErrorModalMessage(msg) {
    alert('Modal error message: ' + msg);
}


function openLightbox() {
    var dialog = dijit.byId('home_weatherlightbox');
    dialog.duration = 1;
    dialog.show();
}

function closeLightbox() {
    var dialog = dijit.byId('home_weatherlightbox');
    if (dialog) {
        dialog.hide();
    }
}

function ouk_openWeatherForm() {
	//alert(city);
    openLightbox();
}

function ouk_closeWeatherForm() {
    closeLightbox();
}

function ouk_saveWeatherForm() {
    go();
}

// currentState:
// 0: CLOSED
// 1: CLOSING
// 2: OPENING
// 3: OPEN

function ouk_pushdown() {
    this.maxHeight            = 350; // This is the fully expanded height.
    this.startingHeight       = 56; // This is the initial collapsed height.
    this.currentHeight        = this.startingHeight; // The default initial value is the same as the startingHeight.
    this.currentState         = 0; // closed
    this.isOpen               = false; // Either true (open) or false (closed). Determined by cookie/pill.
    this.divId                = 'home_pushdown'; // Name of the parent pushdown div that has an overflow:hidden applied.
    this.timeout              = null; // stores a reference to the user initiated timeout.
    this.speed                = 2000; // milliseconds.
    this.pixelsPerInterval    = 3; // How many pixels to move for each timeout/interval.
    this.pixelInterval        = Math.round(this.speed / (this.maxHeight - this.startingHeight) * this.pixelsPerInterval); // Duration between timeout calls.
    this.autocloseDelay       = 7000; // How long to wait before auto collapsing (milliseconds).
    this.autocloseTimeout     = null; // stores a reference to the auto initiated timeout.
    this.autoExpandTimeout    = null;
    this.hasInited            = false;
    this.imageName            = 'pushdown_button_';
    this.cookieName           = 'ouk_pdown_';
}

ouk_pushdown.prototype.startExpand = function() {
	var pushdown = document.getElementById(this.divId);
	this.notifyCampaignViewed(ouk_pushdown_campaign_name);
	this.change_image('close');
	this.currentState=2; // opening
	pushdown.style.height = '' + this.maxHeight + 'px';
        //this.timeout = setTimeout('ouk_pushdown_obj.expand()', 1);
	this.currentState=3; // open
	this.autocloseTimeout = setTimeout('ouk_pushdown_obj.startCollapse()', this.autocloseDelay);
}

/*
ouk_pushdown.prototype.expand = function() {
    var pushdown = document.getElementById(this.divId);
    this.currentHeight = parseInt(pushdown.style.height);
    if(this.currentHeight < this.maxHeight) {
        pushdown.style.height = '' + (this.currentHeight + this.pixelsPerInterval) + 'px';
        this.timeout = setTimeout('ouk_pushdown_obj.expand()', this.pixelInterval);
    } else {
        if(this.currentHeight == this.maxHeight) { // We have reached full expansion.
            this.currentState=3; // open
            this.autocloseTimeout = setTimeout('ouk_pushdown_obj.startCollapse()', this.autocloseDelay);
        }
    }
}
*/

ouk_pushdown.prototype.startCollapse = function() {
	var pushdown = document.getElementById(this.divId);
    this.change_image('open');
	this.currentState=1; // closing
	pushdown.style.height = '' + this.startingHeight + 'px';
    //this.timeout = setTimeout('ouk_pushdown_obj.collapse()', 1);
	this.currentState=0; // closed
	this.isOpen = false;
}

/*
ouk_pushdown.prototype.collapse = function() {
    var pushdown = document.getElementById(this.divId);
    this.currentHeight = parseInt(pushdown.style.height);
    if(this.currentHeight > this.startingHeight) {
        pushdown.style.height = '' + (this.currentHeight - this.pixelsPerInterval) + 'px';
        this.timeout = setTimeout('ouk_pushdown_obj.collapse()', this.pixelInterval);
    }
    else if(this.currentHeight == this.startingHeight) {
	this.currentState=0; // closed
        this.isOpen = false;
    }
}
*/

ouk_pushdown.prototype.manual_open_close = function() {
	if (home_pageLoaded) {
		this.autocloseDelay=15000;
		this.open_close();
	}
}

ouk_pushdown.prototype.open_close = function() {
    clearTimeout(this.timeout);
    clearTimeout(this.autocloseTimeout);
    clearTimeout(this.autoExpandTimeout);

    var pushdown = document.getElementById(this.divId);
    switch(this.currentState) {
        case 0: // closed
            this.startExpand();
        break;
        case 1: // closing
            this.startExpand();
        break;
        case 2: // opening
            this.startCollapse();
        break;
        case 3: // open
            this.startCollapse();
        break;
    }
}

ouk_pushdown.prototype.change_image = function(which) {
    document.getElementById('pushdownbutton').src = '/img/homerefresh09/pushdown_'+which+'_btn.gif';
}

var ouk_pushdown_obj = new ouk_pushdown();

ouk_pushdown.prototype.auto_expand = function() {
	if (!this.hasCampaignBeenViewed(ouk_pushdown_campaign_name)) {
		this.autocloseDelay=7000;
		this.autoExpandTimeout=setTimeout('ouk_pushdown_obj.open_close()', 2000);
	}
}

ouk_pushdown.prototype.notifyCampaignViewed = function(campaignName) {
	while (campaignName.indexOf(",")>-1) {
		campaignName=campaignName.replace(",","");
	}
	var campaignsCookie=dojo.cookie("pushdowncampaigns");
	if ((campaignsCookie==undefined) || (campaignsCookie=="null")) {
		campaignsCookie=campaignName;
	} else {
		var campaignsArray=campaignsCookie.split(",");
		var campaignNameFound=false;
		var index=0;
		while ((!campaignNameFound) && (index<campaignsArray.length)) {
			if (campaignsArray[index]==campaignName) {
				campaignNameFound=true;
			}
			index++;
		}
		if (!campaignNameFound) {
			campaignsCookie+=","+campaignName;
		}
	}
	dojo.cookie("pushdowncampaigns",campaignsCookie,{ path: "/", expires: 730 });
}

ouk_pushdown.prototype.hasCampaignBeenViewed = function(campaignName) {
	var campaignNameFound=false;
	var campaignsCookie=dojo.cookie("pushdowncampaigns");
	//alert("campaigns cookie: "+campaignsCookie);
	if ((campaignsCookie!=undefined) && (campaignsCookie!="null")) {
		var campaignsArray=campaignsCookie.split(",");
		var index=0;
		while ((!campaignNameFound) && (index<campaignsArray.length)) {
			if (campaignsArray[index]==campaignName) {
				campaignNameFound=true;
			}
			index++;
		}
	}
	return(campaignNameFound);
}

// Trims news headlines that are longer than X chars.
// Cuts them off at the preceeding space to keep complete words.
function trimNewsHeadlines(headline) {
    var cutOffPoint = 40;
    var charToMatch = ' ';
    var newSuffix = ' ...';
    var headlineLength = headline.length;

    // Work out the true length of the headline - taking into account entity references.
    var patterns = [
        {'pattern' : /\&\#[0-9]{2}\;/g, 'length' : 4},
        {'pattern' : /\&\#[0-9]{3}\;/g, 'length' : 5},
        {'pattern' : /\&\#[0-9]{4}\;/g, 'length' : 6}
    ];

    // Loop over the patterns and adjust the headline length accordingly.
    for(var i=0; i < patterns.length; i++) {
        var pattern = patterns[i];
        var re = headline.match(pattern.pattern);
        if(re != null) {
            headlineLength = headlineLength - (re.length * pattern.length);
        }
    }

    if(headlineLength > cutOffPoint ) {
        // find the last space before the X pixel cutoff.
        var currentPos = cutOffPoint;
        while(currentPos > 0) {
            if(headline.charAt(currentPos) == charToMatch) {
                headline = headline.substring(0, currentPos);
                return headline + newSuffix;
            }
            // decrement the cut off point to work back to a space.
            currentPos--;
        }
    }
    else {
        return headline;
    }
}