//////////////////////////////////////////////////////
////// ETS CORE JAVASCRIPT LIBRARY ///////////////////
//////////////////////////////////////////////////////
// Library of functions to manage page content. 
// © 2009 Matthew Fries & Equal Temperament Solutions
// It's simple, but I worked hard on this. Please don't 
// steal it without proper credit. :-)
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////



// If they are Javascript friendly, we'll rewrite the URL to use AJAX
if (document.location.href.indexOf("#") < 0) {
	if (document.location.href.indexOf("/page/") > 0) {
		document.location.href = document.location.href.replace("/page/", "/#/");
	}
	else {
		document.location.href = window.location.protocol + "//" +  window.location.host + "/#" + window.location.pathname;
	}
}


//////////////////////////////////////////////////////
// ets_ChangeSection(page) ///////////////////////////////
// update the body CSS so other layouts can be applied

var last_className = "home";
var last_title = "home";

function ets_ChangeSection(page) {
	
	// change the body class to match the section
	var section = page.substring(1,page.length);
	var classes;
	var titles;
	
	// set to home if no page requested
	if (section.length == 0) {
		classes = "home";
		titles = "home";
	}
	
	// replace the slashes with spaces
	var classes = " " + section.replace(/\//g, " ");
	var titles = " " + section.replace(/\//g, " :: ");
	
	// preserve any manually applied styles -- not that there should be any, but just in case...
	// strip out any classNames we've applied
	current_className = document.body.className.replace(last_className, "");
	current_title = document.title.replace(last_title, "");
	
	// reassign the last_className
	last_className = classes;
	last_title = titles
	
	// add the new classes to the body className
	current_className += classes;
	document.body.className = current_className;
	
	current_title += titles;
	document.title = current_title;
	
	// test results
	//alert(document.body.className);
}


//////////////////////////////////////////////////////
// ets_GetContent(page) //////////////////////////////////
// change the CSS, update the url, request the page

function ets_GetContent(page) {
	
	// update the body CSS
	ets_ChangeSection(page);
	
	// update the url
	parent.location.hash = page;
	
	// what to do on reply	
	reply = ets_WriteContent;
	
	// request the page
	var url = '/get_page.php?page=' + page + '&nocache = ' + nocache;
	ets_AjaxSubmit(url);
	
	return false;
}


function ets_WriteContent() {
	// this will write in the page content
	document.getElementById('content').innerHTML = responseText;
	responseText = "";
	// update the CSS of any Inline Player links
	if (inlinePlayer) {
		inlinePlayer.init();
	}
}



//////////////////////////////////////////////////////
// ets_ValidEmail(email) /////////////////////////////////
// returns true if the submitted email appears valid

function ets_ValidEmail(email) {
    invalidChars = "/:,;"

    for (i=0;i<invalidChars.length;i++) {
        badChar = invalidChars.charAt(i)
        if (email.indexOf(badChar,0) > -1) {
            return false
        }
    }
    atPos = email.indexOf("@",1)
    if (atPos == -1) {
        return false
    }
    if (email.indexOf("@",atPos+1) > -1) {
        return false
    }
    periodPos = email.indexOf(".",atPos)
    if (periodPos == -1) {
        return false
    }
    if (periodPos+3 > email.length) {
        return false
    }
    return true;

}


//////////////////////////////////////////////////////
// Javascript Modal Dialog Functions /////////////////
// my own version of an alert popup

var ets_dialog;
var ets_dialog_mask;

function ets_ShowMessage(text, title) {
	
	posY = ets_GetScreenCenterY();
	posX = ets_GetScreenCenterX();
	
	ets_dialog_mask = document.createElement('div');
	ets_dialog_mask.setAttribute('id',"css_dialog_mask");
	ets_dialog_mask.onclick = ets_HideMessage;
	document.body.appendChild(ets_dialog_mask);
	
	ets_dialog = document.createElement('div');
	ets_dialog.setAttribute('id',"css_dialog");
	ets_dialog.style.cssText = "top:" + posY + "px;left:" + posX + "px;";
	var msg_text = "";
	//msg_text += '<a href="#" onClick="ets_HideMessage();" class="close_button">close window</a>';
	(title) ? msg_text += "<h1>" + title + "</h1><p>" + text + "</p>" : msg_text += "<p>" + text + "</p>"
	msg_text += '<a href="#" onClick="ets_HideMessage();" class="confirm_button">OK</a><br style="clear:both;" />';
	ets_dialog.innerHTML = msg_text;
	document.body.appendChild(ets_dialog);
	
	new_top = posY - (ets_dialog.offsetHeight/2);
	ets_dialog.style.top = new_top + "px";
	
}

function ets_HideMessage() {
	if (ets_dialog) {
		document.body.removeChild(ets_dialog_mask);
		document.body.removeChild(ets_dialog);
		ets_dialog = null;
	}
}


function ets_GetScreenCenterY() {
	var y = 0;
	y = ets_GetInnerHeight()/2;
	//y = ets_GetScrollOffset()+(ets_GetInnerHeight()/2);
	return(y);
}

function ets_GetScreenCenterX() {
	return(document.body.clientWidth/2);
}

function ets_GetInnerHeight() {
	var y;
	if (self.innerHeight) { // all except Explorer
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		y = document.documentElement.clientHeight;
	}
	else if (document.body) { // other Explorers
		y = document.body.clientHeight;
	}
	return(y);
}

function ets_GetScrollOffset() {
	var y;
	if (self.pageYOffset) { // all except Explorer
		y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
		y = document.documentElement.scrollTop;
	}
	else if (document.body) { // all other Explorers
		y = document.body.scrollTop;
	}
	return(y);
}




//////////////////////////////////////////////////////
// HTTP Request Functions ////////////////////////////
// 

/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function ets_AjaxObject() {
	var request_type;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		request_type = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		request_type = new XMLHttpRequest();
	}
	return request_type;
}

var http;
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;

var reply; // variable to hold the function to run on reply.
var responseText; // variable to hold the response text.


// gets the reply and displays the response text in the form_message area
function ets_AjaxReply() {
	if (http.readyState == 4) {
		if (document.images['spinner']) {
			document.images['spinner'].src = "/images/no_spin.gif";
		}
		responseText = http.responseText;
		reply();
	}
	
	ets_Controller();
}

function ets_AjaxSubmit(url) {
	if (document.images['spinner']) {
		document.images['spinner'].src = "/images/spin.gif";
	}
	
	nocache = Math.random();
	
	if (url.indexOf('?') > -1) {
		url += '&nocache = ' + nocache;
	}
	else {
		url += '?nocache = ' + nocache;
	}
	
	http = ets_AjaxObject();
	http.open('get', url);
	http.onreadystatechange = ets_AjaxReply;
	http.send(null);
}


function ets_Controller() {
	// prime the links on the site to use AJAX instead of plain old href
	var ets_links = document.getElementsByTagName('a');
	for(var i = 0; i < ets_links.length; i++){
		// 1. only apply to internal links
		// 2. skip links with target="_blank"
		// 3. skip links with an onClick event already assigned.
		// 4. also skipping MP3's for now (let the soundmanager handle them)
		if (ets_GetDomain(ets_links[i].href) == ets_GetDomain(document.location.href) && !ets_links[i].getAttribute('onClick') && ets_links[i].getAttribute('target') != '_blank' && !ets_links[i].href.match(/\.mp3/i)) { 
			ets_links[i].onclick = function(){
				var url = this.getAttribute('href');
				// extract the link and preserve any query strings
				var new_page = url.substring(url.indexOf('/page/')+5, url.length).replace("?", "&"); 
				ets_GetContent(new_page);
				return false;
			}
		}
	}
}

function ets_GetDomain(url) {
	return url.match(/:\/\/(.[^/]+)/)[1];
}