
// trim html string - remove leading and trailing spaces (&nbsp, \s and \xA0) from string toTrim[STRING]
function trimHtmlString(toTrim)
{
	toTrim = trimString(toTrim);

	toTrim = toTrim.replace(/^(&nbsp;|\s|\xA0)+/g,'');
	toTrim = toTrim.replace(/(&nbsp;|\s|\xA0)+$/g,'');

	return toTrim;
}

// removes leading and trailing spaces from string
function trimString(toTrim)
{
	var i, j, ch, str;

	i = 0;
	j = toTrim.length;
	while(j>0)
	{
		ch = toTrim.charAt(j-1);
		if ((ch != ' ') && (ch != '\r') && (ch != '\n') && (ch != '\t'))break;
		j--;
	}
	if (j != 0)
	{
		ch = toTrim.charAt(i);
		while((ch==' ') || (ch=='\r') || (ch=='\n') ||  (ch=='\t'))
		{
			i++;
			ch = toTrim.charAt(i);
		}
	}
	str = toTrim.substring(i,j);
	return str;
}

// checks if s[STRING] is empty
function isEmpty(s)
{
	s = trimString(s);
	return ((s == null) || (s.length == 0))
}



// Copyright (C) krikkit - krikkit@gmx.net
// --> http://www.krikkit.net/
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// notes about security:
// a cause of the tight security settings in mozilla you have to sign the javascript to make it work another way is to change your firefox/mozilla settings
// to do this add this line to your prefs.js file in your firefox/mozilla user profile directory
// user_pref("signed.applets.codebase_principal_support", true);
// or change it from within the browser with calling the "about:config" page

function copyToClipBoard(meintext) {

	if (window.clipboardData) {

		// the IE-manier
		window.clipboardData.setData("Text", meintext);

		// waarschijnlijk niet de beste manier om Moz/NS te detecteren;
		// het is mij echter onbekend vanaf welke versie dit precies werkt:
	} else if (window.netscape) {

		// dit is belangrijk maar staat nergens duidelijk vermeld:
		// you have to sign the code to enable this, or see notes below
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		// maak een interface naar het clipboard
		var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;

		// maak een transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;

		// specificeer wat voor soort data we op willen halen; text in dit geval
		trans.addDataFlavor('text/unicode');

		// om de data uit de transferable te halen hebben we 2 nieuwe objecten
		// nodig om het in op te slaan
		var str = new Object();
		var len = new Object();
		var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
		var copytext=meintext;

		str.data=copytext;
		trans.setTransferData("text/unicode",str,copytext.length*2);

		var clipid=Components.interfaces.nsIClipboard;
		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);
	}
	alert("Nasledovna informacia sa kopirovala do vasej schranky:\n\n" + meintext);
	return false;
}

//
// returns 0 if OK else
// 1 - empty login field
// 2 - empty password
//

function checkLogin(login, password)
{
	var result = 0;

	if (isEmpty(login.value))
	{
		result = 1;
	}

	if (isEmpty(password.value))
	{
		result = 2;
	}

	return result;
}

function checkPasswordLength(pwd, pwdMinLen, pwdMaxLen)
{
	return (pwd == "") || ((pwd.length >= pwdMinLen) && (pwd.length <= pwdMaxLen));
}

//
// returns 0 if OK else
// 1 - bad password length
// 2 - empty password
// 3 - confirm password do not match with password
//
function checkPasswords(adminLogged, inEditMode, password, confirm_password, pwdMinLen, pwdMaxLen)
{
	var result = 0;

	if (!inEditMode || (password.length != 0) || (confirm_password.length != 0))
	{
		password = trimString(password);
		confirm_password = trimString(confirm_password);

		if (password != confirm_password)
		{
			result = 3;
		}
		else
		{
			if ((password.length == 0) || (confirm_password.length == 0))
			{
				result = 2;
			}
			else
			if (  ((password != "") && !checkPasswordLength(password, pwdMinLen, pwdMaxLen))
			||((confirm_password != "") && !checkPasswordLength(confirm_password, pwdMinLen, pwdMaxLen)))
			{
				result = 1;
			}

		}
	}
	return result;
}

