var req = function (reqdata, onSuccess, onError, wait) {

  this.onError = onError;

  if (wait)
    $(wait).css("cursor", "wait");

  Tip('Загрузка');

  var params = {
    url: '/ajax.html',
    type: 'POST',
    processData: true,
    data: reqdata,
    dataType: 'json',
    success: function (data) {
   	  UnTip();
      if (wait) $(wait).css("cursor", "auto");
      onSuccess(data);
    },
    error: function (data) {
      UnTip();
      if (wait) $(wait).css("cursor", "auto");
      req.onError(data);
    }
  };

  $.ajax(params);
};

var selectorOnLoadFunc = function(data) {
  if (!data || !data.values) {
    return;
  }

  //this.text('');

  for(var i = 0; i < data.values.length; i++) {
    this.append($('<option/>').attr('value', data.values[i].id).text(data.values[i].name));
  }
}

$(document).ready(function() {

  $('.secure').css({cursor:'hand', cursor:'pointer'}).click(function(){
    $('#secure').attr('src', '/secure.jpeg?temp='+Math.round((Math.random()* 1000000)));
    return false;
  });

    $('.vote a').click(function(){
		var vote = $(this).parent().attr('name');
		if (!vote) return;
		var review_id = $('[name=review_id]').val();
		var user_id = $('[name=user_id]').val();
		if(!user_id)  {
			window.location.href = '/register.html'
			return false;
		}
		$('#voting').hide();
		$('#processing').show();
		$.ajax({
			url: '/ajax.html',
			type: 'POST',
			processData: true,
			data: {act: 'json-vote-review',vote: vote, review_id: review_id, user_id: user_id},
			dataType: 'json',
			success:function(data){
				$('#count_like').html('+'+data.values.count_like);
				$('#count_dislike').html('-'+data.values.count_dislike);
				$('#voting').show();
				$('#processing').hide();
			},
			error: function(){}
		});
	});

  $('#jq_auth_remind_b').colorbox({width:"402px", href: '#jq_auth_remind',inline:true});
  $('#jq_auth_register_b').colorbox({width:"472px", href: '#jq_auth_register',inline:true});
  $('.jq_auth_required_b').colorbox({width:"472px", href: '#jq_auth_register',inline:true});
  $('#jq_auth_profile_b').colorbox({width:"472px", href: '#jq_auth_profile',inline:true});
  $('.jq_auth_car_create_b').colorbox({width:"731px", href: '#jq_auth_car_create',inline:true});
  $('#jq_auth_password_change_b, #jq_auth_password_change_b2').colorbox({width:"472px", href: '#jq_auth_password',inline:true});
  $('#jq_auth_email_change_b').colorbox({width:"472px", href: '#jq_auth_email',inline:true});
  //$('#jq_auth_car_repair_b').colorbox({width:"747px", href: '#jq_auth_car_repair',inline:true});
  $('#btn_new_message').colorbox({width:"472px", href: '#jq_new_message',inline:true});
  $('#jq_car_mark_edit_b').colorbox({width:"872px", href: '#jq_car_mark_edit',inline:true});
  $('#jq_car_model_edit_b').colorbox({width:"872px", href: '#jq_car_model_edit',inline:true});
  $('#jq_car_line_edit_b').colorbox({width:"402px", href: '#jq_car_line_edit',inline:true});
  $('#jq_car_review_edit_b').colorbox({width:"672px", href: '#jq_car_review',inline:true});

  $('#jq_auth_car_delete_b').click(function() {
	var sz = $('input[type=checkbox]:checked').size();

  	if (sz == 0) {
  		  alert('Вы не отметили ни одной машины для удаления');
  		  return false;
  	}
  
	if (confirm('Вы уверены что хотите удалить ' + sz + ' автомоби(ль)ей и все его события?')) {
		$('#car_delete_form').submit();
	}
	
	return false;
  });
  
  $(".jq_auth_car_edit_b").colorbox({width: '731px', href: '#jq_auth_car_edit', inline: true}, function() {
  });

  var img_ok = '/images/v.gif';
  var img_fail = '/images/!.gif';

  var successRegisterResponse =
    function(data) {
      if (!data) {
        $('#jq_reg_error').text('Failed to contact webserver').css('visibility', 'visible');
        return;
      }

      if (data.error) {
        $('#jq_reg_error').text(data.error).css('visibility', 'visible');
      } else {
        $('#jq_reg_error').css('visibility', 'hidden');
      }

      if (data.reg_name) {
        if (data.reg_name == 'ok') {
          $('#jq_reg_name_val').attr('src', img_ok);
        } else {
          $('#jq_reg_name_val').attr('src', img_fail);
        }
      }

      if (data.reg_email) {
        if (data.reg_email == 'ok') {
          $('#jq_reg_email_val').attr('src', img_ok);
        } else {
          $('#jq_reg_email_val').attr('src', img_fail);
        }
      }

      if (data.reg_pass1) {
        if (data.reg_pass1 == 'ok') {
          $('#jq_reg_pass1_val').attr('src', img_ok);
        } else {
          $('#jq_reg_pass1_val').attr('src', img_fail);
        }
      }

      if (data.reg_pass2) {
        if (data.reg_pass2 == 'ok') {
          $('#jq_reg_pass2_val').attr('src', img_ok);
        } else {
          $('#jq_reg_pass2_val').attr('src', img_fail);
        }
      }

      if (data.reg_code) {
        if (data.reg_code == 'ok') {
          $('#jq_reg_code_val').attr('src', img_ok);
        } else {
          $('#jq_reg_code_val').attr('src', img_fail);
        }
      }

      if (data.reg_ok > 1) {
        alert('Вы успешно зарегистрировались!');
        // window.location.href = window.location.href;
        window.location.href = '/garage/' + data.reg_ok;
      }
    }

  var errorRegisterResponse =
    function() {
      $('#jq_reg_error').text('Webserver request has failed').css('visibility', 'visible');
    };

  $('#jq_message_submit').click(function() {
    $('#jq_message_error').css('visibility', 'hidden');

    var message_data = {
      act: 'json-message-send',
      to_user: $('#jq_message_to').val(),
      subject: $('#jq_message_subject').val(),
      text: $('#jq_message_text').val()
    };

    var params = {
      url: '/ajax.html',
      type: 'POST',
      processData: true,
      data: message_data,
      dataType: 'json',
      success: function (data) {

        if (!data) {
          $('#jq_message_error').text('Failed to contact webserver').css('visibility', 'visible');
          return;
        }

        if (data.error) {
          $('#jq_message_error').text(data.error).css('visibility', 'visible');
          return;
        } else {
          $('#jq_message_error').css('visibility', 'hidden');
        }

        if (data.ok)
        {
          $('#jq_message_error').text(data.ok).css('visibility', 'visible');
          setTimeout( "$.fn.colorbox.close()", 2000);
        }
      },
      error: errorRegisterResponse
    };

    $.ajax(params);
    
    return false;
  });
  
  $('#jq_auth_register_submit').click(function() {
    var reqdata = {
      act: 'json-auth-register',
      reg_name: $('#jq_reg_name').val(),
      reg_email: $('#jq_reg_email').val(),
      reg_pass1: $('#jq_reg_pass1').val(),
      reg_pass2: $('#jq_reg_pass2').val(),
      reg_code: $('#jq_reg_code').val(),
      reg_checkbox: $('#jq_reg_checkbox').attr('checked') ? 1 : 0
    };

    var params = {
      url: '/ajax.html',
      type: 'POST',
      processData: true,
      data: reqdata,
      dataType: 'json',
      success: successRegisterResponse,
      error: errorRegisterResponse
    };

    $.ajax(params);
    
    return false;
  });

  $('#jq_auth_car_pre_register_submit').click(function() {

    $(this).attr('disabled', 'disabled');

    var reqdata = {
      act: 'json-auth-car-pre-register',
      pre_reg_car_mark: $('#jq_marks').val(),
      pre_reg_car_model: $('#jq_models').val(),
      pre_reg_car_year: $('#jq_car_year').val(),
      pre_reg_car_modification: '1-0', //заглушка для модификаций
      pre_reg_fuel_id: $('#jq_fuel_id').val(),
      pre_reg_currency_id: $('#jq_currency_id').val(),
      reg_code: $('#jq_reg_code').val(),
      reg_checkbox: $('#jq_reg_checkbox').attr('checked')?1:0
    };

    var params = {
      url: '/ajax.html',
      type: 'POST',
      processData: true,
      data: reqdata,
      dataType: 'json',
      success: successPreRegisterResponse,
      error: errorPreRegisterResponse
    };

    $.ajax(params);
  });

  var successPreRegisterResponse =
    function(data) {
      $('#jq_auth_car_pre_register_submit').removeAttr('disabled');
      if (!data) {
        alert('Failed to contact webserver');
        return;
      }
      if (data.pre_reg_ok == 'ok') {
        alert('Параметры Вашего авто сохранены, теперь можете зарегистрироваться!');
        // window.location.href = window.location.href;
        $("#jq_auth_register_b").click();
        // colorbox({width:"472px", href: '#jq_auth_register',inline:true});
        // window.location.href = '/garage/' + data.reg_ok;
        window.location.href = 'register.html'
      } else if (data.pre_reg_ok_l > 0) {
        alert('Указанное авто добавлено в Ваш гараж!');
        window.location.href = '/garage/' + data.pre_reg_ok_l;
      } else if (data.error) {
        alert(data.error);
      }
    }

  var errorPreRegisterResponse =
    function() {
      $('#jq_auth_car_pre_register_submit').removeAttr('disabled');
      alert('Webserver request has failed');
    }

  $('#jq_auth_remind_button').click(function() {
    var reqdata = {
      act: 'json-auth-remind',
      reg_email: $('#jq_auth_remind_email').val()
    };

    $('#jq_auth_remind_error').css('visibility', 'hidden');

    var successRemindResponse = function(data) {
      
      if (data.ok) {
        $('#jq_auth_remind_error').css('visibility', 'hidden');
        alert(data.ok);
        $.fn.colorbox.close();
      } else {
        $('#jq_auth_remind_error').text(data.error).css('visibility', 'visible');
      }
    }

    var errorRemindResponse = function(data) {
      $('#jq_auth_remind_error').text('Ошибка обращения к серверу.').css('visibility', 'visible');
    }

    var params = {
      url: '/ajax.html',
      type: 'POST',
      processData: true,
      data: reqdata,
      dataType: 'json',
      success: successRemindResponse,
      error: errorRemindResponse
    };

    $.ajax(params);
  });

  $('#jq_reg_name').change(function() {
    req({ act: 'json-validate-reg', reg_name: $(this).val() }, successRegisterResponse, errorRegisterResponse, $(this));
  });

  $('#jq_reg_email').change(function() {
    req({ act: 'json-validate-reg', reg_email: $(this).val() }, successRegisterResponse, errorRegisterResponse, $(this));
  });

  $('#jq_reg_pass1').change(function() {
    req({ act: 'json-validate-reg', reg_pass1: $(this).val(), reg_pass2: $('#jq_reg_pass2').val() }, successRegisterResponse, errorRegisterResponse, $(this));
  });

  $('#jq_reg_pass2').change(function() {
    req({ act: 'json-validate-reg', reg_pass1: $('#jq_reg_pass1').val(), reg_pass2: $(this).val() }, successRegisterResponse, errorRegisterResponse, $(this));
  });

  $('#jq_reg_code').change(function() {
    req({ act: 'json-validate-reg', jq_reg_code: $('#jq_reg_code').val() }, successRegisterResponse, errorRegisterResponse, $(this));
  });

  var reloadOnSuccess = function(data) {
    if (data.error) {
      $('#jq_auth_user_error').text(data.error).slideDown();
      return;
    }
    //window.location.href = window.location.href;
    window.location.href = '/garage/';
    
    
    window.location.reload(true);
    //alert(data.reg_ok);

  }

  var raiseUserError = function() {
    $('#jq_auth_user_error').text('Ошибка обращения к серверу.').slideDown();
  }

  $('#jq_auth_logout_b').click(function() {
    req({ act: 'json-auth-logout'}, reloadOnSuccess, raiseUserError, $(this));
    return false;
  });

//  $('#jq_auth_password_inp').keydown(function(e) {
//    if (e.keyCode == 13) {
//      authFunc();
//    } 
//  });

  var raiseMessage = function(data) {

    if (data.ok) {
      $('#jq_message_error').css('visibility', 'hidden');
      alert(data.ok);
      $.fn.colorbox.close();
    } else {
      $('#jq_message_error').text(data.error).css('visibility', 'visible');
    }

  }

/*
  function (data) {
      onSuccess(data);
      if (wait) $(wait).css("cursor", "auto");
      UnTip();
    },


  $('#jq_message_submit').click( function () {
    # $('#jq_message_error').slideUp(); 
    var params = {
      act: 'json-message-send',
      to: $('#jq_message_to').val(),
      subject: $('#jq_message_subject').val(),
      text: $('#jq_message_text').val()
    };
    req(params, raiseMessage, raiseUserError, $(this));
    return false;
  });

*/

  $('#jq_auth_login_b').click( function () { return authFunc();} );

  var authFunc = function() {
    $('#jq_auth_user_error').slideUp(); 

    var params = {
      act: 'json-auth-login',
      user_login: $('#jq_auth_login_inp').val(),
      user_password: $('#jq_auth_password_inp').val(),
      remember: $('#jq_auth_remember_inp').attr('checked')
    };
    
    req(params, function(data){
      if (data.error){
        $('#jq_auth_user_error').text(data.error).slideDown();
      } else {
        window.location.href='/garage/';
      }
    }, raiseUserError, $(this));
    
    return false;
  }

  $('#jq_auth_remind_button').click( function () { return authRemindFunc();} );

  var authRemindFunc = function() {
    $('#jq_auth_remind_error').css('visibility', 'visible'); 
    
    var params = {
      act: 'json-auth-remind',
      reg_email: $('#jq_auth_remind_email').val()
    };
    
    req(params, reloadOnSuccess, raiseUserError, $(this));
    
    return false;
  }

  //$('#profilehiddenframe, #carcreatehiddenframe, #passwordhiddenframe, #emailhiddenframe, #repaircreatehiddenframe').load(function() {
  $('#carcreatehiddenframe, #carcreatehiddenframe').load(function() {
    var txt = $(this).contents().text();

    if (txt) {
      if (txt != 'OK') {
        $('<div>'+txt+'<div>').html(txt).dialog({
          modal: true,
          height: 100,
          zIndex: 99990,
          buttons: {
            'OK': function(){ $(this).dialog('close') }
          }
        });
      } else {
        window.location.href = window.location.href;
        // window.location.reload();
      }
    }
  });

  $('#jq_form_profile, #jq_form_password, #jq_form_email').submit(function(){
    $(this).ajaxSubmit(function(req)
    {
      req = req.replace(/<\/?[^>]+>/gi, '');
      if (req != 'OK')
      {
        $('<div>'+req+'</div>').html(req).dialog({
          modal: true,
          height: 100,
          zIndex: 99990,
          buttons: {
            'OK': function(){ $(this).dialog('close') }
          }
        });
      }
      else
      {
        window.location.href = window.location.href;
      }

      return false;
    });

    return false;
  })


  
  //$('#jq_action_repair_date_b').datepicker({dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, altField: '#jq_action_repair_date_hidden', altFormat: 'yy-mm-dd' });
  //$('#jq_action_repair_date_remind_b').datepicker({dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, altField: '#jq_action_repair_date_remind_hidden', altFormat: 'yy-mm-dd' });

  Function.prototype.funcBind = function() {
    var __method = this, args = jQuery.makeArray(arguments), object = args.shift();
    return function() {
      return __method.apply(object, $.merge(args, arguments));
    }
  }

  $(document).ready(function(){
	  $('#jq_car_buy_button').datepicker({dateFormat: 'dd-mm-yy', changeMonth: true, changeYear: true, altField: '#jq_car_buy_hidden', altFormat: 'dd-mm-yy' });
	  
    $('select.jq_loadable').focus(function() {
      var me = $(this);

      if (me.attr('loaded')) {
        return;
      }

      me.attr('loaded', '1');
      me.attr('disabled', 'disabled');
      
      if (!me.attr('load_act')) {
        return;
      }

      req(
        {act: me.attr('load_act')},
        function (data) {
          for(var i = 0; i < data.values.length; i++) {
            me.append($('<option/>').attr('value', data.values[i].id).text(data.values[i].name));
          }
          me.removeAttr("disabled");
        },
        //function() { alert('Не удалось загрузить значения'); },
        $(this)
      );
    });

    $('select#jq_marks').change (function() { JQGarage.onMarkChange(); });
    $('select#jq_car_year').change (function() { JQGarage.onModelChange();JQGarage.onYearChange();});
    $('select#jq_models').change (function() { JQGarage.onModelChange(); });
    $('select#jq_car_modification').change (function() { JQGarage.onModificationChange();});
    $('select#jq_car_year_start').change (function() { JQGarage.onModelChange();});
    //$('select#jq_currency_id').change (function() { JQGarage.onCurrencyChange(); });

    $('select.jq_loadable').focus();
  })


});

