/*
	If this file is added to a page, all these functions will be run. This is why they are common functions.
*/

/* Constants */

var constants = new Array();
constants['images'] = new Array();
constants['images']['quarry'] = 'ennstone-quarry.gif';

/* Functions */

function getBrowserCompatibility() {
	var ibnames = new Array(); //incompatible browser names
	//ibnames.push("Netscape");
	ibnames.push("Microsoft Internet Explorer");
	var browserName=navigator.appName;
	for (var ptr in ibnames) {
		var bname = ibnames[ptr];
		if (bname==browserName) {
			return false;
		}
	}
	return true;
}

/*function setNavigationAppearance() {
	var navcontainer = document.getElementById('navcontainer');
	if (navcontainer) {
		var list = navcontainer.getElementsByTagName('ul')[0];
		var activeclass = "active";
		for (var ptr in list.childNodes) {
			var listitem = list.childNodes[ptr];
			if (listitem.getElementsByTagName) {
				var childLink = listitem.getElementsByTagName('a')[0];
				if (childLink.href == location.href) {
					listitem.className = listitem.className + activeclass;
				}
				//check for homepage
			}
		}
	}
}*/
/*
function hideNavigationLinks() {
	var hideURLs = new Array();
	hideURLs.push("sites.htm");
	var navcontainer = document.getElementById('navcontainer');
	if (navcontainer) {
		var list = navcontainer.getElementsByTagName('ul')[0];
		var hiddenClass = "hidden";
		for (var ptr in list.childNodes) {
			var listitem = list.childNodes[ptr];
			if (listitem.getElementsByTagName) {
				var childLink = listitem.getElementsByTagName('a')[0];
				var clhref = childLink.href;
				for (var urlptr in hideURLs) {
					var hurl = hideURLs[urlptr];
					var endchunk = clhref.substr(clhref.length-hurl.length);
					if (endchunk == hurl) {
						listitem.className = listitem.className + hiddenClass;
					}
				}
			}
		}
	}
}
*/
function NavigationItem(caption, url) {
	this.caption = caption;
	this.url = url;
}

function NavigationManager(navid) {
	this.navigationHTMLID = navid;
	this.items = new Array();
	this.home = new NavigationItem('', '');
	this.add = function(url, caption, home) {
		this.items[url] = new NavigationItem(caption, url);
		if (home && home == true) {
			this.home = this.items[url];
			if (location.pathname == '/' && this.home.url != '/') { //redirects to home page to make navigation menu tidier
				location.href = this.home.url;
			}
		}
	};
	this.validate = function() {
		var navcontainer = document.getElementById(this.navigationHTMLID);
		if (navcontainer) {
			var list = navcontainer.getElementsByTagName('ul')[0];

			//warns of links which are incorrect or missing
				//by going through each link in this list and seeing which ones don't exist in the html
			for (var urlptr in this.items) {
				var hurl = this.items[urlptr];
				var isFound = false;
				var isValidCaption = false;
				for (var ptr in list.childNodes) { // html items
					var listitem = list.childNodes[ptr];
					if (listitem.getElementsByTagName) {
						var childLink = listitem.getElementsByTagName('a')[0];
						var clhref = childLink.href;
						//for (var urlptr in this.items) { // this list of items
							//var hurl = urlptr;
							var endchunk = clhref.substr(clhref.length-hurl.url.length);
							if (endchunk == hurl.url) {
								isFound = true;
								if (hurl.caption == childLink.innerHTML) isValidCaption = true;
							}
						//}
					}
				}
				if (isFound!=true) {
					//listitem.className = listitem.className + hiddenClass;
					//put in debugging message for this?
					this.appendDebug("Link to '"+hurl.url+"' does not exist in navigation list.");
				} else if(isValidCaption!=true) {
					this.appendDebug("Link to '"+hurl.url+"' caption should be '"+hurl.caption+"'.");
				}
			}
			//hides links which shouldn't be there
				//by going through each existing link and seeing which ones don't exist in this list
			/*var hiddenClass = "hidden";
			for (var ptr in list.childNodes) { // html items
				var listitem = list.childNodes[ptr];
				if (listitem.getElementsByTagName) {
					var childLink = listitem.getElementsByTagName('a')[0];
					var clhref = childLink.href;
					var isFound = false;
					for (var urlptr in this.items) { // this list of items
						var hurl = urlptr;
						var endchunk = clhref.substr(clhref.length-hurl.length);
						if (endchunk == hurl) {isFound = true;}
					}
					if (isFound!=true) {
						listitem.className = listitem.className + " " + hiddenClass;
						//put in debugging message for this?
						this.appendDebug("Link labelled '"+childLink.innerHTML+"' has been hidden.");
					}
				}
			}*/
		}
	};
	this.appendDebug = function(message) {
		var navigation = document.getElementById(this.navigationHTMLID);
		var txt = document.createTextNode(message);
		var container = document.createElement('div');
		container.className = "remove";
		container.appendChild(txt);
		var outer = document.createElement('div');
		outer.appendChild(container);
		navigation.appendChild(outer);
	};
	this.setNavigationAppearance = function() {
		var navcontainer = document.getElementById(this.navigationHTMLID);
		if (navcontainer) {
			var list = navcontainer.getElementsByTagName('ul')[0];
			var activeclass = "active";
			for (var ptr in list.childNodes) {
				var listitem = list.childNodes[ptr];
				if (listitem.getElementsByTagName) {
					var childLink = listitem.getElementsByTagName('a')[0];
					if (childLink.href == location.href) {
						listitem.className = listitem.className + activeclass;
					}
				}
			}
		}
	}

}

