// Clear form of all values
jQuery.fn.clear = function(){
  return this.each(function(){
  jQuery(':input', this)
   .not(':button, :submit, :reset, :hidden')
   .val('')
   .removeAttr('checked')
   .removeAttr('selected');
  });
};

$(document).ready(function(){

  var panel    = $("#hd-login"),
      origTop  = panel.css("top"),
      origText = $("a",panel).html();

  $("#hd-login a").toggle(function(){
    $(this).html("close").blur();
    panel
      .css({zIndex:999})
      .addClass("active")
      .animate({top:0});
  }, function(){
    var panel = $("#hd-login");
    $(this).html(origText).blur();
    panel
      .animate({top: origTop },'fast',function(){ panel.css({zIndex:0});panel.removeClass("active"); });
  });

  var wizard, btnNext, btnPrev, btnSubmit, stepValid = true, promoValid = true, promoInfo;

  // Request Demo Form
  if ($("#demo-inline").length) {
    setupDemo();
  }
  
  // We have to do a bunch of preprocessing to get the form the way we have to use it
  function setupDemo(){
    var f;
    $("#request-demo fieldset").wrapAll("<div id='request-demo-wizard'><div class='steps'></div></div>");
    wizard = $("#request-demo-wizard");
    $("#request-demo-wizard fieldset:not(:first)").hide();
    f  =  $("#request-demo-wizard fieldset:first");
    f.addClass("current");
    $("<div class='ctl'><a id='btn-back' class='btn btn-grey' href='#'>&laquo; Back</a><div id='request-demo-wizard-progress'></div><a id='btn-next' class='btn btn-grey' href='#'>Next &raquo;</a></div>").appendTo(wizard);
    btnSubmit = $("input[type=submit]",wizard).appendTo($(".ctl", wizard)).removeClass("btn-submit").addClass("btn-black").val("Send").hide();
    $("img.ajax-loader").insertAfter("#request-demo input[type=submit]");

    $("<h2 id='current-step-title'></h2>").insertBefore("#request-demo");

    $("#demo-inline").addClass("ui-window").appendTo("body");

    $("#request-demo-wizard fieldset:last").prepend($("#request-demo-info"));

    $("legend").hide();

    btnNext = $("#btn-next").live("click", updateStep);
    btnPrev = $("#btn-back").live("click", updateStep);
  }

  $.singleWindow.setup({
    init: function(){
      var self = this;
      this.overlay = $("<div id='ui-overlay' class='ui-overlay'></div>").appendTo("body").hide();
      this.overlay.click(function(){ self.hide(); });
    },
    show: function(content,location,opts){
      wizard.data("current",0);
      this.overlay.fadeIn();
      this.container = content.positionAt(location).fadeIn();
      $("form",this.container).clear();
      if (promoInfo) { promoInfo.remove(); }
      updateTitle($("fieldset.current"));
      btnNext.show();
      btnPrev.hide();
    },
    hide: function(){
      this.overlay.fadeOut();
      $("#request-demo-wizard-progress").css({"backgroundPosition":"0 0"});
      this.container.fadeOut()
        .find("fieldset").hide().first().show().addClass("current");
      return this.container;
    }
  });

  function updateStep(e){
    e.preventDefault();
    var self         = $(e.target).blur(),
        cur          = $("#request-demo .current"),
        back         = self.is("#btn-back"),
        index        = cur.index("#request-demo fieldset") + (back ? -1 : 1),
        getNextPanel = function(){ return cur.removeClass("current").hide()[ back ? 'prev' : 'next']().addClass("current").fadeIn(); },
        next;

    if (index == 3)  {
      btnSubmit.hide();
      btnPrev.hide();
      next = getNextPanel();
      updateTitle(next);
      updateProgress(index);
    } else {
      // Don't validate on back
      if (!back) { validateStep(cur); }
      if ((promoValid && stepValid) || back) {
        next = getNextPanel();
        if (back) {
          if(index === 0) { btnPrev.hide(); } 
          btnNext.show();
          btnSubmit.hide();
        } else {
          if (index == 2) { 
            btnNext.hide();
            btnSubmit.show();
          } 
          btnPrev.show();
        }
        updateTitle(next);
        updateProgress(index);
        return next;
      }
    }
  }

  function updateProgress(index){
    return $("#request-demo-wizard-progress").css({"backgroundPosition":'0 -'+ (index*30) + 'px'});
  }

  function updateTitle(el){
    var title = $("#current-step-title");
    title[0].className = el.attr('id');
    title.html($("legend",el).html());
  }

  // This is a hack because of the way WPCF7 does validation
  function validatePromo() {
    promoValid = false;
    var f       = $('div.wpcf7 > form'), invalid;
    var loading = $("img.ajax-loader").clone().insertAfter("#field-code").css("visibility","visible");
    promoInfo    = $("#promo-info");
    if (promoInfo.length === 0) {
      promoInfo = $("<p id='promo-info' class='notice'>Checking Promo Code</p>").insertAfter(loading);
    }
    $.ajax({data:f.serialize()+"&_wpcf7_is_ajax_call=1",dataType:"json", url:f.attr('action'),type:"POST", success:function(d){ 
        loading.remove();
        // WPCF7 returns an array of objects, so in order to find the right one we have to test if the message
        // is talking about promo codes at all. Lovely
        $.each(d.invalids,function(){ if(/promo/i.test(this.message)) { invalid = this; } });
        if (invalid) {
          promoInfo.html("Code is invalid!")[0].className="error";
          // info.remove();
          // wpcf7NotValidTip($(invalid.into),invalid.message);
        } else {
          promoInfo.html("Code is valid!")[0].className="success";
          promoValid = true;
        }
      } 
    }); 
  }

  $("#field-code").live('blur',function(){ 
    if ($("#field-code").val() !== "") { 
      validatePromo(); 
    } else {
      promoInfo.fadeOut(function(){$(this).remove();});
    }
  });

  function validateStep(cur){
    stepValid = true;
    $("input[type=text],select",cur).each(function(){
      var i = $(this);
      if (i.hasClass("wpcf7-validates-as-email") && !isValidEmail(i.val())) {
        wpcf7NotValidTip(i.parent(),"Email is invalid");
        stepValid = false;
      } else if (i.hasClass("wpcf7-validates-as-required") && i.val() === "") {
        wpcf7NotValidTip(i.parent(),"This is a required field");
        stepValid = false;
      } 
    });

    return stepValid;
  }

  function isValidEmail(str) {
    var regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
    return regex.test(str);
  }

  $("a.demo-inline").live('click',function(e){
    e.preventDefault();
    if($.browser.msie)  {
      $(".ui-overlay").css({opacity:0.2});
    }
    $.singleWindow.show($("#demo-inline"),"center");
  });

  // END REQUEST DEMO
  
  $("#tour").each(function(){
    var self = $(this);
    var toggleable = $(".step-text",self);
    toggleable.hide().before("<a class='ui-toggle btn-toggle'>Read More</a>");
    $(".ui-toggle",self).live("click",function(){
      $(this).next().animate({height:'toggle', opacity:'toggle'});
    });
  });

  $("dt.gallery-icon a")
    .attr('rel','features')
    .fancybox({
      transitionIn		: 'elastic',
      transitionOut		: 'elastic',
      titlePosition 	: 'over'
    });

});


