var t=2000;

function mapPathToStep(path, a)
{
   if (path == 'service')
      return 0;
   else if (path == 'brief')
      return 1;
   else if (path == 'contact')
      return 2;
   else if (path == 'quotes' && !$(a).hasClass('submit'))
      return 3;
   else if (path == 'quotes')
      return 4;

   return -1;
}

function initQuoteForm()
{
   $('.styled-combo').selectbox();

   $(".side-menu a, .nav-button").click(function(e){

      var current = $(".side-menu .active a")[0].href;

      var currentStep = mapPathToStep(current.substring(current.lastIndexOf('/')+1), false);
      var nextStep = mapPathToStep(this.href.substring(this.href.lastIndexOf('/')+1), this);

      if ( currentStep >= nextStep || validateStep(currentStep)  )
      {    
         $("#quoteRequestForm")[0].action = this.href;
         $("#quoteRequestForm")[0].submit();
      }
      else
      {  
         window.scrollTo(0, 0);
      } 
      
      e.preventDefault();
   });

   $("#specialty-area-list :checkbox").click(function(){
      $("#specialty-area-list").removeClass('error');
   })
   
   $("#service-type-list input").click(function(){
      $("#service_"+$(this).val()).appendTo('#specialty-area-list').show().
         siblings().find(':checked').attr('checked', '').end().hide().appendTo($("body"));
   });

   $("#service_"+$('#service-type-list input:checked').val()).show().
      siblings().hide().appendTo($("body"));
   $(".specialty-filler").hide();

   $(".tooltip-trigger").hover(function(e){
      $("#tooltip").css('top',$(this)[0].offsetTop-9).find('.tooltip-text-holder').html(
      $(this).find(".tooltip-text").html()).end().show()},
      function(e){$("#tooltip").find('.tooltip-text-holder').html(
      $(this).find(".tooltip-text").html()).end().hide();
   });

   $(".navbar .next, .navbar .submit").hover(function(){$(".next-text").css('visibility', 'visible')},
      function(){$(".next-text").css('visibility', 'hidden');
   });

   $(".navbar .prev").hover(function(){$(".prev-text").css('visibility', 'visible')},
      function(){$(".prev-text").css('visibility', 'hidden');
   });

   $(".focusable").focus(function(e){
      var parent = $(this).parent();
      parent.addClass('focus');
      if ( $(this).hasClass('expandable') ) {
         parent.parent().addClass('expanded').find('.toggle').html('hide');
         parent.parent().find('.expanded-state').val('expanded');
      }
   });

   $(".focusable").blur(function(e){
      var parent = $(this).parent();
      parent.removeClass('focus');
     
      if ( $(this).hasClass('required') )
         validateBlank($(this));
         
            if($('#QuoteRequestForm_location_id_container').find("li").filter('.selected').html() !='')
            {
                 $('#span-err-msg-state').hide();
            }
   });

   $("#QuoteRequestForm_suburb").blur(function(e){$(this).search();});

   $(".toggle").click(function(e){
      var parent = $(this).parent();
      parent.toggleClass('expanded');
      parent.parent().find('.expanded-state').val(parent.hasClass('expanded') ? 'expanded' : '');
      e.preventDefault();
   });

}

var minBudget = 0;
var maxQuotes = 0;
var minQuotes = 3;
var budgetRatings;

function initQuoteQuotesForm(budgetUrl, ratings, maxQuotesUrl, minQuotesUrl)
{
   budgetRatings = ratings;

   $("#designer-type-holder input").click(function(){
      getMinBudget(budgetUrl);
      getMaxQuotes(maxQuotesUrl);
   });

   $("#interstate-holder input").click(function(){
      getMaxQuotes(maxQuotesUrl);
   });

   $("#budget-holder .input-holder input").blur(function(e){
      getMaxQuotes(maxQuotesUrl);
   });

   $('#budget-holder .input-holder input, #quote-holder .input-holder input').keypress(
      function(e){return isNumberKey(e)
   });

   $("#budget-holder .input-holder input").keyup(function(){
      updateBudgetIndicator($(this).val());
   });

   $("#quote-holder .input-holder input").keyup(function(){
      updateMaxQuotesIndicator($(this).val(), false);
   });

   getMinQuotes(minQuotesUrl);
   getMinBudget(budgetUrl);
   getMaxQuotes(maxQuotesUrl);
}

function getMinBudget(url)
{
   $.ajax({
      type: "GET",
      url: url,
      dataType: 'json',
      data: {"designer_type": $("#designer-type-holder input:checked").val()},
      success: function(response){
         $("#budget-holder .budget-label .dynfield").html(response);
         minBudget = parseInt(response);
         updateBudgetIndicator($("#budget-holder .input-holder input").val());
      }
   });
}

