var minSettingsWidth = 100;
var sections = 0; //текущее кол-во секций
var doors = 0; //текущее кол-во дверей
var minSections = 1; //минимальное кол-во секций
var maxSections = 6; //максимальное кол-во секций
var minDoors = 1; //минимальное кол-во дверей
var maxDoors = 6; //максимальное кол-во дверей
var minSectionsHeight = 250; //минимальная высота секций
var maxSectionsHeight = 275;  //максимальная высота секций
var defSectionsHeight = 250;
var minSectionsWidth = 10; //минимальная ширина секций
var maxSectionsWidth = 200;  //максимальная глубина секций
var defSectionsWidth = 60;
var minSectionsDepth = 20; //минимальная глубина секций
var maxSectionsDepth = 100;  //максимальная ширина секций
var defSectionsDepth = 60;
var minPol = 0; //минимальное кол-во полочек в секции
var maxPol = 200; //максимальное кол-во полочек в секции
var polochki = new Array; //массив кол-ва полочек в каждой секции
var minYasch = 0; //минимальное кол-во полочек в секции
var maxYasch = 5; //максимальное кол-во полочек в секции
var yaschechki = new Array; //массив кол-ва ящичков в каждой секции
var doorFill = new Array(
	'ДСП 10мм',
	'зеркало серебро',
	'зеркало бронза',
	'зеркало сатин',
	'бамбук',
	'раттан',
	'матовое стекло сатин',
	'матовое стекло лакомат',
	'зеркало с рисунком',
	'фотопечать',
	'3D фасад'
);
var doorFillVal = new Array(
		'dsp',
		'mirror',
		'mirror-bronze',
		'mirror-satin',
		'bamboo',
		'bamboo',
		'glass-satin',
		'glass-lacomat',
		'paint',
		'photo',
		'3d'
	);

function startCalc() {
  $('#shkaf').html('');
  $.spin.imageBasePath = '/img/';
  $.spin.timeInterval = 100;
  $('#sectionsSpinner').spin({
	max: maxSections,
	min: minSections,
	buttonUp: function(){addSection();},
	buttonDown: function(){removeSection();}
  });
  $('#doorsSpinner').spin({
	max: maxDoors,
	min: minDoors,
	buttonUp: function(){addDoor();},
	buttonDown: function(){removeDoor();}
  });
  $('#sectionsHeight').spin({
		max: maxSectionsHeight,
		min: minSectionsHeight,
		changed: function(value){
	      setSectionsHeight(value);
	    }
	  });
  $('#sectionsDepth').spin({
		max: maxSectionsDepth,
		min: minSectionsDepth
	  });
  $('#shkaf').append('<div id="out"><div id="outHead">&nbsp;</div></div>');
  $('#out').css('height', minSectionsHeight);
  addSection();
  addSection();
  addDoor();
  addDoor();
}

