/**
 * Nextel Plan Con Todo Generic functions
 * @author Gustavo / Andres
 * @version 2.8
 */

var LAST_STEP = 1;
var IS_BLACKBERRY = 0;

$(document).ready(function() {
  
  $('.js-steps-nav div').click(function() {
    if(LAST_STEP <= $(this).attr('step')) {
      return false;
    }
    
    $('.paso-1-active').removeClass('paso-1-active').addClass('paso-1');
    $('.paso-2-active').removeClass('paso-2-active').addClass('paso-2');
    $('.paso-3-active').removeClass('paso-3-active').addClass('paso-3');
    $('.paso-4-active').removeClass('paso-4-active').addClass('paso-4');
    
    if($(this).attr('step') == 1) {
      step1();
    }
    
    if($(this).attr('step') == 2) {
      step2();
    }
    
    if($(this).attr('step') == 3) {
      step3();
    }
    
    if($(this).attr('step') == 4) {
      step4();
    }
    
    $('.js-step').hide();
    $('.js-step#wrapperconfpaso' + $(this).attr('step')).show();
    
  });
  
  $('.js-show-phone').live('click', function() {
    IS_BLACKBERRY = $(this).attr('is_blackberry');
    show_phone($(this).attr('phone_id'));
  });
  
  $('.js-toggle-customer-type').live('click', function() {
    $('.js-toggle-customer-type').removeClass('active');
    $(this).addClass('active');
    $('#p2tipoplan').slideDown();
  });
  
  $('.js-toggle-plan-type').live('click', function() {
    $('.js-toggle-plan-type').removeClass('active');
    $(this).addClass('active');
    $('#p2tiponum').slideDown();
  });
  
  $('.js-toggle-number-type').live('click', function() {
    $('.js-toggle-number-type').removeClass('active');
    $(this).addClass('active');
    $('#sigpaso2').slideDown();
  });
  
  $('.js-toggle-promo').live('click', function() {
    $('.js-toggle-promo').removeClass('active');
    $(this).addClass('active');
    promo($(this).attr('promo_id'),$(this).attr('promo_price'),$(this).attr('promo_name'));
    $('#wrapperServiciosAdic').show();
    $('.js-services-detail').show();
  });
  
  $('.js-toggle-service').live('click', function() {
    if($(this).hasClass('disabled')) {
      return;
    }
    
    if($(this).hasClass('mandatory') && !$(this).hasClass('js-mandatory')) {
      return;
    }
    
    $(this).removeClass('js-mandatory');
    
    $(this).toggleClass('active');
    
    if(!$(this).attr('relates')) {
      add_remove_service($(this).attr('service_id'),$(this).attr('service_name'),$(this).attr('service_price'));

      $('[relates="' + $(this).attr('service_id') + '"]').toggleClass('disabled');
      $('[relates="' + $(this).attr('service_id') + '"].mandatory').addClass('active');
      add_remove_service($('[relates="' + $(this).attr('service_id') + '"].mandatory').attr('service_id'), $('[relates="' + $(this).attr('service_id') + '"].mandatory').attr('service_name'), $('[relates="' + $(this).attr('service_id') + '"].mandatory').attr('service_price'));
      
      if($(this).hasClass('active')) {
        $('[relates="' + $(this).attr('service_id') + '"]').removeClass('active');
        $('[relates="' + $(this).attr('service_id') + '"]').each(function() {
          $('#service-' + $(this).attr('service_id')).remove();
        });
      }
      
    } else {
      if($('.js-toggle-service[relates="' + $(this).attr('relates') + '"].active').length == $('.js-toggle-service[relates="' + $(this).attr('relates') + '"]').length) {
        $('.js-toggle-service[service_id="' + $(this).attr('relates') + '"]').addClass('active');
        
        add_remove_service($('.js-toggle-service[service_id="' + $(this).attr('relates') + '"]').attr('service_id'), $('.js-toggle-service[service_id="' + $(this).attr('relates') + '"]').attr('service_name'), $('.js-toggle-service[service_id="' + $(this).attr('relates') + '"]').attr('service_price'));
        
        $('.js-toggle-service[relates="' + $(this).attr('relates') + '"].active').removeClass('active').addClass('disabled').each(function() {
          $('#servicios-adicionales #service-' + $(this).attr('service_id')).remove();
        });
      } else {
        add_remove_service($(this).attr('service_id'),$(this).attr('service_name'),$(this).attr('service_price'));
      }
    }
    
    if($(this).attr('excludes')) {
      if($(this).hasClass('active')) {
        $('.js-toggle-service[service_id="' + $(this).attr('excludes') + '"]').removeClass('active').addClass('disabled');
        $('#servicios-adicionales #service-' + $(this).attr('excludes')).remove();
      } else {
        $('.js-toggle-service[service_id="' + $(this).attr('excludes') + '"]').removeClass('disabled');
      }
    }
  });
  
  $('.js-toggle-service').live('mouseover', function() {
    if($(this).hasClass('disabled')) {
      return;
    }
    $('.service_description').hide();
    $('#service_description_' + $(this).attr('service_id')).show();
  });
  
  $('#wrapperOpce').mouseout(function() {
    $('.service_description').hide();
  });
  
  $(".elegirbutton").click(function () {
    var plancontent = $(this).parent().html();
    step2();
    $("#plan-container").append(plancontent);
    $("#plan-container > a.elegirbutton").remove();
    var plan_id = $(this).parent().find('.plan_id').val();
    $.ajax({
      type: 'GET',
      url: "ajax/set_plan/"+plan_id
    });
  });
 

  /**
 * Step 2 -> 3
 */
  $('#sigpaso2').click(function(){
    step3();
  });

  /**
 * Step 3 -> 4
 */
  $('#sigpaso3').click(function() {
    step4();
  });

  /*Back buttons*/
  $('#volverpaso1').click(function(){
    step1();
  });

  $('#volverpaso2').click(function(){
    $("#p3").addClass('paso-3').removeClass('paso-3-active');
    $("#p2").addClass('paso-2-active');
    $("#wrapperconfpaso3").hide();
    $("#sigpaso2").show();
    $("#wrapperconfpaso2").show();
  });
});

