function loadInOpener(openerURL)
{
	opener.location.href = "http://" + getDomain() + openerURL;
	window.close();
}

function getDomain()
{
	if((window.location.port == '80') || (window.location.port == ''))
	{
		return window.location.hostname;
	}
	else
	{
		return window.location.hostname + ":" + window.location.port;
	}
}

//Determines whether a user has a cookie
function checkRadioTimesUser()
{
	var cookieName = "NEW_RADIOTIMES_USER_ID";

	var cookieString = unescape(document.cookie);
	var cookieList = cookieString.split("; ");

	var cookieExists = false;

	var currentCookieName = "";
	var currentCookieValue = "";
	
	for(counter = 0; counter < cookieList.length; counter ++)
	{
	        currentCookie = cookieList[counter];
	        cookieSplitIndex = currentCookie.indexOf("=");
	        currentCookieName = currentCookie.substring(0,cookieSplitIndex);
	        currentCookieValue = currentCookie.substring(cookieSplitIndex+1);

		if(currentCookieName == cookieName)
	        {
			cookieExists = true;
	                break;
	        }
	}
	return cookieExists;
}

function incrementalDate(increment)
{
	var d = new Date();
	d.setDate(d.getDate()+increment);
    var daynumber = (d.getDate());
	if(daynumber < 10){daynumber = ("0" + daynumber)}
    var month = (d.getMonth() + 1);
	if(month < 10){month = ("0" + month)}
    var searchMyDate = daynumber + "/" + month + "/" + d.getFullYear();
	return searchMyDate;
}

function getTimeNow()
{
	var d = new Date();
	var hournumber = d.getHours();
	if(hournumber < 10){hournumber = ("0" + hournumber) }
	var minutenumber = d.getMinutes();
	if(minutenumber < 10){minutenumber = ("0" + minutenumber) }
	var timestring = hournumber + ":" + minutenumber;
	return timestring;
}

function dateForSearching()
{
	var d = new Date();
	var daynumber = (d.getDate());
	if(daynumber < 10){daynumber = ("0" + daynumber)}
	var month = (d.getMonth() + 1);
	if(month < 10){month = ("0" + month)}
	var searchMyDate = daynumber + "/" + month + "/" + d.getFullYear();
	return searchMyDate;
}

function nowTV()
{
	if(checkRadioTimesUser())
	{
		window.location.href = "http://" + getDomain() + "/ListingsServlet?event=13&broadcastType=1&jspGridLocation=/jsp/tv_listings_grid.jsp&jspListLocation=/jsp/tv_listings_single.jsp&jspError=/jsp/error.jsp";
	}
	else
	{
		window.location.href = "http://" + getDomain() + "/tv/now.html";
	}
}

function tonightTV()
{
	if(checkRadioTimesUser())
	{
		window.location.href = "http://" + getDomain() + "/ListingsServlet?event=13&broadcastType=1&jspGridLocation=/jsp/tv_listings_grid.jsp&jspListLocation=/jsp/tv_listings_single.jsp&jspError=/jsp/error.jsp&searchDate=" + dateForSearching() + "&searchTime=18:00";
	}
	else
	{
		window.location.href = "http://" + getDomain() + "/tv/tonight.html";
	}
}

function tomorrowTV()
{
	window.location.href = "http://" + getDomain() + "/ListingsServlet?event=13&broadcastType=1&jspGridLocation=/jsp/tv_listings_grid.jsp&jspListLocation=/jsp/tv_listings_single.jsp&jspError=/jsp/error.jsp&searchDate=" + incrementalDate(1) + "&searchTime=" + getTimeNow();
}

function nowRadio()
{
	window.location.href = "http://" + getDomain() + "/ListingsServlet?event=13&broadcastType=2&jspGridLocation=/jsp/radio_listings_grid.jsp&jspListLocation=/jsp/radio_listings_single.jsp&jspError=/jsp/error.jsp";
}

function tonightRadio()
{
	window.location.href = "http://" + getDomain() + "/ListingsServlet?event=13&broadcastType=2&jspGridLocation=/jsp/radio_listings_grid.jsp&jspListLocation=/jsp/radio_listings_single.jsp&jspError=/jsp/error.jsp&searchDate=" + dateForSearching() + "&searchTime=18:00";
}

function tomorrowRadio()
{
	window.location.href = "http://" + getDomain() + "/ListingsServlet?event=13&broadcastType=2&jspGridLocation=/jsp/radio_listings_grid.jsp&jspListLocation=/jsp/radio_listings_single.jsp&jspError=/jsp/error.jsp&searchDate=" + incrementalDate(1) + "&searchTime=" + getTimeNow();
}

