/**
* ii2 generic JavaScript file
* ALL RIGHTS RESERVED!
*
* @copyright Citypress Oy
**/

/* Calendar */
var calHandlerFunc = function(t)
{
	var response = t.responseText;
	var outerDiv = $('calcontainer');
	var innerDiv = document.createElement('div');
	innerDiv.setAttribute('id', 'cal');
	innerDiv.innerHTML = response;
	outerDiv.appendChild(innerDiv);
}

var calErrFunc = function(t) {
	alert("Error getting calendar data.");
}

function showCalendar(nick, year, month, day)
{
	var url = '/user.php';
	var params = 'nick=' + nick + '&s=calendar&day=' + day + '&month=' + month + '&year=' + year + '&do=getSmallCalendar';

	new Ajax.Request(
	url,
	{
		method: 'get',
		parameters: params,
		onComplete: calHandlerFunc,
		onFailure: calErrFunc
	}
	);

	if ($('cal'))
	{
		var outerDiv = $('calcontainer');
		var innerDiv = $('cal');
		outerDiv.removeChild(innerDiv);
	}
}

/** IMAGE COPY PROTECTION :: DEPRECATED! can be removed **/
function copyNot(target)
{
	document.images[target].onmousemove=function()
	{
		coverMe(this);
	}
}
function coverMe(e)
{
	var shield=document.images.imgShield;
	if(shield.width <= 1)
	{
		shield.style.left=getLeft(e);
		shield.style.top=getTop(e);
		shield.width=e.width + 4;
		shield.height=e.height + 4;
	}
}
function getLeft(l)
{
	if (l.offsetParent) return (l.offsetLeft + getLeft(l.offsetParent));
	else return (l.offsetLeft);
}
function getTop(l)
{
	if (l.offsetParent) return (l.offsetTop + getTop(l.offsetParent));
	else return (l.offsetTop);
}

/**
* Comment posting class
*/
comments = {

	/**
	*	Value to return on postComment()
	*
	*	@var boolean
	*/
	returnVal: false,

	/**
	* Make an AJAX request to post a new comment
	*
	* @param string url URL to post the data
	* @return boolean false if succeeded, true if did not succeed (!)
	*/
	postComment: function( url ) {
		if(!Prototype) {
			return true;
		}

		if($('comment').value == "") {
			return false;
		}

		new Ajax.Request(url, {
			method: 'POST',
			parameters: $('comment').serialize(),
			onSuccess: function( res ) {
				this.returnVal = false;
				comments.postCommentFetch( res );
			},
			onFailure: function( res ) {
				this.returnVal = true;
			}
		});

		Form.disable('cForm');

		return this.returnVal;
	},

	/**
	* Update comment field with html data
	*
	* @param string html
	* @return void
	*/
	updateCommentField: function(html) {
		Element.update('xmlCommentContent', html);
		handleComments('com', 'td');
		popup.process($('com'));
	},

	postCommentFetch: function(r) {
		Form.enable('cForm');
		$('comment').value = '';

		comments.updateCommentField(r.responseText);
	}


}

/** Tag ADD **/
var counter = 0;
function moreFields()
{
	counter++;
	var newFields = $('readroot').cloneNode(true);
	newFields.id = '';
	newFields.style.display = 'block';
	var newField = newFields.childNodes;
	for (var i=0;i<newField.length;i++)
	{
		var theName = newField[i].name;
		/* if (theName) newField[i].name = theName + counter; */
	}
	var insertHere = $('writeroot');
	insertHere.parentNode.insertBefore(newFields,insertHere);
}

/** Prereplies **/
function copyToHtmlElement(targetElement, selectElement, action)
{
	//jos action on 1 niin lisätään reply jo ko. kentässä valmiiksi olevan tekstin eteen
	if(action == 1)
	{
		$(targetElement).value = selectElement.value + "\n" + $(targetElement).value;
	}
	//muussa tapauksessa mahdollinen kentässä jo oleva teksti katoaa
	else
	{
		$(targetElement).value = selectElement.value;
	}
}

/** Common functions **/
function nl2br (s) {
	return s.replace(/\r/g, '<br>');
}
function htmlspecialchars (s) {
	s = s.replace(/</g, '&lt;');
	s = s.replace(/>/g, '&gt;');
	return s;
}
function icon(icon, text) {
	return '<img class=icon src="http://img.ii2.org/html/images/icons/' + icon + '.gif" alt="">' + text;
}
function getTime() {
	var dt = new Date();
	return ((dt.getTime() - dt.getMilliseconds()) / 1000);
}
function shorten(str, length) {
	if(length && str.length > length) {
		str = str.substr(0, length);
		str += "...";
	}
	return str;
}

/**
* Ask for confirmation and go to URL
*
* @param string url url to go
* @return void
*/
function areyousure(url) {
	if(confirm(lang.get("areyousure"))) {
		window.location = url;
	}
}