function addSection () {
  if (sections < maxSections) {
    $('#out').css('display', 'none').appendTo($('#myCalc'));
    sections++;
    //var sectionDiv = '<div id="section'+sections+'"></div>';
    var sectionDiv = '<div id="sectionHolder'+sections+'"><div id="sectionHead'+sections+'"></div><div id="section'+sections+'"></div></div>';
    polochki[sections]=0;
    yaschechki[sections]=0;
    $('#shkaf').append(sectionDiv);

    $('#sectionHolder'+sections).addClass('sectionHolder').css('width', defSectionsWidth).css('height', $('#shkaf').css('height'));
    $('#sectionHead'+sections).addClass('sectionHead').css('width', defSectionsWidth+36).css('z-index', 99-sections);
    $('#section'+sections).addClass('section').css('width', defSectionsWidth).css('height', $('#shkaf').css('height'));
    var settings = '<div id="sectionSettings'+sections+'">'+
                   '<p>ширина:<input type="text" id="sectionWidth'+sections+'" value="'+defSectionsWidth+'" readonly></p>'+
                   '<p>полки:<input type="text" id="sectionPol'+sections+'" value="'+minPol+'" readonly></p>'+
                   '<p>ящики:<input type="text" id="sectionYasch'+sections+'" value="0" readonly></p>'+
                   '<p>вешалки:<br />'+
                   'выдвижные:'+
                   '<input type="text" id="hangersEnd'+sections+'" value="0" readonly><br />'+
                   'штанги:'+
                   '<input type="text" id="hangersWide'+sections+'" value="0" readonly><br />'+
                   '</div>';
                   /*
                   'торцевая <input type="checkbox" id="sectionHangerEnd'+sections+'" onchange="hangerChange(this, '+sections+');"><br />'+
                   'штанга <input type="checkbox" id="sectionHangerWide'+sections+'" onchange="hangerChange(this, '+sections+');"></p>'+
                   '</div>';
                   */
    $('#sectionsSettings').append(settings);
    var sectWidth = (defSectionsWidth < minSettingsWidth) ? minSettingsWidth : defSectionsWidth;
    $('#sectionSettings'+sections).addClass('sectionSettings').css('width', sectWidth);
    //$('#sectionHangerEnd'+sections).change(function() {hangerChange(this, sections);});
    //$('#sectionHangerWide'+sections).change(function() {hangerChange(this, sections);});
    $('#sectionWidth'+sections).spin({
    	  	max: maxSectionsWidth,
    		min: minSectionsWidth,
    		changed: function(value){
          setSectionWidth(value, $(this).attr('id').replace('sectionWidth',''));
          }
      });
    $('#hangersEnd'+sections).spin({
		min: 0
    });
    $('#hangersWide'+sections).spin({
		min: 0
    });
    
    /*
    var sectionHead = '<div id="sectionHead'+sections+'"></div>';
    $('#shkafHead').append(sectionHead);
    $('#sectionHead'+sections).addClass('sectionHead').css('width', minSectionsWidth+36).css('left', minSectionsWidth*(sections-1));
    */
    
    $('#sectionPol'+sections).spin({
  	  max: maxPol,
  		min: minPol,
  		buttonUp: function(){addPol($(this).attr('id').replace('sectionPol',''));},
  		buttonDown: function(){removePol($(this).attr('id').replace('sectionPol',''));}
    });
    $('#sectionYasch'+sections).spin({
  	  max: maxYasch,
  		min: minYasch,
  		buttonUp: function(){addYasch($(this).attr('id').replace('sectionYasch',''));},
  		buttonDown: function(){removeYasch($(this).attr('id').replace('sectionYasch',''));}
    });
    polochki['section'+sections] = 0;
    yaschechki['section'+sections] = 0;
    $('#section'+sections).append('<div id="ground"></div>');
	$('#out').appendTo($('#shkaf')).css('display', 'block');
  }
}
function removeSection () {
  if (sections > minSections) {
    $('#sectionHolder'+sections).remove();
    $('#sectionSettings'+sections).remove();
    //hangerChange(null, sections);
    sections--;
  }
}