/*parse date by format*/
function parsedate(a, format)
{
	var rv,v1,v2,v3,d,m,y,c,e, delimiter;

	if (format == 'YYYY-MM-DD' )
	{
		delimiter = '-';
	}
	else
	{
		delimiter = '.';
	}

	c = a.indexOf(delimiter);
	if (c>0)
	{
		e = a.indexOf(delimiter, c+1);
	}
	if (c == -1 || e == -1)
	{
		return false;
	}

	v1 = parseInt(a.substring(0, c),10);           // day
	v2 = parseInt(a.substring(c+1, e),10);         // month
	v3 = parseInt(a.substring(e+1,10),10);         // year

	if( format == 'YYYY.MM.DD.' || format == 'YYYY-MM-DD' ) // HU OR database date format (YYYY-MM-DD)
	{
		d = v3;
		m = v2;
		y = v1;
	}
	else if (format == 'DD.MM.YYYY' )
	{
		d = v1;
		m = v2;
		y = v3;
	}
	else
	{
		d = v1;
		m = v2;
		y = v3;
	}
	rv = new Array(3);
	rv[0] = d;
	rv[1] = m;
	rv[2] = y;
	return rv;
}

/*parse datetime by format, date, time delimiter is space*/
function parsedatetime(datetime, format)
{
	var c, rv, part1, part2, temp, fpart1, fpart2;
	var delimiter = ' ';

	c = datetime.indexOf(delimiter);
	if (c == -1)//default date
	{
		rv = new Array(2);
		rv[0] = datetime;
		rv[1] = '';
		return rv;
	}
	part1 = datetime.substring(0, c); //date - first
	part2 = datetime.substring(c+1); //time - second

	rv = new Array(2);
	rv[0] = part1;
	rv[1] = part2;

	return rv;
}
/*check date with time, separated by space, date must by first*/
function checkdatetime(a, format, time_optional)
{
	var date, time, rv, rvf;

	rv = parsedatetime(a, format);
	if(!rv)
	{
		return false;
	}
	rvf = parsedatetime(format, format);
	if(!rvf)
	{
		return false;
	}

	//skontrolujem datum
	if( checkdate(rv[0], rvf[0]) && ( rv[1]=='' && time_optional || checktime(rv[1], rvf[1]) ))
	{
		return true;
	}

	return false;
}

/*parse time, 2 formats are alowed: HH:II:SS and HH:II */
function parsetime(time, format)
{
	var delimiter = ':';
	var c, d;

	//parse
	c = time.indexOf(delimiter);
	if (c == -1)
	{
		return false;
	}
	rv = new Array(3);
	if(format == 'HH:II:SS' )
	{
		rv[0] = parseInt(time.substring(0, c),10);           // hour
		d = time.substring(c+1);
		c = d.indexOf(delimiter);
		if (c == -1)
		{
			return false;
		}
		rv[1] = parseInt(d.substring(0, c),10);         // minute
		rv[2] = parseInt(d.substring(c+1),10);         // second
	}
	else if(format == 'HH:II')
	{
		rv[0] = parseInt(time.substring(0, c),10);     // hour
		rv[1] = parseInt(time.substring(c+1) ,10);     // minute
		rv[2] = 0;
	}
	else
	{
		return false;
	}

	return rv;
}

/*check time, 2 formats are alowed: HH:II:SS and HH:II*/
function checktime(a, format)
{
	var delimiter = ':';
	var rv, h, m, s;

	if(format == '' && a != '')
	{
		return false;
	}

	if(format == '' && a == '')
	{
		return true;
	}

	rv = parsetime(a, format);

	if(!rv)
	{
		return false;
	}

	h = rv[0];
	m = rv[1];
	s = rv[2];

	if(h<0 || h>=24 || m < 0 || m>=60 || s<0 || s>= 60)
	{
		return false;
	}

	return true;
}

