var	dir_pages					= 'pages';
var login_password				= '';
var login_password_hash			= 'ecb3ca75175279fd3160ce96866a5e52';
var login_param_hash			= '21232f297a57a5a743894a0e4a801fc3';
var login_message				= '<b>moderator</b>&nbsp;&nbsp;|&nbsp;&nbsp;';
var post_template 				= '<div class="post" id="{id}_post"><div id="{id}" class="{post}"{onclick}>{message}</div><a class="post_mail" id="{id}_mail" href="{mail}"></a><div class="post_signature"><b>{name}</b><br/>{timestamp}</div></div>';
var page_next					= '<a style="padding: 8px; float: right;" onclick="nextCommentsPage();">next &raquo;</a>';
var page_prev					= '<a style="padding: 8px; float: left;" onclick="prevCommentsPage();">&laquo; previous</a>';
var comments_dateformat			= 'F j, Y';
var messages_page				= 0;
var messages_page_max			= 0;
var param						= String(document.location).substring(String(document.location).indexOf('?')+1);
var	timeout						= null;

//------------------------------------------------------------------------------

get	=	function(id) {
	return document.getElementById(id);	
}

//------------------------------------------------------------------------------

checkComment = function() {
	var name	= get('input_name').value.trim();
	var message	= get('input_message').value.trim();
	var	ready	= false;
	
	get('error_name').style.visibility = "hidden";
	get('error_message').style.visibility = "hidden";
	
	if(name.length > 0 && message.length > 0) {
		ready	= true;
	} else {
		if(message.length < 1) {
			get('error_message').style.visibility = "visible";
			get('input_message').focus();
		}
		if(name.length < 1) {
			get('error_name').style.visibility = "visible";
			get('input_name').focus();
		}
	}
	return ready;
}

function sendComment() {
	if(checkComment()) {
		var name	= get('input_name').value.trim();
		var message	= get('input_message').value.trim();
		var forward	= get('input_forward').checked ? 'yes' : 'no';
		load(encodeURI('modules/display.comments.php?name='+name+'&message='+message+'&forward='+forward+'&page='+messages_page+(isModerator() ? '' : '&filter=approved')+'&sid='+randomSessid()),'displayComments');
		get('input_message').value	= '';
		alert('Thank you, your message has been submitted.');
	}
}

function loadComments(page) {
	messages_page	= page;
	messages_page 	= Math.min(messages_page,messages_page_max);
	load(encodeURI('modules/display.comments.php?page='+messages_page+(isModerator() ? '' : '&filter=approved')+'&sid='+randomSessid()),'displayComments');
}
function nextCommentsPage() {
	loadComments(messages_page+1);
}
function prevCommentsPage() {
	loadComments(Math.max(messages_page-1,0));
}

function displayComments(data) {
	eval("var packets	=	"+unescape(data));
	processed						=	processComments(packets);
	get('tabs').style.display 		= 	'block';
	get('content').className		=	'content content_messages';
	get('tabs').innerHTML			=	getTabs();
	get('content').innerHTML		=	processed['messages'];
	if(isModerator()) {
		for(post in processed['properties']) {
			post_mail		= post+'_mail';
			if(get(post)) {
				get(post).isApproved	= 	processed['properties'][post]['isApproved'];
				get(post).isForward		= 	processed['properties'][post]['isForward'];
				get(post).postName		= 	processed['properties'][post]['name'];
				get(post).postMessage	= 	processed['properties'][post]['message']; 
				if(get(post).isApproved) {
					get(post).className	= get(post).className+' post_content_approved';
				}
				if(get(post).isForward) {
					get(post_mail).style.visibility = "visible";
				} else {
					get(post_mail).style.visibility = "hidden";
				}
			}
		}
	}
}