function addTitleOwls() {
	var hideURLs = new Array();
	hideURLs.push("sites.htm");
	var owlsbar = document.getElementById('owlsbar'); //MUST be a block element
	if (owlsbar) { // if element exists then get owlsbar innerHTML, remove it and put it into a new div within owlsbar 
		var innerbar = document.createElement('div');
		innerbar.className = "innerowl";
		var html = owlsbar.innerHTML;
		owlsbar.innerHTML = "";
		innerbar.innerHTML = html;
		owlsbar.appendChild(innerbar);
		owlsbar.className = owlsbar.className + " outerowl";
	}
}

function appendTopLink() {
	var body = document.getElementsByTagName('body')[0];
	var toplink = document.createElement('a');
	toplink.href='#';
	toplink.innerHTML='Back to Top';
	var link_container = document.createElement('p');
	link_container.appendChild(toplink);
	body.appendChild(link_container);
}

/*function checkTextNodes(element, text) {
	var str = new String(element.innerHTML);
	if (str.search('@')) {
		
	}
	for (var ptr in element.childNodes) {
		print_o(element.childNodes[ptr]);
	}
}*/

/*
	The idea is to create effects on text from here
*/

function TextAffected(id, effect, reset) {
	this.id = id;
	this.effect = effect;
	this.max = reset;
	this.current = 0;
	this.stopped = false;

	this.data = new Array();

	this.stepEffect = function() {this.end()&&this.stopped==false?this.current=0:this.current++;};
	this.reset = function() {this.current = 0;};
	this.stop = function() {this.stopped=true;};
	this.start = function() {this.stopped=false;};
	this.end = function() {return this.current>this.max?true:false;};
}

function TextEffects() {
	this.effects = new Array();
	this.interval_id = null;

	this.setInterval = function(interval, obj_name) { //run later, perhaps?
		this.interval_id = window.setInterval(obj_name+'.executeEffects()', interval);
	}

	this.add = function(id, effect, reset_time) {
		this.addAffected(new TextAffected(id, effect, reset_time));
	};
	this.addAffected = function(affected) {
		this.effects.push(affected);
	};
	this.executeEffects = function() { //is run each interval
		for(var i in this.effects) {
			this.executeEffect(this.effects[i]);
		}
	};
	this.executeEffect = function(txtaffected) {
		var effect = txtaffected.effect;
		var htmlid = txtaffected.id;
		var element = document.getElementById(htmlid);

		var op_max = txtaffected.max;
		var current = txtaffected.current;
		switch(effect) {
			case "fade": {
				var current_op = current<(op_max/2)?1-(current*2/op_max):(current*2/op_max)-1;
				element.style.opacity = current_op;
			} break;
			case "waitfadewait": {
				var current_op = 0;
				if (current<(op_max/3)) {
					current_op = 0;
				} else if(current<(op_max*2/3)&&current>(op_max/3)) {
					current_op = ((current*3)/(op_max))-1;
				} else {
					current_op = 1;
				}
				element.style.opacity = current_op;
			} break;
			case "fadeto": {
				var current_op = ((current)/(op_max));
				if (txtaffected.end()) {
					txtaffected.stop();
					txtaffected.data["next"].start();
				}
				element.style.opacity = current_op;
			} break;
			case "colour_rotate": {
			} break;
		}
		txtaffected.stepEffect();
	};
}

function ImageFader(image_ids) {
	this.ids = image_ids;
	//do I need this?
}

var BottomFadingImage = new TextEffects();

var imglist = new Array();
imglist.push("Bintree-greenery.gif");
imglist.push("bintree-greenery2.gif");
imglist.push("bintreewoods-path.jpg");
imglist.push("DSCF0044.JPG");
imglist.push("DSCF0047.JPG");
imglist.push("DSCF0400.jpg");
imglist.push("DSCF0410.jpg");
imglist.push("DSCF0435.jpg");
imglist.push("DSCF0437.jpg");

function getImagesFolder() {
	var pubimgfdr = document.getElementById("set_public_images_folder");
	return pubimgfdr?pubimgfdr.innerHTML:"";
}

function appendFadingImage() {
	//var pubimgfdr = document.getElementById("set_public_images_folder");
	//var public_images = pubimgfdr?pubimgfdr.innerHTML:"";
	var public_images = getImagesFolder();
	var phtml = '<h4 id="bottomtitle" style="color: red; font-weight: bold;">SAVE BINTREE WOODS</h4>';
	//randomly generate image url for this html
	var imgidx = Math.floor(imglist.length*Math.random());
	var fhtml = '<div class="picturefader" style="border: none; width: 300px; height: 199px;"><img src="'+public_images+'images/'+imglist[imgidx]+'" id="img_fod_1"/><img src="'+public_images+'images/ennstone-quarry.gif" id="img_fod_2"/></div>';

	var body = document.getElementsByTagName('body')[0];
	var fader = document.createElement('div');
	fader.innerHTML = phtml+fhtml;
	fader.align = "center";
	fader.className = "fader_container";
	body.appendChild(fader);

	BottomFadingImage.add("img_fod_2", "waitfadewait", 100);
	BottomFadingImage.setInterval(50, "BottomFadingImage");
}

