$(document).ready(function(){



	$(function() {	
		$( "#betatest" ).dialog({
			modal: true,
			width: '820',
			height: '565',
   closeOnEscape: false,
   beforeClose: function(event, ui) { document.location.href = "http://fms.freightaccess.com"; $('body').hide(); },
   open: function(event, ui) { $(".ui-dialog").addClass("beta_dialog_bg"); $(".ui-dialog-titlebar-close").removeClass('ui-dialog-titlebar-close').addClass('custom_beta_title').html("LOGIN NOW"); }

		});
	});
	
	
	$('.custom_beta_title').live('click', function() {
    
    document.location.href = "http://fms.freightaccess.com";
	});
	
	function ucwords(str) {
		return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
			return $1.toUpperCase();
		});
	}

	function monkeyPatchCarriercomplete() {
		var oldFn = $.ui.autocomplete.prototype._renderItem;

		$.ui.autocomplete.prototype._renderItem = function(ul, item) {
			var numeric = parseInt(item.numeric);
			var re = new RegExp("^" + this.term, "i") ;
			var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" + ucwords(this.term) + "</span>");
			return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a><span class=\"auto_carrier\">" + t + "</span></a>" )
					.appendTo(ul);
		};
	}

	monkeyPatchCarriercomplete(); // We are using the same Monkey patch for loadboards as Carriers

	$(".getfaqs").autocomplete({
		source: function(request, response){
       $.ajax({
             url: "faqs/getFAQs",
              data: request,
              dataType: "json",
              type: "POST",
              success: function(data){
                  response(data);
              }
           });
		},
		minLength: 1,
		open: function(event, ui) {
			$(".ui-autocomplete").addClass('faqswidth');
		},
		select: function(event, ui) {
			$(this).val(ui.item.value);
			window.location.href="http://www.freightaccess.com/faqs/view/" + ui.item.id;
			return false;
		}
	});
	
    // Before Including this file make sure you include the tokenizer
			
  $("#navigation ul li a img, .hover").hover(function(){
      $(this).attr('src', getToken($(this).attr('src'),1,".png") + "_h.png" );
    },
    function(){
      $(this).attr('src', getToken($(this).attr('src'),1,"_h.png") + ".png" );
  });
    
  $(".hoverbg").hover(function(){
      $(this).css('background-image', getToken($(this).css('background-image'),1,".png") + "_h.png" );
    },
    function(){
      $(this).css('background-image', getToken($(this).css('background-image'),1,"_h.png") + ".png" );
  });
    
  $(".submitbutton img").hover(function(){
      $(this).attr('src', getToken($(this).attr('src'),1,".png") + "_h.png" );
    },
    function(){
      $(this).attr('src', getToken($(this).attr('src'),1,"_h.png") + ".png" );
  });
  
  $('#dialog_registration_form select').change(function(){
      if ($(this).val() == "Shipper") { $(".fmcnfields").css('display', 'none'); }
      else { $(".fmcnfields").css('display', 'block'); }
  });
    
    
  $(".search").mouseenter(function(){
    $(this).toggleClass('transparent');
    $(this).find('input[type=text]').val("");
  }).mouseleave(function() {
    $(this).toggleClass('transparent');
  });

    
  $('#inputseats').keyup(function(){
      if ($(this).val() >= 500) { alert("Please contact Freight Access for an order of 500 seats or more.\nPhone: (847) 924-9127"); $(this).val(499); }
      if (($(this).val() != "") && ($(this).val() != 0) && (isNaN($(this).val()) == false)) { 
        var newtotal = $(this).val() * 11.97
        var seatsnewtotal = $(this).val() * 11.97;
        if ($("#support_level").val() == 1) { newtotal += 14.97; }
        if ($("#referral_consideration").val() == 1) { newtotal += 14.97; }
        $(".inputseatsamount").text("$" + seatsnewtotal.toFixed(2) + " / mo");
        if ($("#coupon_type").val() == 1) { newtotal -= $("#coupon_savings").val(); }
        else if ($("#coupon_type").val() == 2) { newtotal -= newtotal * $("#coupon_savings").val() / 100; }
        $(".totalamount").text("$" + newtotal.toFixed(2) + " / month");
      }
  });
    
  $("#dialog_registration_form input").focus(function(){
      if ($(this).attr('class') != "ND") { $(this).val(""); $(this).addClass("ND"); }
      $(this).addClass("blueborder");
  });
  
  $("#dialog_registration_form input").blur(function(){
      $(this).removeClass("blueborder");
  });
  
  $("#dialog_registration_form select").focus(function(){
      $(this).addClass("blueborder");
  });
  
  $("#dialog_registration_form select").blur(function(){
      $(this).removeClass("blueborder");
  });

  $("#xhpremium").click(function(){
      $("#xhbasic").removeClass("tdgreen").addClass("tdgrey");
      $(this).removeClass("tdgrey"); $(this).addClass("tdgreen");
      $("#support_level").val(1);
      
      if (($("#inputseats").val() != "") && ($("#inputseats").val() != 0) && (isNaN($("#inputseats").val()) == false)) { 
        var newtotal = $('#inputseats').val() * 11.97;
        if ($("#support_level").val() == 1) { newtotal += 14.97; }
        if ($("#referral_consideration").val() == 1) { newtotal += 14.97; }
        if ($("#coupon_type").val() == 1) { newtotal -= $("#coupon_savings").val(); }
        else if ($("#coupon_type").val() == 2) { newtotal -= newtotal * $("#coupon_savings").val() / 100; }
        $(".totalamount").text("$" + newtotal.toFixed(2) + " / month");
      }
      
  });
    
  $("#xhbasic").click(function(){
      $("#xhpremium").removeClass("tdgreen").addClass("tdgrey");
      $(this).removeClass("tdgrey"); $(this).addClass("tdgreen");
      $("#support_level").val(2);
      
      if (($("#inputseats").val() != "") && ($("#inputseats").val() != 0) && (isNaN($("#inputseats").val()) == false)) { 
        var newtotal = $('#inputseats').val() * 11.97;
        if ($("#support_level").val() == 1) { newtotal += 14.97; }
        if ($("#referral_consideration").val() == 1) { newtotal += 14.97; }
        if ($("#coupon_type").val() == 1) { newtotal -= $("#coupon_savings").val(); }
        else if ($("#coupon_type").val() == 2) { newtotal -= newtotal * $("#coupon_savings").val() / 100; }
        $(".totalamount").text("$" + newtotal.toFixed(2) + " / month");
      }
  });
    
  $("#xhagent").click(function(){
      $("#xhbirddog").removeClass("tdgreen").addClass("tdgrey");
      $(this).removeClass("tdgrey"); $(this).addClass("tdgreen");
      $("#referral_consideration").val(1);
      
      if (($("#inputseats").val() != "") && ($("#inputseats").val() != 0) && (isNaN($("#inputseats").val()) == false)) { 
        var newtotal = $('#inputseats').val() * 11.97;
        if ($("#support_level").val() == 1) { newtotal += 14.97; }
        if ($("#referral_consideration").val() == 1) { newtotal += 14.97; }
        if ($("#coupon_type").val() == 1) { newtotal -= $("#coupon_savings").val(); }
        else if ($("#coupon_type").val() == 2) { newtotal -= newtotal * $("#coupon_savings").val() / 100; }
        $(".totalamount").text("$" + newtotal.toFixed(2) + " / month");
      }
  });
    
  $("#xhbirddog").click(function(){
      $("#xhagent").removeClass("tdgreen").addClass("tdgrey");
      $(this).removeClass("tdgrey"); $(this).addClass("tdgreen");
      $("#referral_consideration").val(2);
      
      if (($("#inputseats").val() != "") && ($("#inputseats").val() != 0) && (isNaN($("#inputseats").val()) == false)) { 
        var newtotal = $('#inputseats').val() * 11.97;
        if ($("#support_level").val() == 1) { newtotal += 14.97; }
        if ($("#referral_consideration").val() == 1) { newtotal += 14.97; }
        if ($("#coupon_type").val() == 1) { newtotal -= $("#coupon_savings").val(); }
        else if ($("#coupon_type").val() == 2) { newtotal -= newtotal * $("#coupon_savings").val() / 100; }
        $(".totalamount").text("$" + newtotal.toFixed(2) + " / month");
      }
  });
    
   // $("#dialog_registration_form").validationEngine();
    
	$(function(){	
		$("#dialog-progress").dialog({
			height: 170,
			width: 450,
			modal: true,
			autoOpen: false
		});
	});

    
  $("#dialog_registration").dialog({
    height: 420,
    width: 660,
    autoOpen: false,
    modal: true
  });
		
  $('input.placeholder').live('focus, blur, click', function() {
    if($(this).val() == $(this).attr('value')) {
      $(this).val(''); $(this).removeClass('placeholder');
    }
  });
  
  $('#betaform input').live('focus, blur, click', function() {
    $(this).addClass('hovercolor');
  });
  
  $('#betaform input').live('blur', function() {
    $(this).removeClass('hovercolor');
  });
  
  
  $(".showprogress").click(function(){
    $('#dialog-progress').dialog('open');
  });
		
  $(".submitbutton img").click(function(){
     $(".placeholder").val(""); // reset all placeholders
     var str = $("#dialog_registration_form").serialize();
     jQuery.ajax({
            data: str,
            type: "POST",
            url: "account/addnew",
            timeout: 5600,
            cache: false,
            error: function(a, c) {
              alert("The server is experience some trouble. Please try again!");
            },
            beforeSend: function(r) {
              
            },           
            success: function(r) { 
              if (r != 0) { $("#dialog_registration").html(r); }
              else { alert("Please double check your form and try again"); }
            }
        });
  });
    
  $("#processorderbtn").click(function(){
     var str = $("#dialog_registration_form").serialize() + "&seats=" + $("#inputseats").val();

     jQuery.ajax({
            data: str,
            type: "POST",
            url: "account/checkout",
            timeout: 20600,
            cache: false,
            error: function(a, c) {
              alert("The server is experience some trouble. Please try again!");
            },
            beforeSend: function(r) {
              $("#processmsg").html('<img src="images/account/processing.gif" /><p style="font-weight: bold; font-size: 11px;">Your order is being processed...</p>');
              $('#dialog-progress').dialog('open');
            },           
            success: function(r) { 
              var returncode = parseInt(r);
            
              if (returncode == 9000) { $('#processmsg').html('<h2 style="color: #ff0000; margin-bottom: 2px;">PAYMENT FAILED</h2><p>Please double check your card information</p>'); }
              else if (returncode == 515) { $('#processmsg').html('<h2 style="color: #ff0000; margin-bottom: 2px;">Uh-Oh!</h2><p>Not all form fields are valid.</p>'); }
              else { $('#processmsg').html('<h2 style="color: green; margin-bottom: 2px;">PAYMENT SUCCESS</h2><p>Your account is now active.</p>'); window.location="http://71.205.115.176/fahome/account/signupdone"; }
            }
        });
        
        return false;
  });
    
  $("#applycoupon").live('click', function(){
     var str = "code=" + $("#inputcoupon").val();
     $("#coupon_code").val($("#inputcoupon").val());
     jQuery.ajax({
            data: str,
            type: "POST",
            url: "account/applycoupon",
            timeout: 5600,
            cache: false,
            error: function(a, c) {
              alert("The server is experience some trouble. Please try again!");
            },
            beforeSend: function(r) {
            },           
            success: function(r) { 
              if (r != 0) { 
              var savings = parseFloat(getToken(r, 1, "@@"));
              var type = parseInt(getToken(r, 2, "@@"));
                  $("#coupon_type").val(type);
                  $("#coupon_savings").val(savings.toFixed(2));
                  if (type == 1) { $("#couponarea").html('<h1 style="color: #00bf43;">COUPON APPLIED</h1><p style="font-size: 11px; margin: 0; color: red; font-weight: bold;">YOU JUST SAVED $' + savings.toFixed(2) + '!</p>'); $('#couponarea').effect("pulsate", { times:5 }, 400); }
                  else if (type == 2) { $("#couponarea").html('<h1 style="color: #00bf43;">COUPON APPLIED</h1><p style="font-size: 11px; margin: 0; color: red; font-weight: bold;">YOU JUST SAVED ' + savings.toFixed(2) + '%!</p>'); $('#couponarea').effect("pulsate", { times:5 }, 400); }
                  else if (type == 3) { $("#couponarea").html('<h1 style="color: #00bf43;">COUPON APPLIED</h1><p style="font-size: 11px; margin: 0; color: red; font-weight: bold;">YOUR FIRST MONTH WILL ONLY BE $' + savings.toFixed(2) + '!</p>'); $('#couponarea').effect("pulsate", { times:5 }, 400); }
                  if (($("#inputseats").val() != "") && ($("#inputseats").val() != 0) && (isNaN($("#inputseats").val()) == false)) { 
                    var newtotal = $('#inputseats').val() * 11.97;
                    if ($("#support_level").val() == 1) { newtotal += 14.97; }
                    if ($("#referral_consideration").val() == 1) { newtotal += 14.97; }
                    if ($("#coupon_type").val() == 1) { newtotal -= $("#coupon_savings").val(); }
                    else if ($("#coupon_type").val() == 2) { newtotal -= newtotal * $("#coupon_savings").val() / 100; }
                    $(".totalamount").text("$" + newtotal.toFixed(2) + " / month");
                  }
              }
              else { $("#couponarea").html('<h1 style="color: #ff0000;">INVALID COUPON</h1><p style="font-size: 11px; margin: 0; color: red; font-weight: bold;">THE COUPON IS UNKNOWN</p>'); setTimeout( function(){$("#couponarea").html('<input type="text" style="border: 1px solid #000; font-size: 16px; font-weight: bold; width: 145px; text-align: center;" name="coupon" id="inputcoupon" /> <p style="font-size: 11px; margin: 0; color: red; font-weight: bold;"><input style="margin-top: 3px;" type="submit" id="applycoupon" name="applycoupon" value="APPLY COUPON" /></p>');}, 6000); }
            }
        });
        

        return false;
  });

  (function(jq) {
      jq.autoScroll = function(ops) {
          ops = ops || {};
          ops.styleClass = ops.styleClass || 'scroll-to-top-button';
          var t = jq('<div class="'+ops.styleClass+'"></div>'),
              d = jq(ops.target || document);
          jq(ops.container || 'body').append(t);

          t.css({
              opacity: 0,
              position: 'absolute',
              top: 0,
              right: 0
          }).click(function() {
              jq('html,body').animate({
                  scrollTop: 0
              }, ops.scrollDuration || 1000);
          });

          d.scroll(function() {
              var sv = d.scrollTop();
              if (sv < 10) {
                  t.clearQueue().fadeOut(ops.hideDuration || 200);
                  return;
              }

              t.css('display', '').clearQueue().animate({
                  top: sv,
                  opacity: 0.8
              }, ops.showDuration || 500);
          });
      };
  })(jQuery);

  $.autoScroll({
      scrollDuration: 2000,
      showDuration: 600,
      hideDuration: 300
  });
  
  
});




