// When loading content from an IFRAME into an HTML element, the 
// convention followed is that if the name of the element is XX,
// the IFRAME is IFRAME_PREFIX + XX. The constant below defines
// the value of the prefix
var IFRAME_PREFIX = "i";

// Gandaspace JavaScript Document
//Function that displays the local time of a machine
function stop() {
  clearTimeout(tick);
 }

function setlocaltime() {
	var ut=new Date();
	var h,m,s;
	var time="      ";
	h=ut.getHours();
	m=ut.getMinutes();
	s=ut.getSeconds();
	if(s<=9) s="0"+s;
	if(m<=9) m="0"+m;
	if(h<=9) h="0"+h;
	// diplay AM or PM symbol
	var ampmValue = "AM";
	if (h < 12) {
		ampmValue = "AM";
	} else {
		ampmValue = "PM";
	}
	// convert 24 hour to 12 hour
	var twelvehour;
	if (h > 0 && h < 13) {
		twelvehour = h;
	} else if (h == 0) {
		twelvehour = 12;
	} else {
		twelvehour = (h - 12);
	}
	time += twelvehour + ":" + m + " " + ampmValue + " Local ";
	document.getElementById("localtime").innerHTML = time;
	//tick=setTimeout("usnotime()",1000); 
}

// Returns false if the field is empty, null, or has the string "null", and pops up
// the message passed to the function
function isNotNullOrEmptyString(fieldName, message) {	
	if (isNullOrEmpty(document.getElementById(fieldName).value)) {	
		alert(message);		
		return false;
	}
	return true;
}

// general purpose function to see if an input value has been
// entered at all or if the input value has a value "null"
function isNullOrEmpty(inputStr) {
	// trim; remove leading and trailing spaces
	var trimmedValue = trimString(inputStr);
	if (isEmpty(trimmedValue) || trimmedValue == "null") {
		return true;
	}
	return false;
}

// general purpose function to see if an input value has been
// entered at all
function isEmpty(inputStr) {
	if (inputStr == null || inputStr == "") {
		return true;
	}
	return false;
}

// Validates the email entered.
function validateEmail(fieldValue){
   // The invalid characters that should not be used in an email address
   var invalidChars = " /:,;"; 
   var emailAddress = fieldValue;
   
   var atPosition = emailAddress.indexOf("@",1);
   var periodPosition = emailAddress.indexOf(".",atPosition);
   
   if (isNullOrEmpty(emailAddress)){
      return false;
   }
   // Checks for the invalid characters listed above.
   for (var i=0; i<invalidChars.length; i++){
      badChar = invalidChars.charAt(i);
	  if (emailAddress.indexOf(badChar,0) > -1){
	     return false;		 
	  }
   }

   if (atPosition == -1){ // Checks for the @
      return false;
   }
   if (emailAddress.indexOf("@",atPosition + 1) > -1){ // Makes sure there is one @
      return false;
   }
   if (periodPosition == -1){ // Makes sure there is a period after the @ 
      return false;
   }
   // Makes sure there is at least 2 characters after the period
   if ((periodPosition + 3) > emailAddress.length){ 
      return false;
   }
   
   return true;
}

// function used to check email and display message
function isValidEmail(fieldname, msg) {
	if (!validateEmail(document.getElementById(fieldname).value)) {
		alert(msg);
		document.getElementById(fieldname).value = "";
		return false;
	}
	return true;
}



//Remove leading and trailing spaces
function trimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}

// general purpose function to see if a suspected numeric input
// is a positive integer and return the message if its not
function isPositiveInteger(fieldName, msg) {
	if (isPosInteger(fieldName)) {
		return true;
	} else {
		alert(msg);
		return false;
	}
}


// general purpose function to see if a suspected numeric input
// is a positive integer
function isPosInteger(fieldName) {
	inputVal = document.getElementById(fieldName).value;
	inputStr = inputVal.toString();
	for (var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i);
		if (oneChar < "0" || oneChar > "9") {
			return false;
		}
	}
	return true;
}

