var tLift, dropped, progressbarid='';

var sys = { ie: (navigator.appName.indexOf('Microsoft') > -1 ) };

var commentTemplate = '<h5>{name} said...</h5><div>{content}</div><div class="date">{date} | {time}</div>';

function styleActual (o, css){
	obj = gel(o); if (!o) return;
	var strValue = "";
	if( document.defaultView && document.defaultView.getComputedStyle ) strValue = document.defaultView.getComputedStyle(o, "").getPropertyValue(css);
	
	else if(o.currentStyle){
		css = css.replace(/\-(\w)/g, function ( strMatch, p1 ){
			return p1.toUpperCase();
		});
		strValue = o.currentStyle[css];
	}
	return strValue;
}

function gel(id) {
	return document.getElementById(id);
}

function profileToggle() {
	var p = gel('blogProfile');
	var h1 = gel('heading').getElementsByTagName('H1')[0];
	if ( styleActual(p, 'display') == 'block' ) {
		p.style.display = 'none';
		gel('aViewProfile').style.display = 'block';
		h1.className = h1.className.replace('higher');
	} else {
		p.style.display = 'block';
		gel('aViewProfile').style.display = 'none';
		h1.className += ' higher';
	}
}

sysEventResolve = function(e) {
	e = e || window.event;
	e.obj = e.target || e.srcElement;
	e.key = e.which || e.keyCode;
	return e;
}

function checkForEnter(e, f) {
	e = sysEventResolve(e);
	if ( e.key == 13 ) eval(f);
}

var comment = {
	name: '',
	content: ''
	};
function commentPost(c, i) {
	var fullname = gel('fullname');
	var content = gel('comment');
	if ( isEmpty(fullname, 'Please supply your name') ) return;
	if ( isEmpty(content, 'You haven\'t commented yet') ) return;
	comment.name = fullname.value;
	comment.content = content.value;
	xhr('c=' + c + '&fullname=' + fullname.value + '&comment=' + escape(content.value) + '&i=' + i, commentPost_r);
}

function commentDelete(id) {
	var name = gel('cn' + id).value;
	if ( confirm("Are you sure you want to delete the comment by " + name + "?") ) {
		var f = document.getElementById('frmBlog');
		f.action = '?a=commentdelete&id=' + gel('cf' + id).value + '&c=' + gel('cc' + id).value + '&i=' + gel('ci' + id).value;
		f.submit();
	}
}

var sysMonths = ["",
  { name: "January", days: 31 },
  { name: "February", days: 28 },
  { name: "March", days: 31 },
  { name: "April", days: 30 },
  { name: "May", days: 31 },
  { name: "June", days: 30 },
  { name: "July", days: 31 },
  { name: "August", days: 31},
  { name: "September", days: 30},
  { name: "October", days: 31},
  { name: "November", days: 30},
  { name: "December", days: 31}
  ];

function addlink() {
	var szURL = prompt("Enter a URL:", "http://");
    if ((szURL != null) && (szURL != "")) {
		//document.getElementById('edit').contentWindow.document.execCommand("CreateLink",false,szURL);
		var inst, r;
		var e = sysGel('iFrameEditable');
		if ( e.contentDocument ) {
			inst = selectedInstance = e.contentDocument ;
		} else if ( document.frames['iFrameEditable'].document ) {
			inst = selectedInstance = document.frames[editor_id].document;
		}
		
		if (inst) {
			inst.execCommand('CreateLink', false, szURL);
		}
    }
}

function commentPost_r(r) {
	if ( r == '') { // successful save
		var firstComment = gel('comments').getElementsByTagName('DIV')[0];
		var c = document.createElement('DIV');
		c.className = 'item first';
		var chtml = commentTemplate;
		chtml = chtml.replace('{name}', comment.name);
		chtml = chtml.replace('{content}', comment.content);
		var d = new Date();
		chtml = chtml.replace('{date}', d.getDate() + ' ' + sysMonths[d.getMonth()+1].name.substr(0,3) + ' ' + d.getFullYear());
		chtml = chtml.replace('{time}', d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds());
		
		c.innerHTML = chtml;
		
		if ( !firstComment ) { // this is the first comment
			gel('comments').appendChild(c);
		} else {
			firstComment.className = firstComment.className.replace('first', '');
			gel('comments').insertBefore(c, firstComment);
		}
		var ccount = gel('commentCount');
		var count = parseInt(ccount.innerHTML) + 1;
		if ( isNaN(count)) count = 1;
		if ( count == 1 ) {
			ccount.innerHTML = count + ' Comment';
		} else {
			ccount.innerHTML = count + ' Comments';
		}
		gel('frmComment').style.display = 'none';
	} else {
		alert('An error occurred while posting your comment. Wait a few minutes then try again');
	}
}