function addToDiary(addDiaryLink)
{
	if(checkRadioTimesUser())
	{
		spawn_window(addDiaryLink, 'prog_details', 'width=653,height=550,resizable=yes,toolbar=0,scrollbars=yes,location=0,menubar=0,status=0,titlebar=0,top=0,left=0');
	}
	else
	{
		window.location.href = "http://" + getDomain() + "/jsp/register/?statusCode=-1010";
	}
}

function addToDiaryFromPopup(addDiaryLink)
{
	if(checkRadioTimesUser())
	{
		window.location.href = "http://" + getDomain() + addDiaryLink;
	}
	else
	{
		opener.location.href = "http://" + getDomain() + "/jsp/register/index.jsp?statusCode=-1010";
		window.close();
	}
}

function progPopup(programmeID,channelID)
{
	spawn_window('/ListingsServlet?event=10&channelId='+channelID+'&programmeId='+programmeID+'&jspLocation=/jsp/prog_details.jsp', 'prog_details', 'width=653,height=550,resizable=yes,toolbar=0,scrollbars=yes,location=0,menubar=0,status=0,titlebar=0,top=0,left=0');
	return false;
}

function progPopupTrivia(programmeID,channelID)
{
	spawn_window('/ListingsServlet?event=10&channelId='+channelID+'&programmeId='+programmeID+'&trivia=true&jspLocation=/jsp/prog_details.jsp#trivia', 'prog_details', 'width=653,height=550,resizable=yes,toolbar=0,scrollbars=yes,location=0,menubar=0,status=0,titlebar=0,top=0,left=0');
	return false;
}

function smsPopup(programmeID,channelID)
{
	spawn_window('/ListingsServlet?event=10&channelId='+channelID+'&programmeId='+programmeID+'&jspLocation=/jsp/sms_reminder.jsp', 'prog_details', 'width=653,height=550,resizable=yes,toolbar=0,scrollbars=yes,location=0,menubar=0,status=0,titlebar=0,top=0,left=0');
	return false;
}

function spawn_window(content, spawn, sizing)
{
	window.open(content, spawn, sizing).focus();
}
//date print
		dayNames = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
		monthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
		var theDate = "";
		
		function myDate()
		{
		        var d = new Date();
		        var dayname = dayNames[d.getDay()]
		        var daynumber = d.getDate();
                        if(daynumber < 10){daynumber = ("0" + daynumber)}
		        var month = monthNames[d.getMonth()]
		        var year = d.getFullYear();
		        theDate = dayname + " " + daynumber + " " + month;
		}
		myDate();

//Ticks all tick boxes passed in as document.FORMNAME.CHECKBOXESCOMMONNAME
function tickAll(boxes) {
  if (typeof boxes != 'undefined') {
  	if (typeof boxes.length == 'undefined') { boxes.checked = true; }
	else {
		for (i = 0; i < boxes.length; i++) {
			boxes[i].checked = true ;
		}

	}
    }
}

//Unticks all tick boxes passed in as document.FORMNAME.CHECKBOXESCOMMONNAME
function unTickAll(boxes) {
  if (typeof boxes != 'undefined') {
  	if (typeof boxes.length == 'undefined') { boxes.checked = false; }
	else {
		for (i = 0; i < boxes.length; i++) {
			boxes[i].checked = false;
		}

	}
    }
}
//Checks the number of tick boxes unchecked passed in as document.FORMNAME.CHECKBOXESCOMMONNAME
//and also checks that there is at least one selected
function numTicked(boxes)
  {
    var numUntick = 0;
		var numTicked = 0;
		
    for (i = 0; i < boxes.length; i++)
    {
      if (boxes[i].checked == false)
        numUntick++;
    }
		
		for (i = 0; i < boxes.length; i++)
    {
      if (boxes[i].checked == true)
        numTicked++;
    }
		
    if (numUntick < 2)
		{
      alert("You must have at least 2 channels in your listings channels");
			return false;
		}
		else if(numTicked == 0)
		{
			alert("Please select the channels you wish to remove");
			return false;
		}
		else
		{
			return true;
		}
  }
	
function someChecked(boxes)
{
	var numTicked = 0;
	if (typeof boxes.length == 'undefined') {
		if (boxes.checked) numTicked++;
	}
	else {
	for (i = 0; i < boxes.length; i++) {
	    if (boxes[i].checked == true)
	      numTicked++;
	  }
	}	
	if(numTicked == 0)
	{
		alert("Please select the channels you wish to add");
		return false;
	}
	else
	{
		return true;
	}
}
//Checks that an option is chosen in a select by passing in document.FORMNAME.SELECTNAME.selectedIndex
function checkSelect(numSelectIndex)
{
  if (numSelectIndex > 0)
  	return true;
    else
    {
      alert("Please choose an option");
      return false;
    }
}

