var doLoadForm = false;
var tinyMCEmode = false;
var unsetClass = false;
var doLoadCache = false;
var etc_path = "/PWE/etc/";

function func(){}

function doLoad(path, arr, elm){
	if (!path) return;
	// Создаем новый объект JSHttpRequest.
	var req = new JsHttpRequest();
	// Код, АВТОМАТИЧЕСКИ вызываемый при окончании загрузки.
	req.onreadystatechange = function() {
	    if (req.readyState == 4) {
			if (req.responseJS) {
				/*if (!elm || elm=='none' || !$(elm)) elm = 'result';
				$(elm).innerHTML = req.responseJS.wf_main;
				if (req.responseJS.message) alert(req.responseJS.message);
				if (tinyMCEmode == true) tinyMCE.updateContent(elm);*/
	      		// Result
				if (!elm || elm=='none' || !$(elm))
					elm = 'result';
				if (doLoadForm) {
					$(elm).value = req.responseJS.wf_main;
					doLoadForm = false;
				} else {
                    if ($(elm)){
                        $(elm).update(req.responseJS.wf_main);
                        new Element.show(elm);
                    }
                    if (elm == 'popUpContent' && popUpJustify == true){
                        var dimensions = $(elm).parentNode.getDimensions();
                        $(elm).parentNode.style.marginLeft = (dimensions.width/2)*(-1);
                        $(elm).parentNode.style.marginTop = (dimensions.height/2)*(-1);
                        popUpJustify = false;
                    }
                }
                if (req.responseJS.iface_title && $('popUpTitle'))
                    $('popUpTitle').update(req.responseJS.iface_title);
				if (tinyMCEmode == true){
					tinyMCE.updateContent(elm);
					if ($('text')){
		            	tinyMCE.execCommand('mceRemoveControl', false, 'text');
		            	tinyMCEmode = false;
					}
				}
                if (unsetClass){
                    $(unsetClass).className = '';
                    unsetClass = false;
                }
			    if ($('wait'))
			        $('wait').remove();                
	      	}
	       	// Отладочная информация
	      	if (req.responseText.length > 0)
				alert(req.responseText);
	    }
	}
	// Разрешаем кэширование (чтобы при одинаковых запросах не обращаться к серверу несколько раз).
	req.caching = doLoadCache;
	// Подготавливаем объект.
	req.open('POST', path, true);
	// Посылаем данные запроса (задаются в виде хэша): req.send({ q:query, test:303 });
	req.send(arr);
}

function popUp(){
    if ($('popUpShell'))
        popUpClose();
    new Insertion.Bottom(document.body, "<div class=popUpShell id=popUpShell></div>");
    new Insertion.Top("popUpShell", "<div class=popUp id=popUp></div>");
    new Insertion.Top("popUp", "<div class=iface align=right id=popUpIface><h1 id=popUpTitle></h1><input type=image src=/PWE/images/iface/close.gif width=21 height=21 onClick=popUpClose('popUp') title='Закрыть'/></div><div id=popUpContent>Идет загрузка...</div>");
    new Insertion.Bottom("popUp", "<div id=popUpIface2 class=iface align=right><img src=/PWE/images/iface/small_move.gif width=11 height=11 alt=''></div>");
    popUpJustify = true;
    new Draggable('popUp', {'handle':'popUpIface'});
    new Draggable('popUp', {'handle':'popUpIface2'});
}

function popUpClose(){
    if ($('popUpShell'))
        $('popUpShell').remove();
}

function abon_auth(source){
    if ($('abonAuth'))
        $('abonAuth').remove();
	var str = "<form method=post><table border=0 cellpadding=3 cellspacing=0 width=1 class=abonAuth id=abonAuth>"+
		"<tr><th>Дилер</th><th align=right><input type=image src=/PWE/images/iface/sm_close.gif onClick=\"$('abonAuth').remove()\" title='Закрыть'/></th></tr>"+
		"<tr><td>Логин</td><td><input type=text name=login size=20/></td></tr>"+
		"<tr><td>Пароль</td><td><input type=password name=password size=20/></td></tr>"+
		"<tr><td></td><td><input type=submit name=abon_auth value=Вход></td></tr>"+
		"</table></form>";
    new Insertion.Bottom(document.body, str);
    new Position.clone(source, 'abonAuth',{'offsetLeft':-150, 'offsetTop': 50});
}

