//com
function addLoadEvent (func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function(){
			oldonload();
	    	func();
		}
	}  
}
function insertAfter (newElement,targetElement) {
	var parent = targetElement.parentNode;
	if (parent.lastChild == targetElement) {
		parent.appendChild(newElement);
	}else {
		parent.insertBefore(newElement,targetElement.nextSibling);
	} 
}
function addClass (element,value) {
	if(!element.className){
		element.className = value;
	} else{
		newClassName = element.className;
		newClassName += "";
		newClassName +=value;
		element.className = newClassName;
	}
}


function highlightPage () {
	if (!document.getElementsByTagName) { return false; }
	if (!document.getElementById) return false;
	var headers = document.getElementsByTagName('header');
	var navs = headers[0].getElementsByTagName('nav');
	var links = navs[0].getElementsByTagName('a');
	var linkurl;
	for (var i = 0; i < links.length; i++) {
		linkurl = links[i].getAttribute("href");	
		if (window.location.href.indexOf(linkurl) != -1) {
			addClass(links[i],"here");
			var linktext = links[i].lastChild.nodeValue.toLowerCase();
			document.body.setAttribute("id", linktext);
		}
	}  
}

//home
function moveElement (elementID,final_x,final_y,interval) {
	if (!document.getElementById) { return false; }
	if (!document.getElementById(elementID)) { return false; }
	var elem = document.getElementById(elementID);
	if (elem.movement) {
		clearTimeout(elem.movement);
	}
	if (!elem.style.left) {
		elem.style.left = "0px";
	}
	if (!elem.style.top) {
		elem.style.top = "0px";
	}
	var xpos = parseInt(elem.style.left, 10);
	var ypos = parseInt(elem.style.top, 10);
	if (xpos == final_x && ypos == final_y) {
		return true;
	}
	if (xpos < final_x) {
		var dist = Math.ceil((final_x-xpos)/10);
		xpos = xpos + dist;
	}
	if (xpos > final_x) {
		var dist = Math.ceil((xpos-final_x)/10);
		xpos = xpos - dist;
	}
	if (ypos < final_y) {
		var dist = Math.ceil((final_y-ypos)/10);
		ypos = ypos+dist;
	}
	if (ypos > final_y) {
		var dist = Math.ceil((ypos-final_y)/10);
		ypos = ypos-dist;
	}
	elem.style.left = xpos + "px";
	elem.style.top = ypos + "px";
	var repeat = "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")";
	elem.movement = setTimeout(repeat,interval);

}
function prepareSlideshow () {
	if (!document.getElementsByTagName) return false;
	if (!document.getElementById) return false;
	if (!document.getElementById("intro")) return false;
	var intro = document.getElementById('intro');
	var slideshow = document.createElement("div");
	slideshow.setAttribute("id", "slideshow"); 
	var frame = document.createElement("img");
	frame.setAttribute("src", "images/frame.gif");
	frame.setAttribute("id", "frame");
	slideshow.appendChild(frame);
	var preview = document.createElement("img");
	preview.setAttribute("src", "images/slideshow.gif");
	preview.setAttribute("alt", 'which you');
	preview.setAttribute("id", "preview");
	slideshow.appendChild(preview);
	insertAfter(slideshow,intro);
	var links = document.getElementsByTagName("a");
	var destination;
	for (var i = 0; i < links.length; i++) {
		links[i].onmouseover = function () {
		 	destination = this.getAttribute("href");
		 	if (destination.indexOf("index.html") != -1) {
		 		moveElement("preview",0,0,5);
		 	}
		 	if (destination.indexOf("about.html") != -1) {
		 		moveElement("preview",-150,0,5);
		 	}
		 	if (destination.indexOf("photos.html") != -1) {
		 		moveElement("preview",-300,0,5);
		 	}
		 	if (destination.indexOf("live.html") != -1) {
		 		moveElement("preview",-450,0,5);
		 	}
		 	if (destination.indexOf("contact.html") != -1) {
		 		moveElement("preview",-600,0,5);
		 	}
		}	 
	}
}

// About


function showSection (id) {
	var sections = document.getElementsByTagName("section");
	for (var i = 0; i < sections.length; i++) {
	 	if (sections[i].getAttribute('id') != id) {
	 		sections[i].style.display = "none";
	 	} else {
	 		sections[i].style.display = "block";
	 	}
	 } 
}
function prepareInternalnav () {
	if(!document.getElementById) {
		return false;
	} 
	if(!document.getElementsByTagName){
		return false;
	}
	var articles = document.getElementsByTagName("article");
	if (articles.length === 0) { return false;}
	var navs = articles[0].getElementsByTagName("nav");
	if (navs.length === 0) { return false;}
	var links = navs[0].getElementsByTagName("a");
	for (var i = 0; i < links.length; i++) {
		var sectionId = links[i].getAttribute("href").split("#")[1];
		if (!document.getElementById(sectionId)) { continue;}
		document.getElementById(sectionId).style.display = "none";
		links[i].destination = sectionId;
		links[i].onclick = function () {
			showSection(this.destination);
			return false;
		}
	}
}
//photos