function checkdate(a, format)
{
	var err=0;
	var rv,d,m,y,tmp;

	//if (a.length != 10) err=1;

	//alert(format);
	tmp = parsedate(a,format);
	d = tmp[0];
	m = tmp[1];
	y = tmp[2];

	//basic error checking
	if( !d || !m || !y ) err = 1;
	if (m<1 || m>12) err = 1;
	if (d<1 || d>31) err = 1;
	if (y<2000) err = 1;


	//advanced error checking

	// months with 30 days
	if (m==4 || m==6 || m==9 || m==11){
		if (d==31) err=1
	}

	// february, leap year
	if (m==2)
	{
		// feb
		var g=parseInt(y/4)
		if (isNaN(g))
		{
			err=1;
		}
		if (d>29) err=1
		if (d==29 && ((y/4)!=parseInt(y/4))) err=1
	}


	return err==1 ? false : true;
}

/**
is city abbreviation ?
*/
function isCityAbbr(city)
{
	if( city.length == 2 && city.toUpperCase() == city )
	{
		return true;
	}
	return false;
}

function StopOnBeforeUnload()
{
	onbeforeunload_stop= true;
}


function CentralToWestern(string_value)
{
	var new_string = '', tr;

	for (i=0; i<string_value.length; i++)
	{
		tr = C_StrippedChars.charAt(C_DiacriticChars.indexOf(string_value.charAt(i)));
		new_string += tr ? tr : string_value.charAt(i);
	}

	return new_string;
}



/**
* return sign of number
**/
function Sign(X)
{
	return (X>0 ? '+' : X<0 ? '-' : ' ')
}

/**
* return +/- 1 depending on number sign
**/
function SignOne(X)
{
	return 1*(Sign(X)+'1');
}

/**
* edhanced round function, with fixed round(-0.5) = 0 bug
**/
function MyRound(number, precision)
{
	var precision_num;

	precision_num = Math.pow(10,precision);
	return SignOne(number) * Math.round(Math.abs(number)*precision_num)/precision_num;
}


function GetDocumentTop()
{

	//define reference to the body object in IE
	var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body

	//define universal dsoc top point
	var dsoctop=document.all? iebody.scrollTop : pageYOffset

	return dsoctop;
}



function GetObjectPosition(obj)
{
	var curleft = curtop = 0;

	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}

	return [curleft,curtop];
}

	function categoryPositionSearchCursorWait(element) {
	 var cursor =
     document.layers ? document.cursor :
     document.all ? document.all.cursor :
     document.getElementById ? document.getElementById('cursor') : null;

     cursor = 'wait';
     element.style.cursor = 'wait';
	}

	function categoryPositionSearchCursorClear(element) {

	 var cursor =
     document.layers ? document.cursor :
     document.all ? document.all.cursor :
     document.getElementById ? document.getElementById('cursor') : null;

     cursor = 'default';
     element.style.cursor = 'default';

}

function HighlightString(string, searched_text, string_search)
{
	var idx = string_search.indexOf(searched_text);

	if(idx<0)
	{
		return string;
	}


	return string.substring(0,idx) + '<b>' + string.substring(idx, idx+searched_text.length) + '</b>' + string.substring(idx+searched_text.length);

}


function IsNumeric(value)
{
	return parseInt(value,10) == value;
}

function IsPositiveNumeric(value)
{
	return parseInt(value,10) == value && value>0;
}

//get radio value
function getRadioCheckedValue(radio)
{
	var i=0;

	for (i=0; i<radio.length; i++)
	{
		if(radio[i].checked == true)
		{
			return radio[i].value;
		}
	}
	return false;
}

//get radio value
function setRadioCheckedValue(radio, value)
{
	var i=0;

	for (i=0; i<radio.length; i++)
	{
		if(radio[i].value == value)
		{
			radio[i].checked = true;
		}
		else
		{
			radio[i].checked = false;
		}
	}
	return true;
}

//is radio checked and has value ?
function isRadioCheckedValue(radio, value)
{
	if( getRadioCheckedValue(radio) === value ) //because of false and 0 values
	{
		return true;
	}
	return false;
}

//set SELECT value
function setSelectedValue(select, value)
{
	var i=0;

	for (i=0; i<select.length; i++)
	{
		if(select[i].value == value)
		{
			select[i].selected = true;
		}
		else
		{
			select[i].selected = false;
		}
	}
	return true;
}