function form2hash(form){
    var hash = new Object();
    for (var i=0; i<form.elements.length; i++){
		el = form.elements[i];
		if (!el.name) continue;
		switch (el.type){
			case "text":
			case "textarea":
			case "hidden":
			case "password":
			case "button":
				hash[el.name] = el.value;
				break;
			case "checkbox":
			case "radio":
			 	if (el.checked)
					hash[el.name] = el.value;
				break;
			case "select-one":
				hash[el.name] = el.options[el.selectedIndex].value;
				break;
			case "select-multiple":
				hash[el.name] = {};
				for (var j=0; j<el.length; j++){
					if (el.options[j].selected)
						hash[el.name][j] = el.options[j].value;
				}
				break;
			case "file":
				hash['file'] = el.value;
				break;
		}
    }
	/*alert(Dump(hash));*/
    return hash;
}

function submitWarn(id){
    if ($(id))
        $(id).className = 'submitWarn';
}
function submitWarnCB(inst){
    if ($('submit'))
        $('submit').className = 'submitWarn';
}

function isArray(a) {
    return isObject(a) && a.constructor == Array;
}
function isFunction(a) {
    return typeof a == 'function';
}
function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}

function new_win(w,h,n)	{
	if (!n) n="new_window";
 	w1=window.open("",n,"resizable=yes, menubar=no, status=yes, scrollbars=yes, width="+w+", height="+h);
	w1.focus();
}

function feedback(){
	document.location.href='mail'+'to:'+'dap'+'@'+'parapet'+'.'+'ru';
}

/* дерево */
var cImg = new Image();
cImg.src = '/PWE/images/plus.gif';
var eImg = new Image();
eImg.src = '/PWE/images/minus.gif';
var ssel = false;

function toggleState(node) {
	var node;
  if(ssel) resetAll(node);
  doToggle(node);
}

function toggleGroup(str){
	var arr = str.split(',');
	for(var i = 0; i < arr.length; i++){
		toggleState(arr[i]);
	}
}

function doToggle(node, reset) {
  var n;
	var node;
  var n = document.getElementById(node);
	if (n){
  	/*m = document.getElementById(ode);*/
    if(!reset) reset = "inline";
    n.style.display = (n.style.display!='none'?'none':reset);
  	/*m.style.background = (n.style.display=="inline"?'url(/pic/d2/item1_abg.gif)':'url(/pic/d2/item1_bg.gif)');*/
  	document.images[node+'Img'].src = (n.style.display=="inline"?eImg.src:cImg.src);
	}
}

function resetAll(node) {
  var node;
  var n;
  var nIdx = getIdx(node);
  /*var d = document.getElementsByTagName("img");*/
  var n = document.getElementById(node);
	if (n){
    if(n.style.display=="none") {
    	for(var i=0; i<d.length; i++)
    		if(d[i].onclick) {
    			node = d[i].onclick.toString();
    			node = node.substr(node.lastIndexOf("(")+2);
    			node = node.substr(0, node.lastIndexOf(")")-1);
    			if(getIdx(node)==nIdx) doToggle(node, "none");
    		}
    }
	}
}

function getIdx(node) {
  var i = 0;
  var n = document.getElementById(node);
  if(n)
  	while(n.parentNode) {
  		n = n.parentNode;
  		i++;
  	}
  return i;
}

function checkCart(href){
  var span = null;
  if (navigator.appName == 'Microsoft Internet Explorer'){
  	span = document.getElementById('js').appendChild(document.createElement("SPAN"));
  } else {
	  span = document.body.appendChild(document.createElement("SPAN"));
  }
  span.style.display = 'none';
  span.innerHTML = 'Text for stupid IE.<s'+'cript></' + 'script>';
  var scr = span.getElementsByTagName("script")[0];
  scr.language = "JavaScript";
  if (scr.setAttribute) scr.setAttribute('src', href); else scr.src = href;
}