function addDoor() {
	if (doors < maxDoors) {
		doors++;
		var doorSel = "<select id='doorFill"+doors+"'>";
		var selected;
		for (var i = 0; i < doorFill.length; i++) {
			selected = (i == 0) ? " selected" : "";
			doorSel += "<option value='"+doorFillVal[i]+"'"+selected+">"+doorFill[i]+"</option>";
		}
		doorSel += "</select> ";
		$('#doorsSels').append(doorSel);
	}
}
function removeDoor() {
	if (doors > minDoors) {
		$('#doorFill'+doors).remove();
		doors--;
	}
}
/*
function hangerChange(e, sect) {
	if (e == null) {
		$('#hangerW'+sect).remove();
		$('#hangerE'+sect).remove();
		$('#sectionHangerEnd'+sect).attr('checked', false);
		$('#sectionHangerWide'+sect).attr('checked', false);
	}
	else if (polochki[sect] > 0) {
		hangerChange(null, sect);
	}
	else {
		var hangerId, hangerClass;
		if ($(e).attr('id') == 'sectionHangerEnd'+sect) {
			$('#sectionHangerWide'+sect).attr('checked', false);
			$('#hangerW'+sect).remove();
			if ($(e).attr('checked')) {
				hangerId = 'hangerE'+sect;
				hangerClass = 'hangerEnd';
			}
			else {
				$('#hangerE'+sect).remove();
			}
		}
		else if($(e).attr('id') == 'sectionHangerWide'+sect) {
			$('#sectionHangerEnd'+sect).attr('checked', false);
			$('#hangerE'+sect).remove();
			if ($(e).attr('checked')) {
				hangerId = 'hangerW'+sect;
				hangerClass = 'hangerWide';
			}
			else {
				$('#hangerW'+sect).remove();
			}
		}
		if (hangerId != null) {
			var hangerDiv = "<div id='"+hangerId+"'></div>";
			$('#section'+sect).append(hangerDiv);
			$('#'+hangerId).addClass(hangerClass);
		}
	}
}
*/
function addPol (sectionId) {
  if (polochki[sectionId]<maxPol) {
    polochki[sectionId]++;
    //hangerChange(null, sectionId);
    var newPol = '<div id="'+sectionId+'pol'+polochki[sectionId]+'"></div>';
    $('#section'+sectionId).prepend(newPol);
    $('#'+sectionId+'pol'+polochki[sectionId]).addClass('pol').css('width', maxSectionsWidth).css('z-index', 99-polochki[sectionId]);
    organizeItems(sectionId);
  }
}
function removePol (sectionId) {
  if (polochki[sectionId]>minPol) {
    $('#'+sectionId+'pol'+polochki[sectionId]).remove();
    polochki[sectionId]--;
	organizeItems(sectionId);
  }
}
function addYasch (sectionId) {
  if (yaschechki[sectionId]<maxYasch) {
    yaschechki[sectionId]++;
    var newYasch = '<div id="'+sectionId+'yasch'+yaschechki[sectionId]+'"><br>&deg;</div>';
    $('#section'+sectionId).append(newYasch);
    var sectionWidth = $('#section'+sectionId).css('width').replace('px', '');
    $('#'+sectionId+'yasch'+yaschechki[sectionId]).addClass('yasch')
                                                  .css('width', maxSectionsWidth)
                                                  .css('bottom', 21*(yaschechki[sectionId]-1))
                                                  .css('padding-left', Math.round(sectionWidth/2))
                                                  .css('z-index', yaschechki[sectionId]);
    organizeItems(sectionId);
  }
}
function removeYasch (sectionId) {
  if (yaschechki[sectionId]>minYasch) {
    $('#'+sectionId+'yasch'+yaschechki[sectionId]).remove();
    yaschechki[sectionId]--;
	organizeItems(sectionId);
  }
}

function setSectionsHeight (value) {
  for (var i=1; i<=sections; i++) {
    $('#section'+i).css('height', value);
    $('#sectionHolder'+i).css('height', value);
	organizeItems(i);
  }
  $('#shkaf').css('height', value);
  $('#out').css('height', value);
}
function setSectionWidth (value, currentSection) {
  $('#section'+currentSection).css('width', value);
  $('#sectionHolder'+currentSection).css('width', value);
  var sectWidth = (value < minSettingsWidth) ? minSettingsWidth : value;
  $('#sectionSettings'+currentSection).css('width', sectWidth);
  $('#sectionHead'+currentSection).css('width', value+36);
  for (var i=1; i<=yaschechki[currentSection]; i++) {
    $('#'+currentSection+'yasch'+i).css('padding-left', Math.round(value/2));
  }
}
function organizeItems(sectionId) {
  var sectionHeight = $('#section'+sectionId).css('height').replace('px', '');
  var step = Math.round((sectionHeight-yaschechki[sectionId]*20)/(polochki[sectionId]+1));
  for (var i=1; i<=polochki[sectionId]; i++) {
    $('#'+sectionId+'pol'+i).css('top', step*(i)-25);
  }
}

