var verzId = 0;
var choose_str = "";
var menuArray = new Array();
var menuStr = "";
var xmlData;
var depth = 0;

function doOnChange (obj) {
		var value = $(obj).find(':eq('+obj.selectedIndex+')').attr('value');
		if (value.match(/sekcija/)) {
			var depth_str = $(obj).parent().attr('class');
			var curDepth = depth_str.split('_')[1];
			$('#product_form > div').filter(function(index) {
				return $(this).attr('class').split('_')[1] > curDepth ? true : false;
			}).replaceWith('');
			newSelect(value.split('_')[1]);
		}
		if (value.match(/stranica/)) {
			window.location = "/code/navigate.asp?Id="+value.split('_')[1];
		}	
}

function newSelect (sekcId) {
	var option_str = "";
	depth++;
	option_str += '<option value="0">'+choose_str+'</option>';
	$(xmlData).find('[@id='+sekcId+']').children().each(function() {
		var tagname = this.tagName.toLowerCase();
		var optionNaziv = $(this).attr('naziv');
		var optionValue = "";
		if (tagname.match(/sekcija/)) {
			optionValue += "sekcija_";
		} else {
			optionValue += "stranica_";
		}
		optionValue += $(this).attr('id');
		option_str += '<option value="'+optionValue+'">'+optionNaziv+'</option>';
	});
	$('<div class="dubina_'+depth+'"><select class="product_select" onchange="doOnChange(this)">'+option_str+'</select></div>').appendTo('#product_form');
}

$(function(){
	$.ajax({
		type: "GET",
		url: "/asp/utils/getXml.asp",
		data: {verzId:"1"},
		dataType: "script",
		beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
		success: function() {
			$.ajax({
				type: "GET",
				url: "/asp/utils/getXml.asp",
				dataType: "xml",
				success: function(xml) {
					xmlData = xml;
					var $verz = $(xmlData).find('root > verzija_'+verzId).children();
					var findStr = "";
					var first = true;
					for (var i=0; i < menuArray.length; i++) {
						$verz.find('[@id='+menuArray[i]+']').each(function() {
							var tagname = this.tagName.toLowerCase();
							var optionNaziv = $(this).attr('naziv');
							var optionValue = "";
							if (tagname.match(/sekcija/)) {
								optionValue += "sekcija_";
								optionValue += $(this).attr('id');
								$('<option value="'+optionValue+'">'+optionNaziv+'</option>').appendTo('#main_select')
							} 
						});
					};
				}
			});
		}
	});
});