function htmlspecialchars(ch)
{
  ch = ch.replace(/&/g,"&amp;") ;
  ch = ch.replace(/"/g,"&quot;") ;
  ch = ch.replace(/'/g,"&#039;") ;
  ch = ch.replace(/</g,"&lt;") ;
  ch = ch.replace(/>/g,"&gt;") ;
  return ch ;
}

//wordwrap text
function wordwrap( str, int_width, str_break, cut, use_htmlspecialchars ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Nick Callen
    // *     example 1: wordwrap('Kevin van Zonneveld', 6, '|', true);
    // *     returns 1: 'Kevin |van Zo|nnevel|d'

    var i, j, s, r = str.split("\n");
    if(int_width > 0) for(i in r){
        for(s = r[i], r[i] = ""; s.length > int_width;
            j = cut ? int_width : (j = s.substr(0, int_width).match(/\S*$/)).input.length - j[0].length || int_width,
            r[i] += (use_htmlspecialchars ? htmlspecialchars(s.substr(0, j)): s.substr(0, j)) + ((s = s.substr(j)).length ? str_break : "")
        );
        r[i] += (use_htmlspecialchars && typeof(s)=== 'string'  ? htmlspecialchars(s) : s);
    }
    return r.join("\n");
}

function RecalculateInvoicePrice(form){

 	total_price = 0;
	ids 		= Array();

 	if(form.elements["invoice_ids[]"].value){
 	 	ids = Array( form.elements["invoice_ids[]"] );
 	}else{
 		ids = form.elements["invoice_ids[]"];
 	}

 	for (var i=0; i< ids.length; i++)
    {
      if (ids[i].checked)
       {
          invoice_id = ids[i].value;
          total_price += Math.round(parseFloat(form.elements["invoice_price["+invoice_id+"]"].value *100)) / 100;
        }
      }

    form.totalprice.value = total_price;
    return true;
}

function RefreshTableByTab(body_id_show, body_ids, tab_number_active, tab_stab_id)
{
	var i=0;
	var obj;

	for (i=0; i<body_ids.length; i++)
	{
		obj = document.getElementById(body_ids[i]);
		if(!obj)
		{
			continue;
		}

		if(body_ids[i] == body_id_show)
		{
			obj.style.display='';
		}
		else
		{
			obj.style.display='none';
		}
	}

	obj = document.getElementById(tab_stab_id);
	if(obj)
	{
		tab_number_active++;
		obj.className = 'stab'+tab_number_active;
	}

	return false;
}

function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function OnClickInteresting(offer_id)
{
	var x,y, elm, add, filename;

	elm = document.getElementById("id_img_" + offer_id);

	if(elm)
	{
		filename = elm.src;

		if(filename.match(/star-s/))
		{
			add = 0;
			filename = filename.replace(/star-s/, 'star');
		}
		else
		{
			add = 1;
			filename = filename.replace(/star/, 'star-s');
		}

		elm.src = filename;

		elm = document.getElementById('id_interesting');

		if(elm)
		{
			var new_count = parseInt(elm.innerHTML,10) + (add ? 1:-1);
			elm.innerHTML = new_count;

			elm = document.getElementById('id_interesting2');
			if(elm)
			{
				elm.innerHTML = '(' + new_count + ')';
			}
		}
	}

	makeHttpRequest(C_DocumentRoot + C_language + '/list_offers.php?ajax=1&interesting_' + (add ? 'add' : 'del')+ '=' + offer_id, 'LO_Redraw', false);

	return false;

}

function OnClickInterestingOffer(offer_id, t_add, t_del)
{
	var x,y, elm, add,classname;

	elm = document.getElementById("offer_add_interesting");
	if(elm.className.match(/del/))
	{
		add = 0;
		classname = "ico-favorite-add";
	}
	else
	{
		add = 1;
		classname = "ico-favorite-del";
	}

	elm.className = classname;
	elm.innerHTML = add ? t_del : t_add; // invert texts

	makeHttpRequest( C_DocumentRoot + C_language + '/list_offers.php?ajax=1&interesting_' + (add ? 'add' : 'del')+ '=' + offer_id, '', false);

	return false;

}

function LO_Redraw(html)
{
	var elm;

	elm = document.getElementById("id_interestingoffers");

	if(elm)
	{
		elm.innerHTML = html;
	}

}

function makeHttpRequest(url, callback_function, return_xml, loader)
{
	var loader = loader || false;
	var http_request = false;

	if (loader) {
		origSrc = document.getElementById(loader).src;
		document.getElementById(loader).src = '/images/ajax-loader.gif';
	}

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request)
	{
		return false;
	}

	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			try{
				if (http_request.status == 200) {
					if (loader) document.getElementById(loader).src= origSrc;

					if(callback_function)
					{
						if (return_xml)
						{
							eval(callback_function + '(http_request.responseXML)');
						}
						else
						{
							eval(callback_function + '(http_request.responseText)');
						}
					}
				}
			}
			catch(e)
			{
				// problem
			}
		}
	}

	http_request.open('GET', url, true);
	http_request.send(null);
}

