var CalcWorker = function(el){

  this._el = el;

  this._elSlider = el.find(".iSlider");
  this._elSliderValue = el.find(".iSliderValue");
  this._elType = el.find("input[name=type]");
  this._elBrand = el.find("input[name=brand]");
  this._elInfo = el.find(".iInfo div");

  this._initSlider();
  this._initType();
  this._initBrand();
  this._initLink();

  this._showInfoMessage(false, false, false);

};
CalcWorker.prototype = {

  _options: {
    area_size: 60
  },

  _el: null,
  _elSlider: null,
  _elSliderValue: null,
  _elType: null,
  _elBrand: null,
  _elInfo: null,

  _sliderValue: 0,
  _typeValue: null,
  _brandValue: null,
  _priceValue: null,


  _initSlider: function()
  {
    var self = this;
    this._elSlider.slider({
      animate: true,
      max: this._options.area_size,
      change: function(event, ui){ self._sliderOnChange(ui.value); },
      slide: function(event, ui){ self._sliderOnSlide(ui.value); }
    });
  },
  //~

  _initType: function()
  {
    var self = this;
    this._elType.each(function(){
      $(this).bind('click', function() {
        self._typeOnChange(this.value);
      });
    });
  },
  //~

  _initBrand: function()
  {
    var self = this;
    this._elBrand.each(function(){
      $(this).bind('click', function() {
        self._brandOnChange(this.value);
      });
    });
  },
  //~

  _initLink: function()
  {
    var self = this;
    this._el.find(".iButtonTermreg").bind('click', function(){
      var params = [];

      var a = '';
      var b = '';
      var c = '';

      if(self._sliderIsSet()){
        params.push( 'area='+self._sliderValue );
      }else{
	a = 'площадь, ';
      }

      if(self._typeIsSet()){
        params.push( 'type='+encodeURIComponent(self._typeValue) );
      }else{
	b = 'тип, ';
      }
      if(self._brandIsSet()){
        params.push( 'brand='+encodeURIComponent(self._brandValue) );
      }else{
	c = 'производителя';
      }
      if(self._priceIsSet()){
        params.push( 'price='+self._priceValue );
      }

      var paramString = '';
      for(var i=0;i<params.length;i++){
        paramString += (i==0? '?': '&') + params[i];
      }

      if(( a != '') || ( b != '') || ( c !='')){
	alert('Необходимо выбрать ' + a + b + c + '!');
        return false;
      }

      window.location = this.href + paramString;
      return false;
    });


    this._el.find(".iButtonOrder").bind('click', function(){
      var params = [];

      var a = '';
      var b = '';
      var c = '';

      if(self._sliderIsSet()){
        params.push( 'area='+self._sliderValue );
      }else{
	a = 'площадь, ';
      }

      if(self._typeIsSet()){
        params.push( 'type='+encodeURIComponent(self._typeValue) );
      }else{
	b = 'тип, ';
      }
      if(self._brandIsSet()){
        params.push( 'brand='+encodeURIComponent(self._brandValue) );
      }else{
	c = 'производителя';
      }
      if(self._priceIsSet()){
        params.push( 'price='+self._priceValue );
      }

      var paramString = '';
      for(var i=0;i<params.length;i++){
        paramString += (i==0? '?': '&') + params[i];
      }

      if(( a != '') || ( b != '') || ( c !='')){
	alert('Необходимо выбрать ' + a + b + c + '!');
        return false;
      }else{

	//$('.iButtonBar .basic').click(function (e) {
		$('#basic-modal-content').modal();

		$('.v_area').html($('.iSliderValue').html() + ' кв.м');
		$('.v_type').html($("input[name='type']:checked").val());
		$('.v_brand').html($("input[name='brand']:checked").val());
		$('.v_price').html($('.iPrice').html());


		$('.forder').bind('click', function(){
		        var errmess = 'Заполните обязательные поля!';

			var temp_val1 = $("input[name='fo_fio']").val();
			var temp_val2 = $("input[name='fo_tlf']").val();
                        var temp_val3 = $("input[name='fo_mail']").val();

			if( (temp_val1 !='') && (temp_val2 != '') && (temp_val3 != '')){
				errmess = '';
			}

			if(errmess == ''){
			/* Оправка аякса */


				$.ajax({
				"url": "calc/calc.send.php",
				"type": "POST",
				"data": {
				"area": $('.iSliderValue').html(),
				"type": $("input[name='type']:checked").val(),
				"brand": $("input[name='brand']:checked").val(),
				"price": $('.iPrice').html(),
				"fio": $("input[name='fo_fio']").val(),
				"tlf": $("input[name='fo_tlf']").val(),
				"email": $("input[name='fo_mail']").val(),
				"address": $("textarea#fo_address").val(),
				"note": $("textarea#fo_note'").val()

				},
				"dataType": "json",
				"success": function(data){ 
$('#fo').html('<p class="fo_msg_info"><b>Заявка успешно отправлена!</b><br/><br/> Для продолжения закройте данное окно.');
$('#simplemodal-container').css('height','320px');
 },
				"error": function(){ return false; },
				"complete": function(){ return false; },
				"cache": false
				});


			}else{
			        alert(errmess);
				return false;
			}
		});
		return false;
	//});
      }
    });


  },
  //~


  _sliderOnChange: function(value)
  {
    if(value != this._sliderValue){
      this._sliderValue = value;
      this.updateInfo();
    }
  },
  //~

  _sliderOnSlide: function(value)
  {
    this._sliderUpdateInfo(value);
  },
  //~

  _typeOnChange: function(value)
  {
    if(value != this._typeValue){
      this._typeValue = value;
      this.updateInfo();
    }
  },
  //~

  _brandOnChange: function(value)
  {
    if(value != this._brandValue){
      this._brandValue = value;
      this.updateInfo();
    }
  },
  //~


  _sliderUpdateInfo: function(value)
  {
    this._elSliderValue.text(value/2); /*as67*/
    //this._elSliderValue.text(value); /*as67*/
  },
  //~

  updateInfo: function()
  {
    var sliderFlag = this._sliderIsSet();
    var typeFlag = this._typeIsSet();
    var brandFlag = this._brandIsSet();

    if(sliderFlag && typeFlag && brandFlag){
      this._request();
    }
    else{
      this._priceValue = null;
      this._showInfoMessage(sliderFlag, typeFlag, brandFlag);
    }
  },
  //~


  _clearInfo: function()
  {
    var self = this;
    this._elInfo.each(function(){
      self._changeInfoBlock($(this), '&nbsp;');
    });
  },
  //~

  _changeInfoBlock: function(el, content)
  {
    el.removeClass('iPrice');
    el.html(content);
  },

  _shdwPrice: function(data, elmid, brand_nm){

    if (!data) {
      return;
    }
    var price = null;
    if(data['price']!==undefined && data['price']!=null && data['price']!=0){
      price = Math.round(data['price']);
    }

    $(elmid).html( price + ' р.');

  },

  //~
  _getInfoElementByBrandId: function(i){
        return $(this._elInfo[i]);
  },

  _getInfoElementByCurrentBrand: function()
  {
    var currentValue = this._brandValue;
    var brands = this._elBrand;

    for(var i=0; i<brands.length; i++){
      if(brands[i].value == currentValue){
        return $(this._elInfo[i]);
      }
    }

    return null;
  },
  //~


  _setPriceInfoBlock: function(value)
  {

    this._clearInfo();

    var brands = this._elBrand;
    var self = this;	

    var el = this._getInfoElementByCurrentBrand();

    el.addClass('iPrice');
	/*as67    el.html(value + ' р.');*/
    //el.html((value/2) + ' р.');
    el.html((value) + ' р.');




    var brand_nm;

    for(var i=0; i<brands.length; i++){				

	elm = this._getInfoElementByBrandId(i);
	elm.attr('id','price_holder'+i);
	elm.addClass('shdwPrice');
        //elm.html($('[name=brand]')[i].value + ' р.');

	//$('[name=brand]')[i].value;

	$.ajax({
	"url": "calc/calc.act.php",
	"type": "POST",
	"data": {
	"area": this._sliderValue/2,
	"type": this._typeValue,
	"brand": $('[name=brand]')[i].value
	},
	"dataType": "json",
	"success": function(data){ self._shdwPrice(data, '#price_holder'+i ,''); },
	"error": function(){ self._requestOnError(); },
	"complete": function(){ self._requestOnComplete(); },
	"cache": false,
	"async":false
	});

    }

    var el = this._getInfoElementByCurrentBrand();

    el.addClass('iPrice');
    el.removeClass('shdwPrice');
    //el.html((value) + ' р.');

  },
  //~

  _showLoadingInfoBlock: function()
  {
    this._clearInfo();

    var el = this._getInfoElementByCurrentBrand();

    el.addClass('iPrice');
    el.html('<span class="iLoading">&nbsp;</span>');
  },
  //~

  _showInfoMessage: function(sliderFlag, typeFlag, brandFlag)
  {
    this._clearInfo();

    if(!sliderFlag){
      $(this._elInfo[0]).html('Выберите площадь');
    }
    if(!typeFlag){
      $(this._elInfo[1]).html('Выберите тип');
    }
    if(!brandFlag){
      $(this._elInfo[2]).html('Выберите бренд');
    }
  },
  //~


  _sliderIsSet: function()
  {
    return this._sliderValue != 0;
  },
  //~

  _typeIsSet: function()
  {
    return this._typeValue !== null;
  },
  //~

  _brandIsSet: function()
  {
    return this._brandValue !== null;
  },
  //~

  _priceIsSet: function()
  {
    return this._priceValue !== null;
  },
  //~


  _request: function()
  {
    this._showLoadingInfoBlock();

    var self = this;
    $.ajax({
      "url": "calc/calc.act.php",
      "type": "POST",
      "data": {
        "area": this._sliderValue/2,
        "type": this._typeValue,
        "brand": this._brandValue
      },
      "dataType": "json",
      "success": function(data){ self._requestOnSuccess(data); },
      "error": function(){ self._requestOnError(); },
      "complete": function(){ self._requestOnComplete(); },
      "cache": false
    });
  },
  //~

  _requestOnSuccess: function(data)
  {
    if (!data) {
      return;
    }

    var price = null;
    if(data['price']!==undefined && data['price']!=null && data['price']!=0){
      price = Math.round(data['price']);
    }
    this._priceValue = price;

    this._setPriceInfoBlock( price===null? '&mdash;': price );
    //alert(this._typeValue + ' '+ this._sliderValue);
  },
  //~

  _requestOnError: function()
  {
    this._setPriceInfoBlock( '&mdash;1' );
  },
  //~

  _requestOnComplete: function()
  {
  }
  //~
};
//~


$(document).ready(function(){

  new CalcWorker($("#calc"));

});

