$(document).ready(function(){
	
	initializeInputs($('body'));
	
	// input autogrow
	$('.inp-input.autogrow').each(function(){
		$(this).attr('minwidth', $(this).width());
		$(this).attr('maxwidth', $(this).parent().width());
		$(this).css({paddingRight: 0});
		input = $(this).find('input');
		tester = $('<span class="tester" style="position: absolute; left: -9999px; top: 245px; width: auto; whiteSpace: nowrap;"></span>').css({
			fontSize: input.css('fontSize'),
			fontFamily: input.css('fontFamily'),
			fontWeight: input.css('fontWeight'),
			letterSpacing: input.css('letterSpacing')
		});
		$(this).append(tester);
		checkinput($(this));
	});
	
	$('.inp-input.autogrow').bind('click focus blur keydown keyup', function(){
		checkinput($(this));
	});
	
	// textarea autogrow
	$('.inp-textarea.autogrow').each(function(){
		$(this).find('textarea').css({overflow: 'hidden' });
		ta = $(this);
		var elem = $(this), arr = [];
		while (elem[0].tagName.toUpperCase() != "BODY"){
			if (elem.css('display') == "none") { arr.push(elem); elem.show(); }
			elem = elem.parent();
		}		
		checkTextarea(ta);
		if ($.browser.webkit) {
			setTimeout(function(){checkTextarea(ta)}, 300);
			setInterval(function(){checkTextarea(ta)}, 1000);
		}
		$.each(arr, function(){ $(this).hide(); });
		
	});
	$('.inp-textarea.autogrow').bind('click focus blur keydown keyup', function(){
		checkTextarea($(this));
	});
	
	// picker arrow active
	$('.inp-picker .picker-arrow').live('mousedown', function(){ $(this).addClass('active'); });
	$(document).mouseup(function(){ $('.picker-arrow').removeClass('active');});
	
	// picker handling
	$('.inp-picker .picker-arrow-up').live('click', function(e){ //click(function(){
		$('#errorsContainer').remove();
		$(this).closest('.inp').find('input').removeClass('inputplaceholder');
		reverse = $(this).closest('.inp').hasClass('dir-reverse');
		changeValue($(this).closest('.inp').find('input'), reverse ? 'next' : 'prev');
		$(this).closest('.inp').removeClass('error');
		e.stopImmediatePropagation();
		return false;
	});
	$('.inp-picker .picker-arrow-down').live('click', function(e){ //click(function(e){
		$('#errorsContainer').remove();
		$(this).closest('.inp').find('input').removeClass('inputplaceholder');
		reverse = $(this).closest('.inp').hasClass('dir-reverse');
		changeValue($(this).closest('.inp').find('input'), reverse ? 'prev' : 'next');
		$(this).closest('.inp').removeClass('error');
		e.stopImmediatePropagation();
		return false;
	});
	
	$('.inp-picker.suggest input[type="text"]').each(function(){
		tester = $('<span class="suggest"></span>').css({
			fontSize: $(this).css('fontSize'),
			fontFamily: $(this).css('fontFamily'),
			fontWeight: $(this).css('fontWeight'),
			letterSpacing: $(this).css('letterSpacing')
		});
		$(this).after(tester);
	});
	
	$('.inp-picker input').live('keydown', function(e){ //keydown(function(e){ 
		$('#errorsContainer').remove();
		if (e.keyCode == 38) $(this).parent().find('.picker-arrow-up').addClass('active');
		if (e.keyCode == 40) $(this).parent().find('.picker-arrow-down').addClass('active');
	}); 
	
	$('.inp-picker input').live('keyup', function(e){//keyup(function(e){
		$('#errorsContainer').remove();
		if (e.keyCode == 38) $(this).parent().find('.picker-arrow-up').removeClass('active');
		if (e.keyCode == 40) $(this).parent().find('.picker-arrow-down').removeClass('active');
		
		reverse = $(this).parent().hasClass('dir-reverse');
		if (e.keyCode == 13) { changeValue($(this), 'curr'); return; }	
		if (e.keyCode == 38) { changeValue($(this), reverse ? 'next' : 'prev'); return; }	
		if (e.keyCode == 40) { changeValue($(this), reverse ? 'prev' : 'next'); return; }
		
		elem = $(this);
		vals = elem.data('values');
		curr = elem.val();
		if (curr.length == 1) { curr = curr.toUpperCase(); elem.val(curr); }
		if (curr == '') { $('.inp-picker span.suggest').hide(); return };
		for (i = 0; i < vals.length; i++)
			if (vals[i].val.toString().indexOf(curr) == 0)
			{
				if (!elem.parent().hasClass('suggest')) return;
				tester = elem.parent().find('span.suggest');
				tester.html('<span>' + curr + '</span>' + vals[i].val.toString().substring(curr.length));
				tester.show();
				return;
			}
		elem.val(curr.substring(0, curr.length - 1));
	});
	var saveValue = "";
	$('.inp-picker input').live('focus', function(){
		$(this).parent().removeClass('error');
		$(this).removeClass('inputplaceholder');
		saveValue = $(this).val();
		$(this).val("");
	});
	$('.inp-picker input').live('blur', function(){
		if ($(this).val() == "") {
			$(this).val(saveValue);
			saveValue == $(this).attr('title') && $(this).addClass('inputplaceholder');
		}
		else
			changeValue($(this), 'curr');
		$('.inp-picker span.suggest').hide();
	});
	
	$('.inp-input input').live('focus', function(){
		if ($('#errorsContainer').text() != $(this).parent().data('errorMessage'))
			setTimeout(function(){ $('#errorsContainer').remove(); }, 100);
			//$('#errorsContainer').fadeOut(function(){ $('#errorsContainer').remove(); });
		if ($(this).attr('type') == 'password') {
			var passwords = 'input.equal-to-' + $(this).attr('class').substring(9);
			if ($(passwords).length) {
				$(passwords).parent().removeClass('error');
				if ($(passwords).eq(0).val().length <= 0 ||
					$(passwords).eq(1).val().length <= 0) return;
				if ($('#errorsContainer').text() != passwordsValidationText && $(passwords).eq(0).val() != $(passwords).eq(1).val())
					showError(passwordsValidationText);
			}
		} else {
			$(this).parent().removeClass('error');
			if ($(this).parent().data('errorMessage') != undefined)
				showError($(this).parent().data('errorMessage'));
		}
	});
	
	$('.inp-input.hint input[title], .inp-textarea.hint textarea[title]').each(function(){
		$(this).after('<span class="input-hint">' + $(this).attr('title') + '</span');
	});
	$('.inp-input.hint input[title], .inp-textarea.hint textarea[title]').hover(
		function() { if (!$(this).hasClass('inputplaceholder') && !$(this).is(':focus'))  $(this).next().show(); },
		function() { $(this).next().hide(); }
	);
	$('.inp-input.hint input[title], .inp-textarea.hint textarea[title]').focus(
		function() { $(this).next().hide(); }
	);
	$('span.input-hint').hover(
		function() { $(this).show(); },
		function() { $(this).hide(); }
	);
	
	$('.radio').live('click', function() {
		nm = $(this).attr('name');
		$('.radio').each(function(){
			if ($(this).attr('name') == nm)
				$(this).removeClass('checked');
		});
		$(this).addClass('checked');
		$('input[name="' + nm + '"]').val($(this).attr('valueid'));
	});
});

