/**
 * Ajax upload
 * Project page - http://valums.com/ajax-upload/
 * Copyright (c) 2008 Andris Valums, http://valums.com
 * Licensed under the MIT license (http://valums.com/mit-license/)
 * Version 3.6 (26.06.2009)
 */

/**
 * Changes from the previous version:
 * 1. Fixed minor bug where click outside the button
 * would open the file browse window
 * 
 * For the full changelog please visit: 
 * http://valums.com/ajax-upload-changelog/
 */

(function(){
	
var d = document, w = window;

/**
 * Get element by id
 */	
function get(element){
	if (typeof element == "string")
		element = d.getElementById(element);
	return element;
}

/**
 * Attaches event to a dom element
 */
function addEvent(el, type, fn){
	if(!el)
		return;
	if (w.addEventListener){
		el.addEventListener(type, fn, false);
	} else if (w.attachEvent){
		var f = function(){
		  fn.call(el, w.event);
		};			
		el.attachEvent('on' + type, f)
	}
}


/**
 * Creates and returns element from html chunk
 */
var toElement = function(){
	var div = d.createElement('div');
	return function(html){
		div.innerHTML = html;
		var el = div.childNodes[0];
		div.removeChild(el);
		return el;
	}
}();

function hasClass(ele,cls){
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
	if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
	ele.className=ele.className.replace(reg,' ');
}

// getOffset function copied from jQuery lib (http://jquery.com/)
if (document.documentElement["getBoundingClientRect"]){
	// Get Offset using getBoundingClientRect
	// http://ejohn.org/blog/getboundingclientrect-is-awesome/
	var getOffset = function(el){
		var box = el.getBoundingClientRect(),
		doc = el.ownerDocument,
		body = doc.body,
		docElem = doc.documentElement,
		
		// for ie 
		clientTop = docElem.clientTop || body.clientTop || 0,
		clientLeft = docElem.clientLeft || body.clientLeft || 0,
		
		// In Internet Explorer 7 getBoundingClientRect property is treated as physical,
		// while others are logical. Make all logical, like in IE8.
		
		
		zoom = 1;
		if (body.getBoundingClientRect) {
			var bound = body.getBoundingClientRect();
			zoom = (bound.right - bound.left)/body.clientWidth;
		}
		if (zoom > 1){
			clientTop = 0;
			clientLeft = 0;
		}
		var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop,
		left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft;
				
		return {
			top: top,
			left: left
		};
	}
	
} else {
	// Get offset adding all offsets 
	var getOffset = function(el){
		if (w.jQuery){
			return jQuery(el).offset();
		}		
			
		var top = 0, left = 0;
		do {
			top += el.offsetTop || 0;
			left += el.offsetLeft || 0;
		}
		while (el = el.offsetParent);
		
		return {
			left: left,
			top: top
		};
	}
}

function getBox(el){
	var left, right, top, bottom;	
	var offset = getOffset(el);
	left = offset.left;
	top = offset.top;
						
	right = left + el.offsetWidth;
	bottom = top + el.offsetHeight;		
		
	return {
		left: left,
		right: right,
		top: top,
		bottom: bottom
	};
}

/**
 * Crossbrowser mouse coordinates
 */
function getMouseCoords(e){		
	// pageX/Y is not supported in IE
	// http://www.quirksmode.org/dom/w3c_cssom.html			
	if (!e.pageX && e.clientX){
		// In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
		// while others are logical (offset).
		var zoom = 1;	
		var body = document.body;
		
		if (body.getBoundingClientRect) {
			var bound = body.getBoundingClientRect();
			zoom = (bound.right - bound.left)/body.clientWidth;
		}

		return {
			x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
			y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
		};
	}
	
	return {
		x: e.pageX,
		y: e.pageY
	};		

}
/**
 * Function generates unique id
 */		
var getUID = function(){
	var id = 0;
	return function(){
		return 'ValumsAjaxUpload' + id++;
	}
}();

function fileFromPath(file){
	return file.replace(/.*(\/|\\)/, "");			
}

function getExt(file){
	return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
}			

// Please use AjaxUpload , Ajax_upload will be removed in the next version
Ajax_upload = AjaxUpload = function(button, options){
	if (button.jquery){
		// jquery object was passed
		button = button[0];
	} else if (typeof button == "string" && /^#.*/.test(button)){					
		button = button.slice(1);				
	}
	button = get(button);	
	
	this._input = null;
	this._button = button;
	this._disabled = false;
	this._submitting = false;
	// Variable changes to true if the button was clicked
	// 3 seconds ago (requred to fix Safari on Mac error)
	this._justClicked = false;
	this._parentDialog = d.body;
	
	if (window.jQuery && jQuery.ui && jQuery.ui.dialog){
		var parentDialog = jQuery(this._button).parents('.ui-dialog');
		if (parentDialog.length){
			this._parentDialog = parentDialog[0];
		}
	}			
					
	this._settings = {
		// Location of the server-side upload script
		action: 'upload.php',			
		// File upload name
		name: 'userfile',
		// Additional data to send
		data: {},
		// Submit file as soon as it's selected
		autoSubmit: true,
		// The type of data that you're expecting back from the server.
		// Html and xml are detected automatically.
		// Only useful when you are using json data as a response.
		// Set to "json" in that case. 
		responseType: false,
		// When user selects a file, useful with autoSubmit disabled			
		onChange: function(file, extension){},					
		// Callback to fire before file is uploaded
		// You can return false to cancel upload
		onSubmit: function(file, extension){},
		// Fired when file upload is completed
		// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
		onComplete: function(file, response) {}
	};

	// Merge the users options with our defaults
	for (var i in options) {
		this._settings[i] = options[i];
	}
	
	this._createInput();
	this._rerouteClicks();
}
			
// assigning methods to our class
AjaxUpload.prototype = {
	setData : function(data){
		this._settings.data = data;
	},
	disable : function(){
		this._disabled = true;
	},
	enable : function(){
		this._disabled = false;
	},
	// removes ajaxupload
	destroy : function(){
		if(this._input){
			if(this._input.parentNode){
				this._input.parentNode.removeChild(this._input);
			}
			this._input = null;
		}
	},				
	/**
	 * Creates invisible file input above the button 
	 */
	_createInput : function(){
		var self = this;
		var input = d.createElement("input");
		input.setAttribute('type', 'file');
		input.setAttribute('name', this._settings.name);
		var styles = {
			'position' : 'absolute'
			,'margin': '-5px 0 0 -175px'
			,'padding': 0
			,'width': '220px'
			,'height': '30px'
			,'fontSize': '14px'								
			,'opacity': 0
			,'cursor': 'pointer'
			,'display' : 'none'
			,'zIndex' :  2147483583 //Max zIndex supported by Opera 9.0-9.2x 
			// Strange, I expected 2147483647					
		};
		for (var i in styles){
			input.style[i] = styles[i];
		}
		
		// Make sure that element opacity exists
		// (IE uses filter instead)
		if ( ! (input.style.opacity === "0")){
			input.style.filter = "alpha(opacity=0)";
		}
							
		this._parentDialog.appendChild(input);

		addEvent(input, 'change', function(){
			// get filename from input
			var file = fileFromPath(this.value);	
			if(self._settings.onChange.call(self, file, getExt(file)) == false ){
				return;				
			}														
			// Submit form when value is changed
			if (self._settings.autoSubmit){
				self.submit();						
			}						
		});
		
		// Fixing problem with Safari
		// The problem is that if you leave input before the file select dialog opens
		// it does not upload the file.
		// As dialog opens slowly (it is a sheet dialog which takes some time to open)
		// there is some time while you can leave the button.
		// So we should not change display to none immediately
		addEvent(input, 'click', function(){
			self.justClicked = true;
			setTimeout(function(){
				// we will wait 3 seconds for dialog to open
				self.justClicked = false;
			}, 2500);			
		});		
		
		this._input = input;
	},
	_rerouteClicks : function (){
		var self = this;
	
		// IE displays 'access denied' error when using this method
		// other browsers just ignore click()
		// addEvent(this._button, 'click', function(e){
		//   self._input.click();
		// });
				
		var box, dialogOffset = {top:0, left:0}, over = false;
									
		addEvent(self._button, 'mouseover', function(e){
			if (!self._input || over) return;
			
			over = true;
			box = getBox(self._button);
					
			if (self._parentDialog != d.body){
				dialogOffset = getOffset(self._parentDialog);
			}	
		});
		
	
		// We can't use mouseout on the button,
		// because invisible input is over it
		addEvent(document, 'mousemove', function(e){
			var input = self._input;			
			if (!input || !over) return;
			
			if (self._disabled){
				removeClass(self._button, 'hover');
				input.style.display = 'none';
				return;
			}	
										
			var c = getMouseCoords(e);

			if ((c.x >= box.left) && (c.x <= box.right) && 
			(c.y >= box.top) && (c.y <= box.bottom)){
							
				input.style.top = c.y - dialogOffset.top + 'px';
				input.style.left = c.x - dialogOffset.left + 'px';
				input.style.display = 'block';
				addClass(self._button, 'hover');
								
			} else {		
				// mouse left the button
				over = false;
			
				var check = setInterval(function(){
					// if input was just clicked do not hide it
					// to prevent safari bug
					 
					if (self.justClicked){
						return;
					}
					
					if ( !over ){
						input.style.display = 'none';	
					}						
				
					clearInterval(check);
				
				}, 25);
					

				removeClass(self._button, 'hover');
			}			
		});			
			
	},
	/**
	 * Creates iframe with unique name
	 */
	_createIframe : function(){
		// unique name
		// We cannot use getTime, because it sometimes return
		// same value in safari :(
		var id = getUID();
		
		// Remove ie6 "This page contains both secure and nonsecure items" prompt 
		// http://tinyurl.com/77w9wh
		var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
		iframe.id = id;
		iframe.style.display = 'none';
		d.body.appendChild(iframe);			
		return iframe;						
	},
	/**
	 * Upload file without refreshing the page
	 */
	submit : function(){
		var self = this, settings = this._settings;	
					
		if (this._input.value === ''){
			// there is no file
			return;
		}
										
		// get filename from input
		var file = fileFromPath(this._input.value);			

		// execute user event
		if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
			// Create new iframe for this submission
			var iframe = this._createIframe();
			
			// Do not submit if user function returns false										
			var form = this._createForm(iframe);
			form.appendChild(this._input);
			
			form.submit();
			
			d.body.removeChild(form);				
			form = null;
			this._input = null;
			
			// create new input
			this._createInput();
			
			var toDeleteFlag = false;
			
			addEvent(iframe, 'load', function(e){
					
				if (// For Safari
					iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
					// For FF, IE
					iframe.src == "javascript:'<html></html>';"){						
					
					// First time around, do not delete.
					if( toDeleteFlag ){
						// Fix busy state in FF3
						setTimeout( function() {
							d.body.removeChild(iframe);
						}, 0);
					}
					return;
				}				
				
				var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;

				// fixing Opera 9.26
				if (doc.readyState && doc.readyState != 'complete'){
					// Opera fires load event multiple times
					// Even when the DOM is not ready yet
					// this fix should not affect other browsers
					return;
				}
				
				// fixing Opera 9.64
				if (doc.body && doc.body.innerHTML == "false"){
					// In Opera 9.64 event was fired second time
					// when body.innerHTML changed from false 
					// to server response approx. after 1 sec
					return;				
				}
				
				var response;
									
				if (doc.XMLDocument){
					// response is a xml document IE property
					response = doc.XMLDocument;
				} else if (doc.body){
					// response is html document or plain text
					response = doc.body.innerHTML;
					if (settings.responseType && settings.responseType.toLowerCase() == 'json'){
						// If the document was sent as 'application/javascript' or
						// 'text/javascript', then the browser wraps the text in a <pre>
						// tag and performs html encoding on the contents.  In this case,
						// we need to pull the original text content from the text node's
						// nodeValue property to retrieve the unmangled content.
						// Note that IE6 only understands text/html
						if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){
							response = doc.body.firstChild.firstChild.nodeValue;
						}
						if (response) {
							response = window["eval"]("(" + response + ")");
						} else {
							response = {};
						}
					}
				} else {
					// response is a xml document
					var response = doc;
				}
																			
				settings.onComplete.call(self, file, response);
						
				// Reload blank page, so that reloading main page
				// does not re-submit the post. Also, remember to
				// delete the frame
				toDeleteFlag = true;
				
				// Fix IE mixed content issue
				iframe.src = "javascript:'<html></html>';";		 								
			});
	
		} else {
			// clear input to allow user to select same file
			// Doesn't work in IE6
			// this._input.value = '';
			d.body.removeChild(this._input);				
			this._input = null;
			
			// create new input
			this._createInput();						
		}
	},		
	/**
	 * Creates form, that will be submitted to iframe
	 */
	_createForm : function(iframe){
		var settings = this._settings;
		
		// method, enctype must be specified here
		// because changing this attr on the fly is not allowed in IE 6/7		
		var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
		form.style.display = 'none';
		form.action = settings.action;
		form.target = iframe.name;
		d.body.appendChild(form);
		
		// Create hidden input element for each data key
		for (var prop in settings.data){
			var el = d.createElement("input");
			el.type = 'hidden';
			el.name = prop;
			el.value = settings.data[prop];
			form.appendChild(el);
		}			
		return form;
	}	
};
})();

/* core */
var aj_base_x = '';
function set_base(str)
{
	aj_base_x = str;
}

var gallery_action = false;
function gallery_move(id, cnt, dir, w, m)
{
	if(gallery_action)
		return;
		
	w = (w) ? w : 200;
	m = (m) ? m : 10;
	
	var curr = document.getElementById("gallery-"+id+"-holder").style.left;
	curr = parseFloat(curr);

	if(isNaN(curr))
		curr = 0;
	if(dir > 0)
	{
		if(curr >= 0)
			return;
	}
	else
	{
		if(curr + cnt * (w + m*2) - (300 / w) * (w + m*2) <= 0)
			return;
	}

	gallery_action = true;
	var offset = w+m;

	if(dir < 0)
		dir = "-";
	else
		dir = "+";
		
	$("#gallery-"+id+"-holder").animate(
		{left : dir+"="+offset+"px"},
		{queue:true, duration:100, complete: function() {gallery_action = false;}}
	);
}

function delete_bookmark(id)
{
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "delete_bookmark", action_type : 'ajax', id: id}),
		dataType: "html",
		success: function(msg)
		{
			$("#bookmark-"+id).fadeOut(500);
		}
	});		
}

