function el(id) { return document.getElementById(id); }
function cT(text) { return document.createTextNode(text); }
function cE(el) { return document.createElement(el); }

if(!Array.indexOf){
	Array.prototype.indexOf = function(obj){
		for(var i=0; i<this.length; i++){
			if(this[i]==obj){
				return i;
			}
		}
		return -1;
	}
}

function datetimeFormat(isodate) {
	return isodate.substr(0, 16);
}

function openComments(oid, isImage) {
	if (el('pselect')) el('pselect').style.display = 'none'; // IE displays drop-down menu on top of comment form. Solution: hide drop-down menu.
	el('curtain').style.display = 'block';
	var elCommenter = el('commenter');
	el('comments').innerHTML = '';
	var para = el('commented_paragraph');
	if (isImage) {
		para.innerHTML = '<div style="text-align: center;"><img src="thumbs/'+oid+'"></div>';
	} else {
		para.innerHTML = el(oid).innerHTML;
	}
	el('comment_otype').value = !isImage?'paragraph':'image';
	el('comment_oid').value = oid;
	elCommenter.style.display = 'block';
	displayComments(oid, isImage);
	return false;
}

function displayComments(oid, isImage) {
	if (!comments[oid]) { return; };
	var commentsDiv = el('comments');
	//for (var i = 0; i < comments[oid].length; i++) {
	for (i in comments[oid]) {
		var commentDiv = cE('div');
		commentDiv.className = 'comment';
		commentDiv.innerHTML = '<div class="comment_meta"><b>' + comments[oid][i].author + '</b> ' + ((comments[oid][i].contact)?'[<a href="' + comments[oid][i].contact + '" target="_blank">URL</a>] ':'') + 'said on ' + datetimeFormat(comments[oid][i].datetime) + ' ' + comments[oid][i].timezone + ':</div><blockquote>' + comments[oid][i].comment + '</blockquote>';
		commentsDiv.appendChild(commentDiv);
	}
}

var cc = false;

function commenterClick() {
	cc = true;
}

function closeComments() {
	if (!cc) {
		el('commenter').style.display = 'none';
		el('curtain').style.display = 'none';
		if (el('pselect')) el('pselect').style.display = 'block'; // IE displays drop-down menu on top of comment form. Solution: hide drop-down menu.

	}
	cc = false;
}

var seed;
var tmpComment;

function getSeed(mode) {
	if (mode == 0) {
		jsonLoader('comments.php', 'getseed', null, getSeed);
	} else {
		seed = mode.seed;
		processComment(1);
	}
}

function getEscapedValue(elem) {
	return encodeURIComponent(el(elem).value);
}

function postProcessComment(response) {
	if (response.retval == true) {
		for (var e in tmpComment) {
			tmpComment[e] = decodeURIComponent(tmpComment[e]);
		}
		tmpComment.id = response.id;
		tmpComment.datetime = response.datetime;
		if (!comments[tmpComment.id_object]) {
			comments[tmpComment.id_object] = [];
		}
		comments[tmpComment.id_object].push(tmpComment);
		var pid = tmpComment.id_object;
		var i = comments[tmpComment.id_object].length - 1;
		var commentsDiv = el('comments');
		var commentDiv = cE('div');
		commentDiv.className = 'comment';
		if (comments[pid][i].author_url != '' && comments[pid][i].author_url.substr(0, 7) != 'http://') {
			comments[pid][i].author_url = 'http://' + comments[pid][i].author_url;
		}
		comments[pid][i].comment = comments[pid][i].comment.replace(/\n/g , "<br>");
		
		commentDiv.innerHTML = '<div class="comment_meta"><b>' + comments[pid][i].author + '</b> ' + ((comments[pid][i].author_url)?'[<a href="' + comments[pid][i].contact + '" target="_blank">URL</a>] ':'') + 'said on ' + datetimeFormat(comments[pid][i].datetime) + ' ' + comments[pid][i].timezone + ':</div><blockquote>' + comments[pid][i].comment + '</blockquote>';
		commentsDiv.appendChild(commentDiv);
		if (tmpComment.id_object == 'guestbook') {
			alert('Thank you for your comment!');
		}
		clearCommentForm();
	} else {
		alert('Oh no, something went wrong!\n' + response.retval);
	}
}

function clearCommentForm() {
	var inputs = el('comment_input_table').getElementsByTagName('input');
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type != 'submit') {
			inputs[i].value = '';
		}
	}
	el('comment_comment').value = '';
}