$(document).ready(function()
{
  $("#betaform").submit(function() {
	var myForm = $('#betaform');
 
	myForm.validate({
			errorClass: "errormessage",
			onkeyup: false,
			errorClass: 'error',
			validClass: 'valid',
			rules: {
				firstname: { required: true, minlength: 3 },
				lastname: { required: true, minlength: 3 },
				companyname: { required: true, minlength: 3 },
				email: { required: true, email: true }
			},
			errorPlacement: function(error, element)
			{
				// Set positioning based on the elements position in the form
				var elem = $(element),
					corners = ['left center', 'right center'],
					flipIt = elem.parents('span.right').length > 0;
 
				// Check we have a valid error message
				if(!error.is(':empty')) {
					// Apply the tooltip only if it isn't valid
					elem.filter(':not(.valid)').qtip({
						overwrite: false,
						content: error,
						position: {
							my: corners[ flipIt ? 0 : 1 ],
							at: corners[ flipIt ? 1 : 0 ],
							viewport: $(window)
						},
						show: {
							event: false,
							ready: true
						},
						hide: false,
						style: {
							classes: 'ui-tooltip-red' // Make it red... the classic error colour!
						}
					})
 
					// If we have a tooltip on this element already, just update its content
					.qtip('option', 'content.text', error);
				}
 
				// If the error is empty, remove the qTip
				else { elem.qtip('destroy'); }
			},
			success: $.noop, // Odd workaround for errorPlacement not firing!
	});
		});
});