function commentsToggle(){
	var c = gel('frmComment');
	if ( c.style.display == 'block' ) {
		c.style.display = 'none';
	} else {
		c.style.display = 'block';
	}
}

function isEmpty (o, m) {
	if ( typeof(o) == 'string' ) o = gel(o);
	if ( o.value.replace(/ /g, '') == '' ) {
		alert(m);
		o.focus();
		return true;
	} else {
		return false;
	}
}

function login() {
	document.getElementById('frmBlog').submit();
}

function logout() {
	var f = document.getElementById('frmBlog');
	f.action += '?a=logout';
	f.submit();
}

var selectedElement, selectedInstance;
function execInstanceCommand (editor_id, command) {
	//var inst = tinyMCE.getInstanceById(editor_id), r;
	var inst, r;
	var e = sysGel(editor_id);
	if ( e.contentDocument ) {
		inst = selectedInstance = e.contentDocument ;
	} else if ( document.frames[editor_id].document ) {
		inst = selectedInstance = document.frames[editor_id].document;
	}
	
	if (inst) {
		//r = inst.selection.getRng();

		//if (typeof(focus) == "undefined") focus = true;

		execCommand(command);

		// Cancel event so it doesn't call onbeforeonunlaod
		if (sys.ie && window.event != null) sysEventCancel(window.event);
	}
}

function execCommand (command, user_interface, value) {
	var inst = selectedInstance;

	// Default input
	user_interface = user_interface ? user_interface : false;
	value = value ? value : null;

	//if (inst) inst.switchSettings();

	switch (command) {
		case "Undo":
			if (this.getParam('custom_undo_redo_global')) {
				if (this.undoIndex > 0) {
					tinyMCE.nextUndoRedoAction = 'Undo';
					inst = this.undoLevels[--this.undoIndex];
					inst.select();

					if (!tinyMCE.nextUndoRedoInstanceId)
						inst.execCommand('Undo');
				}
			} else
				inst.execCommand('Undo');
			return true;

		case "Redo":
			if (this.getParam('custom_undo_redo_global')) {
				if (this.undoIndex <= this.undoLevels.length - 1) {
					tinyMCE.nextUndoRedoAction = 'Redo';
					inst = this.undoLevels[this.undoIndex++];
					inst.select();

					if (!tinyMCE.nextUndoRedoInstanceId)
						inst.execCommand('Redo');
				}
			} else
				inst.execCommand('Redo');

			return true;

		case 'mceFocus':
			var inst = tinyMCE.getInstanceById(value);
			if (inst)
				inst.getWin().focus();
		return;

		case "mceAddControl":
		case "mceAddEditor":
			tinyMCE.addMCEControl(tinyMCE._getElementById(value), value);
			return;

		case "mceAddFrameControl":
			tinyMCE.addMCEControl(tinyMCE._getElementById(value['element'], value['document']), value['element'], value['document']);
			return;

		case "mceRemoveControl":
		case "mceRemoveEditor":
			tinyMCE.removeMCEControl(value);
			return;

		case "mceResetDesignMode":
			// Resets the designmode state of the editors in Gecko
			if (!tinyMCE.isIE) {
				for (var n in tinyMCE.instances) {
					if (!tinyMCE.isInstance(tinyMCE.instances[n]))
						continue;

					try {
						tinyMCE.instances[n].getDoc().designMode = "on";
					} catch (e) {
						// Ignore any errors
					}
				}
			}

			return;
	}

	if (inst) {
		inst.execCommand(command, user_interface, value);
	} else if (tinyMCE.settings['focus_alert'])
		alert(tinyMCELang['lang_focus_alert']);
}

function popup(url, title) {
	window.open(url, title, "menubar=no, width=440, height=100, address=no, resizable=yes");	
}

function photoadd(url) {
	var p = gel('photolist');
	var img = document.createElement('IMG');
	img.src = '../img/uploads/' + url;
	p.innerHTML = p.innerHTML.replace('<div>No images available.</div>', '');
	p.insertBefore(img, p.childNodes[0]);
}