function delete_admin_alert(id, cnt)
{
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "delete_admin_alert", action_type : 'ajax', id: id}),
		dataType: "html",
		success: function(msg)
		{
			$("#alert-"+cnt).slideUp(500);
		}
	});		
}

function delete_recommendation(id, cnt)
{
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "delete_recommendation", action_type : 'ajax', id: id}),
		dataType: "html",
		success: function(msg)
		{
			$("#alert-"+cnt).slideUp(500);
		}
	});		
}

function recommend_email(type, id)
{
	var div_id = (div_id) ? "-" + div_id : "";
	
	var user_sender = document.getElementById('user_sender'+div_id).value;
	var email = document.getElementById('friends_email'+div_id).value;
	
	if(document.getElementById('use_username').value == 1)
	{
		if(user_sender.length < 3)
		{
			alert("Vaše korisničko ime je prekratko.");
			return false;
		}
	}
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false) 
	{
		alert('Email adresa je krivo upisana.');
		return false;
	}
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "recommend_email", action_type : 'ajax', type: type, id: id, email: email, user_sender : user_sender}),
		dataType: "html",
		success: function(msg)
		{
			$("#recommend_form"+div_id).slideUp(500, function(){$("#recommend_text"+div_id).slideDown(500);});
		}
	});		
}

function check_search(c)
{
	var q = document.getElementById('query');
	if(q.value == 'Ključne riječi...')
	{
		q.focus();
		return false;
	}
	
	return true;
}

var wassup_counter = 1;
function wassup_more()
{
	wassup_counter++;
	var new_start = 20 + 10 * wassup_counter;
	var type = document.getElementById('interact-type').value;
	
	$("#wassup_loader").show();
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "load_wassup", action_type : 'ajax', 'new_start' : new_start, 'type' : type}),
		dataType: "html",
		success: function(msg)
		{
			msg = ajax_retrieve_messages(msg);
			document.getElementById('wassup').innerHTML += msg[0];
			$("#wassup_loader").hide();
		}
	});	
}

function show_tags()
{
	$('.hiddentag').fadeIn(1000);
	$("#all-tags").fadeOut(1000);
}

menuopen_current_id = 0;
menuopen_status = 1;
function menuopen(id, seftitle)
{
	document.getElementById('menu').className = 'menu-' + seftitle;
	return;
	
	if($('#submenu' + id).css('display') != 'none')
		return;
		
	if((menuopen_current_id != id) && (menuopen_status == 2))
	{
		$("#submenu"+menuopen_current_id).stop().css('opacity', null).css('filter', null);
	}
	
	$(".submenu").hide();
	
	menuopen_status = 2;
	menuopen_current_id = id;

	$('#submenu' + id).fadeIn(200, function(){menuopen_status = 1;});
	document.getElementById('menu').className = 'menu-' + seftitle;
}

// most read | most comments
function tab(id)
{
	$("#most > div").css("display", "none");
	$("#"+id).css("display", 'block');
	
	document.getElementById('most_read-tab').className = '';
	document.getElementById('most_commented-tab').className = '';
	
	document.getElementById(id + '-tab').className = 'current';
}

function tabs(id)
{
	if (document.getElementById('tab' + id).style.display != 'none')
		return;

	document.getElementById('tab1').style.display = 'none';
	document.getElementById('tab2').style.display = 'none';
	
	document.getElementById('tab1h5').className = 'grey';
	document.getElementById('tab2h5').className = 'grey';
	
	document.getElementById('tab' + id + 'h5').className = 'green';
	
	$('#tab' + id).fadeIn();
}

function vote(vote, id, content)
{	
	var spanname = '#scores'+id;
	
	if(vote == 1)
	{
		var action = "score_up";
	}
	else
	{
		var action = "score_down";
	}
		
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : action, action_type : 'ajax', id : id, content : content}),
		dataType: "html",
		success: function(msg)
		{
			msg = ajax_retrieve_messages(msg);
			$(spanname).fadeOut("slow");
			$("#scores-val-"+id).html(msg[0]);
		}
	});
}

function recommend_tag_a(id, content)
{
	var action = '';

	if($("#tag-"+id).is('.used'))
	{
		action = 'unregister_tag';
		$("#tag-"+id).removeClass('used');
	}
	else
	{
		action = 'register_tag';
		$("#tag-"+id).addClass('used');
	}
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : action, action_type : 'ajax', tag: id, content_id : content}),
		dataType: "html",
		success: function(msg)
		{
		}
	});
}

function bookmark(type, id)
{
	var spanname = '#bookmark'+id;
		
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "save_bookmark", action_type : 'ajax', id : id, type : type}),
		dataType: "html",
		success: function(msg)
		{
			//$(spanname).fadeOut("slow");
			$(spanname).html("Spremljeno");
		}
	});
}


function recommend_to_friends(id)
{
	var spanname = '#recommend-to-friends-'+id;
		
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "do_recommend", action_type : 'ajax', id : id}),
		dataType: "html",
		success: function(msg)
		{
			$(spanname).fadeOut("slow");
		}
	});
}

function recommend_mark(id)
{
	if($('#recommend-user-' + id).hasClass('recommend-no')) 
	{
  	$('#recommend-user-' + id).removeClass('recommend-no');
  	$('#recommend-user-' + id).addClass('recommend-yes');
  }
	else
	{
  	$('#recommend-user-' + id).removeClass('recommend-yes');
  	$('#recommend-user-' + id).addClass('recommend-no');
  }
}

function recommend_do(id, type)
{
	var type = (type) ? type : '';
	
	var users = new Array();
	$(".recommend-yes").each(function(){
		var i = $(this).attr('id');
		i = i.split('-');
		i = i[i.length - 1];
		users[users.length] = i;
	});
	
	if(users.length == 0)
	{
		alert('Moraš izabrati barem jednog korisnika kojemu želiš preporučiti ovaj sadržaj.');
		return;
	}
	
	users = users.join(";");
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "do_recommend", action_type : 'ajax', id : id, users:users, type: type}),
		dataType: "html",
		success: function(msg)
		{
			$('#recommend-list').fadeOut("slow");
		}
	});	
}

function moderator_mark(id)
{
	if($('#recommend-user-' + id).hasClass('recommend-no')) 
	{
  	$('#recommend-user-' + id).removeClass('recommend-no');
  	$('#recommend-user-' + id).addClass('recommend-yes');
  }
	else
	{
  	$('#recommend-user-' + id).removeClass('recommend-yes');
  	$('#recommend-user-' + id).addClass('recommend-no');
  }
	moderator_do();
}

function moderator_do()
{
	var id = $("#ajax-group-id").val();
	
	var users = new Array();
	$(".recommend-yes").each(function(){
		var i = $(this).attr('id');
		i = i.split('-');
		i = i[i.length - 1];
		users[users.length] = i;
	});
	
	users = users.join(";");
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "moderators_save", action_type : 'ajax', id : id, users:users}),
		dataType: "html",
		success: function(msg)
		{
		}
	});	
}

var comment_replays = new Array();
function comment_replay(id, type)
{
	for(var i = 0; i < comment_replays.length; i++)
	{
		if(comment_replays[i] == id)
			return;
	}
	comment_replays[comment_replays.length] = id;
	$("#replay-comment-"+id).append('<textarea id="replay-comment-'+id+'-text"></textarea><p><input type="button" name="comment" class="submit" value="Pošalji" onclick="comment_do_replay('+id+', \''+type+'\');" /></p>');
}

function comment_do_replay(id, type)
{
	var txt = latin2_convert(document.getElementById('replay-comment-'+id+'-text').value);
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "comment_do_replay", action_type : 'ajax', id : id, txt : txt, type: type}),
		dataType: "html",
		success: function(msg)
		{
			msg = ajax_retrieve_messages(msg);
			document.getElementById("replay-comment-"+id).innerHTML = msg[0];
		}
	});	
}

function center(object) {
	var x,y;
	if (self.pageYOffset) // all except Explorer
	{
		y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	// Explorer 6 Strict
	{
		y = document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		y = document.body.scrollTop;
	}
	document.getElementById('popup').style.top = y+180 + 'px';
}

function setVisible(obj, grayout)
{
	var obj_id = obj;
	center(obj);

	obj = document.getElementById(obj);
	obj.style.display = 'none';
	obj.style.visibility = 'visible';
	
	grayOut(true, {'zindex':'50', 'bgcolor':'#000000', 'opacity':'70'});
	$("#darkenScreenObject").animate({'opacity' : 0.7}, 200, 'linear', function(){
		$("#"+obj_id).fadeIn(500);
	});
}

function closeDiv(obj, grayout)
{
	obj = document.getElementById(obj);
	obj.style.visibility = 'hidden';
	if(grayout == true)
	{
		grayOut(false, {});
	}
}

function grayOut(vis, options) {
  var options = options || {}; 
  var zindex = options.zindex || 50;
  //var opacity = options.opacity || 70;
	var opacity = 0;
	
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {

    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }   
    //set the shader to cover the entire page and make it visible.
		dark.style.opacity=0;
		/*                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')';
    */ 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';                          
  } else {
     dark.style.display='none';
  }
}

function mouseClickCoord(e)
{
	if (!e.pageX && e.clientX){
		// In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
		// while others are logical (offset).
		var zoom = 1;	
		var body = document.body;
		
		if (body.getBoundingClientRect) {
			var bound = body.getBoundingClientRect();
			zoom = (bound.right - bound.left)/body.clientWidth;
		}

		return {
			x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
			y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
		};
	}
	
	return {
		x: e.pageX,
		y: e.pageY
	};
}

function fire()
{
	var c = mouseClickCoord(document);
	alert(c.x + ", " + c.y);
}

var current_pitch_cal = 1;
var cal_width = 296;
function pitch_cal_next(total)
{
	var to_move = '-='+cal_width+'px';
	
	if(current_pitch_cal == total)
	{
		to_move = (total - 1) * cal_width;
		to_move = '+='+to_move+'px';
		current_pitch_cal = 0;
	}
	
	//alert(to_move + ": "+ current_pitch_cal+", "+total);
	
	$(".hor_switch_wrap_v").animate({left: to_move}, { duration: "slow" });
	current_pitch_cal++;
}

var current_top_menu = 1;
function doswitch(id, min, max)
{
	if(id != current_top_menu)
	{
		for(var i = min; i <= max; i++)
		{
			$("#image"+i).stop();
			$("#image"+i).css('opacity', 0); 
			$("#image"+i).hide();
			
			$("#title"+i).stop();
			$("#title"+i).css('opacity', 0); 
			$("#title"+i).hide();
		}
		
		$("#image"+id).show();
		$("#image"+id).animate({opacity: 1}, {duration: 300});
		
		$("#title"+id).show();
		$("#title"+id).animate({opacity: 1}, {duration: 300});
		current_top_menu = id;
	}
}

function poll_vote(instance)
{
	var cnt = 0;
	for (var i=0; i < document.forms['answers-'+instance].answer.length; i++)
	{
		if (document.forms['answers-'+instance].answer[i].checked)
		{
			cnt++;
			var ans = document.forms['answers-'+instance].answer[i].value;
		}
	}
	
	if(cnt > 0)
	{
		var pollid = document.getElementById('pollid-'+instance).value;
		
		$("#poll-vote-"+instance).hide();
		$("#poll-results-"+instance).hide();
		$("#poll-show-"+instance).hide();
		
		$.ajax({
			url: "index.php",
			type: "POST",
			data: ({action : 'poll_vote', action_type : 'ajax', answer : ans, pollid : pollid, instance: instance}),
			dataType: "html",
			success: function(msg)
			{
				msg = ajax_retrieve_messages(msg);
				$("#poll_cont-"+instance).attr('innerHTML', msg[0]);
			},	
		});
	}
	else
	{
		alert("Morate odabrati odgovor da bi mogli glasati!");
	}
}

function poll_results(instance)
{
	$("#poll-vote-"+instance).hide();
	$("#poll-results-"+instance).hide();
	$("#poll-show-"+instance).show();

	var pollid = document.getElementById('pollid-'+instance).value;
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'poll_results', action_type : 'ajax', pollid : pollid, instance: instance}),
		dataType: "html",
		cache:false,
		timeout:10000,
		success: function(msg)
		{
			msg = ajax_retrieve_messages(msg);
			$("#poll_cont-"+instance).attr('innerHTML', msg[0]);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			alert(textStatus + ", " + errorThrown);
		}
	});
}

function poll_show(instance)
{
	$("#poll-vote-"+instance).show();
	$("#poll-results-"+instance).show();
	$("#poll-show-"+instance).hide();

	var pollid = document.getElementById('pollid-'+instance).value;
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'poll_show', action_type : 'ajax', pollid : pollid, instance: instance}),
		dataType: "html",
		success: function(msg)
		{
			msg = ajax_retrieve_messages(msg);
			$("#poll_cont-"+instance).attr('innerHTML', msg[0]);
		}
	});
}

function check_profile()
{	
	var tmp = true;
	
	if(!field_check_text('firstname', 1))
	{
		tmp = false;
	}
	
	if(!field_check_text('lastname', 1))
	{
		tmp = false;
	}
	
	if(!check_email('email'))
	{
		tmp = false;
	}
	
	return tmp;
}

function add_friend(id)
{
	var divname = '#add_friend';
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "add_friend", action_type : 'ajax', id : id}),
		dataType: "html",
		success: function(msg)
		{
			$(divname).fadeOut("slow", function() {$("#friend_message").slideDown(200);});
		}
	});
}

function del_friend(id)
{
	var divname = '#del_friend';
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "del_friend", action_type : 'ajax', id : id}),
		dataType: "html",
		success: function(msg)
		{
			$(divname).fadeOut("slow", function() {$("#friend_message").slideDown(200);});
		}
	});
}

function approve_friend(id, v)
{
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "approve_friend", action_type : 'ajax', id : id, v : v}),
		dataType: "html",
		success: function(msg)
		{
			$("#approve-friend-"+id).fadeOut(300);	
			if (document.getElementById("inmessageapprove"))
				$("#inmessageapprove").fadeOut(300);	
		}
	});
}

function check_registration()
{	
	var tmp = true;
	
	if(!field_check_text('username', 3))
	{
		tmp = false;
	}
	
	if(!field_check_text('password', 3))
	{
		tmp = false;
	}
	
	if(!field_check_text('password2', 3))
	{
		tmp = false;
	}
	
	if(document.getElementById('password').value != document.getElementById('password2').value)
	{
		var error = "#d56900";
		document.getElementById('lpassword').style.color = error;
		document.getElementById('lpassword2').style.color = error;
		if(document.getElementById(i+'-error'))
			showdiv(i+'-error');
		
		tmp = false;
	}
	
	if(!check_email('email'))
	{
		tmp = false;
	}
	
	return tmp;
}

