
var path_image = "/resources/imgs/jaseedit/"

/**
 * move_mode = 0 : опшионы перебрасываются в target, и остаются в source
 * move_mode = 1 : опшионы перебрасываются в target, исчезая из source
 * move_mode = 2 : опшионы перебрасываются в target, и остаются в source, но повторно те, которые уже есть в target не добавляются.
 * move_mode = 3 : опшионы "перебрасываются" в target, исчезая из source, но повторно те, которые уже есть в target не добавляются.
 */
function control_select_exchange(source, target, move_mode) {
	var j = (target.options.length == null) ? 0 : target.options.length;
	target.selectedIndex = -1;
	// alert (move_mode + " , " + source.options.length)
	for (var i=0; i<source.options.length; i++) {
		if (source.options[i].selected) {
			// if ((move_mode==2 || move_mode==3) && !has_option_value(target, source.options[i].value)) {
			if ((move_mode==2 || move_mode==0) && !has_option_value(target, source.options[i].value)) {
				target.options[j] = new Option(source.options[i].text, source.options[i].value);
				if (with_exts()) add_handl(target.options[j], "click", load_ext_par)
				target.options[j++].selected = true;
			}
			if (move_mode==1 || move_mode==3) source.options[i--] = null;
		}
	}
}
function control_select_move_option(s, step) {
    if (s.options.length < step + 1) return;
    var wanted_step = s.selectedIndex + step;
    if (wanted_step < 0 || wanted_step > s.options.length - 1) return;
    var selection, option_value, option_text;
    selection = s.selectedIndex;
    option_value = s.options[selection + step].value;
    option_text = s.options[selection + step].text;
    s.options[selection+step].value = s.options[selection].value;
    s.options[selection+step].text = s.options[selection].text;
    s.options[selection].value = option_value;
    s.options[selection].text = option_text;
    s.selectedIndex = selection + step;
}

function has_option_value(select_control, option_value) {
	for (var i=0; i<select_control.options.length; i++) {
		if (select_control.options[i].value==option_value) return true
	}
	return false
}

function with_exts() {

	exchselext_p_for = d.getElementById("exchselext_p_for")
	exchselext_p_ed = d.getElementsByName("exchselext_p_ed")[0]
	if (exchselext_p_for!=null && exchselext_p_ed!=null) {
		return true
	}
	return false
}

function load_ext_par() {

	exchselext_p_for = d.getElementById("exchselext_p_for")
	exchselext_p_ed = d.getElementsByName("exchselext_p_ed")[0]
	// exchselext_p_ev = d.getElementsByName("exchselext_p_ev")

	if (!is_moz) {
		sel_o = window.event.srcElement
	} else {
		sel_o = this
	}
	
	p_for_v = sel_o.value
	p_for_t = sel_o.text
	
	exchselext_p_for.innerHTML = "Enter value for <b>" + p_for_t + "</b>:"
	
	var r = sel_o.parentNode.name.match(/^sd(\[(\d+)\]\[(\d+)\])\[\]$/)
	if (r) {
		// alert(r[1] + ", " + r[2] + ", " + r[3])
		ext_par_to_load = "sdev" + r[1] + "[" + p_for_v + "]"
		// alert(ext_par_to_load)
		// alert(d.getElementsByName(ext_par_to_load)[0].value)
		exchselext_p_ed.value = d.getElementsByName(ext_par_to_load)[0].value
		exchselext_p_ed.setAttribute("sdev_nm", ext_par_to_load)
	}
	// exchselext_p_ed = d.getElementsByName(el_ev_nm + "[" + p_for_v + "]")[0]
	// exchselext_p_ed.value = p_for_v
}

function save_in_pool(o) {
	// alert(o.value + ", " + o.getAttribute("sdev_nm"))
	d.getElementsByName(o.getAttribute("sdev_nm"))[0].value = o.value
}
//-------



var xmlreq
var load_catlist_st_id = null

/**
 * populate dropdown lists
 */
