
var _manufactur = 1
var _Cost = 0
var _aFullCostNames = []
var _aFullCostPrice = []
var _fullCostSumm = 0

//+++++++++++++++++++++++++++++++++++
function initCalculator() {
  oInput = oTree.getElementsByTagName("INPUT")
  for(var i = 0; i < oInput.length; i++) {
  	if (oInput[i].addEventListener) oInput[i].addEventListener("click",calculate,false);
  	else if (oInput[i].attachEvent) oInput[i].attachEvent("onclick", calculate);
  }

  // Проставляем звёздочки
  showAC(2)
  // Пересчитываем
  calculate()
}

//+++++++++++++++++++++++++++++++++++
function calculate() {
  PRICE["additionalLevel"] = 0

  var cost = parseInt(getCost(oTree, 0, false))
  if (cost > 0) cost += parseInt(PRICE["defaultCost"])

  // + Цена за количество отмеченных звёздочек
  cost += parseInt(PRICE["additionalCost"]) * parseInt(PRICE["additionalLevel"])

  // Про производителя
  if (cost > 0 && _manufactur == 3) cost += 270000

  costDIV.innerHTML = "Расчёт стоимости: " + cost + "р."

  _Cost = cost
}

//+++++++++++++++++++++++++++++++++++
function getCost(oTreeNode, n, is_parent_additional_cost) {
  var cost = 0

  var is_additional_cost = isAdditionalCost(oTreeNode)
  var node_cost          = getNodeBaseCost(oTreeNode, n)
  var node_checked       = isNodeChecked(oTreeNode)

  // Про производителя
//  if (oTreeNode.className.match(/level1/i) && _manufactur == 2) node_cost *= 2

  if (_manufactur == 2 || _manufactur == 3) {
  	PRICE[3] = 3100        // если СП и иностранцы
  	if (oTreeNode.className.match(/level3/i) && node_cost == 8500) node_cost = 10400
  	if (oTreeNode.className.match(/level3/i) && node_cost == 11700) node_cost = 13600
  } else PRICE[3] = 1200   // если Российское предприятие


  var childs = 0
  for(var i = 0; i < oTreeNode.children.length; i++) {
    var oChild = oTreeNode.children(i)
    if (oChild.nodeName.toUpperCase() == "DIV" && oChild.style.display != "none" && oChild.className.match(/level/i)) {
      cost += parseFloat(getCost(oChild, n + 1, is_additional_cost))
      childs++
    }
  }

  if (node_checked || cost > 0) cost += node_cost
  if (node_checked) incAdditionalLevelArray(oTreeNode)

  // Добавочная стоимость если у предка звёздочка
  if (cost > 0 && (n == 4 || n == 5) && is_parent_additional_cost) PRICE["additionalLevel"]++

  return parseFloat(cost)
}

//+++++++++++++++++++++++++++++++++++
function isNodeChecked(oLevel) {
  // Ищем внутри чекбокс
  for(var i = 0; i < oLevel.children.length; i++) {
    var oChild = oLevel.children(i)

    if (oChild.nodeName.toUpperCase() == "DIV" && oChild.style.display != "none" && oChild.className.match(/header/i)) {
      var oInputs = oChild.getElementsByTagName("INPUT")
      if (oInputs.length > 0) {
        if (oInputs[0].type.toUpperCase() == "CHECKBOX" && oInputs[0].checked) {
          oChild.style.color = "#005A8C"
          return true
        }
        if (oInputs[0].type.toUpperCase() == "CHECKBOX" && !oInputs[0].checked) {
          oChild.style.color = ""
          return false
        }
      }
    }
  }

  return false
}

//+++++++++++++++++++++++++++++++++++
function isAdditionalCost(oNode) {
  if (oNode.className.match(/additionalCost0/)) return true
  if (oNode.className.match(/additionalCost1/) &&  urovenOtv1.checked) return true
  if (oNode.className.match(/additionalCost2/) && !urovenOtv1.checked) return true

  return false
}

//+++++++++++++++++++++++++++++++++++
function incAdditionalLevelArray(oNode) {
  if (isAdditionalCost(oNode)) PRICE["additionalLevel"]++
}

//+++++++++++++++++++++++++++++++++++
function getNodeBaseCost(oNode, n) {
  if (oNode.getAttribute("cost")) return parseFloat(oNode.getAttribute("cost"))
  if (PRICE[n]) return parseFloat(PRICE[n])
  return 0
}




//+++++++++++++++++++++++++++++++++++
function licenseClick(n) {
  var sDisplay = "none"

  for(var i = 1; i <= 3; i++) {
    if (document.getElementById("license" + i).checked) {
      sDisplay = ""
    }
  }

  var oDivList = document.getElementsByTagName("DIV")
  for(var i = 0; i < oDivList.length; i++) {
    if (oDivList[i].className.match(/showWithLicense/i)) {
      oDivList[i].style.display = sDisplay
    }
  }

  if (document.getElementById("oLicense" + n).style.display == "none") {
    document.getElementById("oLicense" + n).style.display = ""
  } else {
    document.getElementById("oLicense" + n).style.display = "none"
  }

  // Пересчитываем
  calculate()
}