function showPic (whichpic) {
	if (!document.getElementById('placeholder')) { return false; }
	var source = whichpic.getAttribute("href");
	var placeholder = document.getElementById("placeholder");
	placeholder.setAttribute("src", source);
	if (!document.getElementById('description')) { return false;}
	var whictit = whichpic.getAttribute("title");
	if(whictit){
		var text = whictit;
	}else {
		var text = "";
	}
	var description = document.getElementById('description');
	if (description.firstChild.nodeType == 3) {
		description.firstChild.nodeValue = text;
	}
	return false;

}
function preparePlaceholder () {
	if (!document.createElement) { return false;}
	if (!document.createTextNode) {return false;}
	if (!document.getElementById) {return false;}
	if (!document.getElementById('imagegallery')) {return false;}
	var placeholder = document.createElement("img");
	placeholder.setAttribute("id", "placeholder");
	placeholder.setAttribute("src", "images/placeholder.gif");
	placeholder.setAttribute("alt", "my image gallery");
	var description = document.createElement("p");
	description.setAttribute("id", "description");
	var destxt = document.createTextNode("Choose an image");
	description.appendChild(destxt);
	var gallery = document.getElementById('imagegallery');
	insertAfter(description,gallery);
	insertAfter(placeholder,description);
}
function prepareGallery() {
	if (!document.getElementsByTagName) {return false;}
	if (!document.getElementById) {return false;}
	if (!document.getElementById('imagegallery')) {return false;}
	var gallery = document.getElementById('imagegallery');
	var links = gallery.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++) {
		links[i].onclick = function () {
			return showPic(this);
		}
	}

}

//live

function stripeTables () {
	if (!document.getElementsByTagName) { return false;}
	var tabs = document.getElementsByTagName('table');
	for (var i = 0; i < tabs.length; i++) {
		var odd = false;
		var trs = tabs[i].getElementsByTagName("tr");
		for (var j = 0; j < trs.length; j++) {
			if (odd == true) {
				addClass(trs[j],"odd");
				odd = false;
			}else {
				odd =true;
			}
		}
	}
}

function highlightRows() {
	if (!document.getElementsByTagName) { return false;}
	var trs = document.getElementsByTagName('tr');
	for (var i = 0; i < trs.length; i++) {
		trs[i].oldClassName = trs[i].className;
		trs[i].onmouseover = function () {
			 addClass(this,'highlight')
		};
		trs[i].onmouseout = function () {
			 this.className = this.oldClassName; 
		}
	}
}
function displayAbbreviations () {
	if (!document.getElementsByTagName || !document.createElement || !document.createTextNode) {return false;}
	var abbreviations = document.getElementsByTagName('abbr');
	if (abbreviations.length < 1) { return false;}
	var defs = new Array();
	for (var i = 0; i < abbreviations.length; i++) {
		var current_abbr = abbreviations[i];
		if(current_abbr.lastChild.nodeValue.length < 1){ continue;}
		var definition = current_abbr.getAttribute("title");
		var key = current_abbr.lastChild.nodeValue;
		defs[key] = definition;
	}
	var dlist = document.createElement("dl");
	for (key in defs) {
		var definition = defs[key];
		var dts = document.createElement('dt');
		var dt_txt = document.createTextNode(key);
		dts.appendChild(dt_txt);
		var dds = document.createElement('dd');
		var dd_txt = document.createTextNode(definition);
		dds.appendChild(dd_txt);
		dlist.appendChild(dts);
		dlist.appendChild(dds);
	}
	if (dlist.childNodes.length < 1) { return false;}
	var header = document.createElement("h3");
	var	header_text = document.createTextNode("Abbreviations");
	header.appendChild(header_text);
	var article = document.getElementsByTagName('article');
	if (article.length == 0) {return false;}
	var articleo= article[0];
	articleo.appendChild(header);
	articleo.appendChild(dlist);
}

//contant

function focusLabels () {
	if (!document.getElementsByTagName) { return false;}
	var labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {
	 	if (!labels[i].getAttribute("for")) { continue;}
	 	labels[i].onclick = function() {
	 		var l_id = this.getAttribute("for");
	 		if(!document.getElementById(l_id)){ return false;}
	 		var element = document.getElementById(l_id);
	 		element.focus(); 
	 	} 
	 } 
}