function eventResolve (e) {
	e = e || window.event;
	e.obj = e.target || e.srcElement;
	e.key = e.which || e.keyCode;
	return e;
}

function canUploadStory() {
	if ( isEmpty('fullname', 'Please tell us your name') ) return false;
	if ( isEmpty('suggestion', 'You haven\'t told us your suggestion') ) return false;
	return true;
}

function canSubscribe() {
	if ( isEmpty('fullname', 'Please tell us your name') ) return false;
	if ( isEmpty('email', 'Please supply your email address') ) return false;
	return true;
}

function canType(e, limit) {
	e = eventResolve(e);
	
	// only include these keys: 32, 48 - 90, 106 - 111, 188 - 191, 219 - 221
	if ( e.key == 32 || ( e.key >= 48 && e.key <= 90 ) || ( e.key >= 106 && e.key <= 111 ) || ( e.key >= 188 && e.key <= 191 ) || ( e.key >= 219 && e.key <=221 ) ) {
		if ( ( e.obj.value.length + 1 ) > limit ) return false;
	}
	
}

function drop(o) {
	clearTimeout(tLift);
	if ( dropped ) doLift(o.parentNode);
	
	if ( o.parentNode.id.indexOf('sub') == -1 ) {
		dropped = gel(o.parentNode.id + 'sub');
		if (dropped) dropped.style.display = 'block';
	}
}

function doLift() {
	var o = arguments[0];
	if (o) {
		if ( o == dropped ) return;
	}
	if ( dropped ) dropped.style.display = 'none';
}

function lift() {
	tLift = setTimeout(doLift, 300);
}

var tabCurrent = 1;
function tabShow(o) {
	var id = o.id.replace('Button', '');
	gel('tab' + tabCurrent).style.display = 'none';
	tabCurrent = id.replace('tab', '');
	o.parentNode.className = 'hot' + tabCurrent;
	gel(id).style.display = 'block';
}

function toggleRegion(o) {
	var idx = o.id.replace(/[a-z]/gi, '');
	var c = gel('rd' + idx);
	if ( styleActual(c, 'display') == 'block' ) {
		c.style.display = 'none';
	} else {
		c.style.display = 'block';
	}
}

var timerShare;
function initToggleShare() {
	clearTimeout(timerShare);
	timerShare = setTimeout(toggleShare, 500);
}

function canTimerShare() { clearTimeout(timerShare); }

function toggleShare() {
	clearTimeout(timerShare);
	var a = gel('ql4');
	var s = gel('share');
	if ( styleActual(a, 'display') == 'block') {
		a.style.display = 'none';
		s.style.display = 'block';
	} else {
		a.style.display = 'block';
		s.style.display = 'none';
	}
}

function hideLoading() {
	gel('loading').style.visibility = 'hidden';
}

function frameResize(o) {
	var h;
	if ( sys.ie ) {
		h = o.document.body.scrollHeight + 100;
	} else {
		h = o.contentWindow.document.body.scrollHeight + 50;
	}
	o.style.height = ( h ) + 'px';
}

function subscribeComplete() {
	gel('pIntro').innerHTML = 'Congratulations, your request has been received. Keep a look out for a confirmation email from ANCToday.';
}

var scroller = {
	canscroll: false,
	direction: 0,
	div: null,
	limitleft: 0,
	limitright: 0,
	newleft: 0,
	scrollby: 10, // amount of pixels to scroll by
	scrollinterval: 33,
	timer: null
}

function scrollSetup(d) {
	with ( scroller ) {
		direction = d;
		div = gel("scroller");
		limitleft = 0;
		limitright = 0 - div.offsetWidth + gel("scrollThumbs").offsetWidth;
		canscroll = true;
		timer = setTimeout(scrollRun, scroller.scrollinterval);
	}
}

function scrollRun() {
	scroller.newleft = scroller.div.offsetLeft + scroller.scrollby * scroller.direction;
	
	if ( scroller.newleft > 0 ) {
		scroller.newleft = 0;
		scroller.canscroll = false;
	}
	if ( scroller.newleft < ( scroller.limitright ) ) {
		scroller.newleft = scroller.limitright;
		scroller.canscroll = false;
	}
	scroller.div.style.left = scroller.newleft + 'px';
	if ( !scroller.canscroll) return;
	scroller.timer = setTimeout(scrollRun, scroller.scrollinterval);
}

function scrollStop() {
	scroller.canscroll = false;
}