// jQuery
// Info.ajax -> napraviti da radi sa drajverima za elemente koji se prebrikavaju po potrebi

function go_to(loc) { location.assign( /^\w/.test(loc) ? document.location.pathname+'/'+loc : loc); } // FF ne kuži BASE HREF u javascriptu

Array.prototype.filterId = function()
{
	for(var i=0;i<this.length;i++) { this[i] = this[i].replace(/.*[_\-]/,''); }  
	return this;
};

String.prototype.filterId = function() { return this.replace(/.*[_\-]/,''); };

jQuery.fn.extend(
{
	serializeHash: function() 
	{
    	var hash = {};
        jQuery.each(this.serializeArray(), function() { hash[this.name] = this.value; });
		return hash;
	}
});

jQuery.preloadImages = function() {	for(var i = 0; i<arguments.length; i++)	{ jQuery("<img>").attr("src", arguments[i]); } }


/**
 * Copyright (c) 2008 Rob Glazebrook (cssnewbie.com) 
 * Example 1: $(".cols").equalHeights(); Sets all columns to the same height.
 * Example 2: $(".cols").equalHeights(400); Sets all cols to at least 400px tall.
 * Example 3: $(".cols").equalHeights(100,300); Cols are at least 100 but no more
 * 
 */

jQuery.fn.equalHeights = function(minHeight, maxHeight) 
{
	tallest = (minHeight) ? minHeight : 0;
	this.each(function() 
	{
		if(jQuery(this).height() > tallest) 
			{ tallest = jQuery(this).height(); }
	});
	if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
	
	return this.each(function() { jQuery(this).height(tallest).css("overflow","auto"); });
};

// Specific

var CSSRules = function() // CSSRules.add('#popup', 'position:absolute; ...');
{
	var headElement = document.getElementsByTagName("head")[0],
	styleElement = document.createElement("style");
	styleElement.type = "text/css";
	headElement.appendChild(styleElement);

	var add = function() 
	{
		// IE doesn't allow you to append text nodes to <style> elements
		if (styleElement.styleSheet) {
		return function(selector, rule) 
		{
	    	if (styleElement.styleSheet.cssText == '') { styleElement.styleSheet.cssText = ''; }
	    	styleElement.styleSheet.cssText += selector + " { " + rule + " }";
		}
		}
		else 
		{ 
			return function(selector, rule) { styleElement.appendChild(document.createTextNode(selector + " { " + rule + " }")); }
		}
	}();
	
	return { add : add }
}();

function URL(param, nobuild)
{
	var base = location.href.split (/\?/);

	var ret = {};
	
	var	url = base[0].replace(/http:\/\/[^\/]+/,'');
	
	if (! base[1]) base[1] = ''; 
	
	base[1] = base[1].replace(/#[\w_\-]*$/, '');
	
	var parms = base[1] ? base[1].split('&') : [];
	
	for (var i=0; i<parms.length; i++) 
	{
		var pos = parms[i].indexOf('=');
		if (pos > 0) 
		{
			ret[ parms[i].substring(0,pos) ] = parms[i].substring(pos+1);
		}
	}
	
	if (! param) param = {};
	for(i in param) { ret[i] = param[i]; }
	
	if (nobuild) 
		return ret;

	var url = '?';	
	for(i in ret) { if (/./.test(ret[i])) url += i+'='+ret[i]+'&'; }
	return url.replace(/&$/, '');
}

J = jQuery.noConflict();
E = function (e) { return typeof(e)=='object' ? e : document.getElementById(e); }

window.Cookie = 
{
	get: function (c_name)
	{
		if (document.cookie.length>0)
		{
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1)
			{ 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
		    	return unescape(document.cookie.substring(c_start,c_end));
			} 
		}
		
		return "";
	},
	
	set: function(c_name,value,expiredays)
	{
		if (! expiredays) expiredays = 100;
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	},
	
	del: function( c_name )
	{
		var c = this.get(c_name);
		var exdate=new Date();
		if (c) document.cookie=c_name+"=0;expires=" + exdate.toGMTString() + ";" + ";";
		return c;
	}
};

