$(document).ready(function(){

  // scroll spy logic
  // ================

  var activeTarget,
      position = {},
      $window = $(window),
      nav = $('body > .topbar li a'),
      targets = nav.map(function () {
        return $(this).attr('href');
      }),
      offsets = $.map(targets, function (id) {
        return $(id).offset().top;
      });

  function setButton(id) {
    nav.parent("li").removeClass('active');
    $(nav[$.inArray(id, targets)]).parent("li").addClass('active');
  }

  function processScroll(e) {
    var scrollTop = $window.scrollTop() + 10, i;
    for (i = offsets.length; i--;) {
      if (activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1])) {
        activeTarget = targets[i];
        setButton(activeTarget);
      }
    }
  }

  nav.click(function () {
    processScroll();
  });

  processScroll();

  $window.scroll(processScroll);


  // Dropdown example for topbar nav
  // ===============================

  $("body").bind("click", function (e) {
    $('.dropdown-toggle, .menu').parent("li").removeClass("open");
  });
  $(".dropdown-toggle, .menu").click(function (e) {
    var $li = $(this).parent("li").toggleClass('open');
    return false;
  });


  // add on logic
  // ============

  $('.add-on :checkbox').click(function() {
    if ($(this).attr('checked')) {
      $(this).parents('.add-on').addClass('active');
    } else {
      $(this).parents('.add-on').removeClass('active');
    }
  });


  // Disable certain links in docs
  // =============================

  $('ul.tabs a, ul.pills a, .well .btn, .actions .btn, .alert-message .btn, a.close').click(function(e) {
    e.preventDefault();
  });
  
  
  $('div.pagination li.current').each(function(){
	  if(!$(this).hasClass('active')){
		  $(this).addClass('active');
		  var id = $(this).text();
		  $(this).empty().append("<a href='#'>" + id + "</a>");
	  }
  });

  // Copy code blocks in docs
  $(".copy-code").focus(function() {
    var el = this;
    // push select to event loop for chrome :{o
    setTimeout(function () { $(el).select(); }, 1);
  });


  // POSITION TWIPSIES
  // =================

  $('.twipsies.well a').each(function () {
    var type = this.title
      , $anchor = $(this)
      , $twipsy = $('.twipsy.' + type)

      , twipsy = {
          width: $twipsy.width() + 10
        , height: $twipsy.height() + 10
        }

      , anchor = {
          position: $anchor.position()
        , width: $anchor.width()
        , height: $anchor.height()
        }

      , offset = {
          above: {
            top: anchor.position.top - twipsy.height
          , left: anchor.position.left + (anchor.width/2) - (twipsy.width/2)
          }
        , below: {
            top: anchor.position.top + anchor.height
          , left: anchor.position.left + (anchor.width/2) - (twipsy.width/2)
          }
        , left: {
            top: anchor.position.top + (anchor.height/2) - (twipsy.height/2)
          , left: anchor.position.left - twipsy.width - 5
          }
        , right: {
            top: anchor.position.top + (anchor.height/2) - (twipsy.height/2)
          , left: anchor.position.left + anchor.width + 5
          }
      }

    $twipsy.css(offset[type])

  });

});


// Custom code.
	var validationOptions = {
			errorClass : 'inline-help',
			errorElement : 'span',
			highlight: function(element, errorClass, validClass) {
			     $(element).closest('.clearfix').addClass('error');
			  },
			  unhighlight: function(element, errorClass, validClass) {
				  $(element).closest('.clearfix').removeClass('error');
				  
			  },
			  showErrors : function(form, validator) {
				  this.defaultShowErrors();
					if(this.numberOfInvalids()){
						var err = $('.append .inline-help');
						if(err.length){
							$('.append .inline-help').remove();
							err.insertAfter('.append .after');
						}
					}
			  }
	};
	$(document).ready(function(){
		$('form').live('mouseover', function(){
			if($(this).data("validate") == undefined){
					$(this).data("validate", $(this).validate(validationOptions));
					setRequired();
					if( typeof afterValidateSet == 'function')
						afterValidateSet($(this).data('validate'));
				}
		});

		

		$('form').each(function(){
			if($(this).data("validate") == undefined){
					$(this).data("validate", $(this).validate(validationOptions));
					setRequired();
					if( typeof afterValidateSet == 'function')
						afterValidateSet($(this).data('validate'));
				}
		});

		$('.inline-help').each(function(){
				var sib = $(this).prev();
				if(sib.hasClass('input')){
					var e = $(this);
					$(this).remove();
					sib.append(e);	
				}
		});
	});

	function setRequired(){
		$('.required').each(function(){
			var sibling = $(this).parent().prev();
			if(sibling[0] == undefined)
				return;
		
			if( (sibling[0].nodeName.toLowerCase() == "label") && !sibling.hasClass('requiredSet')){
				sibling.append("<span style='color:red'> *</span>");
				sibling.addClass('requiredSet');
			}

		});
	}