function key_change_status(e)
{
	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	
	if(KeyID == 13)
	{
		save_user_status();
		document.getElementById('status_save').focus();
	}
}

function save_user_status(interact)
{
	var interact = (interact) ? true : false;
	var user_status = document.getElementById('user_status').value;
	$("#current_user_status").fadeOut("fast");

	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'user_status', action_type : 'ajax', user_status : user_status}),
		dataType: "html",
		success: function(msg)
		{
			$("#current_user_status").stop();
			msg = ajax_retrieve_messages(msg);
			document.getElementById('user_status_holder').innerHTML = msg[0];
			if(document.getElementById('actions'))
			{
				if(!interact)
					document.getElementById('actions').innerHTML = msg[1] + document.getElementById('actions').innerHTML;
			}
			if(document.getElementById('wassup_holder'))
				document.getElementById('wassup_holder').innerHTML = msg[1] + document.getElementById('wassup_holder').innerHTML;

			$("#last-status-"+msg[2]).show(500);
			$('#status_edit').tooltip({track: true, delay: 200, showURL: false, showBody: " - ", fade: 350, extraClass: 'none' });
			$('#status_save').tooltip({track: true, delay: 200, showURL: false, showBody: " - ", fade: 350, extraClass: 'none' });
			$('#current_user_status').tooltip({track: true, delay: 200, showURL: false, showBody: " - ", fade: 350, extraClass: 'none' });
		}
	});
}

var status_status = 0;
function user_swap_status_change(id)
{
	if(id == 1)
	{
		$("#current_user_status").hide();
		$("#user_status_info").show();
		$("#user_status").focus();
		$("#status_edit").hide();
		$("#status_save").show();
		
		status_status = 1;
		
		$(document).bind("click",function(e)
		{
			if(status_status == 3)
			{
				var pos = $("#status_save").position();
				//alert(pos.left + ", " + pos.top + " " + e.pageX + ", " + e.pageY + " " + status_status);
				if((pos.left - 10 >= e.pageX) && (pos.left + 18 + 1 <= e.pageX) && (pos.top - 3 >= e.pageY) && (pos.top + 18 <= e.pageY))
				{
					$(document).unbind("click");
					save_user_status();
					status_status = 0;
				}
				else
				{
					$("#status_edit").show(); 
					$("#status_save").hide();
					$(document).unbind("click");
					$("#user_status_info").fadeOut(300, function(){$("#current_user_status").show();});
				}
				status_status = 0;
			}
			status_status++;
		});	
		
		status_status = 2;		
	}
	else if(id == 2)
	{
		$("#user_status_info").fadeOut(500, function() {$("#current_user_status").show(); $("#status_edit").show(); $("#status_save").hide();});
		$(document).unbind("click");			
	}
}

function check_blog()
{	
	var tmp = true;
	
	if(!field_check_text('ltitle', 1))
	{
		tmp = false;
	}
	
	if(!field_check_text('ltext', 1))
	{
		tmp = false;
	}
	
	return tmp;
}

function edit_gallery_image(id)
{
	$("#photo-gallery-buttons-"+id).fadeOut(200);
	$("#photo-gallery-image-title-"+id).slideUp(500, function(){$("#photo-gallery-image-edit-"+id).slideDown(500)});
}

function cancel_gallery_image(id)
{
	$("#photo-gallery-image-edit-"+id).slideUp(500, function(){$("#photo-gallery-image-title-"+id).slideDown(500); $("#photo-gallery-buttons-"+id).fadeIn(200);});
}

function save_gallery_image(id)
{
	var txt = $("#photo-gallery-image-editor-"+id).val();
	document.getElementById("photo-gallery-image-editor-"+id).disabled = true;
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'save_gallery_image', action_type : 'ajax', id : id, txt : txt}),
		dataType: "html",
		success: function(msg)
		{
			$("#photo-gallery-image-title-"+id).html('<p>'+txt+'</p>');
			$("#photo-gallery-image-edit-"+id).slideUp(500, function(){$("#photo-gallery-image-title-"+id).slideDown(500); $("#photo-gallery-buttons-"+id).fadeIn(200);});
			document.getElementById("photo-gallery-image-editor-"+id).disabled = false;
		}
	});	
}

function delete_gallery_image(id)
{
	$("#photo-gallery-image-"+id).remove();
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'delete_gallery_image', action_type : 'ajax', id : id}),
		dataType: "html",
		success: function(msg)
		{
			var msg = ajax_retrieve_messages(msg);
			$("#gallery-quota").html(msg[0]);
			if(msg[0] < 100)
			{
				$("#gallery_upload").show();
			}
		}
	});
}

function group_new()
{
	var name = $("#group-new-name").val();
	if(name.length < 3)
	{
		$("#group-new-error-short").slideDown(200);
		return;
	}
	$("#group-new-error").fadeOut(200);
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'group_new', action_type : 'ajax', name : name}),
		dataType: "html",
		success: function(msg)
		{
			var msg = ajax_retrieve_messages(msg);
			if(msg[0] == "success")
			{
				window.location.href="groups/"+msg[1];
			}
			else
			{
				if(msg[1] == "user")
					$("#group-new-error-user").slideDown(200);
				else if(msg[1] == "name")
					$("#group-new-error-name").slideDown(200);
			}
		}
	});
}

var microblogging_current = 'text';
function microblogging_switch(type)
{
	if(type == microblogging_current)
		return;
	
	if(microblogging_current == 'text')
		$("#microblogging-text").slideUp(300);
	if(microblogging_current == 'image')
		$("#microblogging-image").slideUp(300);
	if(microblogging_current == 'link')
		$("#microblogging-link").slideUp(300);
	if(microblogging_current == 'video')
		$("#microblogging-video").slideUp(300);
	
	$("#microblogging-"+type).slideDown(300);
	
	microblogging_current = type;
}

function microblogging_do()
{
	var cnt = "";
	var txt = $("#microblogging-share-text").val();
	if(microblogging_current == 'text')
		cnt = $("#microblogging-share-text").val();
	else if(microblogging_current == 'image')
		cnt = $("#microblogging-share-image-url").val();
	else if(microblogging_current == 'link')
		cnt = $("#microblogging-share-link").val();
	else if(microblogging_current == 'video')
		cnt = $("#microblogging-share-video").val();
	
	if(cnt.length < 1)
		return;
		
	var scores = document.getElementById("microblogging-use-scores").value;
		
	var content = $("#microblogging-content").val();
	var content_id = $("#microblogging-content-id").val();
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'microblogging_do', action_type : 'ajax', cnt : cnt, txt:txt, scores: scores, type: microblogging_current, content: content, content_id: content_id}),
		dataType: "html",
		success: function(msg)
		{
			var msg = ajax_retrieve_messages(msg);
			if(msg[0] == "success")
			{
				$("#microblogging-list").prepend(msg[2]);
				$("#last_microblog").html(msg[1]);
				$("#actions").prepend(msg[2]);
				
				$("#microblogging-share-text").val("");
				
				if(microblogging_current == 'text')
					$("#microblogging-share-text").val("");
				else if(microblogging_current == 'image')
					$("#microblogging-share-image-url").val("");
				else if(microblogging_current == 'link')
					$("#microblogging-share-link").val("");
				else if(microblogging_current == 'video')
					$("#microblogging-share-video").val("");
				$("a[rel^='prettyPhoto']").prettyPhoto();
			}
			else
			{
			}
		}
	});
}

function group_add_mod(uid, gid)
{
	var d = $("#user-fr-"+uid).html();
	$("#user-fr-"+uid).fadeOut(500, function() {$(this).remove();});
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'group_add_mod', action_type : 'ajax', uid : uid, gid : gid}),
		dataType: "html",
		success: function(msg)
		{
			var msg = ajax_retrieve_messages(msg);
			d = '<div id="user-mod-'+uid+'">'+d+'<a onclick="group_remove_mod('+uid+', '+gid+');"><img src="frontend/images/minus.gif" alt="Ukloni" /></a></div>';
			$("#group-moderators").append(d);
		}
	});	
}

function group_remove_mod(uid, gid)
{
	var d = $("#user-mod-"+uid).html();
	$("#user-mod-"+uid).fadeOut(500, function() {$(this).remove();});
	
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'group_remove_mod', action_type : 'ajax', uid : uid, gid : gid}),
		dataType: "html",
		success: function(msg)
		{
			var msg = ajax_retrieve_messages(msg);
			d = '<div id="user-fr-'+uid+'">'+d+'<a onclick="group_add_mod('+uid+', '+gid+');"><img src="frontend/images/minus.gif" alt="Ukloni" /></a></div>';
			$("#possible-moderators").append(d);
		}
	});	
}

wassup_current = 1;
function wassup_move(dir)
{
	$("#wassup-"+wassup_current).fadeOut(150, function(){
		wassup_current += dir;
		if(wassup_current < 1)
			wassup_current = 5;
		else if(wassup_current > 5)
			wassup_current = 1;
		$("#wassup-"+wassup_current).fadeIn(100);
	});	
}

function newsletter_signup()
{
	var email = $("#newsletter-email").val();
	var type_ = (document.getElementById("newsletter-type-1").checked) ? 1 : 2;

	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'newsletter_process', action_type : 'ajax', email: email, type : type_}),
		dataType: "html",
		success: function(msg)
		{
			var msg = ajax_retrieve_messages(msg);
			if(msg[1] == 1)
			{
				$("#newsletter-text").html(msg[0]);
				$("#newsletter-email-after").html(email);
				type_ = (type_ == 1) ? 'dnevni' : 'tjedni';
				$("#newsletter-type-after").html(type_);
				$("#newsletter-2").slideUp(300);
				$("#newsletter-3").slideDown(300);
			}
			else
			{
				$("#newsletter-2").slideUp(300);
				$("#newsletter-4").slideDown(300);
			}
		}
	});		
}

function gallery_slider(count, id)
{
	count = 100 - (3 / count) * 100;
	$('#slider-'+id).slider({
		min : 0,
		max: count,
		animate: 1000,
		slide: function(event, ui){$('#overview-hold-'+id).css('left', $('#overview-hold-'+id).width() * (ui.value / (-100)));}
	});
}

var current_poll = 1;
function poll_slider(dir)
{
	current_poll += dir;
	var total = $('.poll').size();
	if(current_poll < 1)
		current_poll = total;
	if(current_poll > total)
		current_poll = 1;
	
	$(".poll_slider").hide();
	
	$(".poll").slideUp(300);
	$("#poll-"+current_poll).slideDown(300, function(){$(".poll_slider").fadeIn(300)});
}

function delete_tag(id)
{
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'delete_tag', action_type : 'ajax', id:id}),
		dataType: "html",
		success: function(msg)
		{
			$("#tag-edit-"+id).fadeOut(500);
		}
	});	
}

function contact_admin()
{
	$('#contact-admin').slideUp(500);
	$('#contact-admin-message').slideDown();
	setTimeout(function(){$('#contact-admin-message').fadeOut(500);}, 2000);	
	
	var group = $("#ajax-group-id").val();
	var msg = $("#contact-admin-text").val();
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'contact_admin', action_type : 'ajax', group:group, msg:msg}),
		dataType: "html",
		success: function(msg)
		{
			
		}
	});	
}

function report_content()
{
	$('#report-content').slideUp(500);
	$('#report-content-message').slideDown();
	setTimeout(function(){$('#report-content-message').fadeOut(500);}, 2000);	
	
	var group = $("#ajax-group-id").val();
	var msg = $("#report-content-text").val();
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : 'report_content', action_type : 'ajax', group:group, msg:msg}),
		dataType: "html",
		success: function(msg)
		{
			
		}
	});	
}

/*
* hoverFlow - A Solution to Animation Queue Buildup in jQuery
* Version 1.00
*
* Copyright (c) 2009 Ralf Stoltze, http://www.2meter3.de/code/hoverFlow/
* Dual-licensed under the MIT and GPL licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function($){$.fn.hoverFlow=function(c,d,e,f,g){if($.inArray(c,['mouseover','mouseenter','mouseout','mouseleave'])==-1){return this}var h=typeof e==='object'?e:{complete:g||!g&&f||$.isFunction(e)&&e,duration:e,easing:g&&f||f&&!$.isFunction(f)&&f};h.queue=false;var i=h.complete;h.complete=function(){$(this).dequeue();if($.isFunction(i)){i.call(this)}};return this.each(function(){var b=$(this);if(c=='mouseover'||c=='mouseenter'){b.data('jQuery.hoverFlow',true)}else{b.removeData('jQuery.hoverFlow')}b.queue(function(){var a=(c=='mouseover'||c=='mouseenter')?b.data('jQuery.hoverFlow')!==undefined:b.data('jQuery.hoverFlow')===undefined;if(a){b.animate(d,h)}else{b.queue([])}})})}})(jQuery);

/* ------------------------------------------------------------------------
	Class: prettyPhoto
	Use: Lightbox clone for jQuery
	Author: Stephane Caron (http://www.no-margin-for-errors.com)
	Version: 2.4.3
------------------------------------------------------------------------- */