function checkPosInCart(arr){
	for (var k in arr){
		parent.document.getElementById('c'+k).innerHTML = '<div class="cQ"><a href="/cart/">'+arr[k]+'</a></div>';
    /*<img src="/pic/check.gif" width="16" height="16" hspace="6" border="0" alt="отложено" />*/
  }
}

pY = 0;
pX = 0;

function showPosition(e) {
    /*alert("Your mouse is at " + pX + " x " + pY);*/
    pX = Event.pointerX(e);
    pY = Event.pointerY(e);
}

function a2c(id){
	if (isArray(PARAM))
		var params = PARAM;
	else
		var params = false;
    doLoad(etc_path+"loader.php?module=etc/cart&template=cart.aj&mid="+MID+"&id="+id, {'quant':1, 'param':params}, 'incart');
    $('c'+id).innerHTML = '<a href="/cart/"><img src="/pic/check.gif" width="16" height="16" hspace="6" border="0" alt="отложено"/></a>';
}

function wait(){
	new Insertion.Bottom(document.body, '<div class=wait id=wait>Идет загрузка...</div>');
}

function a2cq(mid, id){
    //doLoad(etc_path+'cart.php', );
    var source = 'cart'+id;
    //var dimensions = $(elm).getDimensions();
    var str = "<div id=a2cq class=a2cq><div align=right><input type=image src=/PWE/images/iface/sm_close.gif onClick=$('a2cq').remove() title='Закрыть'/></div>Добавить&#160;к&#160;заказу<br/><input type=text name=quant id=quant value=1 size=5/>шт.&#160;&#160;<input type=button value=OK onclick=\"doLoad('"+etc_path+"loader.php?module=etc/cart&template=base.aj&mid="+mid+"&id="+id+"', {'quant':$('quant').value}, 'incart');$('a2cq').remove();\" /></div>";
    new Insertion.Bottom(document.body, str);
    new Position.clone(source, 'a2cq', {'offsetLeft':-50, 'offsetTop': 10});
}

function a2cD(id){
	var id;
    var a2c = $('a2c');
    if (a2c.style.display == 'none' || a2c.style.display == ''){
  	    a2c.style.display = 'block';
  	    a2c.style.top = pY +'px';
        a2c.style.left = (pX-170) + 'px';
		document.add2cart.id.value = id;
        document.a2cForm.quant.focus();
    } else {
        a2c.style.display = 'none';
    }
  /*alert("Your mouse is at " + pX + " x " + pY);
  document.add2cart.id.value = id;
  document.add2cart.submit();*/
}

function a2cSubmit(quant){
    $('a2c').style.display = 'none';
    document.add2cart.quant.value = quant;
    document.add2cart.submit();
    return false;
}

function toogleMCE(ID) {
    try {
        if(tinyMCEmode==true) {
            tinyMCE.execCommand('mceRemoveControl',false,ID);
			//tinyMCE.removeMCEControl(tinyMCE.getEditorId(ID));
            tinyMCEmode = false;
        } else {
			TinyMCE.idCounter = 0;
			var inst = tinyMCE.getInstanceById(ID);
			if (inst){

            }
			tinyMCE.execCommand('mceAddControl',false,ID);
			//tinyMCE.addMCEControl(document.getElementById(ID), ID);
            tinyMCEmode = true;
        }
    } catch(e) {
        //error handling
		alert('Ошибка при попытке переключения режима редактора.\n tinyMCEmode='+tinyMCEmode+'\n TinyMCE.idCounter='+TinyMCE.idCounter+'\nInstance='+tinyMCE.getInstanceById(ID)+'\n'+e);
    }
}

function checkAll(theForm, chboxName) {
	var sw = -1;
	for (i = 0,n = theForm.elements.length;i<n;i++){
		if (theForm.elements[i].name.indexOf(chboxName) != -1){
			if (sw == -1){
				if (theForm.elements[i].checked == true)
					sw = false;
				else
					sw = true;
			}
			theForm.elements[i].checked = sw;
		}
	}
}

function tooltype_open(ID){
    clearTimeout(_to);
    _to=null;
    $(ID).show();
}

function tooltype_close(ID){
    _to = setTimeout(function() {
        _to=null;
        $(ID).hide();
    }, 500);
}