function xdrn(x, range) { //x different random integers
	var max_flag = Math.floor(x/range)+1;
	var flag_array = new Array(range);
	var ret = new Array(x);
	var i = 0;
	var debug = 0;
	var safe = 0;
	do {
		var rand = Math.floor(range*Math.random());
		if (!flag_array[rand]) flag_array[rand]=0;
		if (flag_array[rand]<max_flag) { //if less than max flag, then assign random number
			debug=1;
			ret[i] = rand;
			i++;
		}
		flag_array[rand]++;
		safe++;
	} while (i<x && safe<(range*max_flag));
	return ret;
}

function getElFromHTML(html, element_type) {
	var container = document.createElement('div');
	container.innerHTML = html;
	//print_o(container.childNodes, true);
	var els = container.getElementsByTagName(element_type);
	//print_o(els[0], true);
	return els;
}

function appendIEImages() {
	var public_images = getImagesFolder();
	var body = document.getElementsByTagName('body')[0];
	var container = document.createElement('div');
	var imgcontainer = document.createElement('div');
	imgcontainer.style.height = "150px";
	imgcontainer.style.position = "relative";
	var phtml = '<h4 id="bottomtitle" style="text-align: center; color: red; font-weight: bold;">SAVE BINTREE WOODS</h4>';
	var imgwidth = 200;
	var imgstyle = 'style="width: '+imgwidth+'px; height: 150px; position: absolute;"';
	var quarryimghtml = '<img src="'+public_images+'images/'+constants['images']['quarry']+'" '+imgstyle+'/>';
	var imgidx = xdrn(3, imglist.length);
	var imgarray = new Array();
	var splitterhtml = 'splitter';//'<!-- splitter -->';
	for(var i in imgidx) {
		imgarray.push('<img src="'+public_images+'images/'+imglist[imgidx[i]]+'" '+imgstyle+'/>'+splitterhtml);
	}
	var imgstr = imgarray.join(quarryimghtml+splitterhtml);
	var imgarray = imgstr.split(splitterhtml);
	for(var i in imgarray) {
		var img = getElFromHTML(imgarray[i], 'img')[0];
		if (img) {
			img.style.left = i*imgwidth;
			imgcontainer.appendChild(img);
		}
	}
	container.innerHTML = phtml;
	container.appendChild(imgcontainer);
	body.appendChild(container);
}

function getFirefox() {
	if (getBrowserCompatibility()==false) {
		var navcontainer = document.getElementById('navcontainer');
		var link = document.createElement('div');
		link.style.width = '200px';
		link.innerHTML = '<p>This website works best<br />when using the free<br /><a href="http://www.mozilla.com/firefox">firefox</a> web browser<br />to view it.</p>';
		navcontainer.appendChild(link);
	}
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

function delayedScripts() {
	//setTimeout(setNavigationAppearance, 1000);
}

/* Data area - This area is specifically for using objects and functions as opposed to making new ones. */

var navman = new NavigationManager('navcontainer');
navman.add("index.php", "Home", true);
navman.add("digupcountryside.php", "Do we really need to dig up the countryside?");
navman.add("infolinks.php", "Information Links");
navman.add("proposals/index.php", "Proposals");
navman.add("whathappensnext.php", "What Happens Next");
navman.add("climatechange.php", "Climate Change");
navman.add("fcrole.php", "Role of the Forestry Commission");
navman.add("story.php", "Story So Far");
navman.add("howwillitaffectyou.php", "How will it affect you?");
navman.add("politicalsupport.php", "Political Support");
navman.add("gallery.php", "Gallery");
navman.add("contacts.php", "Contacts");

function navmanValidate() {
	//navman.validate();
	navman.setNavigationAppearance();
}

/* Loading area - where functions are referenced to be loaded on body load */

addLoadEvent(delayedScripts);
addLoadEvent(addTitleOwls);
//addLoadEvent(setNavigationAppearance);
//addLoadEvent(hideNavigationLinks);
addLoadEvent(appendTopLink); // Needs to go before fading image for top link to be added before fading image.
//if (getBrowserCompatibility()==true) addLoadEvent(appendFadingImage) else addLoadEvent(appendFadingImage);
try {
	if (exclude_fading_image) {}
} catch(e) {
	// Doesn't exist
	exclude_fading_image = null;
}
if (!exclude_fading_image) {
	addLoadEvent(getBrowserCompatibility()==true?appendFadingImage:appendIEImages);
}
//addLoadEvent(appendIEImages);
if (getBrowserCompatibility()) addLoadEvent(navmanValidate);
addLoadEvent(getFirefox);