//+++++++++++++++++++++++++++++++++++
function urovenOtvClick(n) {
  document.getElementById("urovenOtv1").checked = false
  document.getElementById("urovenOtv2").checked = false
  document.getElementById("urovenOtv" + n).checked = true
  // Проставляем звёздочки
  showAC(n)
  // Пересчитываем
  calculate()
}

//+++++++++++++++++++++++++++++++++++
// Проставляем звёздочки
//+++++++++++++++++++++++++++++++++++
function showAC(n) {
  var oSpanList = document.getElementsByTagName("SPAN")
  for(var i = 0; i < oSpanList.length; i++) {
    if (oSpanList[i].className.match(/level[0-2]/i)) {
      if ((oSpanList[i].className.match(/level(0|1)/i) && n == 1) || (oSpanList[i].className.match(/level(0|2)/i) && n == 2)) {
        oSpanList[i].innerHTML = "*"
      } else {
        oSpanList[i].innerHTML = ""
      }
    }
  }
}







//+++++++++++++++++++++++++++++++++++
// Нажатие на заключить договор
//+++++++++++++++++++++++++++++++++++
function signContract() {
  if (_Cost == 0) {
    alert("Необходимо выбрать хотя бы один вид работ!")
  } else {
    var oStep1 = document.getElementById("oStep1")
    oStep1.style.display = "none"

    createFullCostTable()

    var oStep2 = document.getElementById("oStep2")
    oStep2.style.display = ""
  }

  window.event.returnValue = false
}

//+++++++++++++++++++++++++++++++++++
//
//+++++++++++++++++++++++++++++++++++
function createFullCostTable() {
  var oFullCostTable = document.getElementById("oFullCostTable")

  var oldRows = oFullCostTable.rows.length

  _aFullCostNames.length = 0
  _aFullCostPrice.length = 0

  getFullCostArrays(oTree, 0)

  _aFullCostNames[_aFullCostNames.length] = "Оформление лицензии на 5 лет (регистрационные расходы, СНиПы, заключение по охране труда, работа организации и т.д.)"
  _aFullCostPrice[_aFullCostPrice.length] = parseInt(PRICE["defaultCost"])

  if (_manufactur == 3) {
    _aFullCostNames[_aFullCostNames.length] = "Надбавка за оформление лицензии для иностранного предприятия"
    _aFullCostPrice[_aFullCostPrice.length] = 270000
  }

  for(i = _aFullCostNames.length - 1; i >=0; i--) {
    var oTR  = document.createElement("TR")
    var oTD1 = document.createElement("TD")
    var oTD2 = document.createElement("TD")
    oTD1.className = "td1"
    oTD2.className = "td2"

    _aFullCostNames[i] = _aFullCostNames[i].replace(/^[0-9]+\. /, "")
    _aFullCostNames[i] = _aFullCostNames[i].replace(/^ *\- */, "")
//    _aFullCostNames[i] = _aFullCostNames[i].replace(/:\ *$/, "")

    oTD1.innerHTML = _aFullCostNames[i]
    oTD2.innerHTML = (_aFullCostPrice[i] == 0) ? "&nbsp;" : _aFullCostPrice[i]

    oTR.appendChild(oTD1)
    oTR.appendChild(oTD2)

    if (_aFullCostNames[i] != "") oFullCostTable.getElementsByTagName("TBODY")[0].appendChild(oTR)
  }

  // Итого
  var oTR  = document.createElement("TR")
  var oTD1 = document.createElement("TD")
  var oTD2 = document.createElement("TD")
  oTD1.className = "td1"
  oTD2.className = "td2"
  oTD1.innerHTML = "<DIV style='TEXT-ALIGN: right;'><B>Стоимость лицензии составит:</B></DIV>"
  var iSumm = 0
  for(i = _aFullCostNames.length - 1; i >=0; i--) {
    if (_aFullCostNames[i] != "") iSumm += _aFullCostPrice[i]
  }
  _fullCostSumm = iSumm
  oTD2.innerHTML = "<B>" + iSumm + "</B>"
  oTR.appendChild(oTD1)
  oTR.appendChild(oTD2)
  oFullCostTable.getElementsByTagName("TBODY")[0].appendChild(oTR)


  for(i = (oldRows - 1); i >= 0; i--) {
    oFullCostTable.rows(i).removeNode(true)
  }
}