/**
* Ask for confirmation and return info
*
* @return boolean True if user answered yes
*/
function areyousurereturn () {
	if(confirm(lang.get("areyousure"))) {
		return true;
	} else {
		return false;
	}
}
function areyousurecustom(langConst) {
	if(confirm(lang.get(langConst))) {
		return true;
	}
	else {
		return false;
	}
}

function gotoSelectedUrl (url, selectElement, prefix) {
	if(prefix == "") {
		prefix = 0;
	}

	var selected = selectElement.selectedIndex;
	var newIndex = selected + prefix;

	if(newIndex < 0) {
		return;
	}

	if(selectElement[newIndex] == null) {
		return;
	}

	document.location.href = url + selectElement[newIndex].value;
}

/**
* Validate element contents by regexp
*
* If regexp does not match, set className as "error"
*
* @param string elem Element
* @param string vReg Regexp to pass for RegExp class
* @return boolean True if regexp passed
*/
function validate(elem, vReg)
{
	var re = new RegExp(vReg);
	var ret = re.exec(elem.value);

	if(ret)
	{
		elem.className = null;
		return true;
	}
	else
	{
		elem.className = "error";
	}
}

/**
* Add slashes to string
*
* @param string str
* @return string
*/
function addslashes(str){
	return str.replace(/\'/g, '\\\'');
}