function getMinQuotes(url){
     $.ajax({
      type: "GET",
      url: url,
      dataType: 'json',
      success: function(response){
         minQuotes = parseInt(response);         
      }
   });
}

function getMaxQuotes(url)
{
   $.ajax({
      type: "GET",
      url: url,
      dataType: 'json',
      data: {"designer_type": $("#designer-type-holder input:checked").val(),
         "interstate": $("#interstate-holder input:checked").val(),
         "budget": $("#budget-holder .input-holder input").val()},
      success: function(response){
         $("#quote-holder .quote-label .dynfield").html(response);
         maxQuotes = parseInt(response);
         updateMaxQuotesIndicator($("#quote-holder .input-holder input").val(), false);
      }
   });
}

function updateMaxQuotesIndicator(value, validate)
{
   if ( value == '' )
   {
      if ( validate ) {
         $("#quote-holder .quote-rating div").removeClass().addClass('too-many').html('Required');
         return false;
      }
      else
         $("#quote-holder .quote-rating div").removeClass();
   }
   else {
      var num = parseInt(value);

      if ( isNaN(num) ){
         $("#quote-holder .quote-rating div").removeClass().addClass('too-many').html('Invalid');
         return false;
      }
      else if ( num == 0 || (num < minQuotes)){
         $("#quote-holder .quote-rating div").removeClass().addClass('too-many').html('Not enough');
         return false;
      }
      else if ( num > maxQuotes ) {
         $("#quote-holder .quote-rating div").removeClass().addClass('too-many').html('Too many');
         return false;
      }
      else
         $("#quote-holder .quote-rating div").removeClass().addClass('ok').html('OK');
   }
   return true;
}
function isNumberKey(evt)
{
   var charCode = (evt.which) ? evt.which : event.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false;

   return true;
}
function updateBudgetIndicator(value)
{
   var pass = true;
   var num = parseInt(value);
   if ( isNaN(num) ) {
      $("#budget-holder .budget-rating div").html('Below minimum');
      pass = false;
   }
   else
   {
      $.each(budgetRatings, function(){
         if ( num >= (minBudget * this.min_multiplier) && (this.max_multiplier == null || num < (minBudget * this.max_multiplier)) ) {
            
            $("#budget-holder .budget-rating div").removeClass().addClass("c"+this.id).html(this.display);
            
            if (this.display == 'Below minimum') {
               pass = false;
            }
         }
      });
   }
   return pass;
}

function validateBlank(elem)
{
   if ( elem.val() == '' ) {
      elem.parents('.row').removeClass('ok').addClass('error').
         find('.error-msg').hide().end().find('.client-error-msg.blank').show().fadeIn().fadeOut().fadeIn().end();
      return false;
   }
   
   if(elem.attr('id') == 'QuoteRequestForm_email')
   {
   		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   		if(elem.val() != '' && reg.test(elem.val()) == false)
   		{
   			  elem.parents('.row').removeClass('ok').addClass('error').
         	find('.error-msg').hide().end().find('.client-error-msg.blank').show().fadeIn().fadeOut().fadeIn().end();
     		 return false;
   		}
   }
       
   elem.parents('.row').removeClass('error').addClass('ok').
      find('.client-error-msg').hide();
   return true;
}

function validateSuburb(data)
{
   if ( !data ) {
      $("#quote-suburb").removeClass('ok').addClass('error').
         find('.error-msg').hide().end().find('.client-error-msg.exist').show().fadeIn().fadeOut().fadeIn().end();
         $("#val_suburb").val('0');
         return false;
   } else {
      $("#quote-suburb").removeClass('error').addClass('ok').
         find('.client-error-msg').hide();
          $("#val_suburb").val('1');
         return true;
   }
}

function validateStep(step)
{
   var pass = true;

   if (step == 0) {
      if ( $("#specialty-area-list :checked").length <= 0 ) {
         $("#specialty-area-list").addClass('error').find('.error-msg').hide().end().
            find('.client-error-msg').show();
         pass = false;
      }
   }
   else if (step == 2) {
      $("#QuoteRequestForm_suburb").search();
   }
   else if (step == 3) {
      pass = updateMaxQuotesIndicator($("#quote-holder .input-holder input").val(), true);
      pass &= updateBudgetIndicator($("#budget-holder .input-holder input").val());

      if ( $("#quote-period-options :checked").length <= 0 ) {
         $("#quote-period-options").addClass('error').find('.error-msg').hide().end().
            find('.client-error-msg').show();
         pass = false;
      }
   }

   $(".required").each(function(){
      pass &= validateBlank($(this));
   });

   return pass;
}


function removeElemclass(elem)
{


 /*elem.parents('.row').removeClass('ok').addClass('error').
         find('.error-msg').hide().end().find('.client-error-msg.blank').show().css('text-decoration','');
      clearTimeout(t);*/
 
}