var timestamp = 0;

function max_vendor_code(e){
	var max = $('#max').val();
	var count = 0;
	for(var key in get_names_selected()){
		count++;
	}
	if(count > max){
		e.preventDefault();
		alert($('#input_error').val());
	}
}

$(document).ready(function(){ 
	

	load_list("");
	
	
	$('#filter').click( function(){ 
		$(this).val(''); 
	});
	$('#filter').keyup(function(e){
		var val = $(this).val();
		if( (val.length>=1) || val.length == 0 ) {
			waiting = true;
			date = new Date();
			timestamp = date.getTime();
			setTimeout('load_list("'+val.replace(/\"/, '\\"')+'")', 60);
		}
	});
	$('.vendor_code').click( max_vendor_code);
});

carrierList ={
	loaded: false,
	list: null,
	
	filter: function (pattern) {
		var checked1 = get_checked().split(',');
		var checked = {};
		for(var c in checked1){
			checked[checked1[c]] = 1;
		}
		var result = '';
		for (var i in this.list) {
			for (var j in this.list[i]['data']) {
				if(j != 'info' && this.list[i]['data'][j] && this.list[i]['data'][j].match(pattern)){
					result += this.list[i]['html'];
					break;
				}
			}
		}
		$('#div_list').html(result);
		var vCode = $('.vendor_code');
		vCode.click( max_vendor_code);
		vCode.each(function(){
			var che = $(this);
			if(checked[che.attr('value')] === 1){
				che.attr('checked', checked);
			}
		});
	},

	init: function (data) {
		carrierList.loaded = true;
		carrierList.list = {};
		for (code in data) {
			carrierList.list[code] = data[code];
		}
		carrierList.filter(/.*/);
	}
}

function load_list(str_part){
	date = new Date();
	now = date.getTime();
	//console.log('load');
	if(now - timestamp < 45){
		return;
	}
	//console.log('list');
	
	if(!carrierList.loaded){
		/*var url = 'index.php?go=ajax/getvendorslist';
		$.get(url,
			{
				'str_part': str_part,
				'checked': get_checked()
			},
			function(data){carrierList.init(data);}
		);*/
		
		carrierList.init(vendorsList);
		delete vendorsList;
	}else{
		eval("carrierList.filter(/^"+str_part+".*/i);");
	}
}

function get_checked(){
	var checked = '';
	$('.vendor_code').each(function(){
		var che = $(this);
		if(che.attr('checked')){
			checked += che.val()+',';
		}
	});
	return checked;
}

//submit


/*
function get_string_selected(){
	var text = '';
	$('input:checked').each(function(){
		text = text + $(this).attr('value') + ',' ;
	})
	return text;
}
*/
function get_names_selected(){
	names = new Array();
	$('input:checked').each(function(){
		code = $(this).attr('value');			
		names[code] = $('span[name=name_'+code+']').html();			
		names[code] = names[code].replace(/"/g, "'");
	})
	return names;
}

function submit(){
	javascript:parent.submit_vendor_list( get_checked(), get_names_selected() );
	javascript:parent.tb_remove();
}