var $pp_pic_holder;var $ppt;(function(A){A.fn.prettyPhoto=function(W){var E=true;var K=false;var O=[];var D=0;var R;var S;var V;var Y;var F="image";var Z;var M=G();A(window).scroll(function(){M=G();C()});A(window).resize(function(){C();U()});A(document).keypress(function(c){switch(c.keyCode){case 37:if(D==1){return }N("previous");break;case 39:if(D==setCount){return }N("next");break;case 27:L();break}});W=jQuery.extend({animationSpeed:"normal",padding:40,opacity:0.8,showTitle:true,allowresize:true,counter_separator_label:"/",theme:"light_rounded",callback:function(){}},W);if(A.browser.msie&&A.browser.version==6){W.theme="light_square"}A(this).each(function(){var e=false;var d=false;var f=0;var c=0;O[O.length]=this;A(this).bind("click",function(){J(this);return false})});function J(c){Z=A(c);theRel=Z.attr("rel");galleryRegExp=/\[(?:.*)\]/;theGallery=galleryRegExp.exec(theRel);isSet=false;setCount=0;b();for(i=0;i<O.length;i++){if(A(O[i]).attr("rel").indexOf(theGallery)!=-1){setCount++;if(setCount>1){isSet=true}if(A(O[i]).attr("href")==Z.attr("href")){D=setCount;arrayPosition=i}}}X();$pp_pic_holder.find("p.currentTextHolder").text(D+W.counter_separator_label+setCount);C();A("#pp_full_res").hide();$pp_pic_holder.find(".pp_loaderIcon").show()}showimage=function(f,c,j,h,g,d,e){A(".pp_loaderIcon").hide();if(A.browser.opera){windowHeight=window.innerHeight;windowWidth=window.innerWidth}else{windowHeight=A(window).height();windowWidth=A(window).width()}$pp_pic_holder.find(".pp_content").animate({height:g},W.animationSpeed);projectedTop=M.scrollTop+((windowHeight/2)-(h/2));if(projectedTop<0){projectedTop=0+$pp_pic_holder.find(".ppt").height()}$pp_pic_holder.animate({top:projectedTop,left:((windowWidth/2)-(j/2)),width:j},W.animationSpeed,function(){$pp_pic_holder.width(j);$pp_pic_holder.find(".pp_hoverContainer,#fullResImage").height(c).width(f);$pp_pic_holder.find("#pp_full_res").fadeIn(W.animationSpeed,function(){A(this).find("object,embed").css("visibility","visible")});I();if(e){A("a.pp_expand,a.pp_contract").fadeIn(W.animationSpeed)}})};function I(){if(isSet&&F=="image"){$pp_pic_holder.find(".pp_hoverContainer").fadeIn(W.animationSpeed)}else{$pp_pic_holder.find(".pp_hoverContainer").hide()}$pp_pic_holder.find(".pp_details").fadeIn(W.animationSpeed);if(W.showTitle&&hasTitle){$ppt.css({top:$pp_pic_holder.offset().top-22,left:$pp_pic_holder.offset().left+(W.padding/2),display:"none"});$ppt.fadeIn(W.animationSpeed)}}function Q(){$pp_pic_holder.find(".pp_hoverContainer,.pp_details").fadeOut(W.animationSpeed);$pp_pic_holder.find("#pp_full_res object,#pp_full_res embed").css("visibility","hidden");$pp_pic_holder.find("#pp_full_res").fadeOut(W.animationSpeed,function(){A(".pp_loaderIcon").show();a()});$ppt.fadeOut(W.animationSpeed)}function N(c){if(c=="previous"){arrayPosition--;D--}else{arrayPosition++;D++}if(!E){E=true}Q();A("a.pp_expand,a.pp_contract").fadeOut(W.animationSpeed,function(){A(this).removeClass("pp_contract").addClass("pp_expand")})}function L(){$pp_pic_holder.find("object,embed").css("visibility","hidden");A("div.pp_pic_holder,div.ppt").fadeOut(W.animationSpeed);A("div.pp_overlay").fadeOut(W.animationSpeed,function(){A("div.pp_overlay,div.pp_pic_holder,div.ppt").remove();if(A.browser.msie&&A.browser.version==6){A("select").css("visibility","visible")}W.callback()});E=true}function H(){if(D==setCount){$pp_pic_holder.find("a.pp_next").css("visibility","hidden");$pp_pic_holder.find("a.pp_arrow_next").addClass("disabled").unbind("click")}else{$pp_pic_holder.find("a.pp_next").css("visibility","visible");$pp_pic_holder.find("a.pp_arrow_next.disabled").removeClass("disabled").bind("click",function(){N("next");return false})}if(D==1){$pp_pic_holder.find("a.pp_previous").css("visibility","hidden");$pp_pic_holder.find("a.pp_arrow_previous").addClass("disabled").unbind("click")}else{$pp_pic_holder.find("a.pp_previous").css("visibility","visible");$pp_pic_holder.find("a.pp_arrow_previous.disabled").removeClass("disabled").bind("click",function(){N("previous");return false})}$pp_pic_holder.find("p.currentTextHolder").text(D+W.counter_separator_label+setCount);Z=(isSet)?A(O[arrayPosition]):Z;b();if(Z.attr("title")){$pp_pic_holder.find(".pp_description").show().html(unescape(Z.attr("title")))}else{$pp_pic_holder.find(".pp_description").hide().text("")}if(Z.find("img").attr("alt")&&W.showTitle){hasTitle=true;$ppt.html(unescape(Z.find("img").attr("alt")))}else{hasTitle=false}}function P(d,c){hasBeenResized=false;T(d,c);imageWidth=d;imageHeight=c;windowHeight=A(window).height();windowWidth=A(window).width();if(((Y>windowWidth)||(V>windowHeight))&&E&&W.allowresize&&!K){hasBeenResized=true;notFitting=true;while(notFitting){if((Y>windowWidth)){imageWidth=(windowWidth-200);imageHeight=(c/d)*imageWidth}else{if((V>windowHeight)){imageHeight=(windowHeight-200);imageWidth=(d/c)*imageHeight}else{notFitting=false}}V=imageHeight;Y=imageWidth}T(imageWidth,imageHeight)}return{width:imageWidth,height:imageHeight,containerHeight:V,containerWidth:Y,contentHeight:R,contentWidth:S,resized:hasBeenResized}}function T(d,c){$pp_pic_holder.find(".pp_details").width(d).find(".pp_description").width(d-parseFloat($pp_pic_holder.find("a.pp_close").css("width")));R=c+$pp_pic_holder.find(".pp_details").height()+parseFloat($pp_pic_holder.find(".pp_details").css("marginTop"))+parseFloat($pp_pic_holder.find(".pp_details").css("marginBottom"));S=d;V=R+$pp_pic_holder.find(".ppt").height()+$pp_pic_holder.find(".pp_top").height()+$pp_pic_holder.find(".pp_bottom").height();Y=d+W.padding}function b(){if(Z.attr("href").match(/youtube\.com\/watch/i)){F="youtube"}else{if(Z.attr("href").indexOf(".mov")!=-1){F="quicktime"}else{if(Z.attr("href").indexOf(".swf")!=-1){F="flash"}else{if(Z.attr("href").indexOf("iframe")!=-1){F="iframe"}else{F="image"}}}}}function C(){if($pp_pic_holder){if($pp_pic_holder.size()==0){return }}else{return }if(A.browser.opera){windowHeight=window.innerHeight;windowWidth=window.innerWidth}else{windowHeight=A(window).height();windowWidth=A(window).width()}if(E){$pHeight=$pp_pic_holder.height();$pWidth=$pp_pic_holder.width();$tHeight=$ppt.height();projectedTop=(windowHeight/2)+M.scrollTop-($pHeight/2);if(projectedTop<0){projectedTop=0+$tHeight}$pp_pic_holder.css({top:projectedTop,left:(windowWidth/2)+M.scrollLeft-($pWidth/2)});$ppt.css({top:projectedTop-$tHeight,left:(windowWidth/2)+M.scrollLeft-($pWidth/2)+(W.padding/2)})}}function a(){H();if(F=="image"){imgPreloader=new Image();nextImage=new Image();if(isSet&&D>setCount){nextImage.src=A(O[arrayPosition+1]).attr("href")}prevImage=new Image();if(isSet&&O[arrayPosition-1]){prevImage.src=A(O[arrayPosition-1]).attr("href")}pp_typeMarkup='<img id="fullResImage" src="" />';$pp_pic_holder.find("#pp_full_res")[0].innerHTML=pp_typeMarkup;$pp_pic_holder.find(".pp_content").css("overflow","hidden");$pp_pic_holder.find("#fullResImage").attr("src",Z.attr("href"));imgPreloader.onload=function(){var c=P(imgPreloader.width,imgPreloader.height);imgPreloader.width=c.width;imgPreloader.height=c.height;showimage(imgPreloader.width,imgPreloader.height,c.containerWidth,c.containerHeight,c.contentHeight,c.contentWidth,c.resized)};imgPreloader.src=Z.attr("href")}else{movie_width=(parseFloat(B("width",Z.attr("href"))))?B("width",Z.attr("href")):"425";movie_height=(parseFloat(B("height",Z.attr("href"))))?B("height",Z.attr("href")):"344";if(movie_width.indexOf("%")!=-1||movie_height.indexOf("%")!=-1){movie_height=(A(window).height()*parseFloat(movie_height)/100)-100;movie_width=(A(window).width()*parseFloat(movie_width)/100)-100;parsentBased=true}else{movie_height=parseFloat(movie_height);movie_width=parseFloat(movie_width)}if(F=="quicktime"){movie_height+=13}correctSizes=P(movie_width,movie_height);if(F=="youtube"){pp_typeMarkup='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes.width+'" height="'+correctSizes.height+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.youtube.com/v/'+B("v",Z.attr("href"))+'" /><embed src="http://www.youtube.com/v/'+B("v",Z.attr("href"))+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes.width+'" height="'+correctSizes.height+'"></embed></object>'}else{if(F=="quicktime"){pp_typeMarkup='<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="'+correctSizes.height+'" width="'+correctSizes.width+'"><param name="src" value="'+Z.attr("href")+'"><param name="autoplay" value="true"><param name="type" value="video/quicktime"><embed src="'+Z.attr("href")+'" height="'+correctSizes.height+'" width="'+correctSizes.width+'" autoplay="true" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>'}else{if(F=="flash"){flash_vars=Z.attr("href");flash_vars=flash_vars.substring(Z.attr("href").indexOf("flashvars")+10,Z.attr("href").length);filename=Z.attr("href");filename=filename.substring(0,filename.indexOf("?"));pp_typeMarkup='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes.width+'" height="'+correctSizes.height+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="'+filename+"?"+flash_vars+'" /><embed src="'+filename+"?"+flash_vars+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes.width+'" height="'+correctSizes.height+'"></embed></object>'}else{if(F=="iframe"){movie_url=Z.attr("href");movie_url=movie_url.substr(0,movie_url.indexOf("iframe")-1);pp_typeMarkup='<iframe src ="'+movie_url+'" width="'+(correctSizes.width-10)+'" height="'+(correctSizes.height-10)+'" frameborder="no"></iframe>'}}}}$pp_pic_holder.find("#pp_full_res")[0].innerHTML=pp_typeMarkup;showimage(correctSizes.width,correctSizes.height,correctSizes.containerWidth,correctSizes.containerHeight,correctSizes.contentHeight,correctSizes.contentWidth,correctSizes.resized)}}function G(){if(self.pageYOffset){scrollTop=self.pageYOffset;scrollLeft=self.pageXOffset}else{if(document.documentElement&&document.documentElement.scrollTop){scrollTop=document.documentElement.scrollTop;scrollLeft=document.documentElement.scrollLeft}else{if(document.body){scrollTop=document.body.scrollTop;scrollLeft=document.body.scrollLeft}}}return{scrollTop:scrollTop,scrollLeft:scrollLeft}}function U(){A("div.pp_overlay").css({height:A(document).height(),width:A(window).width()})}function X(){toInject="";toInject+="<div class='pp_overlay'></div>";if(F=="image"){pp_typeMarkup='<img id="fullResImage" src="" />'}else{pp_typeMarkup=""}toInject+='<div class="pp_pic_holder"><div class="pp_top"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div><div class="pp_content"><a href="#" class="pp_expand" title="Expand the image">Expand</a><div class="pp_loaderIcon"></div><div class="pp_hoverContainer"><a class="pp_next" href="#">next</a><a class="pp_previous" href="#">previous</a></div><div id="pp_full_res">'+pp_typeMarkup+'</div><div class="pp_details clearfix"><a class="pp_close" href="#">Close</a><p class="pp_description"></p><div class="pp_nav"><a href="#" class="pp_arrow_previous">Previous</a><p class="currentTextHolder">0'+W.counter_separator_label+'0</p><a href="#" class="pp_arrow_next">Next</a></div></div></div><div class="pp_bottom"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div></div>';toInject+='<div class="ppt"></div>';A("body").append(toInject);$pp_pic_holder=A(".pp_pic_holder");$ppt=A(".ppt");A("div.pp_overlay").css("height",A(document).height()).bind("click",function(){L()});$pp_pic_holder.css({opacity:0}).addClass(W.theme);A("a.pp_close").bind("click",function(){L();return false});A("a.pp_expand").bind("click",function(){$this=A(this);if($this.hasClass("pp_expand")){$this.removeClass("pp_expand").addClass("pp_contract");E=false}else{$this.removeClass("pp_contract").addClass("pp_expand");E=true}Q();$pp_pic_holder.find(".pp_hoverContainer, #pp_full_res, .pp_details").fadeOut(W.animationSpeed,function(){a()});return false});$pp_pic_holder.find(".pp_previous, .pp_arrow_previous").bind("click",function(){N("previous");return false});$pp_pic_holder.find(".pp_next, .pp_arrow_next").bind("click",function(){N("next");return false});$pp_pic_holder.find(".pp_hoverContainer").css({"margin-left":W.padding/2});if(!isSet){$pp_pic_holder.find(".pp_hoverContainer,.pp_nav").hide()}if(A.browser.msie&&A.browser.version==6){A("body").addClass("ie6");A("select").css("visibility","hidden")}A("div.pp_overlay").css("opacity",0).fadeTo(W.animationSpeed,W.opacity,function(){$pp_pic_holder.css("opacity",0).fadeIn(W.animationSpeed,function(){$pp_pic_holder.attr("style","left:"+$pp_pic_holder.css("left")+";top:"+$pp_pic_holder.css("top")+";");a()})})}};function B(E,D){E=E.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var C="[\\?&]"+E+"=([^&#]*)";var G=new RegExp(C);var F=G.exec(D);if(F==null){return""}else{return F[1]}}})(jQuery);


/* engine */
function engine_check_unique(id)
{
	showdiv('ajax_icon_'+id);
	var val = document.getElementById(id).value;
	$.ajax({
		type: "POST",
		url: "index.php",
		data: "action_type=ajax&action=check_unique&id="+id+"&value="+val,
		success: function(msg)
		{
			msg = ajax_retrieve_messages(msg);
			if(msg[0] != "unique")
			{
				document.getElementById("ajax_message_"+id).innerHTML = msg[0];
			}
			else if(msg[0] == "unique")
			{
				document.getElementById("ajax_message_"+id).innerHTML = "";
			}
			hidediv('ajax_icon_'+id);
		}
	});	
}

function check_uncheck_all(id, checks)
{
	var checked_status = id.checked;
	$("."+checks).each(function()
	{
		this.checked = checked_status;
	});
}

function delete_confirmation(txt)
{
	if(confirm(txt))
		return true;
	else
		return false;
}