//Moves item in a multiple select up one place
function up(the_object)
{
	var channelToMove = the_object.options.selectedIndex;
	if(channelToMove != -1)
	{
		var channelToMoveText = the_object.options[channelToMove].text;
		var channelToMoveValue = the_object.options[channelToMove].value;
		if(channelToMove != 0)
		{
			var channelToReplace = channelToMove - 1;
			var channelToReplaceText = the_object.options[channelToReplace].text;
			var channelToReplaceValue = the_object.options[channelToReplace].value;
			the_object.options[channelToMove].text = channelToReplaceText;
			the_object.options[channelToMove].value = channelToReplaceValue;
			the_object.options[channelToReplace].text = channelToMoveText;
			the_object.options[channelToReplace].value = channelToMoveValue;
			the_object.options.selectedIndex = channelToReplace;
		}
		else
		{
			alert(channelToMoveText + ' is top in your ordering,\nyou cannot move up any further.');
		}
	}
	else
	{
	alert("Please select a channel to move")
	}
}

//Moves item in a multiple select down one place
function down(the_object)
{
	var channelToMove = the_object.options.selectedIndex;
	if(channelToMove != -1)
	{
		var channelToMoveText = the_object.options[channelToMove].text;
		var channelToMoveValue = the_object.options[channelToMove].value;
		if(channelToMove != the_object.options.length - 1)
		{
			var channelToReplace = channelToMove + 1;
			var channelToReplaceText = the_object.options[channelToReplace].text;
			var channelToReplaceValue = the_object.options[channelToReplace].value;
			the_object.options[channelToMove].text = channelToReplaceText;
			the_object.options[channelToMove].value = channelToReplaceValue;
			the_object.options[channelToReplace].text = channelToMoveText;
			the_object.options[channelToReplace].value = channelToMoveValue;
			the_object.options.selectedIndex = channelToReplace;
		}
		else
		{
			alert(channelToMoveText + ' is bottom in your ordering,\nyou cannot move it down any further.');
		}
	}
	else
	{
	alert("Please select a channel to move")
	}
}

//Moves item in a multiple select to the top of the select
function head(obj) {
	var elements = new Array();
	for (i=0; i<obj.length; i++) {
		if (obj[i].selected) {
			elements[elements.length] = new Array(obj[i].text, obj[i].value, obj[i].selected);
		}
	}
	for (i=0; i<obj.length; i++) {
		if (!obj[i].selected) {
			elements[elements.length] = new Array(obj[i].text, obj[i].value, obj[i].selected);
		}
	}
	for (i=0; i<obj.length; i++) {
		obj[i].text = elements[i][0];
		obj[i].value = elements[i][1];
		obj[i].selected = elements[i][2];
	}
}

//Moves item in a multiple select to the bottom of the select
function bottom(obj) {
	var elements = new Array();
	for (i=0; i<obj.length; i++) {
		if (!obj[i].selected) {
			elements[elements.length] = new Array(obj[i].text, obj[i].value, obj[i].selected);
		}
	}
	for (i=0; i<obj.length; i++) {
		if (obj[i].selected) {
			elements[elements.length] = new Array(obj[i].text, obj[i].value,  obj[i].selected);
		}
	}
	for (i=obj.length-1; i>-1; i--) {
		obj[i].text = elements[i][0];
		obj[i].value = elements[i][1];
		obj[i].selected = elements[i][2];
	}
}

function checkEmail(obj_name)
{
	var addresspos = -1;
	var dotpos = -1;
	var checkstr = "";
	email = obj_name.value;
	addresspos = email.indexOf("@",0);
	if ((addresspos == -1) || (addresspos == 0) || (addresspos == email.length-1))
	{
		return false;
	}
	dotpos = email.indexOf(".",addresspos);	
	if ((dotpos == email.length-1) || (dotpos == -1)) 
	{
		return false
	}
	return true;
}

function checkTextField(theObject)
{
	if(theObject.value == '')
	{
		return false;
	}
	else
	{
		return true;
	}	
}


