var smf_formSubmitted = false;

// Define document.getElementById for Internet Explorer 4.
if (typeof(document.getElementById) == "undefined")
	document.getElementById = function (id)
	{
		// Just return the corresponding index of all.
		return document.all[id];
	}

function expandThumb(thumbID)
{
	var img = document.getElementById('thumb_' + thumbID);
	var link = document.getElementById('link_' + thumbID);
	var tmp = img.src;
	img.src = link.href;
	link.href = tmp;
	img.style.width = '';
	img.style.height = '';
	return false;
}

// Open a new window in a smaller popup.
function reqWin(desktopURL, alternateWidth, alternateHeight)
{
	window.open(desktopURL, 'requested_popup', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=' + (alternateWidth ? alternateWidth : 480) + ',height=' + (alternateHeight ? alternateHeight : 220) + ',resizable=no');

	// Return false so the click won't follow the link ;).
	return false;
}

// Remember the current position.
function storeCaret(text)
{
	// Only bother if it will be useful.
	if (typeof(text.createTextRange) != 'undefined')
		text.caretPos = document.selection.createRange().duplicate();
}

// Replaces the currently selected text with the passed text.
function replaceText(text, textarea)
{
	// Attempt to create a text range (IE).
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		caretPos.select();
	}
	// Mozilla text range replace.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text + end;

		if (textarea.setSelectionRange)
		{
			textarea.focus();
			textarea.setSelectionRange(begin.length + text.length, begin.length + text.length);
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put it on the end.
	else
	{
		textarea.value += text;
		textarea.focus(textarea.value.length - 1);
	}
}

// Surrounds the selected text with text1 and text2.
function surroundText(text1, text2, textarea)
{
	// Can a text range be created?
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;
		caretPos.select();
	}
	// Mozilla text range wrap.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var newCursorPos = textarea.selectionStart;
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text1 + selection + text2 + end;

		if (textarea.setSelectionRange)
		{
			if (selection.length == 0)
				textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
			else
				textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
			textarea.focus();
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put them on the end, then.
	else
	{
		textarea.value += text1 + text2;
		textarea.focus(textarea.value.length - 1);
	}
}

// Checks if the passed input's value is nothing.
function isEmptyText(theField)
{
	// Copy the value so changes can be made..
	var theValue = theField.value;

	// Strip whitespace off the left side.
	while (theValue.length > 0 && (theValue.charAt(0) == ' ' || theValue.charAt(0) == '\t'))
		theValue = theValue.substring(1, theValue.length);
	// Strip whitespace off the right side.
	while (theValue.length > 0 && (theValue.charAt(theValue.length - 1) == ' ' || theValue.charAt(theValue.length - 1) == '\t'))
		theValue = theValue.substring(0, theValue.length - 1);

	if (theValue == '')
		return true;
	else
		return false;
}

// Only allow form submission ONCE.
function submitonce(theform)
{
	smf_formSubmitted = true;
}
function submitThisOnce(item, check_text)
{

	if (check_text == true)
	{
		if (document.postmodify.message.value == '')
		{
			alert('Niste napisali tekst poruke.');
			smf_formSubmitted = false;
			return false;
		}
	}

	// Hateful, hateful fix for Safari 1.3 beta.
	if (navigator.userAgent.indexOf('AppleWebKit') != -1)
		return !smf_formSubmitted;

	for (var i = 0; i < item.form.length; i++)
		if (typeof(item.form[i]) != "undefined" && item.form[i].tagName.toLowerCase() == "textarea")
			item.form[i].readOnly = true;

	return !smf_formSubmitted;
}

// Set the "inside" HTML of an element.
function setInnerHTML(element, toValue)
{
	// IE has this built in...
	if (typeof(element.innerHTML) != 'undefined')
		element.innerHTML = toValue;
	else
	{
		var range = document.createRange();
		range.selectNodeContents(element);
		range.deleteContents();
		element.appendChild(range.createContextualFragment(toValue));
	}
}

// Set the "outer" HTML of an element.
function setOuterHTML(element, toValue)
{
	if (typeof(element.outerHTML) != 'undefined')
		element.outerHTML = toValue;
	else
	{
		var range = document.createRange();
		range.setStartBefore(element);
		element.parentNode.replaceChild(range.createContextualFragment(toValue), element);
	}
}

// Get the inner HTML of an element.
function getInnerHTML(element)
{
	if (typeof(element.innerHTML) != 'undefined')
		return element.innerHTML;
	else
	{
		var returnStr = '';
		for (var i = 0; i < element.childNodes.length; i++)
			returnStr += getOuterHTML(element.childNodes[i]);

		return returnStr;
	}
}

function getOuterHTML(node)
{
	if (typeof(node.outerHTML) != 'undefined')
		return node.outerHTML;

	var str = '';

	switch (node.nodeType)
	{
		// An element.
		case 1:
			str += '<' + node.nodeName;

			for (var i = 0; i < node.attributes.length; i++)
			{
				if (node.attributes[i].nodeValue != null)
					str += ' ' + node.attributes[i].nodeName + '="' + node.attributes[i].nodeValue + '"';
			}

			if (node.childNodes.length == 0 && in_array(node.nodeName.toLowerCase(), ['hr', 'input', 'img', 'link', 'meta', 'br']))
				str += ' />';
			else
				str += '>' + getInnerHTML(node) + '</' + node.nodeName + '>';
			break;

		// 2 is an attribute.

		// Just some text..
		case 3:
			str += node.nodeValue;
			break;

		// A CDATA section.
		case 4:
			str += '<![CDATA' + '[' + node.nodeValue + ']' + ']>';
			break;

		// Entity reference..
		case 5:
			str += '&' + node.nodeName + ';';
			break;

		// 6 is an actual entity, 7 is a PI.

		// Comment.
		case 8:
			str += '<!--' + node.nodeValue + '-->';
			break;
	}

	return str;
}

// Checks for variable in theArray.
function in_array(variable, theArray)
{
	for (var i = 0; i < theArray.length; i++)
	{
		if (theArray[i] == variable)
			return true;
	}
	return false;
}

// Find a specific radio button in its group and select it.
function selectRadioByName(radioGroup, name)
{
	for (var i = 0; i < radioGroup.length; i++)
	{
		if (radioGroup[i].value == name)
			return radioGroup[i].checked = true;
	}

	return false;
}

// Invert all checkboxes at once by clicking a single checkbox.
function invertAll(headerfield, checkform, mask)
{
	for (var i = 0; i < checkform.length; i++)
	{
		if (typeof(mask) != "undefined" && checkform[i].name.substr(0, mask.length) != mask)
			continue;

		if (!checkform[i].disabled)
			checkform[i].checked = headerfield.checked;
	}
}

// Controls the placement of pins on the map.
function placePin (event)
{
	// IE
	if (document.all)
	{
		// IE in standards mode
		if (document.documentElement.scrollLeft || document.documentElement.scrollTop)
		{
			// get the coordinates
			var xPin = event.clientX + document.documentElement.scrollLeft;
			var yPin = event.clientY + document.documentElement.scrollTop;
		}
		// regular IE
		else
		{
			// get the coordinates
			var xPin = event.clientX + document.body.scrollLeft;
			var yPin = event.clientY + document.body.scrollTop;
		}

		// database coordinates
		document.mm.xPin.value = xPin - document.images.map.offsetLeft - 2;
		document.mm.yPin.value = yPin - document.images.map.offsetTop - 2;

		// pin coordinates
		document.images.pin.style.visibility = 'visible';
		document.images.pin.style.left = xPin - 6;
		document.images.pin.style.top = yPin - 6;
	}
	// Netscape, Mozilla, etc
	else
	{
		// get the coordinates
		var xPin = event.clientX + window.pageXOffset;
		var yPin = event.clientY + window.pageYOffset;
		// database coordinates
		document.mm.xPin.value = xPin - document.images.map.offsetLeft;
		document.mm.yPin.value = yPin - document.images.map.offsetTop;
		// pin coordinates
		document.images.pin.style.visibility = 'visible';
		document.images.pin.style.left = xPin - 4 + 'px';
		document.images.pin.style.top = yPin - 4 + 'px';
	}
}

// Fixes position and visibility of pins.
function fixPin (id, x, y)
{
	if (x)
	{
		id.style.visibility = 'visible';
		id.style.left = (x + document.images.map.offsetLeft) + 'px';
		id.style.top = (y + document.images.map.offsetTop) + 'px';
	}
}

//==========================================
// Multi Page jumps
//==========================================

function multi_page_jump (url_bit, total_posts, per_page)
{
	pages = 1;
	smf_lang_tpl_q1  = "Molimo Vas da unesete broj strane izmedju 1 i";
	cur_st = smf_var_st;
	cur_page  = 1;
	
	if ( total_posts % per_page == 0 )
	{
		pages = total_posts / per_page;
	}
	else
	{
		pages = Math.ceil( total_posts / per_page );
	}
	
	msg = smf_lang_tpl_q1 + " " + pages;
	
	if ( cur_st > 0 )
	{
		cur_page = cur_st / per_page; cur_page = cur_page -1;
	}
	
	show_page = 1;
	
	if ( cur_page < pages )
	{
		show_page = cur_page + 1;
	}
	
	if ( cur_page >= pages )
	{
		show_page = cur_page - 1;
	}
 	else
 	{
 		show_page = cur_page + 1;
 	}
 	
	userPage = prompt( msg, show_page );
	
	if ( userPage > 0  )
	{
		if ( userPage < 1 )     {    userPage = 1;  }
		if ( userPage > pages ) { userPage = pages; }
		if ( userPage == 1 )    {     start = 0;    }
		else { start = (userPage - 1) * per_page; }
		
		window.location = url_bit + ";start=" + start;
	}
}


// Shows the page numbers by clicking the dots (in compact view).
function expandPages(spanNode, baseURL, firstPage, lastPage, perPage)
{
	var replacement = '', i, oldLastPage = 0;
	var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
	var is_ie6 = (is_ie && (parseInt(navigator.appVersion) == 6));

	// The dots were bold, the page numbers are not (in most cases).
	spanNode.style.fontWeight = 'normal';
	spanNode.onclick = '';

	// Prevent too many pages to be loaded at once.
	if ((lastPage - firstPage) / perPage > 1000)
	{
		oldLastPage = lastPage;
		lastPage = firstPage + 1000 * perPage;
	}
	
	// Calculate the new pages.
	for (i = firstPage; i < lastPage; i += perPage)
		replacement += '<span class="pg_np"><a href="' + baseURL.replace(/%d/, i) + '">' + (1 + i / perPage) + '</a></span> ';

	if (oldLastPage > 0)
		replacement += '<span style="font-weight: bold; cursor: ' + (is_ie && !is_ie6up ? 'hand' : 'pointer') + ';" onclick="expandPages(this, \'' + baseURL + '\', ' + lastPage + ', ' + oldLastPage + ', ' + perPage + ');"> ... </span> ';

	// Replace the dots by the new page links.
	setInnerHTML(spanNode, replacement);
}

//// Type Quietly ////

// Looks for repeated sequences of uppercase letters being keyed in;
// politely asks user to stop 'shouting'!
// At the moment it only works when the user is typing at the end of the message.
// Should catch most occurrences though.

// Maximum caps in a row (after stripping all non-alphabetical characters)
// Setting this too low may cause it to be triggered by uppercase BBCode/HTML tags
// or acronyms and the like
var TQ_MAX_CAPS = 5;

// Maximum size of text range to sample (should be >= TQ_MAX_CAPS)
var TQ_SAMPLE_SIZE = 10;

// Cutoff point; disable Type Quietly if the message gets long
var TQ_CUT_OFF_POINT = 2000;

// Message to display when user is shouting
var TQ_MESSAGE =
	'Izgleda kao da pokušavate pisati tekst VELIKIM SLOVIMA.\n\n' +
	'Molimo Vas da to ne radite jer je to protiv pravila foruma!'

// Initialisation: Leave these lines as is
var tqIsActive = true;
var tqPrevEndChars = '';
var tqPrevLength = 0;
var tqPrevElement = '';

// Main Type Quietly function
// Always return true in case some 'clever' browser decides to cancel the keypress
function typeQuietly (textEl, event) {
	// Check if active
	if (!tqIsActive) {
		return true;
	}

	// Check arguments
	if ((typeof textEl != 'object') || (typeof event != 'object')) {
		return true;
	}

	// Check string handling requirements (should be fine for IE 4+, NS 4+ etc.)
	if ((typeof RegExp != 'function') || (typeof textEl.value.substr) != 'function') {
		return true;
	}
	
	// Deactivate if message too long
	if (textEl.value.length > TQ_CUT_OFF_POINT) {
		tqIsActive = false;
		return true;
	}

	// Check message is long enough to trigger
	if (textEl.value.length < TQ_MAX_CAPS) {
		return true;
	}

	// Sample last characters of message
	var lastChars = '';
	var selectStart, selectLength;
	if (textEl.value.length < TQ_SAMPLE_SIZE) {
		selectStart = 0;
		selectLength = textEl.value.length;
	}
	else {
		selectStart = textEl.value.length - TQ_SAMPLE_SIZE;
		selectLength = TQ_SAMPLE_SIZE;
	}
	lastChars = textEl.value.substr(selectStart, selectLength);
	
	// Check we caught something
	if (lastChars.length == 0) {
		return true;
	}

	// If we're now looking at a different element, reset
	if ((tqPrevElement == '') || (tqPrevElement != textEl.name)) {
		tqPrevEndChars = lastChars;
		tqPrevLength = 0;
		tqPrevElement = textEl.name;
		return true;
	}	

	// End of message must be changing
	if (lastChars == tqPrevEndChars) {
		return true;
	}
	tqPrevEndChars = lastChars;

	// Last character must itself be a capital
	if (lastChars.substr(lastChars.length - 1, 1).search(eval('/[A-Z]/')) == -1) {
		return true;
	}

	// Don't trigger when deleting or on first keypress
	if ((tqPrevLength == 0) || (textEl.value.length < tqPrevLength)) {
		tqPrevLength = textEl.value.length;
		return true;
	}
	tqPrevLength = textEl.value.length;

	// Strip non-alphabetical characters and trim to size
	lastChars = lastChars.replace(eval('/[^a-zA-Z]/g'), '');
	if (lastChars.length > TQ_MAX_CAPS) {
		lastChars = lastChars.substr(lastChars.length - TQ_MAX_CAPS, TQ_MAX_CAPS);
	}
	else
	{
		// length doesn't exceed TQ_MAX_CAPS
		return true;
	}

	// Show message if needed
	if (lastChars == lastChars.toUpperCase()) {
		alert (TQ_MESSAGE);
		tqIsActive = false;
	}

	return true;
}