function message_box_hide(id)
{
	setTimeout(function() {message_box_hide_do(id);}, 2000);
}

function message_box_hide_do(id)
{
	$('#'+id).fadeOut(2000);
}

function engine_dialog()
{
	$("#dialog").show();
	$("#dialog").dialog("open");

	return false;
}

function engine_check_form_fields(fields)
{
	
	if(fields == "none")
		return true;

	var pass = true;
	fields = fields.split("|");
	for(var i = 0; i < fields.length; i++)
	{
		if(f == '')
			continue;
			
		var p = true;
			
		var f = fields[i];
		f = f.split(",");
		
		if(f[1] == 'varchar')
		{
			if(document.getElementById(f[0]).value == '')
			{
				p = false;
				$('#l'+f[0]).addClass("field-error");
			}
			else
			{
				p = true;
				$('#l'+f[0]).removeClass("field-error");
			}
		}
		else if(f[1] == 'select')
		{
			if(document.getElementById(f[0]).value == '')
			{
				p = false;
				$('#l'+f[0]).addClass("field-error");
			}
			else
			{
				p = true;
				$('#l'+f[0]).removeClass("field-error");
			}
		}
			
		if(p == false)
			pass = false;
	}

	return pass;
}

function textCounter(field, maxlimit) 
{
	if (maxlimit == 0) 
		document.getElementById('charstxt').innerHTML = ' (' + (field.value.length) + ')';
	else if (field.value.length > maxlimit > 0)
		field.value = field.value.substring(0, maxlimit);
	else 
		document.getElementById('chars').innerHTML = ' (' + (maxlimit - field.value.length) + ')';
}

function genSEF(from,to) 
{ 
	var str = deLocalize(from.value);
	str = str.toLowerCase();
	str = str.replace(/[^a-z 0-9]+/g,'');
	str = str.replace(/\s+/g, "-");		
	to.value = str;
}
		
function deLocalize(inStr) 
{
    var outStr = inStr;
    outStr = outStr.replace(/[ćĆ]/g, 'c');
    outStr = outStr.replace(/[čČ]/g, 'c');
    outStr = outStr.replace(/[šŠ]/g, 's');
    outStr = outStr.replace(/[žŽ]/g, 'z');
    outStr = outStr.replace(/[đĐ]/g, 'dj');
    return outStr;
}
		
function spaces_restrict(x) 
{
	if (window.event)
		var key = window.event.keyCode;
	else if (x)
		key = x.which;
	else
		return true;
	var keychar = String.fromCharCode(key);
	keychar.toLowerCase();
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
		return true;
	else if ((("abcdefghijklmnopqrstuvwxyz0123456789,").indexOf(keychar) > -1))
		return true;
	else
		return false;
}

function restrict_alphanumeric(field)
{
	var v = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
	var w = "";
	for(i=0; i < field.value.length; i++)
	{
		x = field.value.charAt(i);
		if(v.indexOf(x,0) != -1)
			w += x;
	}
	field.value = w;
}

function restrict_numeric(field)
{
	var v = "0123456789.,";
	var w = "";
	for(i=0; i < field.value.length; i++)
	{
		x = field.value.charAt(i);
		if(v.indexOf(x,0) != -1)
			w += x;
	}
	field.value = w;
}

function restrict_alpha(field)
{
	var v = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var w = "";
	for(i=0; i < field.value.length; i++)
	{
		x = field.value.charAt(i);
		if(v.indexOf(x,0) != -1)
			w += x;
	}
	field.value = w;
}

function hidediv(id) 
{
	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
}

function showdiv(id) 
{
	//safe function to show an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = '';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = '';
		}
		else { // IE 4
			document.all.id.style.display = '';
		}
	}
}

function field_check_text(i, len, color_ok, color_error)
{
	var f = null;
	var error = (color_error) ? color_error : "#d56900";
	var ok = (color_ok) ? color_ok : "#303030";
	
	len = len || 1;
	
	f = document.getElementById(i);
	if(!f)
		return false;
		
	if(f.value.length < len)
	{
		document.getElementById('l'+i).style.color = error;
		if(document.getElementById(i+'-error'))
			showdiv(i+'-error');
		return false;
	}
	else
	{
		document.getElementById('l'+i).style.color = ok;
		if(document.getElementById(i+'-error'))
			hidediv(i+'-error');
	}
		
	return true;
}

function field_check_select(i, val, color_ok, color_error)
{
	var f = null;
	var error = (color_error) ? color_error : "#d56900";
	var ok = (color_ok) ? color_ok : "#303030";
	
	f = document.getElementById(i);
	if(!f)
		return false;
		
	if(f.value == val)
	{
		document.getElementById('l'+i).style.color = error;
		if(document.getElementById(i+'-error'))
			showdiv(i+'-error');
		return false;
	}
	else
	{
		document.getElementById('l'+i).style.color = ok;
		if(document.getElementById(i+'-error'))
			hidediv(i+'-error');
	}
		
	return true;
}

function create_ajax_object()
{
	var xmlHttp;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				alert("Error!");
				return false;
			}
		}
	}
	return xmlHttp;
}

function ajax_retrieve_messages(str)
{
	var i = 0;
	var counter = 0;
	var msgs = [];
	
	counter = str.indexOf('[<ajax_message>', counter)
	while(counter >= 0)
	{
		var start_m = counter;
		var end_m = str.indexOf('</ajax_message>]', counter);
		var message = str.substring(start_m + 15, end_m);
		msgs[i] = message;
		i++;
		counter = str.indexOf('[<ajax_message>', end_m)
	}
	
	return msgs;
}

function latin2_convert(str)
{
	str = str.replace(/=/g, '*eq*');
	str = str.replace(/&/g, '*amp*');
	str = str.replace(/\n/g, '*br*');
	str = str.replace(/č/g, '[ch]');
	str = str.replace(/ć/g, '[cs]');
	str = str.replace(/š/g, '[s]');
	str = str.replace(/đ/g, '[d]');
	str = str.replace(/ž/g, '[z]');
	str = str.replace(/Č/g, '[CH]');
	str = str.replace(/Ć/g, '[CS]');
	str = str.replace(/Š/g, '[S]');
	str = str.replace(/Đ/g, '[D]');
	str = str.replace(/Ž/g, '[Z]');
	return str;
}