function calculate(addPrice, doorsPrice) {
	var limits = new Array;
	var limscnt = 0, minDoorWidth, maxDoorWidth;
	for (lim in doorsPrice) {
		limscnt++;
		var lim2 = new Array;
		lim2 = lim.split('-');
		limits[lim] = new Array(lim2[0] / 10, lim2[1] / 10);
		if (limscnt == 1) minDoorWidth = lim2[0] / 10;
		maxDoorWidth = lim2[1] / 10;
	}
	var dspPrice = addPrice[$('#dspVendor').val()];
	var doorsTypesPrice = new Array(0, 0, 0, 0, 0, 0), body = 0, polki = 0, yaschiki = 0, hangers = 0;
	var depth = parseInt($('#sectionsDepth').val());
	var width = 0, height = parseInt($('#sectionsHeight').val());
	
	var polochkicount = 0, hangerscount = 0;
	for (var i = 1; i <= sections; i++) {
		width += parseInt($('#sectionWidth'+i).val());
		polochkicount = polochki[i];
		if (yaschechki[i] > 0) polochkicount ++;
		polki += polochkicount * $('#sectionWidth'+i).val() * depth *  dspPrice / 10000;
		yaschiki += yaschechki[i] * addPrice['yaschik'];
		hangerscount = parseInt($('#hangersWide'+i).val()) + parseInt($('#hangersEnd'+i).val());
		hangers += hangerscount * addPrice['hanger'];
		//if ($('#sectionHangerEnd'+i).attr('checked') || $('#sectionHangerWide'+i).attr('checked')) hangers += addPrice['hanger'];
	}
	//alert(polki + yaschiki + hangers);
	var floorDepth = ($('#mountedFloor').attr('checked')) ? depth : 20;
	var topDepth = ($('#mountedTop').attr('checked')) ? depth : 10;
	var leftDepth = ($('#mountedLeft').attr('checked')) ? depth : 10;
	var rightDepth = ($('#mountedRight').attr('checked')) ? depth : 10;
	var backPrice = 0;
	if ($('#mountedBack').attr('checked')) {
		var backPanelsCnt = Math.ceil(width / 200);
		backPrice = backPanelsCnt * addPrice['back'];
	}
	body += (((floorDepth * width) + (topDepth * width) + (leftDepth * height) + (rightDepth * height)) * dspPrice + (sections - 1) * depth * height * dspPrice) / 10000 + backPrice;
	
	var doorWidth = width / doors;
	var doorArea = doorWidth * height / 10000;
	var basePrice = 0, fillPrice = 0;
	if (doorWidth < minDoorWidth) {alert ("Ширина двери не может быть меньше "+minDoorWidth+" см"); return false;}
	else if (doorWidth > maxDoorWidth) {alert ("Ширина двери не может быть больше "+maxDoorWidth+" см"); return false;}
	for (lim in limits) {
		if ((doorWidth >= limits[lim][0]) && (doorWidth <= limits[lim][1])) {var lCat = lim; break;}
	}
	for (hlim in doorsPrice[lCat]) {
		if (parseInt(hlim) >= (height * 10)) {var hCat = hlim; break;}
	}
	//alert(doorsPrice[lCat][hCat]);
	basePrice = doorsPrice[lCat][hCat];
	for (var j = 1; j <= doors; j++) {
		fillType = $('#doorFill'+j).val();
		for (var k = 0; k <= 5; k++) {
			//basePrice = doorsPrice[lCat][hCat] + dspPrice * doorArea;
			//if ((fillType == 'paint') && (doorArea > 2)) fillPrice = basePrice * addPrice['bigpaint'];
			if (fillType != 'dsp') fillPrice = addPrice[fillType];
			else fillPrice = 0;
			doorsTypesPrice[k] += basePrice + fillPrice + addPrice['prof'+(k+1)];
		}
	}
	
	var result1, result2, result3, result4, result5, result6;
	result1 = Math.round(doorsTypesPrice[0] + body + polki + yaschiki + hangers);
	result2 = Math.round(doorsTypesPrice[1] + body + polki + yaschiki + hangers);
	result3 = Math.round(doorsTypesPrice[2] + body + polki + yaschiki + hangers);
	result4 = Math.round(doorsTypesPrice[3] + body + polki + yaschiki + hangers);
	result5 = Math.round(doorsTypesPrice[4] + body + polki + yaschiki + hangers);
	result6 = Math.round(doorsTypesPrice[5] + body + polki + yaschiki + hangers);
	$('#price1').html(result1+" грн");
	$('#price2').html(result2+" грн");
	$('#price3').html(result3+" грн");
	$('#price4').html(result4+" грн");
	$('#price5').html(result5+" грн");
	$('#price6').html(result6+" грн");
}
