function show_preloader(formId) {
	var loader = document.createElement("DIV");
    $(loader).css({
        'position':'absolute',
        'background': '#FFF',
        'opacity': '0.8',
        'width': $('#'+formId).outerWidth(),
        'height': $('#'+formId).outerHeight(),
        'top':$('#'+formId).position().top,
        'left':$('#'+formId).position().left
    });
    loader.innerHTML = "<table style='width:100%; height:100%;'><tr><td style='vertical-align:middle; text-align: center;'><img src='/templates/skin1/images/lightbox-ico-loading.gif' /></td></tr></table>";
	loader.id = 'preloader';
    document.getElementById(formId).appendChild(loader);
}

function validateClientForm(formId){
	show_preloader(formId);
	var postData = {};
	$('#'+formId+' :input').each(function(i,el){
        if(el.name){
			switch (el.type.toLowerCase()) {
				case 'checkbox':
					postData[el.name] = ($(el).attr('checked') == true)?1:0;
					break;
				case 'radio':
					if($(el).attr('checked')){
                        postData[el.name] = $(el).val();
                    }
					break;
				default:
					postData[el.name] = $(el).val();
					break;
			}

		}
	});
	$.ajax({
        type: "POST",
        url: $('#'+formId).attr('action') + '?json',
        dataType: "json",
        data: postData,
        success: function(resp){
            $('#preloader').remove();
            if(resp === true){
                $('#'+formId).submit();
            } else {
				if($('#'+formId+' p.fill').length){
					$('#'+formId+' p.fill').css('display', 'block');
				}
				var hint;
                $('.attn').remove();
                for(var i in resp){
                    for(var j in resp[i]){
                        var key = j.toString();
                        var msg = resp[i][j];
                        var el = $('#'+formId+' :input[name='+key+']');
						hint  = document.createElement("SPAN");
                        hint.className = 'attn';
                        hint.innerHTML = '« ' + msg;
                        //el.parent().children('label').append(hint);
						el.after(hint);
                    }
                }
            }
        }
    });
	return false;
}

function offsetPosition(element) {
	var offsetLeft = 0, offsetTop = 0;
	do {
		offsetLeft += element.offsetLeft + element.clientTop;
		offsetTop  += element.offsetTop + element.clientLeft;
	} while (element = element.offsetParent);
	return [offsetLeft, offsetTop];
}