function getScrollXY() 
{
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function findPosX(obj)
{
	obj = document.getElementById(obj);
	if(obj == null)
		return 0;

	var curleft = 0;
	if(obj.offsetParent)
		while(1) 
		{
			curleft += obj.offsetLeft;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	obj = document.getElementById(obj);
	if(obj == null)
		return 0;
		
	var curtop = 0;
	if(obj.offsetParent)
		while(1)
		{
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
	return curtop;
}


var scroll_delay_timer;
var scroll_direction = 0;
var last_y_scroller_value = -100;

function scroll_window_to(id)
{
	var scrolls = getScrollXY();
	var y_scroll = scrolls[1];
	var scroll_to = findPosY(id);
	
	var move = 20;
	
	if(scroll_direction == 0)
	{
		if(scroll_to < y_scroll)
		{
			scroll_direction = -1;
		}
		else if(scroll_to > y_scroll)
		{
			scroll_direction = 1;
		}
	}

	if(scroll_direction == 1)
	{	
		if(scroll_to <= y_scroll)
		{
			scroll_direction = 0;
		}
	}
	else if(scroll_direction == -1)
	{
		if(scroll_to >= y_scroll)
		{
			scroll_direction = 0;
		}
	}	
	
	if((scroll_direction == 0) || (last_y_scroller_value == y_scroll))
	{
		clearTimeout(scroll_delay_timer);
		last_y_scroller_value = -100;
	}
	else
	{
		last_y_scroller_value = y_scroll;
		window.scrollBy(0,move * scroll_direction); // horizontal and vertical scroll increments
  	scroll_delay_timer = setTimeout(function() {scroll_window_to(id);},10); // scrolls every 100 milliseconds
  }
}

function check_email(id) 
{
	var error = "#d56900";
	var ok = "#303030";
	
	var email = document.getElementById(id);
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email.value))
	{
		document.getElementById('l'+id).style.color = error;
		if(document.getElementById(i+'-error'))
			showdiv(i+'-error');
		return false;
	}
	else
	{
		document.getElementById('l'+id).style.color = ok;
		if(document.getElementById(i+'-error'))
			hidediv(i+'-error');
		return true;
	}
}

/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(8($){j e={},9,m,B,A=$.2u.2g&&/29\\s(5\\.5|6\\.)/.1M(1H.2t),M=12;$.k={w:12,1h:{Z:25,r:12,1d:19,X:"",G:15,E:15,16:"k"},2s:8(){$.k.w=!$.k.w}};$.N.1v({k:8(a){a=$.1v({},$.k.1h,a);1q(a);g 2.F(8(){$.1j(2,"k",a);2.11=e.3.n("1g");2.13=2.m;$(2).24("m");2.22=""}).21(1e).1U(q).1S(q)},H:A?8(){g 2.F(8(){j b=$(2).n(\'Y\');4(b.1J(/^o\\(["\']?(.*\\.1I)["\']?\\)$/i)){b=1F.$1;$(2).n({\'Y\':\'1D\',\'1B\':"2r:2q.2m.2l(2j=19, 2i=2h, 1p=\'"+b+"\')"}).F(8(){j a=$(2).n(\'1o\');4(a!=\'2f\'&&a!=\'1u\')$(2).n(\'1o\',\'1u\')})}})}:8(){g 2},1l:A?8(){g 2.F(8(){$(2).n({\'1B\':\'\',Y:\'\'})})}:8(){g 2},1x:8(){g 2.F(8(){$(2)[$(2).D()?"l":"q"]()})},o:8(){g 2.1k(\'28\')||2.1k(\'1p\')}});8 1q(a){4(e.3)g;e.3=$(\'<t 16="\'+a.16+\'"><10></10><t 1i="f"></t><t 1i="o"></t></t>\').27(K.f).q();4($.N.L)e.3.L();e.m=$(\'10\',e.3);e.f=$(\'t.f\',e.3);e.o=$(\'t.o\',e.3)}8 7(a){g $.1j(a,"k")}8 1f(a){4(7(2).Z)B=26(l,7(2).Z);p l();M=!!7(2).M;$(K.f).23(\'W\',u);u(a)}8 1e(){4($.k.w||2==9||(!2.13&&!7(2).U))g;9=2;m=2.13;4(7(2).U){e.m.q();j a=7(2).U.1Z(2);4(a.1Y||a.1V){e.f.1c().T(a)}p{e.f.D(a)}e.f.l()}p 4(7(2).18){j b=m.1T(7(2).18);e.m.D(b.1R()).l();e.f.1c();1Q(j i=0,R;(R=b[i]);i++){4(i>0)e.f.T("<1P/>");e.f.T(R)}e.f.1x()}p{e.m.D(m).l();e.f.q()}4(7(2).1d&&$(2).o())e.o.D($(2).o().1O(\'1N://\',\'\')).l();p e.o.q();e.3.P(7(2).X);4(7(2).H)e.3.H();1f.1L(2,1K)}8 l(){B=S;4((!A||!$.N.L)&&7(9).r){4(e.3.I(":17"))e.3.Q().l().O(7(9).r,9.11);p e.3.I(\':1a\')?e.3.O(7(9).r,9.11):e.3.1G(7(9).r)}p{e.3.l()}u()}8 u(c){4($.k.w)g;4(c&&c.1W.1X=="1E"){g}4(!M&&e.3.I(":1a")){$(K.f).1b(\'W\',u)}4(9==S){$(K.f).1b(\'W\',u);g}e.3.V("z-14").V("z-1A");j b=e.3[0].1z;j a=e.3[0].1y;4(c){b=c.2o+7(9).E;a=c.2n+7(9).G;j d=\'1w\';4(7(9).2k){d=$(C).1r()-b;b=\'1w\'}e.3.n({E:b,14:d,G:a})}j v=z(),h=e.3[0];4(v.x+v.1s<h.1z+h.1n){b-=h.1n+20+7(9).E;e.3.n({E:b+\'1C\'}).P("z-14")}4(v.y+v.1t<h.1y+h.1m){a-=h.1m+20+7(9).G;e.3.n({G:a+\'1C\'}).P("z-1A")}}8 z(){g{x:$(C).2e(),y:$(C).2d(),1s:$(C).1r(),1t:$(C).2p()}}8 q(a){4($.k.w)g;4(B)2c(B);9=S;j b=7(2);8 J(){e.3.V(b.X).q().n("1g","")}4((!A||!$.N.L)&&b.r){4(e.3.I(\':17\'))e.3.Q().O(b.r,0,J);p e.3.Q().2b(b.r,J)}p J();4(7(2).H)e.3.1l()}})(2a);',62,155,'||this|parent|if|||settings|function|current||||||body|return|||var|tooltip|show|title|css|url|else|hide|fade||div|update||blocked|||viewport|IE|tID|window|html|left|each|top|fixPNG|is|complete|document|bgiframe|track|fn|fadeTo|addClass|stop|part|null|append|bodyHandler|removeClass|mousemove|extraClass|backgroundImage|delay|h3|tOpacity|false|tooltipText|right||id|animated|showBody|true|visible|unbind|empty|showURL|save|handle|opacity|defaults|class|data|attr|unfixPNG|offsetHeight|offsetWidth|position|src|createHelper|width|cx|cy|relative|extend|auto|hideWhenEmpty|offsetTop|offsetLeft|bottom|filter|px|none|OPTION|RegExp|fadeIn|navigator|png|match|arguments|apply|test|http|replace|br|for|shift|click|split|mouseout|jquery|target|tagName|nodeType|call||mouseover|alt|bind|removeAttr|200|setTimeout|appendTo|href|MSIE|jQuery|fadeOut|clearTimeout|scrollTop|scrollLeft|absolute|msie|crop|sizingMethod|enabled|positionLeft|AlphaImageLoader|Microsoft|pageY|pageX|height|DXImageTransform|progid|block|userAgent|browser'.split('|'),0,{}))

/*
 * Lightweight RTE - jQuery Plugin
 * Copyright (c) 2009 Andrey Gayvoronsky - http://www.gayvoronsky.com
 */
//jQuery.fn.rte = function(options, editors) {
//	if(editors == undefined || editors.constructor != Object)
//		editors = new Object();
//}

var RTE_EDITORS = new Array();

jQuery.fn.rte = function(options) {
	$(this).each( function() {
		var p = new lwRTE (this, options); 
		RTE_EDITORS[RTE_EDITORS.length] = p;
		return p;
	});
}

var lwRTE = function (textarea, options) {
	this.css_url	= options.css;
	this.css_class	= options.frame_class;
	this.base_url	= options.base_url;
	this.width		= options.width || '100%';
	this.height		= options.height || 350;

	this.iframe		= null;
	this.iframe_doc	= null;
	this.textarea	= null;
	this.event		= null;
	this.range		= null;
	this.toolbars	= {rte: '', html : ''};
	this.controls	= {rte: {disable: {hint: 'Source editor'}}, html: {enable: {hint: 'Visual editor'}}};

	$.extend(this.controls.rte, options.controls_rte);
	$.extend(this.controls.html, options.controls_html);

	if(document.designMode || document.contentEditable) {
		$(textarea).wrap($('<div></div>').addClass('rte-zone').width(this.width));
		this.textarea	= textarea;
		this.enable_design_mode();
	}
}

lwRTE.prototype.editor_cmd = function(command, args) {
	this.iframe.contentWindow.focus();
	try {
		this.iframe_doc.execCommand(command, false, args);
	} catch(e) {
		console.log(e)
	}
	this.iframe.contentWindow.focus();
}

lwRTE.prototype.get_toolbar = function() {
	var editor = (this.iframe) ? $(this.iframe) : $(this.textarea);
	var mytoolbar = $('.rte-toolbar');
	return mytoolbar;
	return (editor.prev().hasClass('rte-toolbar')) ? editor.prev() : null;
}

lwRTE.prototype.activate_toolbar = function(editor, tb) {
	var old_tb = this.get_toolbar();

	if(old_tb)
		old_tb.remove();

	$(editor).before($(tb).clone(true));
}
	
lwRTE.prototype.enable_design_mode = function() {
	var self = this;

	// need to be created this way
	self.iframe	= document.createElement("iframe");
	self.iframe.frameBorder = 0;
	self.iframe.frameMargin = 0;
	self.iframe.framePadding = 0;
	self.iframe.width = '100%';
	self.iframe.height = self.height || '100%';

	if($(self.textarea).attr('class'))
		self.iframe.className = $(self.textarea).attr('class');

	if($(self.textarea).attr('id'))
		self.iframe.id = $(self.textarea).attr('id');
		
	if ($(self.textarea).attr('name')) 
	{
  	self.iframe.name = $(self.textarea).attr('name');
 		self.iframe.title = $(self.textarea).attr('name');
  }
	
	var content	= $(self.textarea).val();

	$(self.textarea).hide().after(self.iframe).remove();
	self.textarea	= null;

	var css = (self.css_url) ? "<link type='text/css' rel='stylesheet' href='" + self.css_url + "' />" : '';
	var base = (self.base_url) ? "<base href='" + self.base_url + "' />" : '';
	var style = (self.css_class) ? "class='" + self.css_class + "'" : '';

	// Mozilla need this to display caret
	if($.trim(content) == '')
		content	= '<br />';

	var doc = "<html><head>" + base + css + "</head><body " + style + " style='padding:5px'>" + content + "</body></html>";

	self.iframe_doc	= self.iframe.contentWindow.document;
	
	try {
		self.iframe_doc.designMode = 'on';
	} catch ( e ) {
		// Will fail on Gecko if the editor is placed in an hidden container element
		// The design mode will be set ones the editor is focused
		$(self.iframe_doc).focus(function() { self.iframe_doc.designMode(); } );
	}

	self.iframe_doc.open();
	self.iframe_doc.write(doc);
	self.iframe_doc.close();

	if(!self.toolbars.rte)
		self.toolbars.rte	= self.create_toolbar(self.controls.rte);

	self.activate_toolbar(self.iframe, self.toolbars.rte);

	$(self.iframe).parents('form').submit( 
			function() { self.disable_design_mode(true); }
	);

	$(self.iframe_doc).mouseup(function(event) { 
		if(self.iframe_doc.selection)
			self.range = self.iframe_doc.selection.createRange();  //store to restore later(IE fix)

		self.set_selected_controls( (event.target) ? event.target : event.srcElement, self.controls.rte); 
	});

	$(self.iframe_doc).keyup(function(event) { self.set_selected_controls( self.get_selected_element(), self.controls.rte); });
	
	//var rel_name = "#" + self.iframe.id.substr(5);
	//$(self.iframe_doc).onchange(function(event) { $(rel_name).value = $(self.textarea).value; });

	// Mozilla CSS styling off
	if(!$.browser.msie)
		self.editor_cmd('styleWithCSS', false);
		
	var self = this;
	$("#rte-div", self.iframe_doc).droppable({
		drop: function(ev, ui) {
			alert('dropped');
		}
	});
}

lwRTE.prototype.disable_design_mode = function(submit) {
	var self = this;

	self.textarea = (submit) ? $('<input type="hidden" />').get(0) : $('<textarea></textarea>').width('100%').height(self.height).get(0);

	if(self.iframe.className)
		self.textarea.className = self.iframe.className;

	if(self.iframe.id)
		self.textarea.id = self.iframe.id;
		
	if(self.iframe.title)
		self.textarea.name = self.iframe.title;
	
	$(self.textarea).val($('body', self.iframe_doc).html());
	$(self.iframe).before(self.textarea);

	if(!self.toolbars.html)
		self.toolbars.html	= self.create_toolbar(self.controls.html);

	if(submit != true) {
		$(self.iframe).remove();
		self.iframe = null;
		self.activate_toolbar(self.textarea, self.toolbars.html);
	}
}
    
lwRTE.prototype.toolbar_click = function(obj, control) {
	var fn = control.exec;

	$('.rte-panel', this.get_toolbar()).remove();

	if(fn)
		fn.apply(this);
	else if(this.iframe && control.command) {
		var args = control.args;

		if(obj.tagName.toUpperCase() == 'SELECT') {
			args = obj.options[obj.selectedIndex].value;

			if(args.length <= 0)
				return;
		}

		this.editor_cmd(control.command, args);
	}
}
	
lwRTE.prototype.create_toolbar = function(controls) {
	var self = this;
	var tb = $("<div></div>").addClass('rte-toolbar').width('100%').append($("<ul></ul>")).append($("<div></div>").addClass('clear'));
	var obj, li;
	
	for (var key in controls){
		if(controls[key].separator) {
			li = $("<li></li>").addClass('separator');
		} else {
			if(controls[key].select) {
				obj = $(controls[key].select)
					.change( function(e) {
						self.event = e;
						self.toolbar_click(this, controls[this.className]); 
						return false;
					});
			} else {
				obj = $("<a href='#'></a>")
					.attr('title', (controls[key].hint) ? controls[key].hint : key)
					.attr('rel', key)
					.click( function(e) {
						self.event = e;
						self.toolbar_click(this, controls[this.rel]); 
						return false;
					})
			}

			li = $("<li></li>").append(obj.addClass(key));
		}

		$("ul",tb).append(li);
	}

	$('.enable', tb).click(function() {
		self.enable_design_mode();
		return false; 
	});

	$('.disable', tb).click(function() {
		self.disable_design_mode();
		return false; 
	});

	return tb.get(0);
}

lwRTE.prototype.create_panel = function(title, width) {
	var self = this;
	var tb = self.get_toolbar();

	if(!tb)
		return false;

	$('.rte-panel', tb).remove();
	var drag, event;
	var left = self.event.pageX;
	var top = self.event.pageY;
	
	var panel	= $('<div></div>').hide().addClass('rte-panel').css({left: left, top: top});
	$('<div></div>')
		.addClass('rte-panel-title')
		.html(title)
		.append($("<a class='close' href='#'>X</a>")
		.click( function() { panel.remove(); return false; }))
		.mousedown( function() { drag = true; return false; })
		.mouseup( function() { drag = false; return false; })
		.mousemove( 
			function(e) {
				if(drag && event) {
					left -= event.pageX - e.pageX;
					top -=  event.pageY - e.pageY;
					panel.css( {left: left, top: top} ); 
				}

				event = e;
				return false;
			} 
		)
		.appendTo(panel);

	if(width)
		panel.width(width);

	tb.append(panel);
	return panel;
}

lwRTE.prototype.get_content = function() {
	return (this.iframe) ? $('body', this.iframe_doc).html() : $(this.textarea).val();
}

lwRTE.prototype.set_content = function(content) {
	(this.iframe) ? $('body', this.iframe_doc).html(content) : $(this.textarea).val(content);
}

lwRTE.prototype.set_selected_controls = function(node, controls) {
	var toolbar = this.get_toolbar();

	if(!toolbar)
		return false;
		
	var key, i_node, obj, control, tag, i, value;

	for (key in controls) {
		control = controls[key];
		obj = $('.' + key, toolbar);

		obj.removeClass('active');

		if(!control.tags)
			continue;

		i_node = node;
		do {
			if(i_node.nodeType != 1)
				continue;

			tag	= i_node.nodeName.toLowerCase();
			if($.inArray(tag, control.tags) < 0 )
				continue;

			if(control.select) {
				obj = obj.get(0);
				if(obj.tagName.toUpperCase() == 'SELECT') {
					obj.selectedIndex = 0;

					for(i = 0; i < obj.options.length; i++) {
						value = obj.options[i].value;
						if(value && ((control.arg_cmp && control.arg_cmp(i_node, value)) || tag == value)) {
							obj.selectedIndex = i;
							break;
						}
					}
				}
			} else
					obj.addClass('active');
		}  while(i_node = i_node.parentNode)
	}
		
	return true;
}

lwRTE.prototype.get_selected_element = function () {
	var node, selection, range;
	var iframe_win	= this.iframe.contentWindow;
	
	if (iframe_win.getSelection) {
		try {
			selection = iframe_win.getSelection();
			range = selection.getRangeAt(0);
			node = range.commonAncestorContainer;
		} catch(e){
			return false;
		}
	} else {
		try {
			selection = iframe_win.document.selection;
			range = selection.createRange();
			node = range.parentElement();
		} catch (e) {
			return false;
		}
	}

	return node;
}

lwRTE.prototype.get_selection_range = function() {
	var rng	= null;
	var iframe_window = this.iframe.contentWindow;
	this.iframe.focus();
	
	if(iframe_window.getSelection) {
		rng = iframe_window.getSelection().getRangeAt(0);
		if($.browser.opera) { //v9.63 tested only
			var s = rng.startContainer;
			if(s.nodeType === Node.TEXT_NODE)
				rng.setStartBefore(s.parentNode);
		}
	} else {
		this.range.select(); //Restore selection, if IE lost focus.
		rng = this.iframe_doc.selection.createRange();
	}

	return rng;
}

lwRTE.prototype.get_selected_text = function() {
	var iframe_win = this.iframe.contentWindow;

	if(iframe_win.getSelection)	
		return iframe_win.getSelection().toString();

	this.range.select(); //Restore selection, if IE lost focus.
	return iframe_win.document.selection.createRange().text;
};

lwRTE.prototype.get_selected_html = function() {
	var html = null;
	var iframe_window = this.iframe.contentWindow;
	var rng	= this.get_selection_range();

	if(rng) {
		if(iframe_window.getSelection) {
			var e = document.createElement('div');
			e.appendChild(rng.cloneContents());
			html = e.innerHTML;		
		} else {
			html = rng.htmlText;
		}
	}

	return html;
};
	
lwRTE.prototype.selection_replace_with = function(html) {
	var rng	= this.get_selection_range();
	var iframe_window = this.iframe.contentWindow;

	if(!rng)
		return;
	
	this.editor_cmd('removeFormat'); // we must remove formating or we will get empty format tags!

	if(iframe_window.getSelection) {
		rng.deleteContents();
		rng.insertNode(rng.createContextualFragment(html));
		this.editor_cmd('delete');
	} else {
		this.editor_cmd('delete');
		rng.pasteHTML(html);
	}
}

/*
 * Lightweight RTE - jQuery Plugin
 * Basic Toolbars
 * Copyright (c) 2009 Andrey Gayvoronsky - http://www.gayvoronsky.com
 */
var rte_tag		= '-rte-tmp-tag-';

var	rte_toolbar = {
	s1				: {separator: true},
	bold			: {command: 'bold', tags:['b', 'strong']},
	italic			: {command: 'italic', tags:['i', 'em']},
	strikeThrough	: {command: 'strikethrough', tags: ['s', 'strike'] },
	underline		: {command: 'underline', tags: ['u']},
	s2				: {separator: true },
	justifyLeft   	: {command: 'justifyleft'},
	justifyCenter	: {command: 'justifycenter'},
	justifyRight	: {command: 'justifyright'},
	justifyFull		: {command: 'justifyfull'},
	s3				: {separator : true},
	indent			: {command: 'indent'},
	outdent			: {command: 'outdent'},
	s4				: {separator : true},
	subscript		: {command: 'subscript', tags: ['sub']},
	superscript		: {command: 'superscript', tags: ['sup']},
	s5				: {separator : true },
	orderedList		: {command: 'insertorderedlist', tags: ['ol'] },
	unorderedList	: {command: 'insertunorderedlist', tags: ['ul'] },
	s6				: {separator : true },
	block			: {command: 'formatblock', select: '\
<select>\
	<option value="">- style -</option>\
	<option value="<p>">Paragraph</option>\
	<option value="<h1>">Header 1</option>\
	<option value="<h2>">Header 2</options>\
	<option value="<h3>">Header 3</option>\
	<option value="<h4>">Header 4</options>\
	<option value="<h5>">Header 5</option>\
	<option value="<h6>">Header 6</options>\
</select>\
	', arg_cmp: 
		function(node, arg) {
			arg = arg.replace(/<([^>]*)>/, '$1');
			return (arg.toLowerCase() == node.nodeName.toLowerCase());
		}
	, tags: ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']},
	font			: {command: 'fontname', select: '\
<select>\
	<option value="">- font -</option>\
	<option value="arial">Arial</option>\
	<option value="comic sans ms">Comic Sans</option>\
	<option value="courier new">Courier New</options>\
	<option value="georgia">Georgia</option>\
	<option value="helvetica">Helvetica</options>\
	<option value="impact">Impact</option>\
	<option value="times new roman">Times</options>\
	<option value="trebuchet ms">Trebuchet</options>\
	<option value="verdana">Verdana</options>\
</select>\
	', tags: ['font']},
	size			: {command: 'fontsize', select: '\
<select>\
	<option value="">-</option>\
	<option value="1">1 (8pt)</option>\
	<option value="2">2 (10pt)</option>\
	<option value="3">3 (12pt)</options>\
	<option value="4">4 (14pt)</option>\
	<option value="5">5 (16pt)</options>\
	<option value="6">6 (18pt)</option>\
	<option value="7">7 (20pt)</options>\
</select>\
	', tags: ['font']},
	color			: {exec: 
		function() {
			var self = this;
			//alert('sdfsdfsd');
			var panel = self.create_panel('Set color for text', 385);
			var mouse_down = false;
			var mouse_over = false;
			panel.append('\
<div class="colorpicker1"><div class="rgb" id="rgb"></div></div>\
<div class="colorpicker1"><div class="gray" id="gray"></div></div>\
<div class="colorpicker2">\
	<div class="palette" id="palette"></div>\
	<div class="preview" id="preview"></div>\
	<div class="color" id="color"></div>\
</div>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Cancel</button></p>'
).show();

			var preview = $('#preview', panel);
			var color = $("#color", panel);
			var palette = $("#palette", panel);
			var colors = [
				'#660000', '#990000', '#cc0000', '#ff0000', '#333333',
				'#006600', '#009900', '#00cc00', '#00ff00', '#666666',
				'#000066', '#000099', '#0000cc', '#0000ff', '#999999',
				'#909000', '#900090', '#009090', '#ffffff', '#cccccc',
				'#ffff00', '#ff00ff', '#00ffff', '#000000', '#eeeeee'
			];
			
			for(var i = 0; i < 25; i++)
				$("<div></div>").addClass("item").css('background', colors[i]).appendTo(palette);
			
			var height = $('#rgb').height();
			var part_width = $('#rgb').width() / 6;

			$('#rgb,#gray,#palette', panel)
				.mousedown( function(e) {mouse_down = true; return false; } )
				.mouseup( function(e) {mouse_down = false; return false; } )
				.mouseout( function(e) {mouse_over = false; return false; } )
				.mouseover( function(e) {mouse_over = true; return false; } );

			$('#rgb').mousemove( function(e) { if(mouse_down && mouse_over) compute_color(this, true, false, false, e); return false;} );
			$('#gray').mousemove( function(e) { if(mouse_down && mouse_over) compute_color(this, false, true, false, e); return false;} );
			$('#palette').mousemove( function(e) { if(mouse_down && mouse_over) compute_color(this, false, false, true, e); return false;} );
			$('#rgb').click( function(e) { compute_color(this, true, false, false, e); return false;} );
			$('#gray').click( function(e) { compute_color(this, false, true, false, e); return false;} );
			$('#palette').click( function(e) { compute_color(this, false, false, true, e); return false;} );

			$('#cancel', panel).click( function() { panel.remove(); return false; } );
			$('#ok', panel).click( 
				function() {
					var value = color.html();

					if(value.length > 0 && value.charAt(0) =='#') {
						if(self.iframe_doc.selection) //IE fix for lost focus
							self.range.select();

						self.editor_cmd('foreColor', value);
					}
					
					panel.remove(); 
					return false;
				}
			);

			function to_hex(n) {
				var s = "0123456789abcdef";
				return s.charAt(Math.floor(n / 16)) + s.charAt(n % 16);
			}			

			function get_abs_pos(element) {
				var r = { x: element.offsetLeft, y: element.offsetTop };

				if (element.offsetParent) {
					var tmp = get_abs_pos(element.offsetParent);
					r.x += tmp.x;
					r.y += tmp.y;
				}

				return r;
			};
			
			function get_xy(obj, event) {
				var x, y;
				event = event || window.event;
				var el = event.target || event.srcElement;

				// use absolute coordinates
				var pos = get_abs_pos(obj);

				// subtract distance to middle
				x = event.pageX  - pos.x;
				y = event.pageY - pos.y;

				return { x: x, y: y };
			}
			
			function compute_color(obj, is_rgb, is_gray, is_palette, e) {
				var r, g, b, c;

				var mouse = get_xy(obj, e);
				var x = mouse.x;
				var y = mouse.y;

				if(is_rgb) {
					r = (x >= 0)*(x < part_width)*255 + (x >= part_width)*(x < 2*part_width)*(2*255 - x * 255 / part_width) + (x >= 4*part_width)*(x < 5*part_width)*(-4*255 + x * 255 / part_width) + (x >= 5*part_width)*(x < 6*part_width)*255;
					g = (x >= 0)*(x < part_width)*(x * 255 / part_width) + (x >= part_width)*(x < 3*part_width)*255	+ (x >= 3*part_width)*(x < 4*part_width)*(4*255 - x * 255 / part_width);
					b = (x >= 2*part_width)*(x < 3*part_width)*(-2*255 + x * 255 / part_width) + (x >= 3*part_width)*(x < 5*part_width)*255 + (x >= 5*part_width)*(x < 6*part_width)*(6*255 - x * 255 / part_width);

					var k = (height - y) / height;

					r = 128 + (r - 128) * k;
					g = 128 + (g - 128) * k;
					b = 128 + (b - 128) * k;
				} else if (is_gray) {
					r = g = b = (height - y) * 1.7;
				} else if(is_palette) {
					x = Math.floor(x / 10);
					y = Math.floor(y / 10);
					c = colors[x + y * 5];
				}

				if(!is_palette)
					c = '#' + to_hex(r) + to_hex(g) + to_hex(b);

				preview.css('background', c);
				color.html(c);
			}
		}
	},
	image			: {exec:
		function() {
			var self = this;
			var panel = self.create_panel('Insert image', 385);
			panel.append('\
<div id="rte_browser_left"><strong>List of folders:</strong><br /><div id="rte_browser_left_holder"></div></div><div id="rte_browser"><div id="rte_browser_holder"></div></div><div style="clear:both;"></div>\
<p><label>URL</label><input type="text" id="url" size="30" value=""><button id="file">Upload</button><button id="view">View</button></p>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Cancel</button></p>'
).show();
			$.ajax({
				type: "POST",
				url: "../novacms/components/rte/browser.php",
				data: "action=folders",
				success: function(msg){
					document.getElementById('rte_browser_left_holder').innerHTML = msg;
				}
			});		

			$.ajax({
				type: "POST",
				url: "../novacms/components/rte/browser.php",
				data: "action=files",
				success: function(msg){
					document.getElementById('rte_browser_holder').innerHTML = msg;
				}
			});			

			var url = $('#url', panel);
			var upload = $('#file', panel).upload( {
				autoSubmit: false,
				action: '../novacms/components/rte/uploader.php',
				onSelect: function() {
					var file = this.filename();
					var ext = (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
					if(!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
						alert('Invalid file extension');
						return;
					}

					this.submit();
				},
				onComplete: function(response) { 
					if(response.length <= 0)
						return;

					response = eval("(" + response + ")");
					if(response.error && response.error.length > 0)
						alert(response.error);
					else
					{
						url.val((response.file && response.file.length > 0) ? response.file : '');
						if(response.file && response.file.length > 0)
						{
							var dir = response.file.split("/");
							browse_folder(dir[dir.length - 2]);
						}
					}
				}
			});

			$('#view', panel).click( function() {
					(url.val().length >0 ) ? window.open(url.val()) : alert("Enter URL of image to view");
					return false;
				}
			);
			
			$('#cancel', panel).click( function() { panel.remove(); return false;} );
			$('#ok', panel).click( 
				function() {
					var file = url.val();
					self.editor_cmd('insertImage', file);
					panel.remove(); 
					return false;
				}
			)
		}, tags: ['img'] },
		
	embed			: {exec:
		function() {
			var self = this;
			var panel = self.create_panel("Add embeded content", 385);
			panel.append('\<p><label style="width:200px;float:left;text-align:left;">Embed title:</label><input type="text" id="emb-title" style="font-size:1em; width:380px; border:1px solid #ccc;" /><label style="width:200px;float:left;text-align:left;">Embed tag:</label><textarea id="embed" style="font-size:1em; width:380px; height: 200px; border:1px solid #ccc;"></textarea><button id="emb">Attach object</button><button id="cancel">Cancel</button></p><div class="clear"></div>').show();
		$('#cancel', panel).click( function() { panel.remove(); return false; } );
		$('#emb', panel).click( 
			function() {
				var emb = $('#embed', panel).val();
				
				var str = "";
				var t = emb.match(/<param name=['\"]movie['\"] value=['\"]([^>]+)['\"]>/);
				if(t)
				{
					str = '[object: <a href="' + t[1]+'">'+t[1]+'</a>]'+emb+'[/object]';
				}
				else
				{
					t = emb.match(/<embed src=\"([^\"]+)\"(.*)>/);
					if(t)
					{
						str = '[object: <a href="' + t[1]+'">'+t[1]+'</a>]'+emb+'[/object]';
					}
					else
					{
						str = "";
					}
				}
				
				var title = $("#emb-title").val();
				if(title)
				{
					str = '<div class="embed_title">'+title+'</div>'+str;
				}
				
				if (document.all) {
					//var oRng = self.iframe_doc.selection.createRange();
					//var st = self.iframe_doc.body.innerHTML;
					//alert(st);
					self.iframe_doc.body.innerHTML += str;

					//var self = this;
					//var html = self.get_selected_html();
					//if(html.substring(0, 4) != '<img')
					//	return;

					//var oRng = document.getElementById('text').contentWindow.document.selection.createRange();
					//oRng.pasteHTML("dadasdasdasdasdas");
					//oRng.text = "dadasdasdasdasdas";
					//oRng.pasteHTML(str);
					//oRng.collapse(false);
					//oRng.select();
				} else {				
					self.editor_cmd('inserthtml', str);
				}
	
				panel.remove(); 
				return false;
			});
		
		}, tags: ['embed'] },
alttag			: {exec:
		function() {
			var self = this;
			var html = self.get_selected_html();
			if(html.substring(0, 4) != '<img')
				return;
				
			var t = html.match(/alt=['\"]([^>]+)['\"]/);
			var found = false;
			if(t)
			{
				var alt = t[1];
				var alt_a = alt.split("[||]");
				if (alt_a.length == 2) 
				{
					alt = alt_a[0];
					var sign = alt_a[1];
				}
				else
				{
					var sign = "";
				}
				
				found = true;
			}
			else
			{
				var alt = "";
				var sign = "";
			}
			
			var t = html.match(/class=['\"]([^>]+)['\"]/);
			var c_found = false;
			if(t && t[1] != '')
			{
				var img_type = '<p><input type="radio" class="img-type" name="img-type" value="small" /> Mala slika</p><p><input type="radio" class="img-type" name="img-type" checked value="big" /> Velika slika</p>';
				c_found = true;
			}
			else
			{
				var img_type = '<p><input type="radio" class="img-type" name="img-type" checked value="small" /> Mala slika</p><p><input type="radio" class="img-type" name="img-type" value="big" /> Velika slika</p>';
			}
			
			var panel = self.create_panel("Edit Image Alt", 385);
			panel.append('\
<p><label style="width:200px;float:left;text-align:left;">Image Alt:</label><input type="text" value="'+alt+'" id="alt" style="font-size:0.8em; width:380px; border:1px solid #ccc;" /></p><p><label style="width:200px;float:left;text-align:left;">Potpis:</label><input type="text" value="'+sign+'" id="sign" style="font-size:0.8em; width:380px; border:1px solid #ccc;" /></p><br /><br />'+img_type+'<br /><button id="submitalt">Save</button><button id="cancel">Cancel</button>\
<div class="clear"></div>'
).show();
		$('#cancel', panel).click( function() { panel.remove(); return false; } );
		$('#submitalt', panel).click( 
			function() {
				var aaa = $('#alt', panel).val();
				var asign = $('#sign', panel).val();
				
				if(asign)
					aaa = aaa + "[||]" + asign;
				
				var img_type = $(':checked', panel).val();
				panel.remove(); 
				
				if(found)
				{
					var sRegExInput = new RegExp(alt, "g");
					html = html.replace(sRegExInput, aaa);
				}
				else
				{
					html = html.substring(0, html.length - 1);
					html = html + 'alt="' + aaa + '" />';
				}
				
				if(c_found)
				{
					if(img_type != "big")
					{
						html = html.substring(0, html.length - 1);
						html = html + 'class="" />';
					}
				}
				else
				{
					if(img_type == "big")
					{
						html = html.substring(0, html.length - 1);
						html = html + 'class="big-image" />';
					}
				}
				
				self.selection_replace_with(html);
				return false;
			});
		}, tags: ['img'] },
	link			: {exec: 
		function() {
			var self = this;
			var panel = self.create_panel("Create link / Attach file", 385);
			panel.append('\
<p><label>URL</label><input type="text" id="url" size="30" value=""><button id="file">Attach File</button><button id="view">View</button></p>\
<div class="clear"></div>\
<p><label>Title</label><input type="text" id="title" size="30" value=""><label>Target</label><select id="target"><option value="">default</option><option value="_blank">new</option></select></p>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Cancel</button></p>'
).show();

			$('#cancel', panel).click( function() { panel.remove(); return false; } );

			var url = $('#url', panel);
			var upload = $('#file', panel).upload( {
				autoSubmit: true,
				action: 'uploader.php',
				onComplete: function(response) { 
					if(response.length <= 0)
						return;

					response	= eval("(" + response + ")");
					if(response.error && response.error.length > 0)
						alert(response.error);
					else
						url.val((response.file && response.file.length > 0) ? response.file : '');
				}
			});

			$('#view', panel).click( function() {
					(url.val().length >0 ) ? window.open(url.val()) : alert("Enter URL to view");
					return false;
				}
			);
			$('#ok', panel).click( 
				function() {
					var url = $('#url', panel).val();
					url = url.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
					var target = $('#target', panel).val();
					var title = $('#title', panel).val();

					if(self.get_selected_text().length <= 0) {
						alert('Select the text you wish to link!');
						return false;
					}

					panel.remove(); 

					if(url.length <= 0)
						return false;
						
					if(url.substr(0, 7) != 'http://')
						url = 'http://'+url;

					self.editor_cmd('unlink');
					
					//alert(url);

					// we wanna well-formed linkage (<p>,<h1> and other block types can't be inside of link due to WC3)
					self.editor_cmd('createLink', rte_tag);
					var tmp = $('<span></span>').append(self.get_selected_html());

					if(target.length > 0)
						$('a[href*="' + rte_tag + '"]', tmp).attr('target', target);

					if(title.length > 0)
						$('a[href*="' + rte_tag + '"]', tmp).attr('title', title);

					$('a[href*="' + rte_tag + '"]', tmp).attr('href', url);
				
					self.selection_replace_with(tmp.html());
					return false;
				}
			)
		}, tags: ['a'] },
	unlink			: {command: 'unlink'},
	s8				: {separator : true },
	removeFormat	: {exec: 
		function() {
			this.editor_cmd('removeFormat');
			this.editor_cmd('unlink');
		}},
	word			: {exec: function() { this.set_content(cleanup_word(this.get_content(), true, true, true)); }},
	clear			: {exec: function() { if(confirm('Clear Document?')) this.set_content(''); }}
};

var html_toolbar = {
	s1				: {separator: true},
	word			: {exec: function() { this.set_content(cleanup_word(this.get_content(), true, true, true)); }},
	clear			: {exec: function() { if(confirm('Clear Document?')) this.set_content(''); }}
};

function cleanup_word(s, bIgnoreFont, bRemoveStyles, bCleanWordKeepsStructure) {
	s = s.replace(/<o:p>\s*<\/o:p>/g, '') ;
	s = s.replace(/<o:p>[\s\S]*?<\/o:p>/g, '&nbsp;') ;

	// Remove mso-xxx styles.
	s = s.replace( /\s*mso-[^:]+:[^;"]+;?/gi, '' ) ;

	// Remove margin styles.
	s = s.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, '' ) ;
	s = s.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\"" ) ;

	s = s.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, '' ) ;
	s = s.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\"" ) ;

	s = s.replace( /\s*TEXT-ALIGN: [^\s;]+;?"/gi, "\"" ) ;

	s = s.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\"" ) ;

	s = s.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ) ;

	s = s.replace( /\s*tab-stops:[^;"]*;?/gi, '' ) ;
	s = s.replace( /\s*tab-stops:[^"]*/gi, '' ) ;

	// Remove FONT face attributes.
	if (bIgnoreFont) {
		s = s.replace( /\s*face="[^"]*"/gi, '' ) ;
		s = s.replace( /\s*face=[^ >]*/gi, '' ) ;

		s = s.replace( /\s*FONT-FAMILY:[^;"]*;?/gi, '' ) ;
	}

	// Remove Class attributes
	s = s.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;

	// Remove styles.
	if (bRemoveStyles)
		s = s.replace( /<(\w[^>]*) style="([^\"]*)"([^>]*)/gi, "<$1$3" ) ;

	// Remove style, meta and link tags
	s = s.replace( /<STYLE[^>]*>[\s\S]*?<\/STYLE[^>]*>/gi, '' ) ;
	s = s.replace( /<(?:META|LINK)[^>]*>\s*/gi, '' ) ;

	// Remove empty styles.
	s =  s.replace( /\s*style="\s*"/gi, '' ) ;

	s = s.replace( /<SPAN\s*[^>]*>\s*&nbsp;\s*<\/SPAN>/gi, '&nbsp;' ) ;

	s = s.replace( /<SPAN\s*[^>]*><\/SPAN>/gi, '' ) ;

	// Remove Lang attributes
	s = s.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;

	s = s.replace( /<SPAN\s*>([\s\S]*?)<\/SPAN>/gi, '$1' ) ;

	s = s.replace( /<FONT\s*>([\s\S]*?)<\/FONT>/gi, '$1' ) ;

	// Remove XML elements and declarations
	s = s.replace(/<\\?\?xml[^>]*>/gi, '' ) ;

	// Remove w: tags with contents.
	s = s.replace( /<w:[^>]*>[\s\S]*?<\/w:[^>]*>/gi, '' ) ;

	// Remove Tags with XML namespace declarations: <o:p><\/o:p>
	s = s.replace(/<\/?\w+:[^>]*>/gi, '' ) ;

	// Remove comments [SF BUG-1481861].
	s = s.replace(/<\!--[\s\S]*?-->/g, '' ) ;

	s = s.replace( /<(U|I|STRIKE)>&nbsp;<\/\1>/g, '&nbsp;' ) ;

	s = s.replace( /<H\d>\s*<\/H\d>/gi, '' ) ;

	// Remove "display:none" tags.
	s = s.replace( /<(\w+)[^>]*\sstyle="[^"]*DISPLAY\s?:\s?none[\s\S]*?<\/\1>/ig, '' ) ;

	// Remove language tags
	s = s.replace( /<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, "<$1$3") ;

	// Remove onmouseover and onmouseout events (from MS Word comments effect)
	s = s.replace( /<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3") ;
	s = s.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3") ;

	if (bCleanWordKeepsStructure) {
		// The original <Hn> tag send from Word is something like this: <Hn style="margin-top:0px;margin-bottom:0px">
		s = s.replace( /<H(\d)([^>]*)>/gi, '<h$1>' ) ;

		// Word likes to insert extra <font> tags, when using MSIE. (Wierd).
		s = s.replace( /<(H\d)><FONT[^>]*>([\s\S]*?)<\/FONT><\/\1>/gi, '<$1>$2<\/$1>' );
		s = s.replace( /<(H\d)><EM>([\s\S]*?)<\/EM><\/\1>/gi, '<$1>$2<\/$1>' );
	} else {
		s = s.replace( /<H1([^>]*)>/gi, '<div$1><b><font size="6">' ) ;
		s = s.replace( /<H2([^>]*)>/gi, '<div$1><b><font size="5">' ) ;
		s = s.replace( /<H3([^>]*)>/gi, '<div$1><b><font size="4">' ) ;
		s = s.replace( /<H4([^>]*)>/gi, '<div$1><b><font size="3">' ) ;
		s = s.replace( /<H5([^>]*)>/gi, '<div$1><b><font size="2">' ) ;
		s = s.replace( /<H6([^>]*)>/gi, '<div$1><b><font size="1">' ) ;

		s = s.replace( /<\/H\d>/gi, '<\/font><\/b><\/div>' ) ;

		// Transform <P> to <DIV>
		var re = new RegExp( '(<P)([^>]*>[\\s\\S]*?)(<\/P>)', 'gi' ) ;	// Different because of a IE 5.0 error
		s = s.replace( re, '<div$2<\/div>' ) ;

		// Remove empty tags (three times, just to be sure).
		// This also removes any empty anchor
		s = s.replace( /<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '' ) ;
		s = s.replace( /<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '' ) ;
		s = s.replace( /<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '' ) ;
	}

	return s;
}

function browse_folder(dir)
{
	$.ajax({
		type: "POST",
		url: "../novacms/components/rte/browser.php",
		data: "action=files&dir="+dir,
		success: function(msg){
			document.getElementById('rte_browser_holder').innerHTML = msg;
		}
	});		
}

var	rte_toolbar_small = {
	s1				: {separator: true},
	bold			: {command: 'bold', tags:['b', 'strong']},
	italic			: {command: 'italic', tags:['i', 'em']},
	strikeThrough	: {command: 'strikethrough', tags: ['s', 'strike'] },
	underline		: {command: 'underline', tags: ['u']},
	s2				: {separator: true },
	indent			: {command: 'indent'},
	outdent			: {command: 'outdent'},
	s4				: {separator : true},
	subscript		: {command: 'subscript', tags: ['sub']},
	superscript		: {command: 'superscript', tags: ['sup']},
	s5				: {separator : true },
	orderedList		: {command: 'insertorderedlist', tags: ['ol'] },
	unorderedList	: {command: 'insertunorderedlist', tags: ['ul'] },
	s6				: {separator : true },
	embed			: {exec:
		function() {
			var self = this;
			var panel = self.create_panel("Umetni Flash objekt", 385);
			panel.append('\
<p><label style="width:200px;float:left;text-align:left;">Kod Flash objekta:</label><textarea id="embed" style="font-size:0.8em; width:380px; height: 200px; border:1px solid #ccc;"></textarea><button id="emb">Dodaj objekt</button><button id="cancel">Otkaži</button></p>\
<div class="clear"></div>'
).show();
		$('#cancel', panel).click( function() { panel.remove(); return false; } );
		$('#emb', panel).click( 
			function() {
				var emb = $('#embed', panel).val();
				
				var str = "";
				var t = emb.match(/<param name=['\"]movie['\"] value=['\"]([^>]+)['\"]>/);
				if(t)
				{
					//str = '[object: <a href="' + t[1]+'">'+t[1]+'</a>]'+emb+'[/object]';
					str = emb;
				}
				else
				{
					t = emb.match(/<embed src=\"([^\"]+)\"(.*)>/);
					if(t)
					{
						//str = '[object: <a href="' + t[1]+'">'+t[1]+'</a>]'+emb+'[/object]';
						str = emb;
					}
					else
					{
						str = "";
					}
				}
				
				/*
				var title = $("#emb-title").val();
				if(title)
				{
					str = '<div class="embed_title">'+title+'</div>'+str;
				}
				*/
				
				self.editor_cmd('inserthtml', str);
	
				panel.remove(); 
				return false;
			});
		
		}, tags: ['embed'] },
	link			: {exec: 
		function() {
			var self = this;
			var panel = self.create_panel("Dodaj Link", 385);
			panel.append('\
<p><label>URL</label><input type="text" id="url" size="30" value=""></p>\
<div class="clear"></div>\
<p><label>Naslov</label><input type="text" id="title" size="30" value=""><label>Target</label><select id="target"><option value="">isti prozor</option><option value="_blank">novi prozor</option></select></p>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Otkaži</button></p>'
).show();

			$('#cancel', panel).click( function() { panel.remove(); return false; } );

			var url = $('#url', panel);
			var upload = $('#file', panel).upload( {
				autoSubmit: true,
				action: 'uploader.php',
				onComplete: function(response) { 
					if(response.length <= 0)
						return;

					response	= eval("(" + response + ")");
					if(response.error && response.error.length > 0)
						alert(response.error);
					else
						url.val((response.file && response.file.length > 0) ? response.file : '');
				}
			});

			$('#view', panel).click( function() {
					(url.val().length >0 ) ? window.open(url.val()) : alert("Enter URL to view");
					return false;
				}
			);
			$('#ok', panel).click( 
				function() {
					var url = $('#url', panel).val();
					var target = $('#target', panel).val();
					var title = $('#title', panel).val();

					if(self.get_selected_text().length <= 0) {
						alert('Select the text you wish to link!');
						return false;
					}

					panel.remove(); 

					if(url.length <= 0)
						return false;
						
					if(url.substr(0, 7) != 'http://')
						url = 'http://'+url;

					self.editor_cmd('unlink');

					// we wanna well-formed linkage (<p>,<h1> and other block types can't be inside of link due to WC3)
					self.editor_cmd('createLink', rte_tag);
					var tmp = $('<span></span>').append(self.get_selected_html());

					if(target.length > 0)
						$('a[href*="' + rte_tag + '"]', tmp).attr('target', target);

					if(title.length > 0)
						$('a[href*="' + rte_tag + '"]', tmp).attr('title', title);

					$('a[href*="' + rte_tag + '"]', tmp).attr('href', url);
				
					self.selection_replace_with(tmp.html());
					return false;
				}
			)
		}, tags: ['a'] },
	unlink			: {command: 'unlink'},
	s8				: {separator : true },
	removeFormat	: {exec: 
		function() {
			this.editor_cmd('removeFormat');
			this.editor_cmd('unlink');
		}},
	word			: {exec: function() { this.set_content(cleanup_word(this.get_content(), true, true, true)); }},
	clear			: {exec: function() { if(confirm('Očisti dokument?')) this.set_content(''); }}
};

(function(a){a.fn.upload=function(b){b=a.extend({name:"file",enctype:"multipart/form-data",action:"",autoSubmit:true,onSubmit:function(){},onComplete:function(){},onSelect:function(){},params:{}},b);return new a.ocupload(this,b)},a.ocupload=function(e,d){var c=this;var h=new Date().getTime().toString().substr(8);var f=a('<iframe id="iframe'+h+'" name="iframe'+h+'"src="#"></iframe>').css({display:"none"});var g=a('<form method="post" enctype="'+d.enctype+'" action="'+d.action+'" target="iframe'+h+'"></form>').css({margin:0,padding:0});var b=a('<input name="'+d.name+'" type="file" />').css({width:"auto",position:"absolute",right:0,top:0,opacity:0,zoom:1,filter:"alpha(opacity=0)",border:0,"font-size":"10em"});e.wrap("<div></div>");e.wrap(g);e.wrap("<span></span>");e.parent().css({"float":"left","white-space":"nowrap",position:"relative","z-index":1,left:0,top:0,overflow:"hidden",display:"inline",border:0});e.after(b);e.parent().parent().after(f);g=b.parent().parent();b.change(function(){c.onSelect();if(c.autoSubmit){c.submit()}});a.extend(this,{autoSubmit:d.autoSubmit,onSubmit:d.onSubmit,onComplete:d.onComplete,onSelect:d.onSelect,filename:function(){return b.attr("value")},params:function(i){var i=i?i:false;if(i){d.params=a.extend(d.params,i)}else{return d.params}},name:function(i){var i=i?i:false;if(i){b.attr("name",value)}else{return b.attr("name")}},action:function(i){var i=i?i:false;if(i){g.attr("action",i)}else{return g.attr("action")}},enctype:function(i){var i=i?i:false;if(i){g.attr("enctype",i)}else{return g.attr("enctype")}},set:function(k,j){var j=j?j:false;function i(m,l){switch(m){default:throw new Error("[jQuery.ocupload.set] '"+m+"' is an invalid option.");break;case"name":c.name(l);break;case"action":c.action(l);break;case"enctype":c.enctype(l);break;case"params":c.params(l);break;case"autoSubmit":c.autoSubmit=l;break;case"onSubmit":c.onSubmit=l;break;case"onComplete":c.onComplete=l;break;case"onSelect":c.onSelect=l;break}}if(j){i(k,j)}else{a.each(k,function(l,m){i(l,m)})}},submit:function(){this.onSubmit();a.each(d.params,function(i,j){g.append(a('<input type="hidden" name="'+i+'" value="'+j+'" />'))});g.get(0).submit();f.unbind().load(function(){var j=document.getElementById(f.attr("name"));var i=a(j.contentWindow.document.body).text();c.onComplete(i)})}})}})(jQuery);

// celebrities rating
function celeb_rate(id, rate)
{
	$.ajax({
		url: "http://neon.com.hr/index.php",
		type: "POST",
		data: ({action : "celeb_rate", action_type : 'ajax', id: id, rate: rate}),
		dataType: "html",
		success: function(msg)
		{
			msg = ajax_retrieve_messages(msg);
			$("#celeb-rate-"+id).fadeOut(300, function() {$("#celeb-rate-"+id).html(msg[0]); $("#celeb-rate-"+id).fadeIn(600);});
		}
	});		
}