var Profesia = {
	focus: function (element) {
		var elm = document.getElementById(element);
		if (elm) {
			elm.focus();
			elm.selectionStart = elm.selectionEnd = 0;
		}
	}
}

function nextFreeDepth(){
	if (this.___next_free_depth == undefined){
		this.___next_free_depth = 8180;
	}
	return this.___next_free_depth++;
}

function setAutocompleterStyles(tBox,selectBox,full_width) {

		selectBox.css('margin','0px');
		selectBox.css('padding','0px');

		tBox.css('top','0px');
		tBox.css('left','0px');

		if (full_width){
			selectBox.hide();
		} else {
			tBox.css('padding','1px 0 0 3px');
			tBox.css('margin','2px');
		}
                
}

function AutocompletizeSelectBox(selectbox_element_id,selected_value,onclick_behaviour, tab_index , full_width)
{$(document).ready(function(){
		// extract data from selectbox

		var selectBox = $('#' + selectbox_element_id);
		selectBox.wrap('<span style="position:relative;float:left;" class="w_autocompleter"></span>');

		if (typeof(autocompleter_hide_on_start) !== 'undefined' && autocompleter_hide_on_start ){
			$('.w_autocompleter').hide();
		}

		if (typeof(tab_index) == 'undefined' ){
			tab_index = 0;
		}

		if (typeof(full_width) == 'undefined'){
			full_width = false;
		}
		var last_selected_value = '';

		var data = [];

		selectBox.find('option').each(function(){

			// left spaces
			var occ = this.text.match(/^[ \f\n\r\t\v\u00A0\u2028\u2029]+/);
			//
			var space = (occ == null)?0:occ[0].length;
			var txt = this.text.substring(space);
			var seo = CentralToWestern(txt);
			var value = this.value;
            var obj = {'text':txt , 'value':value , 'seo': seo , 'space' : space};

            // console.log(obj);
            data.push(obj);
        });

		// attach inputbox
		var select_box_w = parseInt(selectBox.css('width'));
		var select_box_h = parseInt(selectBox.css('height'))-((full_width)?0:2);
		var tbox_style = "width:" + (select_box_w  - ((full_width)?7:22)) + 'px; height:' + (select_box_h) + 'px;';


		var tbox_id = selectbox_element_id + '_ac';

		selectBox.after('<input type="text" name="'+tbox_id+'" id="'+tbox_id+'" value="" autocomplete="off" style="'+tbox_style+'" />');
		var tBox = $('#'+tbox_id);

		//tBox.css('position','absolute');
		tBox.css('z-index',nextFreeDepth());
                tBox.css('display', 'none');
                tBox.css('color', 'red');

		setAutocompleterStyles(tBox,selectBox,full_width);
		if (selected_value === true){
			tBox.val(data[selectBox[0].selectedIndex].text);
		} else if ( typeof( selected_value ) == 'string' ){
			tBox.val(selected_value);
			if (onclick_behaviour === 1 || onclick_behaviour === 2){
				// attach event on click hide initial text
				tBox.focus(
					function(){
						if ( this.value == selected_value  ){
							this.value = '';
							selectBox.val('');
						}
					}
				);
				tBox.change(
					function(){
						if (this.value != last_selected_value){
							// set matching selectbox value if the text are same and no duplicate elements occurs

							var matches = 0;
							var sel_value = 0;
							for(var kk in data){

								if (CentralToWestern(this.value.toLowerCase()) == data[kk].seo.toLowerCase()){
									sel_value = data[kk].value;
									matches++;
								}
							}

							if (matches === 1){
								// set the proper value
								selectBox.val(sel_value);
							} else {
								selectBox.val('');
							}
						}
					}
				);


			}

			if (onclick_behaviour === 2){
				// attach event on click hide initial text
				tBox.blur(
					function(){
						if ( this.value == '' ){
							this.value = selected_value;
							selectBox.val('');
						}

					}
				);
			}

			// attach other behaviour events

		} else if ( typeof( selected_value ) == 'number' ) {


			tBox.val(data[selected_value].text);
		}


		tBox.autocomplete( data , {
			formatItem:function(row,i,max){
				return row.text;
			},
			formatMatch:function(row,i,max){
				return row.seo +' '+row.text;
			},
			formatResult:function(row,i,max){
				return row.text;
			},
			matchContains:true,
			max:30,
			width: select_box_w
		} ) . result( function(event,data,formatted){
			last_selected_value = data.text;
			selectBox.val(data.value);
			tBox.blur( function(){
				selectBox.val(data.value);
				tBox.blur( function () {} );
			});
		} );

		// attach events
		selectBox.change(
			function (){
				var val = $(this).val();
				for( i in data){
					if (data[i].value == val){
						tBox.val(data[i].text );
						break;
					}
				}
			}
		)
})}


