// Identifies the domain part of the current page.
function whereAmI () {
	var loc = window.location;
	matches = /^(https?\:\/\/[^\/]+)\//.exec(loc);
	if (matches[0].length > 0) {
		return matches[1];
	}
	return '';
}

// All of the AJAX Urls.
var base_url = whereAmI(); //'http://colinbate.local';
var save_content_url = base_url + '/corkboard/l/save-content';
var verify_login_url = base_url + '/corkboard/l/verify';
var content_form_url = base_url + '/corkboard/l/content-form'

// Add some trimming to the String object.
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

// Taken from: http://www.hunlock.com/blogs/Snippets:_Howto_Grey-Out_The_Screen
function grayOut(vis, options) {
	// Pass true to gray out screen, false to ungray
	// options are optional.  This is a JSON object with the following (optional) properties
	// opacity:0-100         // Lower number = less grayout higher = more of a blackout 
	// zindex: #             // HTML elements with a higher zindex appear on top of the gray out
	// bgcolor: (#xxxxxx)    // Standard RGB Hex color code
	// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
	// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
	// in any order.  Pass only the properties you need to set.
	var options = options || {}; 
	var zindex = options.zindex || 50;
	var opacity = options.opacity || 70;
	var opaque = (opacity / 100);
	var bgcolor = options.bgcolor || '#000000';
	var dark=document.getElementById('darkenScreenObject');
	if (!dark) {
		// The dark layer doesn't exist, it's never been created.  So we'll
		// create it here and apply some basic styles.
		// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
		var tbody = document.getElementsByTagName("body")[0];
		var tnode = document.createElement('div');           // Create the layer.
		tnode.style.position='absolute';                 // Position absolutely
		tnode.style.top='0px';                           // In the top
		tnode.style.left='0px';                          // Left corner of the page
		tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
		tnode.style.display='none';                      // Start out Hidden
		tnode.id='darkenScreenObject';                   // Name it so we can find it later
		tbody.appendChild(tnode);                            // Add it to the web page
		dark=document.getElementById('darkenScreenObject');  // Get the object.
	}
	if (vis) {
		// Calculate the page width and height 
		if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
			var pageWidth = document.body.scrollWidth+'px';
			var pageHeight = document.body.scrollHeight+'px';
		} else if( document.body.offsetWidth ) {
			var pageWidth = document.body.offsetWidth+'px';
			var pageHeight = document.body.offsetHeight+'px';
		} else {
			var pageWidth='100%';
			var pageHeight='100%';
		}   
		//set the shader to cover the entire page and make it visible.
		dark.style.opacity=opaque;                      
		dark.style.MozOpacity=opaque;                   
		dark.style.filter='alpha(opacity='+opacity+')'; 
		dark.style.zIndex=zindex;        
		dark.style.backgroundColor=bgcolor;  
		dark.style.width= pageWidth;
		dark.style.height= pageHeight;
		dark.style.display='block';                          
	} else {
		dark.style.display='none';
	}
}

function fadeOut (id, options, func) {
	var log = document.getElementById('logfile');
	var options = options || {};
	var none;
	options.timespan = options.timespan || 1000;
	if (options.remaining == none) {
		options.remaining = options.timespan;
	}
	if (options.start == none) {
		options.start = 100;
	}
	options.end = options.end || 0;
	if (options.cop == none) {
		options.cop = options.start;
	}
	options.steps = options.steps || 10;
	if (log) { log.innerHTML = 'ts: '+options.timespan+' rem: '+options.remaining+' cop: '+options.cop; }
	if (typeof id == "string") {
		var obj = document.getElementById(id);
	} else {
		var obj = id;
	}
	if (obj) {
		var inc = (options.end - options.start) / options.steps;
		var tinc = (options.timespan / options.steps);
		var opacity = (options.cop / 100);
		obj.style.opacity=opacity;
		obj.style.MozOpacity=opacity;
		obj.style.KhtmlOpacity=opacity;
		obj.style.filter='alpha(opacity='+opacity+')';
		if (options.remaining > 0) {
			options.remaining -= tinc;
			options.cop += inc;
			setTimeout(function(){fadeOut(obj, options, func)}, tinc);
		} else {
			// Run end function.
			if (func != none) {
				var lam = function(){func(id)};
				lam();
			}
		}
	}
}

function disappear (id) {
	if (typeof id == "string") {
		obj = document.getElementById(id);
	} else {
		obj = id;
	}
	if (obj) {
		obj.style.display = 'none';
		obj.style.zIndex = -1;
	}
}

function moveSlide (id) {
	if (typeof id == "string") {
		var str_id = id;
		var obj = document.getElementById(id);
	} else {
		var obj = id;
		var str_id = obj.id;
	}
	var num_this = parseInt(str_id.substr(7));
	var num_next = num_this + 1;
	var next_id = 'ssphoto'+num_next;
	var log = document.getElementById('logfile');
	var next_obj = document.getElementById(next_id);
	if (!next_obj) {
		next_id = 'ssphoto1';
		next_obj = document.getElementById(next_id);
		num_next = 1;
	}
	
	if (obj) {
		obj.className = 'hide';
		if (next_obj) {
			var x = parseInt((500 - next_obj.width) / 2);
			next_obj.style.left = x+'px';
			next_obj.className = 'present';
			setOpacity(next_obj, 0);
			var opts = {'start': 0, 'end': 100};
			//fadeOut(next_obj, opts);
			fadeOut(next_obj, opts, function(){timeSlide(num_next)});
			//fadeOut('ssphoto$c', {}, moveSlide);
		}
	}
}