function populate_ddlist(control_name, level, parid, mode, control_clean, control_sequenced, has_sublevels) {
	// url = "repository.php?list=catbyparid&parid=" + parid
	sequence_stop = false
	url_ = ""
	try {
		// try to use global "url"
		url_ = url
	} catch (e) {}
	if (!/xml$/.test(url_) && url_.length>0) {
		url_ = url_ + parid + ".xml"
	} else {
		if (has_sublevels==1) {
			url_ = "/jase/t_lv;46," + parid + ".xml"
		} else {
			url_ = "/jase/p_lv;55," + parid + ".xml"
			sequence_stop = true
			// alert ("zzz")
			// @gvozdi:
			try {
				control_o = d.getElementsByName("src_" + control_name)[0]
				url_ = "/jase/pa_lv;57," + parid + ".xml"
			} catch (e) {}
		}
	}
	url = url_
	// alert(url)
	if (typeof(xmlreq)=="object" && xmlreq.readyState==1 && load_catlist_st_id==null) {
		load_catlist_st_id = setTimeout("populate_ddlist('" + control_name + "', " + level + ", " + parid + ", " + mode + ", " + control_clean + ", " + control_sequenced + ", " + has_sublevels + ")", 1000)
	} else {

		// alert("### " + sequence_stop)
		
		control_o = null
		try {
			control_o = d.getElementsByName("src_" + control_name)[0]
			// alert("1: " + control_o);
			// sequence_stop = true
		} catch (e) {alert("1: " + e)}

		if (typeof(control_o)=="undefined" && control_sequenced>0) try {
			control_o = d.getElementsByName("l" + control_sequenced + "_" + control_name)[0]
			// alert("2: " + control_o);
		} catch (e) {alert("2: " + e)}

		if (typeof(control_o)=="undefined" && control_sequenced>0) try {
			control_o = d.getElementsByName(control_name)[0];
			sequence_stop = true
			// alert("3: " + control_o);
		} catch (e) {alert("3: " + e)}
		
		// alert("###" + control_o.name + " , " + control_sequenced)
		
		if (typeof(control_o)=="undefined" || control_o==null) return

		switch_icon_to_loading(control_o.name)

		

		if (window.XMLHttpRequest) {
			xmlreq = new XMLHttpRequest()
			xmlreq.onreadystatechange = function() {process_load_catlist(control_o, control_name, level, mode, control_clean, control_sequenced, sequence_stop); return false;}
			xmlreq.open("GET", url, true)
			xmlreq.send(null)
		} else if(window.ActiveXObject) {
			xmlreq = new ActiveXObject("Microsoft.XMLHTTP")
			if (xmlreq) {
				xmlreq.onreadystatechange = function() {process_load_catlist(control_o, control_name, level, mode, control_clean, control_sequenced, sequence_stop); return false;}
				xmlreq.open("GET", url, true)
				xmlreq.send()
			}
		}
	}
}

function process_load_catlist(cn, control_name, level, mode, control_clean, control_sequenced, sequence_stop) {
	// alert(xmlreq.readyState)
	if (xmlreq.readyState == 4) {
		if (xmlreq.status == 200) {
			navpath_pop(control_name, level)
			navpath_deploy(control_name)

			// alert("***" + cn.name + " , " + control_sequenced)

			if (control_sequenced>0) control_sequenced++

			if (control_clean==1) {
				cn.length = 0
				j = 0
			} else {
				j = cn.length
			}
			response = xmlreq.responseXML.documentElement
			cat_arr = response.getElementsByTagName("i")

			for (i=0; i<cat_arr.length; i++) {
				cn.options[j] = new Option(cat_arr[i].firstChild.data, cat_arr[i].getAttribute("id"))
				set_attr(cn.options[j], control_name, cat_arr[i].getAttribute("id"), level, mode, cat_arr[i].firstChild.data, cat_arr[i].getAttribute("nl"), control_sequenced)
				//// if (cat_arr[i].getAttribute("nl")==1) {
					if (!sequence_stop) add_handl(cn.options[j], "click", ch_subcat)
				//// } else {
					// cn.options[j].className = "nnl"
					//// cn.options[j].setAttribute("title", cn.options[j].getAttribute("title") + " (there is no sublevels)")
					// if (mode==0) add_handl(cn.options[j], "dblclick", si_browse)
					// if (mode>0) add_handl(cn.options[j], "click", cl_subcat)
				//// }
				j++
			}
			// if (!is_moz && !sequence_stop) add_handl(cn, "change", ch_subcat)
			if (!is_moz && !sequence_stop) add_handl(cn, "click", ch_subcat)
			cn.disabled = false
			switch_icon_to_regular(cn.name)
		} else {
			alert("There was a problem retrieving data from server:\n" + xmlreq.statusText);
			switch_icon_to_regular(cn.name)
		}
	}
	// switch_icon_to_regular(cn.name)
}