function processComments(data) {
	var output		=	new Array();
	var	comments	=	new Array();
	var properties	=	new Array();
    for(index in data) {
		var	entry			= data[index];
		
		if(index == 'last') {
			messages_page_max	= entry;
			var comment = '';
			if(messages_page > 0) {
				comment = comment+page_prev;
			}
			if(messages_page < messages_page_max) {
				comment = comment+page_next;
			}
			comments[comments.length]	=	comment;
			
		} else {
			
			properties[index]	= new Array();
			properties[index]['isApproved']	= isApproved(entry['status']);
			properties[index]['isForward']	= isForward(entry['forward']);
			
			if(isApproved(entry['status']) || isModerator()) {
				var	comment	=	post_template;
			} else {
				var	comment	=	'';
			}
			
			for(field in entry) {
				var	value		=	entry[field];
				if(field == 'timestamp') {
					var date	=	new Date(value*1000);
					value		=	date.formatDate(comments_dateformat);
				}
				comment						= comment.replace('{'+field+'}',value);
				properties[index][field]	= value;
			}
			comment		= comment.replaceAll('{id}',index);
			comment		= comment.replace('{post}',isModerator() ? 'post_content post_content_active' : 'post_content');
			comment		= comment.replace('{onclick}',isModerator() ? 'onclick="toggleStatus(this.id);"' : '');
			comment		= comment.replace('{mail}',(isModerator() && isForward(entry['forward'])) ? mailLink(entry['name'],entry['message']) : '');
			comments[comments.length]		=	comment;
		}
	}
	output['messages']		=	comments.join('');
	output['properties']	=	properties;
    return	output; //comments.reverse().join('');
}

function toggleStatus(post) {
	var status			= 'approved';
	if(get(post).isApproved) {
		status					= 'pending';
		get(post).isApproved	= false;
		get(post).className		= get(post).className.replace(' post_content_approved','');
	} else {
		status					= 'approved';
		get(post).isApproved	= true;
		get(post).className		= get(post).className+' post_content_approved';
	}
	load(encodeURI('modules/display.comments.php?id='+post+'&status='+status+'&page='+messages_page+(isModerator() ? '' : '&filter=approved')+'&sid='+randomSessid()),'displayComments');
}

function isApproved(status) {
	return status.indexOf('approved') > -1;	
}

function isForward(forward) {
	return forward.indexOf('yes') > -1;	
}

function mailLink(name,message) {
	var mail_body	= mail_template;
	mail_body	= mail_body.replaceAll('{name}',name.trim());
	mail_body	= mail_body.replace('{message}',message.trim());
	return encodeURI('mailto:'+mail_recipient+'?subject='+mail_subject+'&body='+mail_body);
}

function getTabs() {
	var tab_spacer		= '<div class="tab_spacer"></div>';
	var tab_active		= '<span class="tab" style="left: {left}px;">{label}</span>';
	var tab_navigation 	= '<span class="tab" style="left: {left}px;" onclick="loadComments({page});">{label}</span>';
	var tab_inactive 	= '<span class="tab tab_inactive" style="left: {left}px;" onclick="loadComments({page});">{label}</span>';
	var tab_disabled 	= '<span class="tab tab_disabled" style="left: {left}px;" onclick="loadComments({page});">{label}</span>';
	var tabs			= '';//tab_spacer;
	var tab				= '';
	for(i = 0; i <= messages_page_max; i++) {
		tab				= (i == messages_page ? tab_active : tab_inactive);
		tab				= tab.replace('{label}',i+1);
		tab				= tab.replace('{left}',i*30+6);
		tab				= tab.replace('{page}',i);
		tabs			+= tab;
	}
	tab				= (messages_page > 0 ? tab_navigation : tab_disabled);
	tab				= tab.replace('{label}','&laquo;');
	tab				= tab.replace('{left}',i*30+6);
	tab				= tab.replace('loadComments({page})','prevCommentsPage()');
	tabs			+= tab;
	i++;
	tab				= (messages_page < messages_page_max ? tab_navigation : tab_disabled);
	tab				= tab.replace('{label}','&raquo;');
	tab				= tab.replace('{left}',i*30+6);
	tab				= tab.replace('loadComments({page})','nextCommentsPage()');
	tabs			+= tab;
	return	tabs;
	
}


//------------------------------------------------------------------------------

function loadPage(id) {
	get('tabs').style.display 	= 'none';
	get('content').className	= 'content';
	load(dir_pages+'/'+id+'.txt?'+randomSessid(),'displayPage');
}

function displayPage(data) {
	page	= unescape(data);
	if(page.indexOf('<html>') == -1) page = page.nl2br();
	get('content').innerHTML = '<div class="text">'+page+'</div>';
}

//------------------------------------------------------------------------------

function login() {
	login_password = get('input_password').value.trim();
	if(isModerator()) {
		get('message').innerHTML = login_message+'you are logged in as a <b>moderator</b>.';
		loadComments(0);
	} else {
		get('message').innerHTML = login_message+'login failed.';
	}
}

