$(document).ready(function() {
	for(var i=0; i < userIds.length; ++i) {
		for( var j=1; j<=3; ++j) {
			//set slider
			$("#slider_" + j + "_" + userIds[i]).slider({
		    	orientation: 'horizontal',
		    	range: 'min',
		    	max: 10,
		    	change: function(event, ui) { $(this).next().text(ui.value); }  
		    });
		    //set tooltip
		    $("#slideroff_" + j + "_" + userIds[i]).tooltip({
		    	bodyHandler: function() {
        			return $("<div>" +  Math.round($(this).children().css('width').replace('%', '')) + "%</div>");
        		}  
		    });
		}
	}
});

function save(userId) {
	$("#ratingForm_Route .errors").empty();
	var types = new Array();
	var values = new Array();
	for( var j=1; j<=3; ++j) {
		if ($("#slider_" + j + "_" + userId).length) {
			types.push(j);
			values.push($("#slider_" + j + "_" + userId).slider('value'));
		}
	}

	var url = '/' + lang + '/user/rateajax/user_id/' + userId + '/route_id/' + routeId + '/types/' + 
			types.join(',') + '/values/' + values.join(',');
	$.getJSON(url,
				function(data) {
					if (Boolean(data['res'])) {
						for(var type in data['rating']) {
							var oParent = $("#slider_" + type + "_" + userId).parent();
							oParent.empty();
							oParent.append('<div id="slideroff_' + type + '_' + userId + '" class="slider ui-slider ui-slider-horizontal ' + 
													'ui-widget ui-widget-content ui-corner-all">' +
												'<div class="ui-slider-range ui-widget-header" style="width: ' + 
													data['rating'][type] * 10 + '%;"></div>' +
											'</div>');
							oParent.children().tooltip({
					    		bodyHandler: function() {
			        				return $("<div>" +  Math.round($(this).children().css('width').replace('%', '')) + "%</div>");
			        			}
					    	});
						}
						$("#save_" + userId).replaceWith('<li class="save" id="rerate_' + userId + 
															'"><a href="javascript:rerate(' + userId + ');">' + 
															rerateName + '</a></li>');
					}
					$("#ratingForm_Route .errors").html(Boolean(data['message']) ? data['message'] : ""); 
				});

}

function rerate(userId) {
	$("#ratingForm_Route .errors").empty();

	for( var type=1; type<=3; ++type) {
		if ($("#slideroff_" + type + "_" + userId).length) {
			var oParent = $("#slideroff_" + type + "_" + userId).parent();
			oParent.empty();
			oParent.append('<div id="slider_' + type + '_' + userId + 
							'" class="slider"></div><div class="value">0</div>');
			$("#slider_" + type + "_" + userId).slider({
		    	orientation: 'horizontal',
		    	range: 'min',
		    	max: 10,
		    	change: function(event, ui) { $(this).next().text(ui.value); }  
		    });
		}
	}
	$("#rerate_" + userId).replaceWith('<li class="save" id="save_' + userId + 
			'"><a href="javascript:save(' + userId + ');">' + saveName + '</a></li>');
} 