function set_attr(e, c, v, l, m, t, nl, control_sequenced) {
	e.setAttribute("title", t)
	e.setAttribute("cvlm", [c, v, l, m, nl, control_sequenced].join(","))
}

function cl_subcat() {
	cvlm = (is_moz) ? this.getAttribute("cvlm") : window.event.srcElement.parentNode.getAttribute("cvlm")
	cvlm_arr = cvlm.split(",");
	cn = d.getElementsByName(cvlm_arr[0] + "_l" + (parseInt(cvlm_arr[2])+1))[0]
	cn.length = 0
}

function ch_subcat() {
	try {
		if (!is_moz) {
			sel_o = window.event.srcElement
			cvlm = sel_o.options[sel_o.selectedIndex].getAttribute("cvlm")
		} else {
			cvlm = this.getAttribute("cvlm")
		}
		// cvlm = (is_moz) ? this.getAttribute("cvlm") : window.event.srcElement.parentNode.getAttribute("cvlm")
		cvlm_arr = cvlm.split(",");
		cn = cvlm_arr[0]
		catid = cvlm_arr[1]
		level = cvlm_arr[2]
		mode = cvlm_arr[3]
		has_sublevels = cvlm_arr[4]
		control_sequenced = cvlm_arr[5]
		// alert("from ch_subcat: " + control_sequenced)

		navpath_arr[cn][navpath_arr[cn].length++] = new npi(catid, (is_moz) ? this.title : window.event.srcElement.parentNode.title, level, mode, has_sublevels)
		
	} catch(e) {}
	try {
		populate_ddlist(cn, parseInt(level) + 1, catid, mode, 1, control_sequenced, has_sublevels)
	} catch(e) {}
}

//-------
function switch_icon_to_loading(control_name) {

	try {
		loading_icon_o = d.getElementById("li_" + control_name)
		if (loading_icon_o.tagName.toUpperCase()=="IMG") {
			loading_icon_o.src = path_image + "loading_icon.gif"
		}
	} catch(e) {}
}

function switch_icon_to_regular(control_name) {

	try {
		loading_icon_o = d.getElementById("li_" + control_name)
		if (loading_icon_o.tagName.toUpperCase()=="IMG") {
			loading_icon_o.src = path_image + "blank.gif" 
		}
	} catch(e) {}
}
//-------

navpath_arr = new Array()

// nav path item
function npi(catid, cattitle, level, mode, has_sublevels) {
	this.catid = catid
	this.cattitle = cattitle
	this.level = level
	this.mode = mode
	this.has_sublevels = has_sublevels
}