// general purpose function to ensure that a field does not contain zero as a value
function isNotZero(fieldName, msg) {
	if (document.getElementById(fieldName).value == "0") {
		alert(msg);
		return false;
	} else {
		return true;
	}
}

// function to enable text field
function enableField(fieldName) {
	document.getElementById(fieldName).disabled = false;
	document.getElementById(fieldName).className = "";
}

// function to disable text field
function disableField(fieldName) {
	document.getElementById(fieldName).disabled = true;
	document.getElementById(fieldName).className = "disabledfield";
	//Also, clear the control values
	//document.getElementById(fieldName).value = "";
}

// function to delete nth element in array
function deleteElement(array, n) {
  //delete the nth element of array
  var length = array.length;
  if (n >= length || n<0)
    return;
  for (var i=n; i<length-1; i++)
    array[i] = array[i+1];
  	array.length--;
}

// Transfer the HTML within the BODY tag from an IFRAME to the specified target.
// The convention followed is that content from an IFRAME called iXX is loaded
// into an element XX.
function transferHTML(target) {
   // The name of the IFRAME into which the external document is loaded
   var srcIFrame = document.getElementById(IFRAME_PREFIX + target);
   // The content in the IFrame contained within the body tag this code handles NN6, IE 5.5 and 6
   document.getElementById(target).innerHTML = (srcIFrame.contentDocument) ? srcIFrame.contentDocument.getElementsByTagName("BODY")[0].  innerHTML : (srcIFrame.contentWindow) ? srcIFrame.contentWindow.document.body.innerHTML : "";  
}



function showWords(word, language) {
	frames['isearch_words'].location.href = "search_words_results.php?word=" + document.getElementById(word).value + "&from=" + language;
}

function showArtPieces() {
	frames['iartpieces'].location.href = "exhibitionart.php?artist=" + document.getElementById('artist').value;
}

//The functions below are for the premium dictionary
 function showNearMatchTranslation(index) {
	 document.getElementById('englishword').value = document.getElementById(index).value;
	 showWords('englishword', 'english');
 }

// function to deal with selecting a default submit button
 function keyDownHandler(btn) { 
        // process only the Enter key
        if (event.keyCode == 13)  {
            // cancel the default submit
            event.returnValue=false;
            event.cancel = true;
            // submit the form by programmatically clicking the specified button
            document.getElementById(btn).click();
        }
 }
 
 
function showLayer(name) {
	var layers = document.getElementsByName(name);
	for (var i=0; i < layers.length; i++) {
		layers[i].style.visibility = "inherit";
	}
}

function hideLayer(name) {
	var layers = document.getElementsByName(name);
	for (var i=0; i < layers.length; i++) {
		layers[i].style.visibility = "hidden";
	}
}

//focuses on the English field
function focusOnEnglish(){
   disableField('lugandago');
	document.getElementById('englishgo').disabled = false;
	document.getElementById('englishgo').className = "formButton";
	document.getElementById('englishword').focus();
}

//focuses on the Luganda field
function focusOnLuganda(){
   disableField('englishgo');
	document.getElementById('lugandago').disabled = false;
	document.getElementById('lugandago').className = "formButton";
	document.getElementById('lugandaword').focus();
}


// set the form action where data is to be submitted
function setFormAction(formAction) {
	document.forms[0].action = formAction;
}

// function to check number of characters in textfield
function checkNumberofCharacters(textfieldName, counterFieldName) {
	var maxcharacters = 750;
	updateMessageCounter();
	var text = document.getElementById(textfieldName).value;
	var textLength = text.length;
	if (textLength > maxcharacters) {
		alert('You can only enter a maximum of ' + maxcharacters +' characters');
		// show only up to limit of charatcters
		var maxString = text.substring(0,maxcharacters);
		document.getElementById(textfieldName).value = maxString;
		// reset counter
		document.getElementById(counterFieldName).innerHTML = maxcharacters;
		return false;
	}
	return true;	
}

function updateMessageCounter() {
	var text = document.getElementById("text").value;
	var textLength = text.length;
	document.getElementById("counterdiv").innerHTML = textLength;
}