// ver tab
function verTabs(tabToShow){
  $('#wrapperconfpaso1, #wrapperconfpaso2, #wrapperconfpaso3, #wrapperconfpaso4').hide();
  $('#wrapperconfpaso'+tabToShow).show();
  var idToChange = '#p'+tabToShow;
  $(idToChange).removeClass().addClass('paso-'+tabToShow+'-active');
}


/**
 * Show Phone Info
 * @parmam id int
 */
function show_phone(id) {
  $('#sigpaso3').hide();//Primero oculta el boton
  $('#wrapperServiciosAdic').hide();
  $('.js-services-detail').hide();
  $('#servicios-adicionales').html('');
  
  $.ajax({
    type: 'POST',
    url: "ajax/get_phone",
    data: "id="+id,
    dataType: "html",
    beforeSend: function() {
      $('#wrapcelajax').html('<div align="center" style="height: 250px; padding-top: 100px;"><img src="assets/images/loading.gif" /></div>');
    },
    success: function(datos) {
      $("#wrapcelajax").html('');
      $('#wrapcelajax').html(datos);

      //Consulto las promos para ese telefono
      $.ajax({
        type: 'GET',
        url: "ajax/get_promotions_by_phone/"+id,
        dataType: "html",
        beforeSend: function(){
          $('#promotion-holder').html('<div align="center" style="height: 250px; padding-top: 100px;"><img src="assets/images/loading.gif" /></div>');
        },
        success: function(datos){
          $("#promotion-holder").html('');
          $('#promotion-holder').html(datos);
        }
      });

      //Consulto los servicios para ese telefono
      $.ajax({
        type: 'GET',
        url: "ajax/get_service/"+id,
        dataType: "html",
        success: function(datos) {
          $('#wrapperServiciosAdic').html(datos);
        }
      });

    }
  });
}

/**
 * Show Phone Slider
 */
function show_phones() {
  $.ajax({
    url: "ajax/get_phones",
    dataType: "html",
    beforeSend: function(){
      $('.wrapperThumb').html('<div align="center" style="height: 250px; padding-top: 100px;"><img src="assets/images/loading.gif" /></div>');
    },
    success: function(datos){
      $(".wrapperThumb").html('');
      $('.wrapperThumb').html(datos);
    }
  });
}

function add_remove_service(id,name,price) {
  if($("#service-"+id).length == 0) {
    if(id != undefined) {
      $('#servicios-adicionales').append('<table id="service-'+id+'" width="100%"><tr><td width="80%"><span class="bulletSmall"></span>'+name+'</td><td width="20%"><span class="">$'+price+'</span></td></tr></table>');
    }
  } else {
    $("#service-"+id).remove();
  }
}

function openwindow(url){
  window.open(url,"mywindow","location=1,status=1,scrollbars=1,width=750,height=500");
}

// steps
function step1() {
  $("#plan-container").html('');
  $("#p2").addClass('paso-2').removeClass('paso-2-active');
  $("#p1").addClass('paso-1-active');
  $("#wrapperconfpaso2").hide();
  $("#wrapperconfpaso1").show();
  LAST_STEP = 1;
}