jQuery.fn.extend({
	autocomplete: function(url, delimiter, callback){
		this.keydown(function(e){
			var code = e.charCode || e.keyCode;
			var box = $('#'+($(this).attr('id')+ '_autocomplete'));
			if(code == 13 && box.length){
				if(box.children('.active').length){
					e.preventDefault();
				}
				
			}

		});
		this.keyup(function(e){
			var code = e.charCode || e.keyCode;
			var curText = this.value;

			if(typeof delimiter == 'string'){
				curText = curText.split(delimiter);
				curText = curText[curText.length -1];
			}
			curText = jQuery.trim(curText);
			var self = $(this);	
			
			var box = $('#'+(self.attr('id')+ '_autocomplete'));
			if (code == 40 && box.length) { //arrow down
				if(box.children('.active').length){
					box.children('.active').next().focus();
					box.children('.active').prev().blur();
				} else {
					box.children().first().focus();
				}
				box.scrollTop(box.children('.active')[0].offsetTop);
				return;
			} else if(code == 38 && box.length){ //arrow up
				if(box.children('.active').length){
					box.children('.active').prev().focus();
					box.children('.active').next().blur();
				} else {
					box.children().last().focus();
				}				
				box.scrollTop(box.children('.active')[0].offsetTop);
				return;
			} else if(code == 27){
				self.hideAutocomplite();
				return;
			} else if(code == 13 && box.length){
				//e.preventDefault();
				if(box.children('.active').length){
					var newVal  = box.children('.active').html().replace('<b>','').replace('</b>','');
                    if($('#'+(self.attr('id')+ '_val')).length) {
                        $('#'+(self.attr('id')+ '_val')).val(box.children('.active').attr('value'));
                    }
                    
					self.val(self.val().substr(0, self.val().length - curText.length) + newVal);
					self.hideAutocomplite();
				}
				return;
			}
			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {current: curText},
				success: function(resp){
                    if(!callback){
                        if((typeof resp == 'object' || typeof resp == 'array') && resp.length){
                            self.showAutocomplite(resp, curText);
                        } else {
                            self.hideAutocomplite();
                        }
                    } else {
                        callback.apply();
                    }
				}
			});
		});
		this.click(function(){
			$(this).hideAutocomplite();
        });
		this.dblclick(function(){
			//$(this).hideAutocomplite();
            var self = $(this);	
            var curText = this.value;
            $.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {current: curText},
				success: function(resp){
                    if(!callback){
                        if((typeof resp == 'object' || typeof resp == 'array') && resp.length){
                            self.showAutocomplite(resp, curText);
                        } else {
                            self.hideAutocomplite();
                        }
                    } else {
                        callback.apply();
                    }
				}
			});
		}).blur(function(e){
            //console.log(e);
            e.preventDefault();
            //alert('onblur');
            //setTimeout('alert(this)', 100);
			setTimeout('$(this).hideAutocomplite()', 50);
		});
	},
	showAutocomplite: function(itemsData,curValue){
		var cBody;
        var w = 150 | this.width();
		if(!$('#'+(this.attr('id')+ '_autocomplete')).length){
			cBody = $(document.createElement('UL'));
			cBody.attr('id',this.attr('id')+ '_autocomplete').attr('class', 'autocomplete');
			$(document.body).append(cBody);
		} else {
			cBody = $('#'+(this.attr('id')+ '_autocomplete'));
		}
		var offset = offsetPosition(this[0]);
		cBody.children().remove();
		cBody.css({
			'position': 'absolute',
			'background': '#CCEBF2',
			'border': '1px solid #019ABC',
			'display': 'block',
            'max-height': 100,
			'width': w,
			'z-index': 9999,
			'overflow-x': 'auto',
			'overflow-y': 'none',
			'top': offset[1] + this[0].offsetHeight,
			'left': offset[0]
		});
		var items = {};
        var keyword;
        var item_text;
		for(var v in itemsData){
			items[v] = document.createElement('LI');
            
            if(typeof itemsData[v] == 'object'){
                item_text = itemsData[v].text;
                $(items[v]).attr('value',itemsData[v].id);
            } else {
                item_text = itemsData[v];
            }

            keyword = item_text.toString().replace(curValue,'<b>'+curValue+'</b>' );
			$(items[v])
            .mouseenter(function(e){
				$(this).focus();
			})
            .mouseleave(function(e){
                $(this).blur();
			})
			.focus(function(e){
				$(this).addClass('active');
			})
			.blur(function(e){
				$(this).removeClass('active');
			})
			.html(keyword)
			.css({
				'cursor': 'pointer'
			})
            .bind('click',[this,item_text, curValue],(function(e){
                //alert('click');
				var inp = e.data[0];
				var searchVal = e.data[2];
				var newVal = e.data[1];
				var curVal = inp.val();
				inp.val(curVal.substr(0, curVal.length - searchVal.length) + newVal);
                if($('#'+(inp.attr('id')+ '_val')).length) {
                    //$('#'+(inp.attr('id')+ '_val')).val(e.data[3]);
                    $('#'+(inp.attr('id')+ '_val')).val($(this).attr('value'));
                }
				inp.hideAutocomplite();
				inp.focus();
			})
			);
            
             
             /**/

		}
		cBody.append(items);
	},
	hideAutocomplite: function(){
		if($('#'+(this.attr('id')+ '_autocomplete'))){
			$('#'+(this.attr('id')+ '_autocomplete')).remove();
		}
	}
	
});