// update a hidden field from a checkbox
function updateCheckBoxHiddenField(fieldName) {
	if (document.getElementById(fieldName + "_checkbox").checked) {
		// set the hidden field value to true
		document.getElementById(fieldName).value = "Y";
	} else {
		// set the hidden field value to true
		document.getElementById(fieldName).value = "N";
	}
	return true;
}

// update a hidden field from a checkbox
function updateCheckBoxHiddenFieldForAccount(fieldName) {
	if (document.getElementById(fieldName + "_checkbox").checked) {
		// set the hidden field value to true
		document.getElementById(fieldName).value = "N";
	} else {
		// set the hidden field value to true
		document.getElementById(fieldName).value = "Y";
	}
	return true;
}

// function to disable text field
function disableFieldValue(fieldName) {
	document.getElementById(fieldName).disabled = true;
	document.getElementById(fieldName).className = "disabledfield";
	//Also, clear the control values
	document.getElementById(fieldName).value = "";
}


// function to open a pop-up
function openSMSHelpWindow(URL) {
aWindow=window.open(URL,"awindow","toolbar=no,scrollbars=no,status=no,resizable=no,menubar=no,width=320,height=450,left=300,top=100");
}

// function to ensure that at least one checkbox has been selected
function ischeckboxSelected(msg) {
   count = 0;
   for (var i=0; i < document.forms[0].elements.length; i++) {	
      if (document.forms[0].elements[i].checked) {
	     count++;
	  }
   }
   if (count == 0) {
      alert(msg);
	  return false;
   }
   return true;
}

// function to check number of characters in textfield
function checkNumberofCharactersForNewsText(textfieldName, counterFieldName) {
	updateMessageCounter();
	var maxcharacters = 150;
	var text = document.getElementById(textfieldName).value;
	var textLength = text.length;
	if (textLength > maxcharacters) {
		alert('You can only enter a maximum of ' + maxcharacters +' characters');
		// show only up to limit of charatcters
		var maxString = text.substring(0,maxcharacters);
		document.getElementById(textfieldName).value = maxString;
		// reset counter
		document.getElementById(counterFieldName).innerHTML = maxcharacters;
		return false;
	}
	return true;	
}
//Function to update the number of words in a texbox
function updateWordsCounter(textfield) {
	var textfield = document.getElementById(textfield);
	
	//alert("Text: " + textfield.value + "\n Words: "+ CountWords(textfield));
	document.getElementById("counterdiv").innerHTML = CountWords(textfield);
}

//Function to count the number of words in a field.
function CountWords (this_field, show_word_count, show_char_count) {
	if (show_word_count == null) {
		show_word_count = true;
	}
	if (show_char_count == null) {
		show_char_count = false;
	}
	//alert(thefield); 
	//this_field = document.getElementById(thefield);
	//alert(this_field.value); 
	var char_count = this_field.value.length;
	var fullStr = this_field.value + " ";
	var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
	var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
	var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
	var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
	var splitString = cleanedStr.split(" ");
	var word_count = splitString.length -1;
	if (fullStr.length <2) {
		word_count = 0;
	}
	if (word_count == 1) {
		wordOrWords = " word";
	}
	else {
		wordOrWords = " words";
	}
	if (char_count == 1) {
		charOrChars = " character";
	} else {
		charOrChars = " characters";
	}
	if (show_word_count & show_char_count) {
		//alert ("Word Count:\n" + "    " + word_count + wordOrWords + "\n" + "    " + char_count + charOrChars);
	}
	else {
		if (show_word_count) {
		//alert ("Word Count:  " + word_count + wordOrWords);
		}
		else {
			if (show_char_count) {
				//alert ("Character Count:  " + char_count + charOrChars);
			}
		}
	}
	return word_count;
}
//Function to ensure that a number entered in a field does not have a leading zero and returns a message
function hasLeadingZero(numberField, message) {
	var number = document.getElementById(numberField).value;
	if(number.charAt(0)=='0') {
		alert(message);
		return false;
	}
	return true;
}