var ss_speed = 3000;
function timeSlide (num) {
	var slide = 'ssphoto'+num;
	setTimeout(function(){fadeOut(slide, {}, moveSlide);}, ss_speed);
}

function setOpacity(obj, opacity) {
	obj.style.opacity=opacity;
	obj.style.MozOpacity=opacity;
	obj.style.KhtmlOpacity=opacity;
	obj.style.filter='alpha(opacity='+opacity+')';
}

function createLoginBox(submitTo) {
	var lbox=document.getElementById('echoLoginBox');
	if (!lbox) {
		var tbody = document.getElementsByTagName("body")[0];
		var tnode = document.createElement('div');
		tnode.id = 'echoLoginBox';
		tnode.style.display = 'none';
		tnode.style.position = 'absolute';
		tnode.style.width = '250px';
		tnode.style.height = '150px';
		tbody.appendChild(tnode);                            // Add it to the web page
		lbox=document.getElementById('echoLoginBox');
	}
	//lbox.innerHTML = '<form action="/corkboard/l/verify" name="elb" method="post" accept-charset="utf-8"><label for="frm_username">Username</label><input type="text" name="username" value="" class="txt" id="frm_username" size="20" /><label for="frm_password">Password</label><input type="password" name="password" class="txt" value="" id="frm_password" size="20" /><p><input type="button" value="Login" onclick="checkLogin(this);return true;"> <input type="button" value="Cancel" onclick="closeLoginBox();return true;"></p></form>';
	lbox.innerHTML = getLoginBox(true, '');
	var l = (window.innerWidth - 250) / 2;
	var t = (window.innerHeight - 150) / 2;
	//alert('Left: '+l+' Top: '+t);
	lbox.style.left = l+'px';
	lbox.style.top = t+'px';
	//lbox.style.left = '100px';
	//lbox.style.top = '100px';
	lbox.style.backgroundColor = '#ffffff';
	lbox.style.zIndex = 60;
	grayOut(true);
	lbox.style.display = 'block';
	document.elb.username.focus();
}

function closeLoginBox() {
	var lbox=document.getElementById('echoLoginBox');
	lbox.style.display = 'none';
	grayOut(false);
}

function checkLogin(obj) {
	var lbox=document.getElementById('echoLoginBox');
	var un = document.elb.username.value;
	var pw = document.elb.password.value;
	var esc_un = encodeURIComponent(un);
	var esc_pw = encodeURIComponent(pw);
	var url = verify_login_url + '?username='+esc_un+'&password='+esc_pw;
	fetch(url, loginResults);
	lbox.innerHTML = getLoginBox(false, "Checking...");
}

// Returns the HTML for the login box. If 'form' is false, outputs 'txt'.
function getLoginBox (form, txt) {
	var html =    '<div class="innerbox"><div style="display: table-cell; vertical-align: middle;">' + "\n";
	if (form) {
		html = html + '<form action="/corkboard/l/verify" name="elb" method="post" accept-charset="utf-8">';
		html = html + '  <label for="frm_username">Username</label>';
		html = html + '  <input type="text" name="username" value="" class="txt" id="frm_username" size="20" />';
		html = html + '  <label for="frm_password">Password</label>';
		html = html + '  <input type="password" name="password" class="txt" value="" id="frm_password" size="20" />';
		html = html + '  <p>';
		html = html + '    <input type="button" value="Login" onclick="checkLogin(this);return true;">';
		html = html + '    <input type="button" value="Cancel" onclick="closeLoginBox();return true;">';
		html = html + '  </p>';
		html = html + '</form>';
	} else {
		html = html + '<p style="font-size: 14pt;">' + txt + '</p>';
	}
	html = html + '</div></div>' + "\n";
	return html;
}

function loginResults() {
	if (http.readyState == 4) {
		var lbox = document.getElementById('echoLoginBox');
		var res = http.responseText;
		var obj = eval('(' + res + ')');
		if (obj.result == 'Verified') {
			document.cookie = 'echo_user='+obj.uid+'; path=/';
			document.cookie = 'echo_authcode='+obj.nonce+'; path=/';
			lbox.innerHTML = getLoginBox(false, "Verified");
			var mm = document.getElementById('mainmenu');
			mm.innerHTML = mm.innerHTML + obj.links;
		} else {
			lbox.innerHTML = '<p style="text-align: center; font-size: 12pt;">Failed</p>';
		}
		window.setTimeout(closeLoginBox, 1000);
    }
}