function checkTextBox(theObject,alertText)
{
	if(theObject.value == '')
	{
		alert(alertText);
		return false;
	}
	else
	{
		return true;
	}	
}
function checkSearchStr()
{
	searchStr = document.getElementById('progSearchText').value.toString();
	stripAstriskExpr = /\*/g;
	searchstr = searchStr.replace(stripAstriskExpr,'');
	stripPercentExpr = /%/g;
	searchstr = searchStr.replace(stripPercentExpr,'');
	
	document.getElementById('progSearchText').value = searchStr;
	if (searchStr.length < 2) {
		alert("Please enter a longer search term");
		return false;
	}
	else {
		return true;
	}
}
function checkFilledTextBox(theObject,alertText,originalText)
{
	
	testObjectVal = theObject.value.toString();
	stripPercentExpr = /%/g;
	testObjectVal = testObjectVal.replace(stripPercentExpr,'');
	stripAstriskExpr = /\*/g;
	theObject.value = testObjectVal.replace(stripAstriskExpr,'');
	
	if((theObject.value == '') || (theObject.value == originalText))
	{
		alert(alertText);
		return false;
	}
	else
	{
		theObject = theObject.value.toString();
		if(theObject.length < 2)
		{
			alert("Your search terms must be at least 2 characters long");
			return false;
		}

		return true;
	}	
}
//Gets variables from the querystring
function getQueryVariable(variable) 
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) 
  {
    var pair = vars[i].split("=");
    if (pair[0] == variable) 
    {
      var strCode = pair[1];
      if (strCode != '')
        return strCode;
    }
  } 
}
//Makes div visible and shows error text based on strErrorCode
//Usage: var strStatusCode = getQueryVariable("statusCode") ; if (strStatusCode != null) errorMessage("errorDiv", "errortext", strStatusCode);
function errorMessage(strDivName, strDivErrorName, strErrorCode)
{
  document.getElementById(strDivName).style.visibility = "visible";
  document.getElementById(strDivName).style.display = "block";
  switch(strErrorCode)
  {
    case "-1001": 
      strErrorText = "<span class='alertText'>This email address is already registered with Radio Times. Please log in at the top of the page.</span>";
      break
    case "-1002": 
      strErrorText = "<span class='alertText'>This postcode is not recognised - please check that you have entered the information correctly. Should you continue to experience difficulties, please email your postcode to radio.times@bbc.co.uk and we will endeavour to rectify the problem.</span>";
      break
	case "-1006": 
      strErrorText = "<span class='alertText'>Not all the required fields have been completed. Please add this information before trying again.</span>";
      break
    case "-1007": 
      strErrorText = "<span class='alertText'>Sorry, your request cannot be fulfilled at the moment owing to a technical error - please come back later and try again. However, if you prefer, you may email your details to radio.times@bbc.co.uk and we will complete the registration process on your behalf. We apologise for any inconvenience.</span>";
      break
    case "-1008": 
      strErrorText = "<span class='alertText'>Your browser does not accept cookies. To register with Radio Times, your browser's cookies must be enabled - please check your settings before trying again.</span>";
      break
    case "-1012": 
      strErrorText = "<span class='alertText'>In order to view Your Programmes, you must first log in at the top of the page or register with us.<br /><br />Registration is free, extremely simple and will not invite unsolicited emails.</span>";
      break
    case "-1011": 
      strErrorText = "<span class='alertText'>In order to change your settings, you must first log in at the top of the page or register with us.<br /><br />Registration is free, extremely simple and will not invite unsolicited emails.</span>";
      break
    case "-1010": 
      strErrorText = "<span class='alertText'>In order to add this to Your Programmes, you must first log in at the top of the page or register with us.<br /><br />Registration is free, extremely simple and will not invite unsolicited emails.</span>";
      break
    default:
      strErrorText = "<span class='alertText'>Unknown error</span>";
  }
  //Browser Sniff For writing to div
  var agt=navigator.userAgent.toLowerCase();
  var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
              && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
              && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
  if (is_nav){
    document.getElementById(strDivErrorName).innerHTML = strErrorText; 
  }
  else{
    eval(strDivErrorName).innerHTML = strErrorText;
  }
}
//Show a div
function showDiv(strDivName)
{
  document.getElementById(strDivName).style.visibility = "visible";
  document.getElementById(strDivName).style.display = "block";
}
//Hide a div
function hideDiv(strDivName)
{
  document.getElementById(strDivName).style.visibility = "hidden";
  document.getElementById(strDivName).style.display = "none";
}
//Encode/Decode
function checkPassword(passwordString,encodedPassword)
{
	var finalPwd = '';
	
	for(x = 0; x < (encodedPassword.length / 4); x++)
	{
		currentChar = encodedPassword.substring((4 * x),((4 * x)+4))
		currentChar = currentChar.substring(2);
		finalPwd = finalPwd + unescape('%'+currentChar);
	}
	if(finalPwd == passwordString)
	{
		return true;
	}
	else
	{
		return false;
	}
}