// function to check number of characters in the sms textfield, update a counter field and return a //message if the characters //are greater than 140. I
function checkNumberofSMSCharacters(textfieldName, counterFieldName) {
	var maxcharacters = 110;
	var text = document.getElementById(textfieldName).value;
	var textLength = text.length;
	if (textLength > maxcharacters) {
		alert('Your SMS can only be a maximum of 110 characters.');
		// show only up to limit of charatcters
		var maxString = text.substring(0,maxcharacters);
		document.getElementById(textfieldName).value = maxString;
		// reset counter
		document.getElementById(counterFieldName).value= maxcharacters;
		return false;
	}
	document.getElementById(counterFieldName).value = textLength;
	return true;	
}

// function to display the phone prefix for the selected mobile network
function showPhonePrefix() {
		var servicecombo = document.getElementById("service");
		var selectednetwork = servicecombo.options[servicecombo.selectedIndex].text;	
		var networks = new Array("MTN Uganda", "Celtel Uganda", "Uganda Telecom", "T-Mobile UK", "Verizon USA");
		var network_prefixes = new Array("772", "752", "712", "7", "");
		for (i=0; i<networks.length; i++) {
			if( selectednetwork== networks[i]) {
				document.getElementById("to").value = network_prefixes[i];
			}
		}
				
}

// function to open a pop-up window with specific width
function openPopUpWindow(URL) {
aWindow=window.open(URL,"newwindow","toolbar=yes,scrollbars=yes,status=yes,location=yes,resizable=yes,menubar=yes,width=500,height=500,left=600,top=100");
}

// function to open a pop-up window to view product larger image
function openLargerProductImage(URL) {
aWindow=window.open(URL,"newwindow","toolbar=no,scrollbars=no,status=no,location=no,resizable=no,menubar=no,width=320,height=200,left=200,top=100");
}

// function to open a pop-up window to view product larger image
function openLargerArtistImage(width, height, URL) {
aWindow=window.open(URL,"newwindow","toolbar=no,scrollbars=no,status=no,location=no,resizable=no,menubar=no,width="+width+",height="+height+",left=200,top=100");
}

// function to check against the minimum number of characters in a phone number field
function checkPhoneNumberCharacters() {
	var mincharacters = 9;
	var text = document.getElementById('to').value;
	var textLength = text.length;
	if (textLength < mincharacters) {
		alert('Please enter a valid phone number to send your SMS to.');
		return false;
	}
	return true;	
}

// function to format the hours entered to 2 decimal places
function FormatAmount(amount){
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}


//function that prints the bookmark this site link
function CreateBookmarkLink(thetitle, theurl) {
	//alert("the url is " + theurl);
	//alert("the title is " + thetitle);
 	if (window.sidebar) { 
	// Mozilla Firefox Bookmark		
		//window.sidebar.addPanel(thetitle, theurl,"");
		// do nothing, this currently causes an error
	} else if( window.external ) { 
		// IE Favorite		
		window.external.AddFavorite(theurl, thetitle); 
	} 
	//else if(window.opera && window.print) { 
		// Opera Hotlist		
		//  
	//} 
}


function approveArtistProfile(action) {
	// submit form for processing
	if(action =='approved') {
		document.getElementById('action').value = 'Approved';
		document.getElementById("submitform").click();	
	} else {
		if (isNullOrEmpty(document.getElementById('approvalcomments').value)) {	
			alert('Please add a comment for rejecting the artist profile');
			return false;
		} else {
			document.getElementById('action').value = 'Rejected';
			document.getElementById("submitform").click();		
		}
	}	
}


		function approveArtpiece(action) {
	// submit form for processing
	if(action =='approved') {
		document.getElementById('action').value = 'Approved';
		document.getElementById("submitform").click();	
	} else {
		if (isNullOrEmpty(document.getElementById('approvalcomments').value)) {	
			alert('Please add a comment for rejecting the artpiece');
			return false;
		} else {
			document.getElementById('action').value = 'Rejected';
			document.getElementById("submitform").click();		
		}
	}	
}
	
	
	