function AutocompletizeSelectBoxWithOG(selectbox_element_id,selected_value,onclick_behaviour, tab_index)
{$(document).ready(function(){
		// extract data from selectbox

		var selectBox = $('#' + selectbox_element_id);
		selectBox.wrap('<span style="position:relative;float:left;" class="w_autocompleter"></span>');

		if (typeof(autocompleter_hide_on_start) !== 'undefined' && autocompleter_hide_on_start ){
			$('.w_autocompleter').hide();
		}

		if (typeof(tab_index) == 'undefined' ){
			tab_index = 0;
		}

		var data_parents = [];
		var data = [];
		var parent_map = [];

		selectBox.find('optgroup').each(function(){

			var p_obj_id = data_parents.length;
			$(this).find('option').each(function(){
				data.push( {'text':this.text, 'parent_id':p_obj_id , 'id':data.length , 'value':this.value} );
			});

			data_parents.push( {'text':this.label ,'parent_id':p_obj_id} );

		});

        // attach inputbox
		var select_box_w = parseInt(selectBox.css('width'));
		var select_box_h = parseInt(selectBox.css('height'))-2;
		var tbox_style = "width:" + (select_box_w - 22 ) + 'px; height:' + (select_box_h) + 'px;';
		var tbox_id = selectbox_element_id + '_ac';

		selectBox.after('<input type="text" name="'+tbox_id+'" id="'+tbox_id+'" value="" autocomplete="off" style="'+tbox_style+'" />');
		var tBox = $('#'+tbox_id);

		//tBox.css('position','absolute');

		tBox.css('z-index',nextFreeDepth());

		setAutocompleterStyles(tBox,selectBox);

		if (selected_value === true){
			tBox.val(data[selectBox[0].selectedIndex].text);
		} else if ( typeof( selected_value ) == 'string' ){
			tBox.val(selected_value);
			if (onclick_behaviour === 1 || onclick_behaviour === 2){
				// attach event on click hide initial text
				tBox.focus(
					function(){
						if ( this.value == selected_value ){
							this.value = '';
							selectBox.val('');
						}
					}
				)
			}

			if (onclick_behaviour === 2){
				// attach event on click hide initial text
				tBox.blur(
					function(){
						if ( this.value == '' ){
							this.value = selected_value;
							selectBox.val('');
						}
					}
				)
			}

			// attach other behaviour events

		} else if ( typeof( selected_value ) == 'number' ) {
			tBox.val(data[selected_value].text);
		}

		tBox.autocomplete( data , {
			formatItem: function(row, i, max){

					// position
					var str = '';
					// display parent category if is first result
					if (i == 1){
						// reset cat_map
						parent_map = [];
					}
					if (parent_map[row.parent_id] != true){
						//
						str += '<strong>' + data_parents[row.parent_id].text  + '</strong><br />';
						parent_map[row.parent_id] = true;
					}
					str += '<span style="margin-left:10px;">'+ row.text + '</span>';
					return str;

			},
			formatMatch: function(row, i, max ){

					// position
					// attach category to match its label + search
					var cat = data_parents[row.parent_id] ;

					var str = CentralToWestern(row.text) + ' ' + row.text  +' '+ CentralToWestern(cat.text) +' '+cat.text ;
					return str.toLowerCase();

			},
			formatResult: function(row, i, max ){

					// position
					// attach category to match its label + search
					var cat = data_parents[row.parent_id] ;
					var str = row.text +' ('+ cat.text +')' ;
					return str;

			},
			matchContains:true,
			max:30,
			width: select_box_w
		} ) . result( function(event,data,formatted){
			selectBox.val(data.value);
			tBox.blur( function(){
				selectBox.val(data.value);
				tBox.blur( function () {} );
			});

		} );

		// attach events
		selectBox.change(
			function (){
				var val = $(this).val();
				for( i in data){
					if (data[i].value == val){
						tBox.val(data[i].text );
						break;
					}
				}
			}
		)

})}