function StoredContent(id) {
	this.id=id;
	var me=this;
	this.showform=function() {
		if (http.readyState == 4) {
			var cbox=document.getElementById(me.id);
			var formtext = http.responseText;
			cbox.oldz = cbox.style.zIndex;
			cbox.oldc = cbox.className;
			cbox.className = 'editfloat';
			cbox.old = cbox.innerHTML;
			cbox.style.position = 'absolute';
			cbox.style.zIndex = 70;
			grayOut(true);
			cbox.innerHTML = formtext;
		}
	}
	this.showcontent=function() {
		if (http.readyState == 4) {
			var cbox=document.getElementById(me.id);
			cbox.className = "stored";
			cbox.style.position = 'static';
			grayOut(false);
			cbox.style.zIndex = cbox.oldz;
			cbox.innerHTML = http.responseText;
		}
	}
}

function cancelStoredContent(id) {
	var cbox=document.getElementById(id);
	grayOut(false);
	cbox.className = cbox.oldc;
	cbox.innerHTML = cbox.old;
	cbox.style.position = 'static';
	cbox.style.zIndex = cbox.oldz;
}

function cancelNewWeblog () {
	var new_post = document.getElementById('new_post_box');
	new_post.style.display = 'none';
	grayOut(false);
}

function saveStoredContent(id, fobj) {
	var form = fobj.parentNode.parentNode;
	var title = form.title.value;
	var content = form.content.value;
	var tags = form.tags.value;
	var tmpl = form.template.value;
	var filter = form.filter.value;
	//alert('Title: '+title);
	//alert('Content: '+content);
	var scs = new StoredContent(id);
	var url = save_content_url;
	var params = 'content_id=' + encodeURIComponent(id) + '&title=' + encodeURIComponent(title) + '&content=' + encodeURIComponent(content);
	params = params + '&tags=' + encodeURIComponent(tags) + '&template=' + encodeURIComponent(tmpl) + '&filter=' + encodeURIComponent(filter);
	ajaxPost(url, params, scs.showcontent);
	
}

function saveWeblog(fobj, container) {
	var form = fobj.parentNode.parentNode;
	var title = form.title.value;
	var content = form.content.value;
	var tags = form.tags.value;
	var tmpl = form.template.value;
	//alert('Title: '+title);
	//alert('Content: '+content);
	var scs = new WeblogEntry(container);
	var url = save_content_url;
	var params = 'content_id=&title=' + encodeURIComponent(title) + '&content=' + encodeURIComponent(content);
	params = params + '&tags=' + encodeURIComponent(tags) + '&template=' + encodeURIComponent(tmpl);
	ajaxPost(url, params, scs.showcontent);
	
}

function editStoredContent(id) {
	//var cbox=document.getElementById(id);
	esc_id = encodeURIComponent(id);
	var editform = content_form_url + '?id='+esc_id;
	var scf = new StoredContent(id);
	fetch(editform, scf.showform);
}

function WeblogEntry (container) {
	this.id=container;
	var me=this;
	this.showform=function() {
		if (http.readyState == 4) {
			var new_post = document.getElementById('new_post_box');
			if (!new_post) {
				new_post = document.createElement('div');
				new_post.id = 'new_post_box';
				new_post.style.backgroundColor = '#fff';
				var tbody = document.getElementsByTagName("body")[0];
				new_post.style.display = 'none';
				tbody.appendChild(new_post);
			}
			var formtext = http.responseText;
			new_post.className = 'newfloat';
			new_post.style.position = 'absolute';
			new_post.style.zIndex = 70;
			grayOut(true);
			new_post.innerHTML = formtext;
			new_post.style.display = 'block';
			//alert('w: '+new_post.offsetWidth);
			var l = (window.innerWidth - parseInt(new_post.offsetWidth)) / 2;
			var t = (window.innerHeight - parseInt(new_post.offsetHeight)) / 2;
			//alert('L: '+l+ ' T: '+t);
			new_post.style.left = l+'px';
			new_post.style.top = t+'px';
		}
	}
	this.showcontent=function() {
		if (http.readyState == 4) {
			var cbox=document.createElement('div');
			cbox.className = "weblogentry";
			var list = document.getElementById(me.id);
			list.appendChild(cbox);
			grayOut(false);
			var new_post = document.getElementById('new_post_box');
			new_post.style.display = 'none';
			cbox.innerHTML = http.responseText;
		}
	}
}

function newWeblogWithTags (container, tags, tmpl) {
	esc_tags = encodeURIComponent(tags);
	esc_tmpl = encodeURIComponent(tmpl);
	esc_con = encodeURIComponent(container);
	var editform = content_form_url + '?c='+esc_con+'&t='+esc_tmpl+'&tags='+esc_tags;
	var wle = new WeblogEntry(container);
	fetch(editform, wle.showform);
}

function showPhoto (id) {
	var pbox=document.getElementById(id);
	grayOut(true, {'bgcolor': '#ffffff'});
	pbox.style.display = 'block';
	//var l = (window.innerWidth - 500) / 2;
	//var t = (window.innerHeight - 500) / 2;
	pbox.style.position = 'absolute';
	pbox.style.left = '0px';
	pbox.style.top = '0px';
	pbox.style.zIndex = 80;
}

function closePhoto (id) {
	var pbox=document.getElementById(id);
	pbox.style.display = 'none';
	grayOut(false);
}







