var GLOBALS = {};

$(function(){	
	$("#message").fadeOut(20000);
	$("#error").fadeOut(20000);
		
	//$("form#php-vars-to-js :hidden").each(function(){
		//eval('GLOBALS.'+$(this).attr("name")+' = "' + $(this).val() + '"');		
	//});
	
});

function onChangeUrban(){
	select = $(this);	
	//$("#other").val('').attr("disabled", false);
	// Clear all options of children selects
	select.nextAll("select").addClass("hidden").children().each(function(){
		//alert($(this).text());
		if($(this).val() != ''){ // Keep the label
			$(this).remove();
		}
	});
	if(!select.val()){
		$("#star-location").attr("class", "error");
		return;
	}
	$.getJSON("/ajax/main/get-urban", {id: select.val()},
		function(json){		
				
			if(json.length == 0){
				$("#star-location").attr("class", "message");
				//$("#other").attr("disabled", true);
			}else{
				$("#star-location").attr("class", "error");
				var options = "";				
				for(var i in json){
					options += "<option value='"+json[i].id+"'>" + json[i].name + "</option>";
				}					
				select.next().removeClass("hidden").append(options);		
			}		
			
		} );
	
}

function setCatsDropdown(){
	selects = $("#category>select");
	if(selects.length == 0){
		getSubcats($("input#root").val());
	}else{
		selects.change(function(){
			$(this).nextAll().remove();	
			getSubcats($(this).val());
		});
	}
}

function getSubcats(parent){
	if(parent === ''){
		$("#star-category").attr("class", "error");
		return;				
	}
	$("#loading").show();
	$.getJSON("/ajax/main/get-subcats", {parent_id: parent},
		function(json){				
			
			if(json && json.length > 0){
				var select = '<select name="category[]" id="subs-of" size="7">';				
				select += '<option value="">--</option>';				
				for(var i in json){
					//alert(json[i].name);
					select += '<option  value="'+json[i].id+'">'+json[i].name+'('+json[i].children+')</option>';
				}			
				select+='</select>';
				select=$(select).change(function(){
					$(this).nextAll('select').remove();	
					getSubcats($(this).val());
				});
				if($("div#category>select").length) {
					$("div#category>select:last").after(select);
				}
				else {
					$("div#category").prepend(select);
				}
				$("#star-category").attr("class", "error");
			}else{
				$("#star-category").attr("class", "message");
			}
			$("#loading").hide();
			
		});
}

$.fn.exists = function () {
    return $(this).length !== 0;
}