/**
* Convert textual links to HTML <a links
*
* @param string s Text
* @return string Text with HTML formatted links
*/
function addLinks(s)
{
	var linkRegExp = / http:\/\/([^ \,\;\:\!\)\(\"\'\<\>\f\n\r\t\v])+/g;
	return s.replace(linkRegExp, function ($str) { return $str.link($str); });
}

/**
* Toggle editor & content boxes (e.g. editor = visible, content = hidden and vice versa
*
* @param string name Element name prefix (name_editor, name_content used)
* @return void
*/
function boxToggle(name) {
	Element.toggle(name + '_editor');
	Element.toggle(name + '_content');
}

function boxSetVisible(divName, divList)
{
	Element.show(divName);

	divList.each(function(item) {
		Element.hide(item);
	});
}
function publicBoxSetVisible(divName, divList)
{
	divName.each(function(item) {
		Element.show(item);
	});

	divList.each(function(item) {
		Element.hide(item);
	});
}

/** Comment handler / smiley parser **/
var smileyson = true;
function handleComments(elemId, tagName, tempSmileys) {
	if(tempSmileys == "n" || smileyson == false) {
		smileyson = false;
		return false;
	}

	var allTableData = $(elemId);

	if(allTableData == null) {
		return;
	}

	allTableData = allTableData.getElementsByTagName('td');

	for(var i=0;i<allTableData.length;i++)
	{
		var tdrel = allTableData[i].getAttribute("rel");

		if(tdrel && tdrel != "comment") {
			continue;
		}

		modifyText(allTableData[i]);
	}
}

/**
* Smileys class
*/
smileys = {
	/**
	* URL of smiley images
	*
	* @var string
	*/
	htmlurl: "http://img1.ii2.org/html/beta/images/smileys/",

	/**
	* Smileys to be converted
	*
	* @var array
	*/
	smil_from: new Array("8)", ":o", "&gt;:(", ":D", ":(", ":)", ":P", ";)", "x)", ":|", ":/", ";D", "xD", ":'(", "xP", "=D", "=)", "=p", ";P", "&lt;ashamed&gt;", "&gt;&gt;:(", "&lt;alien&gt;", "P)", "&gt;)", ":S", "&lt;puke&gt;", ":x", "(y)", "(n)", "&lt;skull&gt;", "$)", "&lt;3", "&lt;/3", "&lt;ii2&gt;", "&lt;green&gt;", "&lt;rainbow&gt;", "&lt;bomb&gt;", "&lt;tux&gt;"),

	/**
	* Smiley images that texts will be converted to
	*
	* @var array
	*/
	smil_what: new Array("8).gif", "amazed.gif", "angry.gif", "laugh.gif", "sad.gif", "smile.gif", "tongue.gif", "wink.gif", "x).gif", "neutral.gif", "noname.gif", "laugh2.gif", "xD.gif", "cry.gif", "xp.gif", "laugh3.gif", "smile2.gif", "tongue2.gif", "tongue3.gif", "ashamed.gif", "angry2.gif", "alien.gif", "pirate.gif", "evilgrin.gif", "mutru.gif", "puke.gif", "sealed.gif", "thumb_up.png", "thumb_down.png", "skull.gif", "$).gif", "heart.gif", "brokenheart.gif", "ii2smiley.png", "green.png", "rainbow.png", "bomb.png", "tux.png"),

	/**
	* Show a clickable list of smileys
	*
	* @param string targetId Smiley text will be appended to targetId.value field when clicked
	* @param string onClickEval a code to be evaluated if clicked
	* @return string HTML list
	*/
	showList: function(targetId, onClickEval) {
		var html = "";

		for(var i=0; i < smileys.smil_from.length; i++) {
			html +=
			'<div style="width: 25px; height: 25px; float: left;">' +
			'<a onclick="$(\'' + targetId + '\').value += \' ' + addslashes(smileys.smil_from[i]) + '\'; ' + onClickEval + '">' + smileys.getSmiley(i) + '</a>' +
			'</div>';
		}

		return html;
	},

	/**
	* Show a clickable list of smileys for TinyMCE popup
	*
	* @param string altText Smiley image alternate text
	* @return string HTML list
	*/
	showTinyMCEList: function() {
		var html = '';

		for (var i = 0; i < smileys.smil_from.length; i++) {
			html +=
			'<div style="width: 25px; height: 25px; float: left;">' +
			'<a onclick="javascript:insertEmotion(\'' + smileys.htmlurl + smileys.smil_what[i] + '\', \'\');">' + smileys.getSmiley(i) + '</a>' +
			'</div>';
		}

		return html;
	},

	/**
	* Return smiley image for smiley text
	*
	* @param int indexNum array number from smil_what table
	* @return string HTML
	*/
	getSmiley: function (indexNum) {
		return '<img class="smiley" src="' + smileys.htmlurl + smileys.smil_what[indexNum] + '" alt="' + smileys.smil_from[indexNum] + '">';
	}
}

/**
* ii2Plus smileys class
*/
smileys_ii2plus = {
	/**
	* URL of ii2Plus smiley images
	*
	* @var string
	*/
	htmlurl: "http://img1.ii2.org/html/beta/images/smileys/animated/",

	/**
	* ii2Plus smiley texts to be converted
	*
	* @var array
	*/
	smil_from: new Array("&lt;laugh&gt;", "&lt;cry&gt;", "&lt;peep&gt;", "&lt;party&gt;", "&lt;sleep&gt;", "&lt;bang&gt;", "&lt;pheart&gt;", "&lt;bheart&gt;", "&lt;lovers&gt;"),

	/**
	* ii2Plus smiley images that texts will be converted to
	*
	* @var array
	*/
	smil_what: new Array("laugh.gif", "cry.gif", "peep.gif", "party.gif", "sleep.gif", "bang.gif", "pumpingheart.gif", "heart2.gif", "lovers.gif"),

	/**
	* Show a clickable list of ii2Plus smileys
	*
	* @param string targetId ii2Plus smiley text will be appended to targetId.value field when clicked
	* @param string onClickEval A code to be evaluated if clicked
	* @param boolean ii2PlusAuthed A flag that defines if the user if authed to use the ii2Plus smileys or not
	* @return string HTML list
	*/
	showList: function(targetId, onClickEval, ii2PlusAuthed) {
		var html = "";

		for(var i=0; i < smileys_ii2plus.smil_from.length; i++) {
			html += '<div style="width: 35px; height: 25px; float: left;">';

			if (ii2PlusAuthed) {
				html += '<a onclick="$(\'' + targetId + '\').value += \' ' + addslashes(smileys_ii2plus.smil_from[i]) + '\'; ' + onClickEval + '">' + smileys_ii2plus.getSmiley(i) + '</a>';
			} else {
				html += '<a onclick="pulsate(\'ii2plusAd_smileys\');">' + smileys_ii2plus.getSmiley(i) + '</a>';
			}
			html +=	'</div>';
		}

		return html;
	},

	/**
	* Show a clickable list of ii2Plus smileys for TinyMCE popup
	*
	* @param string altText ii2Plus smiley image alternate text
	* @return string HTML list
	*/
	showTinyMCEList: function() {
		var html = '';

		for (var i = 0; i < smileys_ii2plus.smil_from.length; i++) {
			html +=
			'<div style="width: 35px; height: 25px; float: left;">' +
			'<a onclick="javascript:insertEmotion(\'' + smileys_ii2plus.htmlurl + smileys_ii2plus.smil_what[i] + '\', \'\');">' + smileys_ii2plus.getSmiley(i) + '</a>' +
			'</div>';
		}

		return html;
	},

	/**
	* Return ii2Plus smiley image for ii2Plus smiley text
	*
	* @param int indexNum array number from smil_what table
	* @return string HTML
	*/
	getSmiley: function (indexNum) {
		return '<img class="smiley" height="15" src="' + smileys_ii2plus.htmlurl + smileys_ii2plus.smil_what[indexNum] + '" alt="' + smileys_ii2plus.smil_from[indexNum] + '">';
	}
}

function modifyText(item) {
	// jos ei itemiä
	if(item == null) {
		return;
	}

	// haetaan sisältö
	if(typeof(item) == "object") {
		var code = " " + item.innerHTML;
	} else {
		var code = " " + item;
	}

	// hymiöiden lisäys
	for(var n=0;n<smileys.smil_from.length;n++) {
		while(indx = code.indexOf(" " + smileys.smil_from[n]) >= 0) {
			code = code.replace(" " + smileys.smil_from[n] + "",' ' + smileys.getSmiley(n));
		}
	}

	// ii2Plus smileys
	for(var n=0;n<smileys_ii2plus.smil_from.length;n++) {
		while(indx = code.indexOf(" " + smileys_ii2plus.smil_from[n]) >= 0) {
			code = code.replace(" " + smileys_ii2plus.smil_from[n] + "",' ' + smileys_ii2plus.getSmiley(n));
		}
	}

	// sisällön laitto takaisin
	if(typeof(item) == "object") {
		item.innerHTML = code;
	} else {
		return code;
	}
}

/** Image selection **/
function selectAllImages(imgArr)
{
	for(var i=0;i<imgArr.length;i++)
	{
		selectImage(imgArr[i]);
	}
}
function selectImage (pictid)
{
	var elem = $('img[' + pictid + ']');
	var layer = $('layer[' + pictid + ']');

	if(elem.value !== "y")
	{
		// asetetaan valinta
		layer.style.background = '#ff0000';
		elem.value = "y";
	}
	else
	{
		// poistetaan valinta
		layer.style.background = "#ffffff";
		elem.value = "n";
	}
}

/** Video selection **/
function selectAllVideos(imgArr)
{
	for(var i=0;i<imgArr.length;i++)
	{
		selectVideo(imgArr[i]);
	}
}
function selectVideo(pictid)
{
	var elem = $('video[' + pictid + ']');
	var layer = $('layer[' + pictid + ']');

	if(elem.value !== "y")
	{
		// asetetaan valinta
		layer.style.background = '#ff0000';
		elem.value = "y";
	}
	else
	{
		// poistetaan valinta
		layer.style.background = "#ffffff";
		elem.value = "n";
	}
}

/** JS dropdown lists **/
function folderAction (oUrl, action, foldid, id, type)
{
	if ( type == undefined ) type = 'img';

	switch(action)
	{
		case "delete":
		{
			if( confirm( lang.get("confirmdelete" + (type == 'video' ? 'video' : '')) ) )
			{
				document.location.href = oUrl + '&do=delete&do-' + type + '=' + id;
			}
			break;
		}

		case "edit":
		{
			document.location.href = oUrl + '&' + type + '=' + id + '&do=' + (type == 'img' ? 'image' : type) + 'Settings';
			break;
		}

		case "hide":
		case "profileImage":
		case "show":
		case "move":
		{
			document.location.href = oUrl + '&do=' + action + '&do-' + type +'=' + id;
			break;
		}

		case "publicmessage":
		{
			document.location.href = '/products/sms_ohje_txt.php?pictid=' + id;
			break;
		}
	}
}


/** User list **/
function uListMenu (uid)
{
	$('uid[' + uid + ']').innerHTML = $('userListDropDown').innerHTML;
}

function prevNextLink (pageNum, curPage)
{
	if($('userList-' + pageNum) == null)
	{
		return true;
	}
	else
	{
		$('userList-' + pageNum).style.display = '';

		if(curPage != pageNum)
		{
			$('userList-' + curPage).style.display = 'none';
		}
		document.location.hash = '#' + pageNum;

		return false;
	}
}

function uListInitialize (curPage)
{
	var hash = document.location.hash;
	if(hash.length > 1)
	{
		hash = hash.substr(1, 10);

		if($('userList-' + hash) != null)
		{
			curPage = hash;
		}
	}

	$('userList-' + curPage).style.display = '';
}

/** AJAX tab selection **/
var activetab = new Array();
function setTab(uid, cName, forceReload)
{
	var tid = 'user_' + uid + '_' + cName;

	if(forceReload != true)
	{
		$('status_' + uid).innerHTML = '';
	}

	var elem = $(tid);
	if(elem.innerHTML == '' || forceReload == true)
	{
		// haetaan tiedot
		elem.innerHTML = "<h1>" + lang.get("loading") + "</h1>";

		new Ajax.Updater (tid, tabUrl + '?ajax=true&uid=' + uid + '&s=' + cName, { evalScripts: true });
	}

	// piilotetaan mahdl. aikaisempi
	if(typeof(activetab[uid]) != 'undefined')
	{
		Element.hide('user_' + uid + '_' + activetab[uid]);
	}

	// näytetään nykyienn
	Element.show(tid);
	activetab[uid] = cName;
}

/**
* ii2 yleinen luokka
**/
ii2 = {
	pos_x: 0,
	pos_y: 0,

	// popup-laatikon tiedot
	popup_height: 0,
	popup_width: 0,

	// hiiren etäisyys
	popup_mouseDistance: 20,

	// minimi etäisyys yläosasta
	popup_minYdistance: 0,

	initialize: function() {
		if(Prototype) {
			Event.observe(document, 'mousemove', this.mousemove.bindAsEventListener(this));
		}
	},

	mousemove: function (e) {
		try {
			this.pos_x = Event.pointerX(e);
			this.pos_y = Event.pointerY(e);

			this.movePopup();
		} catch (e) {
			// nothing
		}
	},

	movePopup: function () {
		var posY = 0;
		var posX = 0;

		// x koordinaatti
		if(ii2.pos_x + ii2.popup_width + 50 > document.body.offsetWidth) {
			posX = ii2.pos_x - ii2.popup_width - this.popup_mouseDistance;
		} else {
			posX = ii2.pos_x + this.popup_mouseDistance;
		}

		// y koordinaatti
		if(ii2.pos_y - ii2.popup_height - 50 - document.body.scrollTop - ii2.popup_minYdistance > 0) {
			posY = ii2.pos_y - ii2.popup_height - this.popup_mouseDistance;
		} else {
			posY = ii2.pos_y + this.popup_mouseDistance;
		}

		// siirretään boksia
		if( $('smallImg') && $('smallImg').style )
		{
			$('smallImg').style.left = posX + "px";
			$('smallImg').style.top = posY + "px";
		}
	},

	updatePopup: function (txt) {
		// asetetaan sisältö
		$('smallImg').innerHTML = txt;

		// asetetaan leveys yms
		var dim = Element.getDimensions('smallImg');
		this.popup_height = dim["height"];
		this.popup_width = dim["width"];

		this.movePopup();

		Element.show('smallImg');
	},

	hidePopup: function() {
		try {
			Element.hide('smallImg');
		} catch (e) {
		}
	},

	require: function(className) {
		document.write("<script type=\"text/javascript\" src=\"/js/" + className + ".js/123\"></script>");
	}
}
ii2.initialize();

/**
* Popup process
**/
popup = {
	timer: null,
	enabled: true,
	matcher: /^(http:\/\/.*\.ii2\.org){0,1}\/user.php\?nick\=([^ \&]{1,})$/,
	waitTime: 575,
	fetchActive: false,

	/* toisen popupin avaustiedot */
	waitTimeSecond: 100,
	useSecond: false,
	secondTimer: null,

	state_loading: false,
	popupCache: Object(),
	fetch_type: null,
	fetch_val: null,
	allowImagePopup: false,

	process: function(elem) {
		if(!this.enabled) {
			return false;
		}

		if(elem == null) {
			elem = document;
		}

		var links = elem.getElementsByTagName("a");

		for(var i=0;i<links.length;i++) {
			var ret = this.matcher.exec(links[i].getAttribute("href"));

			if(ret != null) {
				var nick = ret[2];

				Event.observe(links[i], 'mouseover', this.mouseover.bindAsEventListener(this), false);
				Event.observe(links[i], 'mouseout', this.mouseout.bindAsEventListener(this), false);
			}
		}
	},

	mouseover: function(e) {
		// jos on jo timer päällä
		if(this.timer != null) {
			return;
		}

		var elem = Event.element(e);

		// jos on joku muu kuin A tagi
		if(elem.tagName != "A") {
			// kuville ei popuppeja
			// jos halutaan pakottaa popup, <img class=allowPopup> toimii
			if(this.allowImagePopup == false && elem.tagName == "IMG" && elem.className != "allowPopup") {
				return false;
			}

			// haetaan parent
			elem = elem.parentNode;
		}

		// löytyykö linkkiä
		var ret = this.matcher.exec(elem.getAttribute("href"));
		if(ret == null) {
			return false;
		}
		var nick = ret[2];

		// escapet
		if(nick.search(/%/)) {
			nick = unescape(nick);
		}

		this.fetch_type = 'user';
		this.fetch_val = nick;

		// aloitetaan ajastin
		this.timer = setTimeout(this.fetch.bind(this), this.useSecond ? this.waitTimeSecond : this.waitTime);
		this.fetchActive = true;
	},

	fetch: function() {
		if(this.timer != null) {
			clearTimeout(this.timer);
			this.timer = null;
		}

		debug("fetching: " + this.state_loading);

		if(this.state_loading != false) {
			return false;
		}

		this.state_loading = this.fetch_type + "_" + this.fetch_val;

		// tarkistetaan josko löytyy jo cachesta
		if(typeof(this.popupCache[this.state_loading]) != "undefined") {
			debug("cache found!");
			var reply = this.popupCache[this.state_loading];

			this.showPopup(reply);
			return true;
		}

		debug("making request");

		new Ajax.Request('/misc/popup.php', {
			method: 'get',
			parameters: 'type=' + this.fetch_type + '&val=' + this.fetch_val,
			onComplete: this.showPopup.bind(this)
		});
	},

	showPopup: function(reply) {
		debug("got reply!");

		// jos ei enää aktiivinen haku
		if(!this.fetchActive) {
			return false;
		}

		// jos objekti
		if(typeof(reply) == "object") {
			reply = reply.responseText;
		}

		if(new RegExp(/::POPUPNOTAUTHED::/).exec(reply)) {
			return false;
		}

		// jos state päällä
		if(this.state_loading == false) {
			return false;
		}

		// cachetus
		this.popupCache[this.state_loading] = reply;
		this.state_loading = false;

		// siirrä etusivun bannerit menujen tieltä
		if( ( $('banner_2') || $('banner_3') || $('banner_4') || $('fullscreenflash') ) && $('smallImg') )
		{
			if( $('banner_2') )
			{
				$('banner_2').style.visibility = 'hidden';
			}
			if( $('banner_3') )
			{
				$('banner_3').style.visibility = 'hidden';
			}
			if( $('banner_4') )
			{
				$('banner_4').style.visibility = 'hidden';
			}
			if( $('fullscreenflash') )
			{
				$('fullscreenflash').style.visibility = 'hidden';
			}
		}

		// näytetään
		ii2.updatePopup(reply);

		debug("set state loading to: " + this.state_loading);
	},

	mouseout: function(e) {
		if(this.timer != null) {
			clearTimeout(this.timer);
			this.timer = null;
		}

		// ei aktiivista hakua
		this.fetchActive = false;

		// asetetaan second päälle, ja timer sen pois asettamiseksi
		this.useSecond = true;
		this.secondTimer = setTimeout('popup.useSecond = false;', 2000);

		// ei enää ladata
		this.state_loading = false;

		// palautetaan bannerit
		if( ( $('banner_2') || $('banner_3') || $('banner_4') || $('fullscreenflash') ) && $('smallImg') )
		{
			if( $('banner_2') )
			{
				$('banner_2').style.visibility = 'visible';
			}
			if( $('banner_3') )
			{
				$('banner_3').style.visibility = 'visible';
			}
			if( $('banner_4') )
			{
				$('banner_4').style.visibility = 'visible';
			}
			if( $('fullscreenflash') )
			{
				$('fullscreenflash').style.visibility = 'visible';
			}
		}

		// popup piilotus
		ii2.hidePopup();
	}
}

function debug(txt) {
	// jos objekti on olemassa
	if(typeof($('debug')) != "object") {
		return false;
	}

	//$('debug').innerHTML += txt + "<br>";
}

/* image rating functions */
function toggleBlocks(position)
{
	block0 = "http://galleria.city.fi/icon/fam/star_disabled.png";
	block1 = "http://galleria.city.fi/icon/fam/star.png";

	for(i=1; i<eval(position) + 1; i++)
	{
		$("block_" + i).src = block1;
	}
	for(j=i; j<11; j++)
	{
		$("block_" + j).src = block0;
	}
}
function clearBlocks()
{
	if(!$('block0')) {
		return;
	}
	for(i=1; i<11; i++)
	{
		$("block_" + i).src = block0;
	}
}

/**
* Hoverbox implementation
*
* mainly used for ii2 top dropdowns (language, theme, etc)
*/
hoverBox = {
	boxId: null,
	active: false,
	timer: null,
	timerStart: null,
	blockingElements: false,

	/**
	* Set element visible for user
	*
	* @param string id Box ID (<div id=...)
	* @param string aElement
	* @access public
	*/
	show: function(id, aElement) {
		if(this.boxId != null) {
			this.active = false;
			this.check();
		}

		this.active = true;

		hoverBox.boxId = id;
		hoverBox.setPosition(aElement);
		this.setBlockingElements(false);
		Element.show(hoverBox.boxId);
	},

	setPosition: function(aElement) {
		var offset = Position.cumulativeOffset(aElement);
		var dim = Element.getDimensions(hoverBox.boxId);

		// x koordinaatti
		var place_x = offset[0] + 0;

		// y koordinaatti
		if(ii2.pos_y > 300) {
			var place_y = ii2.pos_y - dim["height"] - 10;
		} else {
			var place_y = offset[1] + 20;
		}

		// asetetaan
		$(hoverBox.boxId).style.left = place_x + "px";
		$(hoverBox.boxId).style.top = place_y + "px";
		// hymiöt kusasee
		if (hoverBox.boxId == 'dropDown_smileys') {
			$(hoverBox.boxId).style.position = 'fixed';
			$(hoverBox.boxId).style.left = (place_x + 20) + "px";
			$(hoverBox.boxId).style.top = (place_y - 350) + "px";
		}

		// siirrä etusivun bannerit menujen tieltä
		if( $('banner_1') && $('banner_2') )
		{
			// mitat
			var offset_1 = Position.cumulativeOffset( $('banner_1') );
			var dim_1 = Element.getDimensions( $('banner_1') );

			var offset_2 = Position.cumulativeOffset( $('banner_2') );
			var dim_2 = Element.getDimensions( $('banner_2') );

			var siirra_1 = (offset[0] - offset_1[0] - dim_1["width"] - 5) * -1;
			var siirra_2 = ((offset_2[1] - offset[1]) - dim["height"] - 25) * -1;

			var dim_3 = Element.getDimensions( $('frontAds_right') );

			// siirrä bannerit
			if( $('banner_2') )
			{
				// piilota scrollaamalla, muut selaimet kuin opera
				if( (navigator.userAgent.indexOf('Opera') == -1) )
				{
					if(siirra_2 > 0) {
						$('frontAds_right').style.margin = siirra_2 + ' 0 0 0px';
					}

					$('banner_2').style.overflow = "scroll";
					$('banner_2').style.height = $('banner_2').offsetHeight - siirra_2;
					$('banner_2').scrollTop = siirra_2;
				}
				else
				{
					// operalla piilota banneri
					$('banner_2').style.visibility = 'hidden';
				}
			}

			if(siirra_1 > 0) {
				// will be below zero if no ad
				$('banner_1').style.padding = '0 ' + siirra_1 + ' 0 0px';
			}
		}
	},

	mouseOut: function () {
		this.active = false;
		hoverBox.timerStart = setTimeout('hoverBox.startTimer()', 200);
	},

	startTimer: function() {
		hoverBox.timer = setInterval('hoverBox.check()', 100);
	},

	setBlockingElements: function(visibility) {
		if(hoverBox.blockingElements != true) {
			return false;
		}
		return true;
	},

	check: function() {
		if(hoverBox.active == false) {
			this.setBlockingElements(true);

			if(hoverBox.timer != null) {
				clearTimeout(hoverBox.timer);
			}

			if(hoverBox.timerStart != null) {
				clearTimeout(hoverBox.timerStart);
			}

			Element.hide(hoverBox.boxId);

			// palauta bannerit paikoilleen
			if( $('banner_1') && $('banner_2') )
			{
				$('banner_1').style.padding = '0 0 0 0px';
				if( $('banner_2') )
				{
					if( (navigator.userAgent.indexOf('Opera') == -1) )
					{
						$('frontAds_right').style.margin = '0 0 0 0px';
						$('banner_2').style.height = 350;
						$('banner_2').scrollTop = 0;
						$('banner_2').style.overflow = "hidden";
					}
					else
					{
						$('banner_2').style.visibility = 'visible';
					}
				}
			}
		}
	}
}

/**
* Close extra divider
*/
function closeExtraDiv () {
	$('extraDiv').innerHTML = '';
	$('extraDiv').hide();
	Element.hide('float_overlay');
	toggleBanners();
}

/**
* Show Ajax loading graph
*
* @param string elemName Element name which will contain the loading image
* @param string loadingTxt Text for loading
* @return void
*/
function AJAX_showLoading( elemName, loadingTxt )
{
	var elem = $(elemName);
	if( elem )
	{
		$(elemName).innerHTML = '<center><img src="http://img1.ii2.org/html/beta/images/lightbox/loading.gif"> <br>' + lang.get("loading") + '</center>';
	}
}

/**
* Toggle ii2 ad banners visibility
*/
function toggleBanners()
{
	if($('banner_1') )
	{
		Element.toggle('banner_1');
	}
	if($('banner_2') )
	{
		Element.toggle('banner_2');
	}
	if($('banner_3') )
	{
		Element.toggle('banner_3');
	}
	if($('banner_4') )
	{
		Element.toggle('banner_4');
	}
	if($('fullscreenflash') )
	{
		Element.toggle('fullscreenflash');
	}
}

/**
* Counter which can be used to show a reducing counter
*
* Was initially used for ii2 publishment date
*/
counter = {
	/**
	* Return item (day, hour, etc)
	*
	* @param int seconds Numeric seconds
	* @param int n1
	* @param int n2
	* @param boolean zeros Insert zeros to beginning
	* @return string
	*/
	counterItem: function(seconds, n1, n2, zeros) {
		str = ((Math.floor(seconds/n1))%n2).toString();
		if (zeros && str.length < 2) {
			str = "0" + str;
		}
		return str;
	},

	/**
	* Update the counter field and set timer for next update
	*
	* @param int seconds
	* @return void
	*/
	updateCounter: function (seconds) {
		$("countDown").innerHTML =
		counter.counterItem(seconds, 86400, 100000, false) + "d " +
		counter.counterItem(seconds, 3600, 24, false) + "h " +
		counter.counterItem(seconds, 60, 60, true) + "m " +
		counter.counterItem(seconds, 1, 60, true) + "s ";

		setTimeout("counter.updateCounter(" + (seconds-1) + ")", 990);
	},

	/**
	* Start the timer
	*
	* @param string endDate End date in javascript date form
	* @return void
	*/
	start: function(endDate) {
		var seconds = Math.floor(new Date(new Date(endDate) - new Date()).valueOf()/1000);
		counter.updateCounter(seconds);
	}
}

var openAnswer = null;
function showAnswer( elem )
{
	// New answer is opened
	if( openAnswer == null )
	{
		openAnswer = elem;
	}
	else
	{
		// Current answer is about to closed
		if( openAnswer == elem )
		{
			openAnswer = null;
		}
		else
		{
			// New answer is opened WHILE previous is still not closed
			if( $( openAnswer ) )
			{
				Element.toggle( openAnswer );
			}
			openAnswer = elem;
		}
	}
	Element.toggle(elem);
}

var openSubcat = null;
function openFAQSubcat( elem, level )
{
	if( level > 0 )
	{
		Element.toggle(elem);
		return;
	}
	else if( openSubcat != null && openSubcat == elem )
	{
		return;
	}

	if( openSubcat == null )
	{
		openSubcat = elem;
	}
	else
	{
		// Current subcat is about to closed
		if( openSubcat != elem )
		{
			// New subcat is opened WHILE previous is still not closed
			if( $( openSubcat ) )
			{
				Element.toggle( openSubcat );
			}
			openSubcat = elem;
		}

	}

	Element.toggle(elem);
}

function closeFAQ()
{
	openAnswer=null;
	openSubcat=null;
	closeExtraDiv();
}

function openIframe( url, width, height )
{
	var canvas = $('canvas');

	var iframe = document.createElement('IFRAME');
	iframe.src = url;
	iframe.width = width;
	iframe.height = height;
	iframe.style.border = '0px';

	canvas.innerHTML = "";
	canvas.appendChild( iframe );
}

var openCat = null;
function boldFAQCat( elem )
{
	if( openCat != null && openCat == elem )
	{
		return;
	}

	if( openCat == null )
	{
		openCat = elem;
	}
	else
	{
		// Current cat is about to closed
		if( openCat != elem )
		{
			// New subcat is opened WHILE previous is still not closed
			if( $( openCat ) )
			{
				$( openCat ).style.fontWeight = '';
			}
			openCat = elem;
		}

	}

	$( elem ).style.fontWeight = 'bold';
}

/**
* Div toggler
*
* usage:
*
* tmp = new divToggler;
* tmp.divPrefix = 'publicMsg_';
* tmp.toggle();
**/
divToggler = {
	divPrefix: null,
	divCount: 3,
	current: 0,
	interval: 8000,

	toggle: function () {
		if(!divToggler.divPrefix) {
			return false;
		}

		Effect.SlideUp($(divToggler.divPrefix + divToggler.current), {duration:.6}); // Element.hide => jotain joka piilottaa

		divToggler.current++;

		if(divToggler.current > divToggler.divCount -1) {
			divToggler.current = 0;
		}

		setTimeout('divToggler.show($(divToggler.divPrefix + divToggler.current))', 600);

		divToggler.start();
	},

	start: function() {
		setTimeout('divToggler.toggle()', divToggler.interval);
	},

	show: function (id) {
		Effect.SlideDown(id, {duration:.8}); // Element.show => jotain joka nÃ¤yttÃ¤Ã¤
	}
}

/**
* Div toggler
* same as above
*
* usage:
*
* tmp = new divToggler;
* tmp.divPrefix = 'publicMsg_';
* tmp.toggle();
**/
instantDivToggler = {
	divPrefix: null,
	divCount: 3,
	current: 0,
	interval: 8000,

	toggle: function () {
		if(!instantDivToggler.divPrefix) {
			return false;
		}

		Effect.SlideUp($(instantDivToggler.divPrefix + instantDivToggler.current), {duration:.6}); // Element.hide => jotain joka piilottaa

		instantDivToggler.current++;

		if(instantDivToggler.current > instantDivToggler.divCount -1) {
			instantDivToggler.current = 0;
		}

		setTimeout('instantDivToggler.show($(instantDivToggler.divPrefix + instantDivToggler.current))', 600);

		instantDivToggler.start();
	},

	start: function() {
		setTimeout('instantDivToggler.toggle()', instantDivToggler.interval);
	},

	show: function (id) {
		Effect.SlideDown(id, {duration:.8}); // Element.show => jotain joka nÃ¤yttÃ¤Ã¤
	}
}

function pulsate(elemId, setBack, num) {
	if(num == null) {
		num = 3;
	}

	if(num % 2 == 0) {
		$(elemId).style.background = "";
	} else {
		$(elemId).style.background = "#eee";
	}

	num = num - 1;

	if(num >= 0) {
		setTimeout("pulsate('" + elemId + "', true, '" + num + "');", 50);
	}
}


function boxSetVisibleAjax(url, showDiv, hideDiv) {

	var pyynto = new Ajax.Request('/misc/ajaxbox.php?do=' + url, {
		method: 'get',
		onComplete:
		function closeDiv(t) {
			$(showDiv).innerHTML = t.responseText;

			boxSetVisible(showDiv, new Array(hideDiv));
		}
	});

}
function publicboxSetVisibleAjax(url, contentDiv, showDiv, hideDiv) {

	var pyynto = new Ajax.Request('/misc/ajaxbox.php?do=' + url, {
		method: 'get',
		onComplete:
		function closeDiv(t) {
			$(contentDiv).innerHTML = t.responseText;

			publicBoxSetVisible(showDiv, hideDiv);
		}
	});

}


