var mds_maxGoodsID = new Number(9999999);
var mds_minGoodsID = new Number(1000000);
var mds_parserURL = new String("http://"+document.location.hostname+"/data.php");
var mds_pictpath = new String("");
var local_pictpath = new String("");
var mds_sid = new String("");
var mds_CntxID = new String(""); /*Идентификатор контекстного объекта*/
var mds_CntxMenuAlias = new String(""); /*Алиас контекстного объекта*/
var contTB;
var mainfrm;
var tisertab;
//var StateManager = EXANIMO.managers.StateManager;


StateManager.onstatechange = function(e)
 {
 var mainEl;
  mainfrm = document.getElementById("groupContent");
  if (mainfrm){
    mainEl=mainfrm;
  }
  else {
	contTB = document.getElementById("cmainfrm");
	mainEl = contTB;
  }
  if (mainEl){
     removeChildren(mainEl);
     var contHeader = document.createElement('div');
     contHeader.id='contentHeader';
     mainEl.appendChild(contHeader);
     var breadCrumbs = document.getElementById("breadcrumbs");
     if (!breadCrumbs) {
        breadCrumbs = document.createElement('span');
        breadCrumbs.id='breadcrumbs';
        mainEl.appendChild(breadCrumbs);
     }
     var targetEl = document.createElement('div');
     targetEl.id='groupContent';
     mainEl.appendChild(targetEl);
     var goodsInfo = document.createElement('div');
     goodsInfo.id='goodsInfo';
     mainEl.appendChild(goodsInfo);
       function onGoodsLoaded(data) {
//		alert(data);
		jQuery("#cmainfrm").html(data);
		//alert(elId);
	    StateManager.setState(elId);
	   }
/*Start request*/
	mdsShowClocks(targetEl, 'Загружаем содержимое группы '+elId+' ...');
	jQuery.get("http://"+document.location.hostname+"/index2.php", {option: 'com_goods', view: 'category', id: elId},onGoodsLoaded, "html");

    StateManager.setTitle('My Website :: ' + e.id);
 
   }
 }        

/*Функция для проверки правильности идентификатора товара*/
function mds_goodsID_correct(inID) {
	if ((inID>=mds_minGoodsID) & (inID<=mds_maxGoodsID)) {
		return true;
	}
	else {
		return false;
	}
}
function removeChildren(inNode) {
	if (inNode){
		if (typeof(inNode.childNodes)=='object'){
				while (inNode.childNodes[0]) {
					inNode.removeChild(inNode.childNodes[0]);
				}
		}
	}
}
function replaceChildren(sourceNode, targetNode){
  if (sourceNode&&targetNode){
	while (sourceNode.childNodes[0]) {
		targetNode.appendChild(sourceNode.childNodes[0]);
	}
  }
}
function mdsShowClocks(targEl, msg){
  if (targEl && (typeof(targEl)=='object')) {
    var clocks = document.createElement('img');
    clocks.src='http://'+document.location.hostname+'/templates/tradepilot/images/mdstreeloader.gif';
    targEl.appendChild(clocks);
    if (typeof(msg)=='string') {
      var clocksmsg = document.createElement('span');
      clocksmsg.innerHTML = '<span class="treePath">'+msg+'</span>';
      targEl.appendChild(clocksmsg);
    }
  }
}
function showTreeContent(elId) {
	    StateManager.setState(elId);
		return false;
}
function showGoods(goodsId) {
	var elGroupContent = document.getElementById(goodsId);
    var targetEl = document.getElementById("goodsInfo");
    removeChildren(this.targetEl);
	if (elGroupContent.thisgroupe==1) {
      showTreeContent(elGroupContent.shortId);
	}
	else {
       function onGoodsInfoLoaded(data) {
		 for(var i=0; i<data.length; i++) {
		   var prop = data[i];
		   var div = document.createElement('div');
		   div.id=prop.name;
		   //стиль элементов описания товара
		   div.className='treeGroup';
		   div.innerHTML = prop.name+'='+prop.val;
		   targetEl.appendChild(div);
	     }
	   }
 var reqData= {mdsAction: 'getGoods', id: goodsId, includeGoods: 1, cntxObjID: getCntxID(), sID: getMdsSid()}
 $.getJSON(mds_parserURL, reqData, onGoodsInfoLoaded);
 }
}
/*Объект mds_goodsTreePath предназначен для отображения пути в дереве товаров
Для отображения элементов используется стиль treePath*/
function mds_goodsTreePath(targetElementID, inId) {
  if (!targetElementID) {
    targetElementID='breadcrumbs';
  }
  if (!inId) {
    if (typeof(currentGoods)!='undefined') inId=currentGoods;
    alert('Current goods found! ID='+currentGoods);
  }
  var targetEl = document.getElementById(targetElementID);
  if (targetEl&&inId){
	function onTreePathLoaded(data){
	removeChildren(targetEl);
	var lastBranchID= new Number();
	var span = document.createElement('span');
	span.innerHTML = '<a href="http://'+document.location.hostname+'" class="pathway">Главная</a>';
        targetEl.appendChild(span);
		 for(var i=0; i<data.length; i++) {
		   var prop = data[i];
		   var id = new Number(prop.id);
		   if (mds_goodsID_correct(id)) {
		     var span = document.createElement('span');
   		     span.innerHTML = '<span class="treePath" onclick="showTreeContent('+id+')">'+"("+id+") "+prop.name+'</span>';
			 lastBranchID=id;
		     targetEl.appendChild(span);
			/*Добавим элемент в дерево*/
			mds_GoodsGroupTree.addElem(id, prop.name, prop.parent_id, prop.isFolder, false);
			/*alert('Parent '+prop.parent_id);*/
	       }
	     }
	     if (mds_goodsID_correct(currentGoods)) {
	       mds_GoodsGroupTree.openNode("");
	     }
	     else {
	       if (mds_goodsID_correct(lastBranchID)) {
		/*Откроем узел в дереве*/
		mds_GoodsGroupTree.openNode(lastBranchID);
	       }
	     }
	}
	/*Start request*/
    mdsShowClocks(targetEl, 'Загружаем путь для группы товаров '+inId+' ...');
	var reqData= {mdsAction: 'getTreePath', id: inId, includeGoods: 1, cntxObjID: getCntxID(), sID: getMdsSid()};
    jQuery.getJSON(mds_parserURL, reqData, onTreePathLoaded);
  }
}
function setPictPath (data) {
    mds_pictpath=data[0].value;
    local_pictpath=data[1].value;
}
function onLoadError(error) {
	var msg = "Ошибка "+error.errcode;
	if (error.message) msg = msg + ' :'+error.message;
	alert(msg);
}
function onAjaxError(xhr, status){
	var errinfo = { errcode: status }
		if (xhr.status != 200) {
				// может быть статус 200, а ошибка
				// из-за некорректного JSON
				errinfo.message = xhr.statusText
			} else {
				errinfo.message = 'Data loading error!';
			}
		onLoadError(errinfo);
	}