function processComment(mode) {
	if (mode != 1) {
		getSeed(0);
		return;
	}
	var otype = el('comment_otype').value;
	var oid = el('comment_oid').value;
	var in_reply_to = el('comment_in_reply_to').value;
	var author = getEscapedValue('comment_author');
	var author_email = getEscapedValue('comment_author_email');
	var author_url = getEscapedValue('comment_author_url');
	var timezone = encodeURIComponent(new Date().toString().substr(-5, 5));
	var in_reply_to = getEscapedValue('comment_in_reply_to');
	var comment = getEscapedValue('comment_comment');

	var stringtoencode = seed + author + comment;
	debug(stringtoencode);
	var checksum = hex_md5(stringtoencode);
	if (author == '' || comment == '') {
		alert('Please enter your name and a comment!');
		return;
	}
	var newcomment = {
		objecttype:otype,
		id_object:oid,
		in_reply_to:in_reply_to,
		author: author,
		author_email: author_email,
		author_url: author_url,
		timezone:timezone,
		comment: comment,
		checksum: checksum
	}
	tmpComment = newcomment;
	jsonLoader('comments.php', 'save', newcomment, postProcessComment);
}

var imageFilename, videoFilename;

function showImage(imageF, obj) {
	imageFilename = imageF;
	if (el('pselect')) el('pselect').style.display = 'none'; // IE displays drop-down menu on top of image. Solution: hide drop-down menu.
	var elImage = el('image');
	var elCaption = el('imagecaption');
	elCaption.innerHTML = '';
	elImage.src = 'uiimages/transblack50.png';
	el('imagecurtain').style.display = 'block';
	var elImageViewer = el('imageviewer');
	makeDraggable(elImage);
	// var w = elImageViewer.clientWidth;
	elImage.src = 'images/'+imageFilename;
	el('image').removeAttribute('width');
	el('image').removeAttribute('height');
	resizeImage(autoResize);
	var caption = obj.parentNode.lastChild.innerHTML;
	if (caption != null) {
		elCaption.innerHTML = caption;
	}
	el('imagecommentcount').innerHTML = (comments[imageF]?comments[imageF].length:"");
	return false;
}

function getImageId() {
	return imageFilename;
}

function getVideoId() {
	return videoFilename;
}

function closeImage() {
	if (!cc) {
		// el('imageviewer').style.display = 'none';
		el('imagecurtain').style.display = 'none';
		el('videocurtain').style.display = 'none';
		if (el('pselect')) el('pselect').style.display = 'block';// IE displays drop-down menu on top of image. Solution: hide drop-down menu. Here we re-show.
	}
	cc = false;
}

var autoResize = false;
function resizeImage(mode) {
	if (!mode) {
		el('image').removeAttribute('width');
		el('image').removeAttribute('height');
		autoResize = false;
	} else {
		var elImage = el('image');
		var container = elImage.parentNode;
		var widthReduction = elImage.clientWidth/container.clientWidth;
		var targetHeight = elImage.clientHeight/widthReduction;
		if (targetHeight > container.clientHeight) {
			elImage.setAttribute('height', container.parentNode.clientHeight);
		} else {
			elImage.setAttribute('width', container.parentNode.clientWidth);
		}
		autoResize = true;
	}
}

var aviHandlers = -1;
var instPlugins = {};
function determinePluginCapabilities() {
	var prefmimetype = "application/x-mplayer2";
	var numPlugins = navigator.plugins.length;
	var pluginfound = false, plugin, mimetype;
	aviHandlers = [];

	navigator.plugins.refresh(false);
	if (numPlugins > 0) {
		for (var i = 0; i < numPlugins; i++) {
			plugin = navigator.plugins[i];
			instPlugins[plugin.name] = 1;
			for (var j = 0; j < plugin.length; j++) { // Iterate through MIME-Types
				mimetype = plugin[j];
				if (mimetype.type == prefmimetype) {
					// We've found it.
					pluginfound = true;
					if (mimetype.enabledPlugin) {
						pluginname = plugin.name;
						if (pluginname.indexOf("VLC") != -1) {
							aviHandlers[aviHandlers.length] = "vlc";
						}
						if (pluginname.indexOf("Windows Media") != -1) {
							aviHandlers[aviHandlers.length] = "wmp";
						}
					}
				}
			}
		}
	}
}