function initializeInputs(cont){
	// prevent auto browser suggestion/completion
	cont.find('input').each(function(){
		$(this).attr("autocomplete", "off");
	});
	
	cont.find('.inp-input input, textarea').searchField();
	
	// set initial value for picker
	cont.find('.inp-picker input').each(function(){
		if ($(this).val() != "") return;
		$(this).addClass('inputplaceholder');
		$(this).val( $(this).attr('title') );
	});
}

function changeValue(elem, dir)
{
	elem_hidden = elem.parent().find('input[type="hidden"]');
	vals = elem.data('values');
	curr = elem.val();
	$('.inp-picker span.suggest').hide();
	if (curr == '' && dir != "curr") { elem.val(vals[0].val); elem_hidden.val(vals[0].key); return; }
	for (i = 0; i < vals.length; i++)
		if (vals[i].val.toString().indexOf(curr) == 0)
		{
			var ind;
			if (dir == "prev")      ind = (i == 0 ? vals.length - 1 : i - 1);
			else if (dir == "next") ind = (i == vals.length - 1 ? 0 : i + 1);
			else                    ind = i;
			elem.val(vals[ind].val);
			elem_hidden.val(vals[ind].key);
			return;
		}
	elem.val(vals[0].val);
	elem_hidden.val(vals[0].key);
	elem.removeClass('inputplaceholder');
}

function checkinput(elem)
{
	input  = elem.find('input');
	tester = elem.find('span.tester');
	tester.html(input.val().replace(/&/g, '&amp;').replace(/\s/g,'&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'));
	w = Math.min(tester.width() + 10, parseInt(elem.attr('maxwidth')));
	w = Math.max(w, parseInt(elem.attr('minwidth')));
	input.width( w );
	elem.width( w );
}

function checkTextarea(elem)
{
	textarea = elem.find('textarea');
	textarea.height(textarea.attr('minheight'));
	h = textarea.attr("scrollHeight");
	//if (h == 0) return;
	textarea.height( h );
	elem.height( h );
}

jQuery.fn.searchField = function(mark){
	return this.each(function() {
		var mark = mark || this.title;
		
		if (!mark)
			return;
			
		var target = this;
		var original = $(this);
		if (this.type == "password") {
			target = $("<input />")
				.insertBefore(this)
				.css("display", $(this).css("display"))
				.attr("size", this.size)
				.attr("title", this.title)
				.attr("class", this.className)
				.addClass("inputplaceholder")[0];
			if (!this.value) {
				$(this).hide();
			} else {
				$(target).hide();
			}
		}
		
		if(!target.value || mark == this.value) {
			$(target).addClass("inputplaceholder");
		}
		
		// setup initial value
		if (!this.value || target != this) {
			target.value = mark;
		}
		
		$(target).focus(function() {
				if (target != original[0]) {
				$(this).hide();
				original.show().focus();
			} else if (this.value == mark) {
				this.value = '';
				$(this).removeClass("inputplaceholder");
			}
		});
		$(this).blur(function() {
			if (!this.value.length) {
				if (target != original[0]) {
					$(target).show();
					original.hide();
				} else {
					this.value = mark;
					$(this).addClass("inputplaceholder")
				}
			}
		});
		
		// make sure that when the form is submitted, the inputplaceholder is
		// replaced with the empty string, which is usually the expected behavior.
    	$(this).parents("form:first").submit(function(){
       		if ($(target).hasClass("inputplaceholder")) {
               $(target).attr("value", "");
               $(target).removeClass("inputplaceholder");
        	}
       });
	});
};