function isModerator() {
	return hex_md5(login_password) == login_password_hash;
}

function showLogin() {
	get('message').innerHTML = login_message+'password:&nbsp;<input class="input_password" id="input_password" alt="name" type="password" size="12" maxlength="12"></input>&nbsp;&raquo;&nbsp;<span class="link_system" onmouseover="this.className = \'link_system_over\';" onmouseout="this.className = \'link_system\';" onclick="login();">go</span>';
	get('message').style.display = 'block';	
}


/* XMLHTTP ------------------------------------------------------------------*/

var xmlhttp	=	false;

function initXMLHTTP() {
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try {
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
	} catch (e) {
		try {
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
		} catch (E) {
			xmlhttp=false
		}
	}
	@else
		xmlhttp=false
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp	=	new XMLHttpRequest();
		} catch (e) {
			xmlhttp	=	false;
	 	}
	}
}

function resetXMLHTTP() {
	xmlhttp	=	false;
	initXMLHTTP();
}

function load(url,target) {
	timeout = window.setTimeout("setLoading();",250);
	resetXMLHTTP();
	if(xmlhttp && url.length > 0 && target.length > 0) {
		xmlhttp.open("GET", url, true);
		xmlhttp.onreadystatechange	=	function() {
			if (xmlhttp.readyState == 4) {
				window.clearTimeout(timeout);
				eval(target+"('"+escape(xmlhttp.responseText)+"')");
			}
		}
		xmlhttp.send(null);
	}
}

function setLoading() {
	/*if(!isModerator())	*/	get('content').innerHTML	=	'<div class="loading"><center><div class="loading_icon"></div><span>&nbsp;loading...</span></center></div>';
}
	

//--------------------------------------------------------------------------

String.prototype.trim	=		function(string) {
	return (this != window ? this : string).replace(/^\s+/g, '').replace(/\s+$/g, '');
};
String.prototype.nl2br	=	function(string) {
	string		=	this != window ? this : string;
	from		=	'\n';
	to			=	'<br>';
	index		=	string.indexOf(from);
    while (index>-1) {      
        string	=	string.replace(from,to);
        index	=	string.indexOf(from);
    }
    return string;
}
String.prototype.replaceAll = function(strTarget,strSubString){
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
	while (intIndexOfMatch != -1){
		strText = strText.replace( strTarget, strSubString )
		intIndexOfMatch = strText.indexOf( strTarget );
	}
	return( strText );
}
function randomSessid() {
	return	Math.round(Math.pow(10,5)+Math.random()*Math.pow(10,6));
}

//----------------------------------------------------------------------

function init() {
	window.onresize	=	function() {
		setMainWidth();
	}
	if(hex_md5(param) == login_param_hash) {
		showLogin();
	}
	setMainWidth();
	externalLinks();
	loadPage('intro');
}
function setMainWidth() {
	document.getElementById('main').style.width	=	(parseInt(window.innerWidth ? window.innerWidth : document.body.offsetWidth)-20)+'px';
}
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
		    anchor.getAttribute("rel") == "external")
				anchor.target = "_blank";
	}
}

//----------------------------------------------------------------------

Array.prototype.exists = function (x) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == x) return true;
    }
    return false;
}