window.Info = 
{
	show_y:0,
	
	show: function (o)
	{
		var gif = o.ok ? 'ok' : 'bad';
		var msg = o.msg;
		
		if (o.loading) gif = 'loading';

		if (/\n/.test(msg))
		{
			msg = '<ul><li>' + msg.replace(/\n/g, '</li><li>') + '</li></ul>';
		}
		
		e = E('message_box');
		
		e.style.backgroundImage = 'url(/gem/img/'+gif+'.gif)';
		e.style.backgroundPosition = '5px 7px';
		e.style.top = (J(window).scrollTop()+10+Info.show_y)+'px';
		
		e.style.display='block';
		e.innerHTML = msg;
		
		clearTimeout(this._report_timeout);
		this._report_timeout = setTimeout(function () { e.style.display='none' }, 3000);
		
		if (o.ok)
		{
			e.style.border='2px solid #080';
			e.style.backgroundColor='#84FF84';
		}
		else
		{
			e.style.border='2px solid #800';
			e.style.backgroundColor='#FAC7A9';
		}
	},
	warn: function (t) { this.show({ msg:t }) },
	ok: function (t) { this.show({ ok:1, msg:t }) },
	alert: function (t) { this.show({ msg:t }) },
	close: function () { E('message_box').style.display='none' },
	flash: function (t, f) 
	{ 
		Cookie.set('linfo', t);
		if (f == 1)	f = location.href
		location.href = f || location.href;
	},
	ajax: function(el, on)
	{
		if (! el) return;

		if (on)
			setTimeout(function() { Info.ajax(el) }, 3000);

		var e = E(el);
		if (! e) return;

		if (e.nodeName == 'INPUT')
		{
			e.disabled = on ? true : false;
			return;
		}
		
		var img = on ? 'url(/!res/pak/jquery/loading.gif)' : 'none';
		
		if (e.className == 'no-info') return;
		
		J(e).css(
		{ 
			'background-repeat':'no-repeat', 
			'background-image':img,
			'background-position':'99% 1%'
		});
	}
};