function setMdsSid(sid) {
	mds_sid=sid;
	return mds_sid;
}
function getMdsSid() {
	return mds_sid;
}
function setCntxID(cId,cAlias) {
	mds_CntxID=cId;
	mds_CntxMenuAlias=cAlias;
	return mds_CntxID;
}
function getCntxID() {
	return mds_CntxID;
}
function killOldDreadCrumbs(){
  breadcrumbs=document.getElementById("breadcrumbs"); 
}
function insertTiserTab(){
  /*Прорисуем рамки*/
  contTB = document.getElementById("contenttb");
  if (contTB) {
	tisertab = document.getElementById("tisertab");
	if (tisertab){
	  mainfrm = document.getElementById("mainfrm");
	  if (mainfrm){
	    /*Переносим содержимое contenttb*/
	    replaceChildren(contTB, mainfrm);
	  }
	  /*Переносим рамку*/
	  contTB.appendChild(tisertab);   
	}
  }
}
function tpRebuildPage() {
  /*Оn every page ready*/
  /*Получим путь картинок*/
  jQuery.getJSON(mds_parserURL,{mdsAction: "getSessionVar" ,varName: "picturePath", cntxObjID: getCntxID(), sID: getMdsSid()},setPictPath);
  insertTiserTab();
}

function mdsShowDescription(descrID){
var url_article="descr_show.php?gescr_id="+descrID;
window.open("http://"+document.location.hostname+"/"+url_article,"","height=600,width=460,status=no,location=no,toolbar=no,directories=no,resizable=yes,scrollbars=no,,menubar=no,top=50,left=50");
}


function showGoodsDescriptions(){
jQuery('.licontentGoods').each(function(){var el=$(this);$.get("http://"+document.location.hostname+"/descr_show_JSON.php?gescr_id="+el.get(0).id,{},function(data){el.find('.listpostext').html(data)},'html');});
}

function addToCart(ID,descr,price){
	function showCart(data) {
		jQuery(data).find('.basketbr').each(function(){jQuery(".basketbr").html($(this))});
		jQuery(data).find('#maincontenttab').each(function(){jQuery("#basketcontent").html($(this))});
		//$(data).find('#maincontenttab').each(function(){$(this).attr("id","baskettable");$("#contenttb").prepend($(this))});
	}
	jQuery.post("http://"+document.location.hostname+"/index.php", { edtqty: "1" ,edtprodcode: ID, edtshorttext: descr, edtunitprice: price, option: "com_basket", action: "addtocart"},showCart, "html");
}