function step2() {
  $("#wrapperconfpaso1").css('display', 'none');
  $("#wrapperconfpaso2").css('display', 'block');
  $("#p2").addClass("paso-2-active");
  $("#p1").removeClass().addClass("paso-1");
  LAST_STEP = 2;
}

function step3() {
  $("#sigpaso2").show();

  var customer_type = $('.js-toggle-customer-type.active').attr('customer_type_id');
  var plan_type = $('.js-toggle-plan-type.active').attr('plan_type_id');
  var number_type = $('.js-toggle-number-type.active').attr('number_type_id');
  $.ajax({
    type: 'POST',
    url: "ajax/set_customer",
    data: "customer_type="+customer_type+"&plan_type="+plan_type+"&number_type="+number_type,
    beforeSend: function(){
    },
    success: function(){
      
      $.ajax({
        type: 'GET',
        url: "ajax/get_plan_box/",
        success: function(datos){
          $("#box-plan-step2").html('');
          $('#box-plan-step2').html(datos);
        }
      });
      
      $("#p2").removeClass('paso-2-active');
      verTabs(3);
      show_phones();
    }
  });
  
  LAST_STEP = 3;
}

function step4() {
  if(IS_BLACKBERRY == 1 && !$('.js-toggle-service[for_blackberry="1"].active').length) {
    var msg = 'Debes seleccionar ';
    var names = [];
    $('.js-toggle-service[for_blackberry="1"]').each(function() {
      names.push($(this).attr('service_name'));
    });
    
    if(names.length >= 2) {
      msg += names.join(' o ');
    } else {
      msg += 'al menos un servicio para BlackBerry';
    }
    
    msg += '.';
    
    return alert(msg);
  }
  
  $("#p3").addClass('paso-3').removeClass('paso-3-active');
  verTabs(4);
  var promotion_id = $('.js-toggle-promo.active').attr('promo_id');
  var services = [];
  $(".js-toggle-service.active").each(function() {
    services.push($(this).attr('service_id'));
  });
    
  $.ajax({
    url: "ajax/set_promotion_services",
    type: 'POST',
    data: {
      "promotion_id": promotion_id,
      "services": services
    },
    beforeSend: function(){
      $('#wrapperconfpaso4').html('<div align="center" style="height: 250px; padding-top: 100px;"><img src="assets/images/loading.gif" /></div>');
    },
    success: function(datos){
      $.ajax({
        url: "ajax/get_step_4",
        dataType: "html",
        beforeSend: function(){
          $('#wrapperconfpaso4').html('<div align="center" style="height: 250px; padding-top: 100px;"><img src="assets/images/loading.gif" /></div>');
        },
        success: function(datos) {
          $('#wrapperconfpaso4').html(datos);
        }
      });
    }
  });
  
  LAST_STEP = 4;
}

function validateEmail($email) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  if( !emailReg.test( $email ) ) {
    return false;
  } else {
    return true;
  }
}

//Step 4 send form
function sendMail() {
  if($("#name").val() != '' && $("#lada1").val() != '' && $("#phone").val() != '' && $("#email").val() != '' && $("#contact_type_id").val() != '' && validateEmail($("#email").val())) {

    $.ajax({
      type: "POST",
      url: "ajax/customer_save",
      data: {
        "name": $("#name").val(),
        "lada1": $("#lada1").val(),
        "phone": $("#phone").val(),
        "email": $("#email").val(),
        "contact_type_id": $("#contact_type_id").val(),
        "optin": $('.js-toggle-contact.active').length,
        "lada2": $("#lada2").val(),
        "phone2": $("#phone2").val(),
        "comments": $("#comments").val()
      },
      success: function(response) {
        $('#form-email').hide();
        if ($('#optin').val() == "si" ) {
          $('#thic2').hide();
          $('#thic1').show();
        } else {
          $('#thic2').show();
          $('#thic1').hide();
        }
      }
    });
    
  } else {
    if ($("#name").val() == '')
      $("#name").addClass('error');
    else if($("#name").hasClass('error'))
      $("#name").removeClass('error');

    if ($("#lada1").val() == '')
      $("#lada1").addClass('error');
    else if($("#lada1").hasClass('error'))
      $("#lada1").removeClass('error');

    if ($("#phone").val() == '')
      $("#phone").addClass('error');
    else if($("#phone").hasClass('error'))
      $("#phone").removeClass('error');

    if ($("#contact_type_id").val() == '')
      $("#contact_type_id").addClass('error');
    else if($("#contact_type_id").hasClass('error'))
      $("#contact_type_id").removeClass('error');

    if ($("#email").val() == '' || !validateEmail($("#email").val()))
      $("#email").addClass('error');
    else if($("#email").hasClass('error'))
      $("#email").removeClass('error');
  }
  
  return false;  
}