// Transfer the HTML within the BODY tag from an IFRAME to the specified target.
// The convention followed is that content from an IFRAME called iXX is loaded
// into an element XX.
function transferContent() {
   // The name of the IFRAME into which the external document is loaded
   var srcIFrame = document.getElementById('iartpieces');
   // The content in the IFrame contained within the body tag this code handles NN6, IE 5.5 and 6
   document.getElementById('artpieces').innerHTML = srcIFrame.contentWindow.document.body.innerHTML;  
}

// function to open a pop-up window to a custom pop-up window with specific attributes
function openCustomPopUpWindow(width, height, URL) {
aWindow=window.open(URL,"newwindow","toolbar=no,scrollbars=no,status=no,location=no,resizable=no,menubar=no,width="+width+",height="+height+",left=200,top=100");
}
// Function to validate a comma delimited list of email addresses
function validateEmailAddressList(emailAddressList, message){
	var pos = 0;
	var i = 0;
	var origin = 0;
	originalString = stringReplace(document.getElementById(emailAddressList).value, " ", "");
	pos = originalString.indexOf(',');
	while (pos != -1){
		// Get the position of '/'
		preString = originalString.substring(0, pos);
		// Get the item between two ','
		emailAddress = originalString.substring(origin, pos);
		//validate the email address
		if(validateEmailAddress(emailAddress, message)) {
		origin = pos+1;
		postString = originalString.substring(pos+1, originalString.length);
		originalString = preString + ' ' + postString;
		pos = originalString.indexOf(',');
		i++
		}
		else {
			return false;
		}
	}
			emailAddress = originalString.substring(origin, originalString.length);
	return validateEmailAddress(emailAddress, message);
} 

// function to check whether an email address is well formed
// Validates the email entered.
function validateEmailAddress(inputValue, message){
   // The invalid characters that should not be used in an email address
   var invalidChars = " /:,;"; 
   var emailAddress = inputValue;
   var atPosition = emailAddress.indexOf("@",1);
   var periodPosition = emailAddress.indexOf(".",atPosition);
   
   // Checks for the invalid characters listed above.
   for (var i=0; i<invalidChars.length; i++){
      badChar = invalidChars.charAt(i);
	  if (emailAddress.indexOf(badChar,0) > -1){
	     alert(message);
		 return false;
	  }
   }
   // Checks for the @
   if (atPosition == -1){ 
      alert(message);
	  return false;
   }
   // Makes sure there is one @
   if (emailAddress.indexOf("@",atPosition + 1) > -1){ 
      alert(message);
	  return false;
   }
   // Makes sure there is a period after the @ 
   if (periodPosition == -1){ 
      alert(message);
	  return false;
   }
   // Makes sure there is at least 2 characters after the period
   if ((periodPosition + 3) > emailAddress.length){ 
      alert(message);
	  return false;
   }
   
   return true;
}

// Function that replaces alll instances on a value in the string
function stringReplace(originalString, findText, replaceText) {
	var pos = 0;
	pos = originalString.indexOf(findText);
	while (pos != -1) {
		preString = originalString.substring(0,pos);
		postString = originalString.substring(pos+1, originalString.length);
		originalString = preString + replaceText + postString;
		pos = originalString.indexOf(findText);
	}
	return originalString;
}
// function to check number of words in a field
function checkNumberofWords(textfieldName, counterFieldName, maxwords) {
	
	updateWordsCounter(textfieldName);
	var text = document.getElementById(textfieldName).value;
	//alert(text);
	//var maxwords = 60;
	if (CountWords(document.getElementById(textfieldName)) > maxwords) {
		alert('You can only enter a maximum of ' + maxwords +' words');
		// show only up to limit of words
		var maxString = text.substring(0,text.lastIndexOf(' '));
		document.getElementById(textfieldName).value = maxString;
		// reset counter
		document.getElementById(counterFieldName).innerHTML = maxwords;
		return false;
	}
	return true;	
}