var JQSearch = {
	onCarYearStartChange: function() {
		var car_year_start = $('#jq_car_year_start').val();
		onModelChange
		console.log(car_year_start);
	}
}

var JQGarage = {
  onMarkChange: function() {
    var models = $('#jq_models');
    var modifications = $('#jq_car_modification');
    var mark_id = $('#jq_marks').val();
    modifications.children().remove().end();
    modifications.append($('<option/>').attr('value', 0).text('Выберите мод-цию'));
    
    if (mark_id > 0)
    {

      models.children().remove().end();
      req(
        {act: 'json-models-load', mark_id: mark_id},
        function (data) {
          models.append($('<option/>').attr('value', 0).text('Модель'));
          for(var i = 0; i < data.values.length; i++) {
            models.append($('<option/>').attr('value', data.values[i].id).text(data.values[i].name));
          }
          models.removeAttr("disabled");
          UnTip();
        },
        function() {
          models.removeAttr("loaded");
          setTimeout( "JQGarage.onMarkChange()", 2000);
          // alert('Не удалось загрузить марки');
        },
        $(this)
      );

    }
  },
  onModelChange: function() {
	var modifications = $('#jq_car_modification');
	var model_id = $('#jq_models').val();
	var car_year = $('#jq_car_year').val();
	var car_year_start = $('#jq_car_year_start').val();
	if (!car_year && car_year_start) car_year = car_year_start;
	
	if (model_id > 0)
    {
		modifications.children().remove().end();
		modifications.append($('<option/>').attr('value', 0).text('Модификация'));
		
		req(
			{act: 'json-modifications-load', model_id: model_id, car_year: car_year },
			function (data) {
				if (data.values.length==0) return;
				modifications.children().remove().end();
				modifications.append($('<option/>').attr('value', 0).text('Модификация'));
				data.values[-1]=new Object();
				for(var i = 0; i < data.values.length; i++) {
					if(data.values[i-1].model_type_id!=data.values[i].model_type_id) modifications.append($('<optgroup/>').attr('label', data.values[i].model_type));
					modifications.append($('<option/>').attr('value', data.values[i].model_type_id+'-'+data.values[i].id).text(data.values[i].modification));
				}
				modifications.removeAttr("disabled");
				UnTip();
			},
			function() {
				modifications.removeAttr("loaded");
				setTimeout( "JQGarage.onModelChange()", 2000);
				//alert('Не удалось загрузить модификации');
			},
			$(this)
		);
    }
    
	var year_start = $('#jq_car_year_start');
	
	if (year_start.attr('loaded')) {
	       return;
	    }
	
    var years = $('#jq_car_year');
    
    if (years.attr('loaded')) {
       return;
    }
    
    if ($('#jq_models').val() > 0)
    {

      years.attr('loaded', '1');
      
      years.children().remove().end();
      
      req(
        {act: years.attr('load_act')},
        function (data) {
        	UnTip();
          years.append($('<option/>').attr('value', 0).text('Год выпуска'));
          for(var i = 0; i < data.values.length; i++) {
            years.append($('<option/>').attr('value', data.values[i].id).text(data.values[i].name));
          }
          years.removeAttr("disabled");
        },
        function() {
          years.removeAttr("loaded");
          setTimeout( "JQGarage.onModelChange()", 2000);
          //alert('Не удалось загрузить модели');
        },
        $(this)
      );

    }
  },
  onYearChange: function() {
    var fuels = $('#jq_fuel_id');

    if (fuels.attr('loaded')) {
      return;
    }

    if ($('#jq_car_year').val() > 0)
    {

      fuels.attr('loaded', '1');

      fuels.children().remove().end();
      req(
        {act: fuels.attr('load_act')},
        function (data) {
          fuels.append($('<option/>').attr('value', 0).text('Тип топлива'));
          for(var i = 0; i < data.values.length; i++) {
            fuels.append($('<option/>').attr('value', data.values[i].id).text(data.values[i].name));
          }
          fuels.removeAttr("disabled");
          UnTip();
        },
        function() {
          fuels.removeAttr("loaded");
          setTimeout( "JQGarage.onYearChange()", 2000);
          // alert('Не удалось годы');
        },
        $(this)
      );

    }
  },
  onModificationChange: function() {
	  var model_id = $('#jq_models').val();
	  var car_year = $('#jq_car_year').val();
	  var modification = $('#jq_car_modification').val();
	  req(
		{act: 'json-engine-volume-load', model_id: model_id, car_year: car_year, modification: modification },	  
		function (data) {
			if (data.values[0]==0) {
				var volume = $('#jq_car_modification option:selected').text();
				regexp = /\d{1}(\.|\,)\d{1}/i;
				volume = regexp.exec(volume);
				volume = volume ? volume[0]*1000 : volume;
			}
			else {
				var volume = data.values[0];
			}
			$('input[name=car_volume_engine]').attr('value',volume);
		},
		function() {
			setTimeout( "JQGarage.onModificationChange()", 2000);
	    },
	    $(this)
	 );
  },
  onCurrencyChange:  function() {
    var currencys = $('#jq_currency_id');

    if (currencys.attr('loaded')) {
      return;
    }

    if ($('#jq_fuel_id').val() > 0)
    {

      currencys.attr('loaded', '1');

      currencys.children().remove().end();
      req(
        {act: currencys.attr('load_act')},
        function (data) {
          currencys.append($('<option/>').attr('value', 0).text('Валюта'));
          for(var i = 0; i < data.values.length; i++) {
            currencys.append($('<option/>').attr('value', data.values[i].id).text(data.values[i].name));
          }
          currencys.removeAttr("disabled");
          UnTip();
        },
        function() {
          currencys.removeAttr("loaded");
          setTimeout( "JQGarage.onCurrencyChange()", 2000);
          // alert('Не удалось валюты');
        },
        $(this)
      );

    }
  }
}