function navpath_deploy(control_name) {
	try {
	var np = d.getElementById('navpath_' + control_name)
	np.innerHTML = ""
	na = navpath_arr[control_name]
	for (var i=0; i<na.length; i++) {
		el = d.createElement('SPAN')
		el.className = "npi" + ((i==na.length-1) ? " l" : "")
		if (i<na.length-1) {
			set_attr(el, control_name, na[i].catid, na[i].level, na[i].mode, na[i].cattitle, na[i].has_sublevels)
			add_handl(el, "click", ch_subcat)
		}
		el.appendChild(d.createTextNode(navpath_arr[control_name][i].cattitle))
		np.appendChild(d.createTextNode(" / "))
		np.appendChild(el)
	}
	} catch(e) {}
}

function navpath_pop(control_name, start_from_level) {
	// if (typeof(navpath_arr)!="undefined")
	try
	{
		l = navpath_arr[control_name].length
		for (var i=start_from_level; i<l; i++) navpath_arr[control_name].pop()
	} catch(e) {}
}

function si_browse() {
	cvlm = (is_moz) ? this.getAttribute("cvlm") : window.event.srcElement.parentNode.getAttribute("cvlm")
	cvlm_arr = cvlm.split(",");
	cn = cvlm_arr[0]
	catid = cvlm_arr[1]
	level = cvlm_arr[2]
	mode = cvlm_arr[3]
	// alert(cvlm_arr)
	load_silist("silist", catid, 0, 500)
}

function si_browse_b() {
	cvlm = d.getElementsByName('sc')[0].options[d.getElementsByName('sc')[0].selectedIndex].getAttribute('cvlm')
	cvlm_arr = cvlm.split(",");
	catid = cvlm_arr[1]
	has_sublevels = cvlm_arr[4]
	if (has_sublevels==0) load_silist("silist", catid, 0, 500)
}

// ------------------------------------------------------------------------


function load_silist(control_name, catid, sf, st) {
	url = "repository.php?list=sibycatid&catid=" + catid + "&sf=" + sf + "&st=" + st
	if (window.XMLHttpRequest) {
		xmlreq = new XMLHttpRequest()
		xmlreq.onreadystatechange = function() {process_load_silist(control_name); return false;}
		xmlreq.open("GET", url, true)
		xmlreq.send(null)
	} else if(window.ActiveXObject) {
		xmlreq = new ActiveXObject("Microsoft.XMLHTTP")
		if (xmlreq) {
			xmlreq.onreadystatechange = function() {process_load_silist(control_name); return false;}
			xmlreq.open("GET", url, true)
			xmlreq.send()
		}
	}
}

function process_load_silist(silist_id) {
	if (xmlreq.readyState == 4) {
		if (xmlreq.status == 200) {
			silist_o = d.getElementById(silist_id)
			silist_o.innerHTML = ""
			// while(plist.hasChildNodes()) plist.removeChild(plist.lastChild)
			response = xmlreq.responseXML.documentElement
			// if (response.getElementsByTagName("sibycatid") ) {
			//@todo добавить проверку на существование sibycatid в ответе
			si_arr = response.getElementsByTagName("sibycatid")[0].getElementsByTagName("si")
			j = 0
			for (i=0; i<si_arr.length; i++) {
				
				si_id = si_arr[i].getAttribute("id")
				si_p = (si_arr[i].getAttribute("sc_p")==0) ? "no" : "yes"
				si_dp = (si_arr[i].getAttribute("sc_dp")==0) ? "no" : "yes"
				si_mn = (si_arr[i].getAttribute("sc_mn")>0) ? si_arr[i].getAttribute("sc_mn") : ""
				
				tr = d.createElement('TR')
				
				td = d.createElement('TD')
				td.appendChild(d.createTextNode(si_arr[i].getElementsByTagName("title")[0].firstChild.data))
				tr.appendChild(td)
				
				td = d.createElement('TD')
				td.appendChild(d.createTextNode(si_mn))
				tr.appendChild(td)
				
				td = d.createElement('TD')
				td.appendChild(d.createTextNode(si_p))
				tr.appendChild(td)
				
				td = d.createElement('TD')
				td.appendChild(d.createTextNode(si_dp))
				tr.appendChild(td)
				
				add_handl(tr, "mouseover", silist_over)
				add_handl(tr, "mouseout", silist_out)
				add_handl(tr, "click", silist_click)
				tr.setAttribute("si_id", si_id)

				silist_o.appendChild(tr)

				// add_handl(cn.options[j], "click", ch_subcat)
			}
		} else {
			alert("There was a problem retrieving data from server:\n" + xmlreq.statusText);
		}
	}
}