// The functions are used inthe Gandaspace modern verson 
///////////////////////////////////////////////////////////////////////////////////////////////

function showTabIfVisible(mname, shown) {
	if (document.getElementById(mname+'_layer').style.visibility == (shown ? 'inherit' : 'hidden')) return;
		//document.all[mname+'lt'].className = shown ? 'bgontabbottom' : 'bgofftabbottom';
		document.getElementById(mname+'lnk').className = shown ? 'bgontabbottommid' : 'bgofftabbottommid';
		document.getElementById(mname+'txt').className = shown ? 'smalltextnolink' : 'smallgraytextnolink';
		//document.all[mname+'rt'].className = shown ? 'bgontabbottom' : 'bgofftabbottom';
		document.getElementById(mname+'_layer').style.zIndex = shown ? 0 : -1;
		document.getElementById(mname+'_layer').style.visibility = shown ? 'inherit' : 'hidden';
		//document.images[mname+'lti'].src=document.images[mname+'lti'].src.replace(shown ? /_plain/ : /_stroked/,shown ? '_stroked' : '_plain');
		//document.images[mname+'rti'].src=document.images[mname+'rti'].src.replace(shown ? /_plain/ : /_stroked/,shown ? '_stroked' : '_plain');
}

function showTab(lname) {
   showTabIfVisible('tab1', lname == 'tab1');
   showTabIfVisible('tab2', lname == 'tab2');
   showTabIfVisible('tab3', lname == 'tab3');
   showTabIfVisible('tab4', lname == 'tab4');
   showTabIfVisible('tab5', lname == 'tab5');
   showTabIfVisible('tab6', lname == 'tab6');
// showTab('tab4', lname == 'tab4');
   //showTab('tab5', lname == 'tab5');
   //showTab('tab6', lname == 'tab6');
   //showTab('tab7', lname == 'tab7');   
}