Date.prototype.formatDate = function (input,time) {
    // formatDate :
    // a PHP date like function, for formatting date strings
    // See: http://www.php.net/date
    //
    // input : format string
    // time : epoch time (seconds, and optional)
    //
    // if time is not passed, formatting is based on 
    // the current "this" date object's set time.
    //
    // supported:
    // a, A, B, d, D, F, g, G, h, H, i, j, l (lowercase L), L, 
    // m, M, n, O, r, s, S, t, U, w, W, y, Y, z
    //
    // unsupported:
    // I (capital i), T, Z    

    var switches =    ["a", "A", "B", "d", "D", "F", "g", "G", "h", "H", 
                       "i", "j", "l", "L", "m", "M", "n", "O", "r", "s", 
                       "S", "t", "U", "w", "W", "y", "Y", "z"];
    var daysLong =    ["Sunday", "Monday", "Tuesday", "Wednesday", 
                       "Thursday", "Friday", "Saturday"];
    var daysShort =   ["Sun", "Mon", "Tue", "Wed", 
                       "Thu", "Fri", "Sat"];
    var monthsShort = ["Jan", "Feb", "Mar", "Apr",
                       "May", "Jun", "Jul", "Aug", "Sep",
                       "Oct", "Nov", "Dec"];
    var monthsLong =  ["January", "February", "March", "April",
                       "May", "June", "July", "August", "September",
                       "October", "November", "December"];
    var daysSuffix = ["st", "nd", "rd", "th", "th", "th", "th", // 1st - 7th
                      "th", "th", "th", "th", "th", "th", "th", // 8th - 14th
                      "th", "th", "th", "th", "th", "th", "st", // 15th - 21st
                      "nd", "rd", "th", "th", "th", "th", "th", // 22nd - 28th
                      "th", "th", "st"];                        // 29th - 31st

    function a() {
        // Lowercase Ante meridiem and Post meridiem
        return self.getHours() > 11? "pm" : "am";
    }
    function A() {
        // Uppercase Ante meridiem and Post meridiem
        return self.getHours() > 11? "PM" : "AM";
    }

    function B(){
        // Swatch internet time. code simply grabbed from ppk,
        // since I was feeling lazy:
        // http://www.xs4all.nl/~ppk/js/beat.html
        var off = (self.getTimezoneOffset() + 60)*60;
        var theSeconds = (self.getHours() * 3600) + 
                         (self.getMinutes() * 60) + 
                          self.getSeconds() + off;
        var beat = Math.floor(theSeconds/86.4);
        if (beat > 1000) beat -= 1000;
        if (beat < 0) beat += 1000;
        if ((""+beat).length == 1) beat = "00"+beat;
        if ((""+beat).length == 2) beat = "0"+beat;
        return beat;
    }
    
    function d() {
        // Day of the month, 2 digits with leading zeros
        return new String(self.getDate()).length == 1?
        "0"+self.getDate() : self.getDate();
    }
    function D() {
        // A textual representation of a day, three letters
        return daysShort[self.getDay()];
    }
    function F() {
        // A full textual representation of a month
        return monthsLong[self.getMonth()];
    }
    function g() {
        // 12-hour format of an hour without leading zeros
        return self.getHours() > 12? self.getHours()-12 : self.getHours();
    }
    function G() {
        // 24-hour format of an hour without leading zeros
        return self.getHours();
    }
    function h() {
        // 12-hour format of an hour with leading zeros
        if (self.getHours() > 12) {
          var s = new String(self.getHours()-12);
          return s.length == 1?
          "0"+ (self.getHours()-12) : self.getHours()-12;
        } else { 
          var s = new String(self.getHours());
          return s.length == 1?
          "0"+self.getHours() : self.getHours();
        }  
    }
    function H() {
        // 24-hour format of an hour with leading zeros
        return new String(self.getHours()).length == 1?
        "0"+self.getHours() : self.getHours();
    }
    function i() {
        // Minutes with leading zeros
        return new String(self.getMinutes()).length == 1? 
        "0"+self.getMinutes() : self.getMinutes(); 
    }
    function j() {
        // Day of the month without leading zeros
        return self.getDate();
    }    
    function l() {
        // A full textual representation of the day of the week
        return daysLong[self.getDay()];
    }
    function L() {
        // leap year or not. 1 if leap year, 0 if not.
        // the logic should match iso's 8601 standard.
        var y_ = Y();
        if (         
            (y_ % 4 == 0 && y_ % 100 != 0) ||
            (y_ % 4 == 0 && y_ % 100 == 0 && y_ % 400 == 0)
            ) {
            return 1;
        } else {
            return 0;
        }
    }
    function m() {
        // Numeric representation of a month, with leading zeros
        return self.getMonth() < 9?
        "0"+(self.getMonth()+1) : 
        self.getMonth()+1;
    }
    function M() {
        // A short textual representation of a month, three letters
        return monthsShort[self.getMonth()];
    }
    function n() {
        // Numeric representation of a month, without leading zeros
        return self.getMonth()+1;
    }
    function O() {
        // Difference to Greenwich time (GMT) in hours
        var os = Math.abs(self.getTimezoneOffset());
        var h = ""+Math.floor(os/60);
        var m = ""+(os%60);
        h.length == 1? h = "0"+h:1;
        m.length == 1? m = "0"+m:1;
        return self.getTimezoneOffset() < 0 ? "+"+h+m : "-"+h+m;
    }
    function r() {
        // RFC 822 formatted date
        var r; // result
        //  Thu    ,     21          Dec         2000
        r = D() + ", " + j() + " " + M() + " " + Y() +
        //        16     :    01     :    07          +0200
            " " + H() + ":" + i() + ":" + s() + " " + O();
        return r;
    }
    function S() {
        // English ordinal suffix for the day of the month, 2 characters
        return daysSuffix[self.getDate()-1];
    }
    function s() {
        // Seconds, with leading zeros
        return new String(self.getSeconds()).length == 1?
        "0"+self.getSeconds() : self.getSeconds();
    }
    function t() {

        // thanks to Matt Bannon for some much needed code-fixes here!
        var daysinmonths = [null,31,28,31,30,31,30,31,31,30,31,30,31];
        if (L()==1 && n()==2) return 29; // leap day
        return daysinmonths[n()];
    }
    function U() {
        // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
        return Math.round(self.getTime()/1000);
    }
    function W() {
        // Weeknumber, as per ISO specification:
        // http://www.cl.cam.ac.uk/~mgk25/iso-time.html
        
        // if the day is three days before newyears eve,
        // there's a chance it's "week 1" of next year.
        // here we check for that.
        var beforeNY = 364+L() - z();
        var afterNY  = z();
        var weekday = w()!=0?w()-1:6; // makes sunday (0), into 6.
        if (beforeNY <= 2 && weekday <= 2-beforeNY) {
            return 1;
        }
        // similarly, if the day is within threedays of newyears
        // there's a chance it belongs in the old year.
        var ny = new Date("January 1 " + Y() + " 00:00:00");
        var nyDay = ny.getDay()!=0?ny.getDay()-1:6;
        if (
            (afterNY <= 2) && 
            (nyDay >=4)  && 
            (afterNY >= (6-nyDay))
            ) {
            // Since I'm not sure we can just always return 53,
            // i call the function here again, using the last day
            // of the previous year, as the date, and then just
            // return that week.
            var prevNY = new Date("December 31 " + (Y()-1) + " 00:00:00");
            return prevNY.formatDate("W");
        }
        
        // week 1, is the week that has the first thursday in it.
        // note that this value is not zero index.
        if (nyDay <= 3) {
            // first day of the year fell on a thursday, or earlier.
            return 1 + Math.floor( ( z() + nyDay ) / 7 );
        } else {
            // first day of the year fell on a friday, or later.
            return 1 + Math.floor( ( z() - ( 7 - nyDay ) ) / 7 );
        }
    }
    function w() {
        // Numeric representation of the day of the week
        return self.getDay();
    }
    
    function Y() {
        // A full numeric representation of a year, 4 digits

        // we first check, if getFullYear is supported. if it
        // is, we just use that. ppks code is nice, but wont
        // work with dates outside 1900-2038, or something like that
        if (self.getFullYear) {
            var newDate = new Date("January 1 2001 00:00:00 +0000");
            var x = newDate .getFullYear();
            if (x == 2001) {              
                // i trust the method now
                return self.getFullYear();
            }
        }
        // else, do this:
        // codes thanks to ppk:
        // http://www.xs4all.nl/~ppk/js/introdate.html
        var x = self.getYear();
        var y = x % 100;
        y += (y < 38) ? 2000 : 1900;
        return y;
    }
    function y() {
        // A two-digit representation of a year
        var y = Y()+"";
        return y.substring(y.length-2,y.length);
    }
    function z() {
        // The day of the year, zero indexed! 0 through 366
        var t = new Date("January 1 " + Y() + " 00:00:00");
        var diff = self.getTime() - t.getTime();
        return Math.floor(diff/1000/60/60/24);
    }
        
    var self = this;
    if (time) {
        // save time
        var prevTime = self.getTime();
        self.setTime(time);
    }
    
    var ia = input.split("");
    var ij = 0;
    while (ia[ij]) {
        if (ia[ij] == "\\") {
            // this is our way of allowing users to escape stuff
            ia.splice(ij,1);
        } else {
            if (switches.exists(ia[ij])) {
                ia[ij] = eval(ia[ij] + "()");
            }
        }
        ij++;
    }
    // reset time, back to what it was
    if (prevTime) {
        self.setTime(prevTime);
    }
    return ia.join("");
 }