function silist_over() {
	tr = (is_moz) ? this : window.event.srcElement.parentNode
	tr.className = "silist_over"
}

function silist_out() {
	tr = (is_moz) ? this : window.event.srcElement.parentNode
	tr.className = "silist_out"
}

function silist_click() {
	si_id = (is_moz) ? this.getAttribute("si_id") : window.event.srcElement.parentNode.getAttribute("si_id")
	// tr.className = "silist_out"
	// alert("ddfgdfg" + si_id)
	window.location = "stuff_class.edit.php?stuff_class_id=" + si_id
}

// ------------------------------------------------------------------------



is_ie = (navigator.appName == "Microsoft Internet Explorer");

resizer_eventHandlers = false;

function set_resizing(e, editor_id) {
	e = typeof(e) == "undefined" ? window.event : e;
	
	// alert(e)
	
	// var resizer = TinyMCE_AdvancedTheme._resizer;
	// var editorContainer = document.getElementById(editor_id + '_parent');
	// var editorArea = document.getElementById(editor_id + '_parent').firstChild;
	var resizeBox = document.getElementById(editor_id);// + '_resize_box');
	// var inst = tinyMCE.getInstanceById(editor_id);

		// Place box over editor area
		//var width = resizeBox.clientWidth;
		//var height = resizeBox.clientHeight;

		//resizeBox.style.width = width + "px";
		//resizeBox.style.height = height + "px";

		//resizer.iframeWidth = inst.iframeElement.clientWidth;
		//resizer.iframeHeight = inst.iframeElement.clientHeight;

		// Hide editor and show resize box
		// editorArea.style.display = "none";
		// resizeBox.style.display = "block";

		// Add event handlers, only once
		
		if (!resizer_eventHandlers) {
			if (is_ie)
				add_handl(document, "mousemove", _resizeEventHandler);
			else
				add_handl(window, "mousemove", _resizeEventHandler);

			add_handl(document, "mouseup", _resizeEventHandler);

			resizer_eventHandlers = true;
		}

		// resizer.resizing = true;
		resizeBox.downX = e.screenX;
		resizeBox.downY = e.screenY;
		resizeBox.style.width = parseInt(resizeBox.style.width);
		resizeBox.style.height = parseInt(resizeBox.style.height);
		// alert(e.screenX)
		// resizer.editorId = editor_id;
		// resizer.resizeBox = resizeBox;
		// resizer.horizontal = tinyMCE.getParam("theme_advanced_resize_horizontal", true);

}
function _resizeEventHandler(e) {
	/* var resizer = TinyMCE_AdvancedTheme._resizer;

	e = typeof(e) == "undefined" ? window.event : e;

	
	var resizeBox = resizer.resizeBox;
	var editorId = resizer.editorId;*/
	
	var resizeBox = document.getElementById('treenavigator');
	
	var dx = e.screenX - resizeBox.downX;
	var dy = e.screenY - resizeBox.downY;

	switch (e.type) {
		case "mousemove":
			var w, h;

			w = resizeBox.width + dx;
			h = resizeBox.height + dy;

			w = w < 1 ? 1 : w;
			h = h < 1 ? 1 : h;

			//if (resizer.horizontal)
			resizeBox.style.width = w + "px";

			resizeBox.style.height = h + "px";

			break;

		case "mouseup":
			// TinyMCE_AdvancedTheme._setResizing(e, editorId, false);
			// TinyMCE_AdvancedTheme._resizeTo(tinyMCE.getInstanceById(editorId), resizer.width + dx, resizer.height + dy, resizer.horizon

			break;
	}
}