function togglePlay() {
	var player = el('videoplayer');
	if (player.isplaying()) {
		player.pause();
		el('playbutton_image').src = 'uiimages/play.png';
	} else {
		player.play();
		el('playbutton_image').src = 'uiimages/pause.png';
	}
}


function toggleFullScreen(really) {
	if (really == 'yes') {
		el('video_fullscreenwarning').style.display = 'none';
		if (el('videoplayer').isplaying()) {
			el('videoplayer').fullscreen();
		}
	} else {
		el('video_fullscreenwarning').style.display = 'block';
		window.setTimeout("toggleFullScreen('yes')", 1500);
	}
}

function showVideo(videoF, obj) {
	videoFilename = videoF;
	if (el('pselect')) el('pselect').style.display = 'none'; // IE displays drop-down menu on top of video. Solution: hide drop-down menu.
	var elVideoContainer = el('videocontainer');
	var elCaption = el('videocaption');
	elVideoContainer.innerHTML = '';
	elCaption.innerHTML = '';
	el('videocurtain').style.display = 'block';

	if (aviHandlers == -1) {
		determinePluginCapabilities();
	}

	// var width = 640; height = 480;
	var width = 320; height = 240;

	if (aviHandlers.indexOf('wmp') == -1) {
		var videoHTML = '<embed type="application/x-vlc-plugin" id="videoplayer" name="videoplayer" src="videos/' + videoF + '" name="mediaplayer" style="width: ' + width + 'px; height: ' + height + 'px;" transparentatstart="0" autostart="1" animationatstart="0" showcontrols="1" autosize="0" displaysize="0" showstatusbar="1"></embed>';
		elVideoContainer.innerHTML = videoHTML;
		var videoController = cE('div');
		videoController.id = 'vlccontrol';

		var playButton = cE('div');
		playButton.className = 'button';
		playButton.id = 'playbutton';
		playButton.addEventListener('click', togglePlay, true);
		playButton.innerHTML = '<img id="playbutton_image" src="uiimages/pause.png">';
		videoController.appendChild(playButton);

		var fsButton = cE('div');
		fsButton.className = 'button';
		fsButton.id = 'fsbutton';
		fsButton.addEventListener('click', toggleFullScreen, true);
		fsButton.innerHTML = '<img id="fsbutton_image" src="uiimages/fs.png">';
		videoController.appendChild(fsButton);

		var fsWarnBox = cE('div');
		fsWarnBox.style.display = 'none';
		fsWarnBox.id = 'video_fullscreenwarning';
		fsWarnBox.innerHTML = 'Double click the video to exit full-screen view';
		videoController.appendChild(fsWarnBox);

		/*var timeBox = cE('div');
		timeBox.innerHTML = '<span id="video_timesofar">?</span>/<span id="video_timetotal">?</span>';
		videoController.appendChild(timeBox);*/

		elVideoContainer.appendChild(videoController);
	} else {
		var videoHTML = '<object style="width: ' + width + 'px; height: ' + (height+72) + 'px;" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." type="application/x-oleobject">'
		videoHTML += '<param name="filename" value="asxgen.php?v=' + videoF + '">'
		videoHTML += '<param name="transparentatstart" value="true">'
		videoHTML += '<param name="autostart" value="true">'
		videoHTML += '<param name="animationatstart" value="false">'
		videoHTML += '<param name="showcontrols" value="true">'
		videoHTML += '<param name="showstatusbar" value="true">'
		videoHTML += '<param name="autosize" value="false">'
		videoHTML += '<param name="stretchtofit" value="1">'
		videoHTML += '<param name="displaysize" value="0">'
		videoHTML += '<embed type="application/asx" pluginspage="http://www.microsoft.com/windows/mediaplayer/" src="asxgen.php?v=' + videoF + '" name="mediaplayer" style="width: ' + width + 'px; height: ' + (height+72) + 'px;" transparentatstart="0" autostart="1" animationatstart="0" showcontrols="1" autosize="0" displaysize="0" stretchtofit="1" showstatusbar="1"></embed>'
		videoHTML += '</object>'
		elVideoContainer.innerHTML = videoHTML;
	}

	var caption = obj.parentNode.lastChild.nodeValue;
	if (caption != null) {
		elCaption.innerHTML = caption;
	}
	el('videocommentcount').innerHTML = (comments[videoF]?comments[videoF].length:"");
	el('videosavelink').href = 'videos/' + videoF;
	return false;
}

function domail(mailLink) {
	mailLink.setAttribute('href', 'mailto:' + mailLink.innerHTML + '@' + 'gmail.com');
}