function resetFields (whichform) {
	//如果if返回true则结束当前函数
	if (Modernizr.input.placeholder)  return;
	for (var i = 0; i < whichform.elements.length; i++) {
		var element = whichform.elements[i];
		if(element.type == "submit") continue;
		var check = element.placeholder || element.getAttribute("placeholder");
		if(!check) continue;
		element.onfocus = function () {
			var text = this.placeholder || this.getAttribute("placeholder");
			if (this.value == text) {
				this.value = "";
				this.className = "";
			} 
		}
		element.onblur = function () {
			if (this.value == "") {
				this.value = this.placeholder || this.getAttribute("placeholder");
				this.className = "placeholder";
			} 
		}
		element.onblur();
	}
}
function validateForm(whichform) {
	for (var i = 0; i < whichform.elements.length; i++) {
		 	var element = whichform.elements[i];
		 	if (element.getAttribute('required') == 'required') {
		 		if (!isFilled(element)) {
		 			alert("Please fill in the "+element.name+"field");
		 			return false;
		 		}
		 	}
		 	if (element.getAttribute('type') == "email") {
		 		if (!isEmail(element)) {
		 			alert("The"+element.name+"field must be a valid email address.");
		 			return false;
		 		}
		 	}
		}
		return true;	 
}

// function isFilled (field) {
// 	if (field.value.replace(' ','').length == 0) { return false;}
// 	var placeholder = field.placeholder || field.getAttribute('placeholder'); 
// 	return (field.value != placeholder);
// }
// function isEmail (field) {
// 	return (field.value.indexOf('@') != -1 || field.value.indexOf('.') != -1); 
// }
function isFilled(field) {
  return (field.value.length > 1 && field.value != field.placeholder);
}

function isEmail(field) {
  return (field.value.indexOf("@") != -1 && field.value.indexOf(".") != -1);
}
function prepareForms () {
	for (var i = 0; i < document.forms.length; i++) {
	 	var thisform = document.forms[i];
	 	resetFields(thisform);
	 	thisform.onsubmit = function () {
	 		if (!validateForm(this)) { return false; }
	 		var article = document.getElementsByTagName('article')[0];
	 		if (submitFormWithAjax(this, article)) return false;
	 			return true;
	 			 
	 	}
	 } 
}

//ajax
function getHTTPObject () {
	if (typeof XMLHttpRequest == "undefined") 
		XMLHttpRequest = function () {
			try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
				catch (e) {}
			try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
				catch (e) {}
			try { return new ActiveXObject("Msxml2.XMLHTTP"); }
				catch (e) {}
				return false;

		} 
		return new XMLHttpRequest();
}

function displayAjaxLoading (element) {
	while (element.hasChildNodes()) {
	    element.removeChild(element.lastChild);
	 }
	 var content = document.createElement('img');
	 content.setAttribute("src", "images/loading.gif");
	 content.setAttribute("alt", "Loading...");
	 element.appendChild(content); 
}
function submitFormWithAjax (whichform,thetarget) {
	var request = getHTTPObject();
	if (!request) { return false; }
	displayAjaxLoading(thetarget);
	var dataParts = [];
	var element;
	for (var i = 0; i < whichform.elements.length; i++) {
	 	element = whichform.elements[i];
	 	dataParts[i] = element.name + '=' + encodeURIComponent(element.value);
	 } 
	 var data = dataParts.join('&');
	 request.open('POST', whichform.getAttribute("action"), true);
	 request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	 request.onreadystatechange = function () {
	 	//验证当前文档的状态
	 	if (request.readyState == 4) {
	 		//响应成功
	 		if (request.status == 200 || request.status == 0) {
	 			//读取响应文本match()可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配
	 			var matches = request.responseText.match(/<article>([\s\S]+)<\/article>/);
	 			if (matches.length > 0) {
	 				thetarget.innerHTML = matches[1];
	 			} else {
	 				thetarget.innerHTML = '<p>Oops, there was an error. Sorry.</p>';
	 			}
	 		} else {
	 			thetarget.innHTML = '<p> + request.statusText + </p>';
	 		}

	 	} 
	 };
	 request.send(data);
	 return true;
}
function loadEvents() {
  // home
  prepareSlideshow();
  // about
  prepareInternalnav();
  // photos
  preparePlaceholder();
  prepareGallery();
  //live
  stripeTables ();
  highlightRows();
  displayAbbreviations();
  //contact
  focusLabels ();
  prepareForms ();
}

// Load events
addLoadEvent(highlightPage);
addLoadEvent(loadEvents);

 书中的综合案例,讲述了部分常用的函数