//+++++++++++++++++++++++++++++++++++
function getFullCostArrays(oTreeNode, n, isParentAdditionalCost) {
  var cost = 0
  var childs = 0
  var nodeText = ""

  // Поиск звёздочки
  var is_additional_cost = isAdditionalCost(oTreeNode)

  // Определение цены узла
  var node_cost = 0
  if (PRICE[n]) node_cost = parseFloat(PRICE[n])
  if (oTreeNode.getAttribute("cost")) {
    node_cost = parseFloat(oTreeNode.getAttribute("cost"))
  }

  // Про производителя
/*  if (oTreeNode.className.match(/level1/i)) {
  	if (_manufactur == 2) node_cost *= 2
  }
*/
  if (_manufactur == 2 || _manufactur == 3) {
	if (oTreeNode.className.match(/level3/i) && node_cost == 8500) node_cost = 10400
	if (oTreeNode.className.match(/level3/i) && node_cost == 11700) node_cost = 13600
  }

  // Если у предка была звёздочка
  if (isParentAdditionalCost) node_cost += parseInt(PRICE["additionalCost"])

  var nodeChecked = false
  for(var i = oTreeNode.children.length - 1; i >= 0; i--) {
    var oChild = oTreeNode.children(i)

    if (oChild.nodeName.toUpperCase() == "DIV" && oChild.style.display != "none") {
      // Ищем DIV с чекбоксами
      if (oChild.className.match(/header/i)) {
        nodeText = oChild.innerText
        // Ищем внутри INPUT
        var oInputs = oChild.getElementsByTagName("INPUT")
        if (oInputs.length > 0 && oInputs[0].type.toUpperCase() == "CHECKBOX" && oInputs[0].checked) {

//+++++++++++++++++++++++++++++++++
// Здесь возможно нада проверять присутствие звёздочки у текущего элемента
// isAdditionalCost(oChild)
//+++++++++++++++++++++++++++++++++
          // Ищем звёздочку
          if (is_additional_cost) node_cost += parseInt(PRICE["additionalCost"])

          nodeChecked = true
          _aFullCostNames[_aFullCostNames.length] = nodeText
          _aFullCostPrice[_aFullCostPrice.length] = parseInt(node_cost)
        }
      }
      // Ищем DIV со вложенными ветвями
      if (oChild.className.match(/level/i)) {
        childs++
        var subCost = getFullCostArrays(oChild, n + 1, is_additional_cost)
        cost += parseFloat(subCost)
      }
    }
  }

  // Добавляем цену если цена потомков больше 0 (отмечены потомки)
  if ((childs > 0 && n > 0 && cost != 0) || nodeChecked) {
    cost += node_cost

    if (!nodeChecked) {
      _aFullCostNames[_aFullCostNames.length] = nodeText
      _aFullCostPrice[_aFullCostPrice.length] = parseInt(node_cost)
    }
  }

  return(parseFloat(cost))
}

//++++++++++++++++++++++++++++++++++++++++++++
function signContractReturn() {
  var oStep2 = document.getElementById("oStep2")
  oStep2.style.display = "none"

  var oStep1 = document.getElementById("oStep1")
  oStep1.style.display = ""

  window.event.returnValue = false
}



var oPrintWindow = null
//++++++++++++++++++++++++++++++++++++++++++++
function openPrintWindow() {
  oPrintWindow = window.open("http://www.topstroy.ru/print.html", "print_window", "width=600,height=400,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes");
//  var myurl = escape(document.location.href.replace(/http:\/\/([^\/].*?)\/.*?$/, '$1'));
//  oPrintWindow = window.open("http://"+myurl+"/print.html", "print_window", "width=683,height=400,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes");

  setTimeout("printWindowContent()", 500)
}

//++++++++++++++++++++++++++++++++++++++++++++
function printWindowContent() {
  var oFullCostTable = document.getElementById("oFullCostTable")
  oPrintWindow.document.getElementById("Content").innerHTML = "<B style=\"FONT: bold 13px tahoma; COLOR: #005A8C;\">Выбранные виды работ:</B><BR><BR>" + oFullCostTable.outerHTML

//  oPrintWindow.print()
//  oPrintWindow.close()
}

//++++++++++++++++++++++++++++++++++++++++++++
function saveAsMsWord() {
  var oForm  = document.getElementById("MsWordForm")
  var oInput = document.getElementById("MsWordInput")
  var oSumm  = document.getElementById("MsWordSumm")

  var str = ""
  for(i = _aFullCostNames.length - 1; i >=0; i--) {
    if (_aFullCostNames[i] != "") {
      if (str != "") str += "__row__";

      var price = (_aFullCostPrice[i] == 0) ? "" : _aFullCostPrice[i]
      str += ("" + _aFullCostNames[i] + "__cell__" + price)
    }
  }

  oInput.value = str
  oSumm.value  = _fullCostSumm
  oForm.submit()
}

//++++++++++++++++++++++++++++++++++++++++++++
function orderNow() {
  var oForm  = document.getElementById("OrderForm")
  var oInput = document.getElementById("OrderInput")
  var oSumm  = document.getElementById("OrderSumm")

  var str = ""
  for(i = _aFullCostNames.length - 1; i >=0; i--) {
    if (_aFullCostNames[i] != "") {
      if (str != "") str += "__row__";

      var price = (_aFullCostPrice[i] == 0) ? "" : _aFullCostPrice[i]
      str += ("" + _aFullCostNames[i] + "__cell__" + price)
    }
  }

  oInput.value = str
  oSumm.value  = _fullCostSumm
  oForm.submit()
}



//+++++++++++++++++++++++++++++++++++
function manufacturClick(n) {
	_manufactur = n

	// Пересчитываем
	calculate()
}