/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//      GandaVideos Javascript                     //
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
function openVideoWindow(videoURL) {
	var URL = "playvideo.php?id=" + videoURL;
	aWindow=window.open(URL,"video_window","toolbar=no,scrollbars=no,status=no,resizable=no,menubar=no,width=450,height=660");
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Radio Adverts Javascript
//////////////////////////////////////////////////////////////////////////////////////////////////////

// Base price for special announcements
var BASECOST_SPECIAL = 25.00;

var BASECOST_ORDINARY = 15.00;

var ADDITIONALCOST_SPECIAL = 12.50;

var ADDITIONALCOST_ORDINARY = 5.00;


function openWindow(URL) {
	aWindow=window.open(URL,"pron_window","toolbar=no,scrollbars=no,status=no,resizable=no,menubar=no,width=200,height=200");
}

// function to check number of words in a field
function checkNumberofWordsForAdvertText(textfieldName, maxwords) {
	
	var text = document.getElementById(textfieldName).value;
	// alert(text);
	// var maxwords = 100;
	if (CountWords(document.getElementById(textfieldName)) > maxwords) {
		alert('You can only enter a maximum of ' + maxwords +' words');
		// show only up to limit of words
		var maxString = text.substring(0,text.lastIndexOf(' '));
		document.getElementById(textfieldName).value = maxString;
		// reset counter
		updateAdvertCounter()
		return false;
	}
	return true;	
}


// update the unit cost field 
function updateUnitCost(advertcategory) {
	var unitcostvalue = BASECOST_ORDINARY;
	
	for(var i=0; i< advertcategory.length; i++) {
		if (advertcategory[i].checked) {
			categoryvalue = advertcategory[i].value;
			//alert(categoryvalue);
		}
	}

	if (categoryvalue == "Premium") {
		unitcostvalue = BASECOST_SPECIAL;
		productcode = 'GS016';
	} else {
		unitcostvalue = BASECOST_ORDINARY;
		productcode = 'GS015';
	}
	//document.getElementById("unitcostdiv").innerHTML = unitcostvalue;
	//document.getElementById("unitcost").value = unitcostvalue;
	document.getElementById("productcode").value = productcode;
}

// Get the number of reading days
function updateNumberofReadingDays() {
	var numofreadingdays = 0;
	
	return numofreadingdays;
	
}

// calculate the total number of readings for the advert
function calculateAdvertTotals() {
	// total number of advert readings
	var totalAdvertReadings;
	var readingsperday = 0;
	// var readingdays;
	
	// Obtain the number ofreadings per day
	readingsperday = document.getElementById('readingsperday').value;
	// Calculate the reading days
	// readingdays = updateNumberofReadingDays();
	// Total number of readings
	totalAdvertReadings = readingsperday;
	// Total cost for adverts
	totalAdvertCost = totalAdvertReadings * document.getElementById('unitcost').value;
	//alert('Readings Per day: '+readingsperday + ' Reading days: '+readingdays + ' Total Readings: '+totalAdvertReadings + ' Total Advert Cost: '+totalAdvertCost);
	document.getElementById("totalreadingsdiv").innerHTML = totalAdvertReadings;
	document.getElementById("totalcostdiv").innerHTML = totalAdvertCost;
	document.getElementById("totalreadings").value = totalAdvertReadings;
	document.getElementById("totalcost").value = totalAdvertCost;
}
// function to check whether the total number of readings exceeds the available readings in the package
function validateTotalReadingTimes(day, package, maxDays, message){
	var dayIndex = 0;
	var totalReadings = 0;
	var dayreadings = 0;
	var readingssofar = 0;
   //Check whether two fields have same value, alert message and return false when they don't
   var packageReadings = new Number(document.getElementById(package).value);
 
   for (dayIndex; dayIndex < maxDays; dayIndex++) {
	   totalReadings += new Number (document.getElementById("readings_"+dayIndex).value);	   
   }
    if(totalReadings > packageReadings){	  	
		if(day != "" || day == 0) {
			dayreadings = document.getElementById("readings_"+day).value;
			document.getElementById("readings_"+day).value = "";
			document.getElementById("readings_"+day).text = "0";
		}
		readingssofar= totalReadings - dayreadings;
		alert("The package you have selected has a maximum of " + packageReadings + " readings. You cannot select more readings than you have in your package.  You have already selected " + readingssofar + " readings. ")
		return false;
	}
		return true;	
	
}

//function to display the releant packages depending on the selected announcement category
function showPackages(category, package, packagename) {
	frames['ipackages'].location.href = "packages.php?category=" + category + "&package=" + package + "&packagename=" + packagename;
}

//function to display  and set the total cost of the readings
function setTopicAndPackage() {
	document.getElementById("totalreadingsdiv").innerHTML = document.getElementById('topic').value + " - " + document.getElementById('package').value + " readings";
}

//function to obtain the cost of the readings by category and package
function setTotalCost(category) {
	// Obtain the selected package
	var thepackage = document.getElementById("package").value;
	var cost = "";
	
	if(category == 'Standard') {
		if(thepackage == '2') {
			cost = 15.00;
		} else if(thepackage =='4') {
			cost = 25.00;
		} else if(thepackage =='6') {
			cost = 35.00;
		} else if(thepackage == '8') {
			cost = 45.00;
		} else if(thepackage == '10') {
			cost = 55.00;
		} else if(thepackage =='15') {
			cost = 75.00;
		}
	} else if(category == 'Premium') {
		if(thepackage == '2') {
			cost = 25.00;
		} else if(thepackage =='4') {
			cost = 50.00;
		} else if(thepackage =='6') {
			cost = 75.00;
		} else if(thepackage == '8') {
			cost = 100.00;
		} else if(thepackage == '10') {
			cost = 125.00;
		} else if(thepackage =='15') {
			cost = 187.50;
		}
	}

	document.getElementById("totalcostdiv").innerHTML = "<b>$" + cost + "</b>";
	document.getElementById('totalcost').value = cost;
	
}

// function to disable the payer name field when the check field is checked 
// and make the values the same as the advertiser names
function makeSameAsAdvertiser() {
	if (document.getElementById('payernamecheckbox').checked == true ){
	 	disableField('namesofpayer');
		document.getElementById('namesofpayer').value = document.getElementById('namesofadvertiser').value;
	}	else {
		enableField('namesofpayer');
	}
}

// function to open a help window for radio adverts
function openRadioAdvertsHelpWindow(URLAnchor) {
aWindow=window.open("help.php#"+URLAnchor,"newwindow","toolbar=no,scrollbars=yes,status=no,location=no,resizable=yes,menubar=no,width=400, height=600, left=400");
}

// reset the form fields when a different package is selected
function resetFormFields() {
	document.getElementById("totalreadingsdiv").innerHTML = "";
	document.getElementById("totalcostdiv").innerHTML = "$0.00";
	document.getElementById("totalreadings").value = "";
	document.getElementById("totalcost").value = "";
	// Rest all 7 readings controls
	for (i=0; i < 7; i++) {
		// check if the first option is zero for each of the readings. When the page is first loaded
		// the first element is zero, but when the adverted is edited after preview the second element at index 1
		// is zero since the value selected before is at zero
		if (document.getElementById("readings_" + i).options[0].text == "0") {
			document.getElementById("readings_" + i).options[0].selected = "1";
		} else {
			document.getElementById("readings_" + i).options[1].selected = "1";
		}
	}
}

// check if the user has entered all the reading days for the selected package
function validateReadingTimes(){
   var packageReadings = new Number(document.getElementById("package").value);
   var readingssofar = new Number(
	document.getElementById("readings_0").options[document.getElementById("readings_0").selectedIndex].value) +
	new Number(document.getElementById("readings_1").options[document.getElementById("readings_1").selectedIndex].value) +
	new Number(document.getElementById("readings_2").options[document.getElementById("readings_2").selectedIndex].value) +
	new Number(document.getElementById("readings_3").options[document.getElementById("readings_3").selectedIndex].value) +
	new Number(document.getElementById("readings_4").options[document.getElementById("readings_4").selectedIndex].value) +
	new Number(document.getElementById("readings_5").options[document.getElementById("readings_5").selectedIndex].value) +
	new Number(document.getElementById("readings_6").options[document.getElementById("readings_6").selectedIndex].value);
   	// alert("the package readings are "+ packageReadings);
	// alert("the readings so far are "+ readingssofar);
	if(readingssofar < packageReadings){
 		alert("The package you selected has a maximum of " + packageReadings + " readings. You have only selected " + readingssofar + " readings. Please select more reading days.");
		return false;
	}
	return true;
}

// function to check number of characters in textfield
function checkNumberofCharactersInAdvert(textfieldName, counterFieldName) {
	var maxcharacters = 100;
	updateAdvertCounter();
	var text = document.getElementById("adverttext").value;
	var textLength = text.length;
	if (textLength > maxcharacters) {
		alert('You can only enter a maximum of ' + maxcharacters +' characters');
		// show only up to limit of charatcters
		var maxString = text.substring(0,maxcharacters);
		document.getElementById("adverttext").value = maxString;
		// reset counter
		document.getElementById("counterdiv").innerHTML = maxcharacters;
		return false;
	}
	return true;	
	
}

function updateAdvertCounter() {
	var numofwords = CountWords(document.getElementById("adverttext"));
	//alert ("number of words is" + numofwords);
	document.getElementById("counterdiv").innerHTML = numofwords + "       " + "words";
}

function deleteEntity(url, entity, name) {
	message = "Are you sure you want to delete " + entity + ": '" + name +"'? \n" + 
					"Press OK to delete the " + entity +"\n" + 
					"Cancel to stay on the current page";
	if (window.confirm(message)) {
		window.location.href=url;
	}
}

// prompts the user whether or not they would like to delete the user
function deleteVideo(url) {
	message = "Are you sure you want to delete the selected video? \n" + 
					"Press OK to delete the selected video and \n" + 
					"Cancel to stay on the current page";
	if (window.confirm(message)) {
		window.location.href=url;
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