function SBAutocompletizer(selectbox_element_id)
{
	this._selectbox_element_id = selectbox_element_id;
	this._sb = $('#' + selectbox_element_id );        
	this._data = [];
	this._resultDisplayParent = true;
	this._entered_text = '';
	this._selected_text = '';
	this._callbacks = [];
}

var p = SBAutocompletizer.prototype;

p.DEFAULT_STRING_MODE_NONE = 0;
p.DEFAULT_STRING_MODE_HIDE = 1;
p.DEFAULT_STRING_MODE_RESET = 2;

p.PARSING_MODE_SIMPLE = 0;
p.PARSING_MODE_TREE_BY_SPACE = 1;
p.PARSING_MODE_OPT_GROUP = 2;

p.setDefaultString = function(str){
	this._defaultString = str;
}
p.setDefaultStringBehaviour = function(mode){
	this._defaultStringBehaviour = mode;
}

p.setParsingMode = function(mode){
	this._parsingMode = mode;
}
p.setTabIndex = function( tabindex ){
	this._tabIndex = tabindex;
}
p.setResultDisplayParent = function(bool){
	this._resultDisplayParent = bool;
}
p.loadData = function(){


	var last_space = false;
	var parents = {};
	var data = this._data;

	var ac_obj = this;
	var clearing_re = /^[ \f\n\r\t\v\u00A0\u2028\u2029]+/;

	if (this._parsingMode == this.PARSING_MODE_OPT_GROUP){

		this._sb.find('optgroup').each(function(){

			var par_label = this.label;
			$(this).find('option').each(function(){
				if (this.selected && this.text != ''){
					ac_obj._selected_text = this.text;
				}
				data.push( {'text':this.text + ' (' + par_label +')', 'value':this.value , 'seo':  CentralToWestern(this.text.toLowerCase()+' '+ par_label.toLowerCase() )} );
			});
		});

	}else{

		this._sb.find('option').each(function(){

			// left spaces
			var occ = this.text.match(clearing_re);
			//
			clname = $(this).attr('class');
			if (occ == null && clname.substr(0,4) == 'padd'){
				var space = parseInt(clname.substr(4))*4;
				var txt = this.text;
			} else {
				var space = (occ == null)?0:occ[0].length;
				var txt = this.text.substring(space);
			}


			var seo = CentralToWestern(txt.toLowerCase());
			if (this.selected && txt != ''){
				ac_obj._selected_text = txt;
			}

			var value = this.value;
	        var obj = {'text':txt , 'value':value , 'seo': seo , 'space' : space};

	        if (space > last_space && last_space != -1){
				parents[space] = data.length - 1;
			}

			obj.parent_id = parents[space];
			last_space = space;

	        data.push(obj);
	    });

	}

}