window.RPC = 
{
	_timeout: 8000, // AJAX se mora izvrisit u 8 sekundi
	
	_make_func: function(func)
	{
		if (typeof(func)=='string')
		{
			func = func.replace(/^\]/, '>');
			var str = func;
			if (/\//.test(str)) // je URL
			{
				func = function (o) { if (o.ok) Info.flash(o.msg, str); }
			}
			else if (/^>/.test(str)) // AJAX
			{
				str = str.replace(/>/,'');
				func = function (o) { if (o.ok) window.RPC.ajax(str);  }
			}
			else // hide ELEMENT
			{
				func = function (o) { if (o.ok) document.getElementById(str).style.display='none' }
			}
		}
		
		return func;
	},
	
	x: function(proc, oobj, p) // use this, exec, info obsolete
	{
		var obj = oobj;
		
		if (! p) p = {}
		if (! obj) obj = {}
		
		if(obj.nodeName == 'FORM') 
		{
			obj = J(obj).serializeHash()
		}

		if (p.confirm)
		{
			if (! confirm (p.confirm) )
				return false;
		}
		
		if ( p.ajax ) // refresh local block and do ajax
		{
			obj['/ajax'] = p.ajax
			
			if(oobj.nodeName == 'FORM')
				obj['/href'] = oobj.action
		}
		
		if ( p.info )
			Info.show ({ ok:1, loading:1, msg: p.info == 1 ? '...' : p.info }, proc);

		if ( p.mask ) Info.ajax (p.mask, 1);
		
		this.exec ( proc, obj, function (o) 
		{
			if ( p.info ) Info.show (o);
			if ( p.func ) p.func(o, obj);
			if ( p.mask ) Info.ajax (p.mask);
			
			if (o.ok)
			{
				if ( p.ifok ) p.ifok(o, obj);
				
				if ( p.hide ) 
				{
					if (typeof(p.hide) == 'string') // ako je string samo sakrij
						J('#'+p.hide).hide(0)
					else if (typeof(p.hide) == 'object')
						J(p.hide).hide(0);
					else
						J('#'+p.hide[0]).hide(p.hide[1]) // ako nije onda animiraj
				}

				if ( p.redirect ) 
				{ 
					if (/=$/.test(p.redirect)) p.redirect += o.id
					Info.flash(o.msg, p.redirect) 
				}
				
				if(! p.id && oobj.nodeName == 'FORM' && ! p.noreset) oobj.reset();
			}
		})
		
	},

	exec: function (proc, obj, func, reportTarget) 
	{
		var addres = '/rpc/'+proc;
		
		if (! obj) { obj = {} }
		else if (typeof(obj) != 'object')
		{
			alert('RPC.exec error, data not HASH');
			return;
		}
		else if (obj.nodeName == 'FORM')
		{
			obj = J(obj).serializeHash();
		}
		
		obj['/res']='JSON';
		obj['/token'] = USER.token;
		
		if (obj['/ajax'])
		{
			obj['/rpc'] = proc;
			
			for (i in obj)
			{
				if (/^\w/.test(i))
				{
					obj['/rpc'] += ';'+i+':'+escape(obj[i])
					delete obj[i]
				}
			}
			
			addres = obj['/href'] || location.href;
			addres += /\?/.test(addres) ? '&' : '?';
			addres += 'gemajax='+obj['/ajax'];
		}

		var log = '/rpc/'+proc;
		if (window.Log) Log.debug('<a href="'+log+'">'+log+'</a>');
		Info.ajax(reportTarget, 1);

		func = this._make_func(func);
		var me = this;
		
		var Xhr = jQuery.ajax(
		{
			type:'POST',
			url: addres,
			data: obj,
			cache: false,
			error: function (XMLHttpRequest, textStatus, errorThrown) 
			{ 
				if (obj['/ajax']) RPC.ajax(obj['/ajax']);
				else
					Info.alert('AJAX greška: '+textStatus+','+errorThrown) 
			},
			success: function(res)
			{ 
				Info.ajax(reportTarget);
				Xhr=0;

				if (! /^\s*\{/.test(res)) alert('RPC bad response: '+res)
				else
				{
					eval('var o='+res);
					
					if (window.pageTracker)
					{
						for (i in o.event) { window.pageTracker._trackEvent( o.event[i] ) }
					}
					
					if (o.pagepart) 
					{ 
						J('#'+obj['/ajax']).html(o.pagepart) 
					}
					
					if (func) func(o) // uvijek zelim json objekt
				}
			}
		});

		setTimeout (function()
		{
			if ( Xhr && Xhr.readyState < 4) 
			{
				Xhr.abort();
				Info.ajax(reportTarget);
			}
		}, 
			this._timeout);
	},

	info: function ( proc, data, func, reportTarget )
	{
		Info.show ({ ok:1, loading:1, msg:'...' }, proc);
	
		func = this._make_func(func);
		
		this.exec ( proc, data, function (o) 
		{
			Info.show (o);
			if (func && o.ok) func(o)
		}, 
			reportTarget)
	}
};

window.Rpc = function(a,b,c) { RPC.x(a,b,c) }

// AutoComplete

/*
	AC.init(
	{ 
		rpc:'user.search',   - rpc
		obj:'trazit',        - HTML el ID
		form: 'trazit_form', - disable form submit
		y:26,                - y offset
		render: function(o) { return '<img width="24" height="24" style="vertical-align:middle;" src="'+(o.avatar||'/res/images/avatar.gif')+'" border="0" alt="" /> '+o.nick; },
		select: function(o) { alert('Handle: '+o.nick);	}
		before: function(o) { ... } - izvrsi prije RCP-a. vraca vrijednost za rpc
	});
*/

var AC = 
{
	cache: 
	{ 
		data: [],
		raw : {}
	},
	
	select: function (e)
	{ 
		if (this.cache.form) this.cache.form.submit( function() { return false; } );
		
		if (this.o.select) 
		{
			this.clear();
			this.o.select(e);
		}
		else
			alert('SELECT not defined!') 
	},
	
	select_node: function(val)
	{
		var n = AC.cache.data[0] + val;
		var target = J('#ac_el_'+n);
		
		if (! target.attr('id')) return;
		
		J('#ac_el_'+AC.cache.data[0]).removeClass('active');
		J('#ac_el_'+n).addClass('active');
		
		AC.cache.data[0]=n;
	},
	
	clear: function()
	{
		AC.cache.data = [];
		AC.cache.data[0] = 0;
		J('#ac_el, #AutoComplete').remove();
	},

	get: function()
	{
		var o = this.o;
		var p = o.param;
		
		p[o.qs] = this.e.attr('value');

		if (o.before)
		{
			p[o.qs] = o.before(p[o.qs]);
		}

		if (! p[o.qs]) return;

		var cacheID = o.rpc+p[o.qs];

		var me = this;
		
		function ac_rpc(res)
		{
			me.cache.raw[cacheID] = res;
			
			var ret = ''
			AC.cache.data = [];

			me.clear();
			o.rpcEnd(me.e);

			for (var i=1;res.msg[i];i++)
			{
				var el = {};
				for (var j=0;res.msg[i][j];j++) { el[ res.msg[0][j] ] = res.msg[i][j]; }
				AC.cache.data[i]=el;
				
				var render = o.render(el);
				ret += '<div id="ac_el_'+i+'" rel="'+i+'" class="ac_el"  style="display:block;" onclick="AC.select(AC.cache.data['+i+'])">'+render+'</div>\n';	
			}
			
			var data = o.wrap(ret);
			
			me.e.before(data);
			
			J('.ac_el').hover(function(){ J(this).addClass('active');AC.cache.data[0]=J(this).attr('rel') }, function(){ J(this).removeClass('active') } );
			AC.cache.data[0]=0;
		}

		var cache_data = me.cache.raw[cacheID];
		
		if (typeof(cache_data) == 'object') 
			ac_rpc(cache_data)
		else
		{
			AC.tOut = setTimeout(function()
			{
				o.rpcStart(me.e);
				RPC.exec(o.rpc, p, ac_rpc);
			}, 
				this.o.timeout);
		}
	},
	
	init: function(o)
	{
		this.e = J('#'+o.obj) || alert('BIND elament nije pronađen!'); 
		
		var parent = E(o.obj).parentNode
		
		while (parent)
		{
			if (parent.nodeName == 'FORM')
			{
				this.cache.form = J(parent);
			}

			parent = parent.parentNode;
		}
		
		if (this.e.attr('value') == this.lastValue) return;
		this.lastValue = this.e.attr('value');
		
		this.e.attr('autocomplete', 'off');
		this.clear();
		
		if (AC.tOut) clearTimeout(AC.tOut);
		
		var me = this;
		
		if (! this.e.attr('KeySet'))
		{
			this.e.keydown(function (e) 
			{
				var key = e.which;
				 
				if (key == 38) { me.select_node(-1); }
				else if (key == 40) { me.select_node(1); }
				else if (key == 13) { J('#ac_el_'+AC.cache.data[0]).click();  }
			});
			
			this.e.attr('KeySet', 1);
		}
		
		o.rpc || alert('RPC nije definiran');
		o.render || alert('RENDER-func nije definiran');
		o.qs = o.qs || this.e.attr('name');
		o.cssClass = o.cssClass || 'autocomplete';
		o.param = o.param || {};
		o.x = o.x || 0;
		o.y = o.y || 0;
		o.timeout = o.timeout || 300;
		o.wrap  = o.wrap || function (data) { return '<div id="AutoComplete" class="'+o.cssClass+'" style="position:absolute;left:'+o.x+'px;top:'+(o.y+26)+'px">\n'+data+'</div>' }
		o.rpcStart = o.rpcStart || function () { 1; }
		o.rpcEnd = o.rpcStart || function () { 1; }
		this.o = o;
		this.get();				
	},
	
	bind: function(params)
	{
		J('#'+params.obj).keyup( function (k) { AC.init(params) })
	}
};

var Ajax = 
{
	// blok - local blok id="#blok"
	// url  - {} ili string
	refresh: function(blok, url, func)
	{
		if(! url) { url = {} }

		if (typeof(url) == 'object')
		{
			if (url.nodeName == 'A')
			{
				url = url.href;
			}
			else
			{
				url['gemajax'] = blok;
				url = URL ( url );
			}
		}
		
		Info.ajax(blok, 1);

		jQuery.ajax({ type: 'GET', url: url, cache: false, success: function(res) 
		{ 
			jQuery('#'+blok).html(res);
			
			Info.ajax(blok);
			
			if (func) func();
		}});
		
		return false;
	},
	
	form: function ( el_form, target, func )
	{
		var el = E( el_form );
		var id = el.id || alert('Ajx forma nema ID!')
		
		if (! el.nodeName == 'FORM') alert('Element nije FORMA, on je +'.el.nodeName);
		
		var data = J(el).serializeHash();
		if (target) data['gemajax'] = target;

		Info.ajax(target, 1);
		
		jQuery.ajax({ type: el.method || 'post', url: el.action || location.href, data:data, cache: false, success: function(res) 
		{ 
			Info.ajax(target);
			
			if (! target) // local RPC submit? daj info
			{
				Info.show(res);	
			}
			else if ( typeof (target) == 'function' ) { target(res); }
			else
			{	
				J('#'+target).html( res );
			}
		}});
		
		return false;
	}
};

// ellipsis - Text overflow, http://dl.getdropbox.com/u/534786/index.html

jQuery.fn.ellipsis = function(enableUpdating){
		var s = document.documentElement.style;
		if (!('textOverflow' in s || 'OTextOverflow' in s)) {
			return this.each(function(){
				var el = jQuery(this);
				if(el.css("overflow") == "hidden"){
					var originalText = el.html();
			        var w = el.width();
			        var t = jQuery("#_ellipsis_calc");
			        var ex = t.length < 1;
			        if(ex){
			        	t = jQuery("<span id='_ellipsis_calc'/>").html(originalText).hide().appendTo("body");
			        }	
			        
			        var text = originalText;
			        while(text.length > 0 && t.width() > el.width()){
			        	text = text.substr(0, text.length - 1);
			        	t.html(text + "...");
			        }
			        el.html(t.html());
			        if(!ex)t.remove();
			        
			        if(enableUpdating == true){
						var oldW = el.width();
			       		setInterval(function(){
				      		if(el.width() != oldW){
				      			oldW = el.width();
				      			el.html(originalText);
				      			el.ellipsis();
				      		}
				      	}, 200);
			        }
			    }  
			});   
	    } else return this; 
	}


// Finish

if (window.DEV)
	window.onerror = function (s1, s2, s3) { alert('JS ERR in '+s2+'\n\n'+s1) }

jQuery(function() 
{ 
	if (! E('message_box') )
		jQuery(document.body).append('<div id="message_box" style="display:none; position:absolute; top:100px; left:30px; padding:4px 15px 4px 28px; background-repeat:no-repeat; background-position:4px 4px; font-family:verdana; font-size:13px;"></div>'); 

	if (jQuery.browser.mozilla) // base fix za debilni FF
	{
		var base = jQuery('head base').attr('href');
		
		jQuery('a[href]').each( function() 
		{
			var href = this.getAttribute('href');
			
			if ( /^\w/.test(href) && ! /^\w+:/.test(href))
				this.setAttribute('href', base+href);
		});
	}
});

window.Util = window.Util || {};

Util.opts = function(elin)
{
	var data = elin.nodeName ? J(elin).attr('class') : elin;
	
	var elms = data.split(' ');
	var opt = {};
	
	for ( var i=0; elms[i]; i++ )
	{
		var part = elms[i].split(':', 2);
		if (part[1]) opt[part[0]] = part[1];
	}
	
	return opt;
}

Util.monitor = function(el, func)
{
	jQuery(function()
	{
		var e = J('#'+el);
		var val = e.attr('type')=='checkbox' ? e.is(':checked') : J('#'+el).val();
		func(val);
		J('#'+el).change( function() 
		{ 
			var e = J('#'+el);
			var val = e.attr('type')=='checkbox' ? e.is(':checked') : J('#'+el).val();
			func( val ) 
		})
	})
}

J(function() // IE fix base HREF
{
	if (! J.browser.msie) 
		return;
	
	var b = document.getElementsByTagName('base');
	if (! b) return;
	b = b[0].getAttribute('href');
	
	if (b.substr(b.length-1) != '/')
		return;
	
	J('a').each(function()
	{
		var loc = this.getAttribute('href');
		
		if (loc && loc.charAt(0) != '/')
			this.setAttribute('href', b + loc);
	});
});