p.render = function(){


	this.loadData();

	var selectBox = $('#' + this._selectbox_element_id);
	selectBox.wrap('<span style="position:relative;float:left;" class="w_autocompleter"></span>');

	if (typeof(autocompleter_hide_on_start) !== 'undefined' && autocompleter_hide_on_start ){
		$('.w_autocompleter').hide();
	}
        selectBox.hide();
        
	var data = this._data;
	var select_box_w = parseInt(selectBox.css('width'));
	var select_box_h = parseInt(selectBox.css('height'))-2;
	var tbox_style = "width:" + (select_box_w - 22 ) + 'px; height:' + (select_box_h) + 'px;';
	var tbox_id = this._selectbox_element_id + '_ac';
	var last_selected_value = '';
	var selected_value = this._defaultString;
	var onclick_behaviour = this._defaultStringBehaviour;
	var ac_obj = this;

	selectBox.after('<input type="text" name="'+tbox_id+'" id="'+tbox_id+'" value="" autocomplete="off" style="'+tbox_style+'" />');
	var tBox = $('#'+tbox_id);

	this._sb = selectBox;
	this._tb = tBox;

	//tBox.css('position','absolute');
	tBox.css('z-index',nextFreeDepth());

	setAutocompleterStyles(tBox,selectBox);


	if (selected_value === true){
		tBox.val(data[selectBox[0].selectedIndex].text);
	} else if ( typeof( selected_value ) == 'string' ){
		tBox.val((this._selected_text != '')? this._selected_text : selected_value);
		if (onclick_behaviour === 1 || onclick_behaviour === 2){
			// attach event on click hide initial text
			tBox.focus(
				function(){
					if ( this.value == selected_value ){
						this.value = '';
						selectBox.val('');
					}
				}
			);
			tBox.change(
				function(){
					if (this.value != last_selected_value){
						var matches = 0;
						var sel_value = 0;
						for(var kk in data){

							if (CentralToWestern(this.value.toLowerCase()) == data[kk].seo.toLowerCase()){
								sel_value = data[kk].value;
								matches++;
							}
						}

						if (matches === 1){
							// set the proper value
							selectBox.val(sel_value);
						} else {
							selectBox.val('');
						}
					}
				}

			);
		}

		if (onclick_behaviour === 2){
			// attach event on click hide initial text
			tBox.blur(
				function(){
					if ( this.value == '' ){
						this.value = selected_value;
						selectBox.val('');
					}
				}
			)
		}

		tBox.keyup(
			function(e){
				if(e.keyCode != 13) {
					ac_obj._entered_text = this.value;
				}
			}
		);
		// attach other behaviour events

	} else if ( typeof( selected_value ) == 'number' ) {
		tBox.val(data[selected_value].text);
	}
	var obj = this;

	tBox.autocomplete( data , {
		formatItem:function(row,i,max){

			if (row.parent_id && ac_obj._resultDisplayParent ){
				return row.text +' ('+ data[row.parent_id].text +')';
			} else {
				return row.text;
			}

		},
		formatMatch:function(row,i,max){
			return row.seo +' '+row.text;
		},
		formatResult:function(row,i,max){

			if (row.parent_id && ac_obj._resultDisplayParent){
				return row.text +' ('+ data[row.parent_id].text +')';
			} else {
				return row.text;
			}
		},
		matchContains:true,
		max:30,
		width: select_box_w
	} ) . result( function(event,data,formatted){


		last_selected_value = data.text;
		selectBox.val(data.value);

		for( i in obj._callbacks ) {
			// call the callbacks
			if (obj._callbacks[i].cb != undefined )
				obj._callbacks[i].cb.apply( obj, [ data.value , obj._callbacks[i].args ]  );
		}
		tBox.blur( function(){
			selectBox.val(data.value);
			tBox.blur( function(){} );
		});

	} );

	selectBox.change(
		function (){
			var val = $(this).val();
			for( i in obj._callbacks ) {
				// call the callbacks
				if (obj._callbacks[i].cb != undefined )
					obj._callbacks[i].cb.apply( obj, [ val , obj._callbacks[i].args ]  );
			}
			for( i in data){
				if (data[i].value == val){
					if (data[i].parent_id){
						tBox.val(data[i].text +' ('+ data[data[i].parent_id].text +')');
					}else{
						tBox.val(data[i].text);
					}
					break;
				}
			}
		}
	);
}

p.getSelectBox = function(){
	return this._sb;
}


p.getTextBox = function(){
	return this._tb;
}

p.getEnteredText = function(){
	return this._entered_text;
}

p.addCallback = function( cb ,args ){
	this._callbacks.push( {'cb':cb, 'args':args});
}

delete p;

