// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

$(document).ready(function(){

  $("ul li:first-child").addClass("first");
  $("ul li:last-child").addClass("last");
  $("input.submit, input.submit-arrow, input.sendbutton").wrap("<span class='submit-wrap'></span>");

  $("#blog-cat .carrot:first").addClass("show");
  $("#blog-cat span:first-child").addClass("show");
  $("#blog-cat span:last-child").addClass("show");

  $(".quotes li p:last-child, .pad p:last").addClass("last");


  $('.menubar a').each(function(){
    if (parseUri($(this).attr('href')).directory.match(location.pathname) && (location.pathname!="/bryanfranklin/")) {
      $(this).parent().addClass("selected");
    };
  });
//  $('#blog-cat a').each(function(){
//    if (parseUri($(this).attr('href')).directory.match(location.pathname) && (location.pathname!="/bryanfranklin/")) {
//      $(this).addClass("selected");
//    };
//  });


  $("#home-slideshow ul.cycle").cycle({
    timeout: 7000,
    fx: 'scrollHorz',
    prev: '.home-left',
    next: '.home-right',
    pager: '.pagination',
    easing: 'easeOutQuad',
    pagerAnchorBuilder: function(idx, slide) {
        return '<li><a href="#"></a></li>';
    }
  });

  $('.cform input.single, .cform textarea').each(function(){
    $(this).form_prompt(function() {
      return $(this).prev().find("span").html();
    });
  });

  $(".af-form-wrapper input.text").each(function(){
    $(this).form_prompt(function() {
      return $(this).parent().siblings("label").html().split(":")[0];
    });
  });

  $('input#s, .swap').each(function(){
    $(this).form_prompt(function() {
      return $(this).attr('alt');
    });
  });

  $("#free-download .success, #free-download .failure, #free-download-home .success, #free-download-home .failure").prev().hide();


  // --- csx: 09/20/2010: if a program-and-events page is called by an AWeber success link
  // then display Thank you message and fade it out slowly
  var hash = location.hash;
  if (hash=="#thanks") {
    location.hash = '';
    $(".thanks_signup_aweber").css('display','block').delay(3000).fadeOut(1800,0);
  }

  $("#program-content").cycle({
    timeout: 0,
    pager: '#program-menu',
    containerResize: 0,

    after: onAfter,
    before: onBefore,
    pagerAnchorBuilder: function(idx, slide) {
      return '#program-menu li:eq(' + idx + ') a';
    }
  });
  function onAfter(curr, next, opts, fwd) {
    //get the height of the current slide
    var $ht = $(this).height();
    $(this).parent().css("height", $ht);
    $(".quotes").fadeIn(300);
    //set the container's height to that of the current slide
  };
  function onBefore() {
    $(".quotes").fadeOut(300);
  }

  $("#resource-content").cycle({
    timeout: 0,
    pager: '#resource-menu',
    pagerAnchorBuilder: function(idx, slide) {
      return '#resource-menu li:eq(' + idx + ') a';
    }
  });
  if (location.hash=="#videos") {
    $("#resource-content").cycle(0);
  } else if (location.hash=="#audio") {
    $("#resource-content").cycle(1);
  } else if (location.hash=="#articles") {
    $("#resource-content").cycle(2);
  } else if (location.hash!="") {
    var showIndex = $(location.hash).index();
    $("#program-content").cycle(showIndex);
  }

  // download form
  $(".sidebar form").validate({
    rules: {
      // simple rule, converted to {required:true}
      name: "required",
      // compound rule
      email: {
        required: true,
        email: true
      }
    },
    submitHandler: function(form) {
      $.cookie('sb_name', $(".sidebar input.text:first").val(), { expires: 9999, path: '/' });
      $.cookie('sb_secret_post_id', $("#form-id").html(), { expires: 9999, path: '/' });
      $.post(form.attr('action'), form.serialize());
    }
  });
  // oops page
  $(".left-form-col form").validate({
    rules: {
      // simple rule, converted to {required:true}
      name: "required",
      // compound rule
      email: {
        required: true,
        email: true
      }
    },
    submitHandler: function(form) {
      $.cookie('sb_name', $(".left-form-col input.text:first").val(), { expires: 9999, path: '/' });
      $.cookie('sb_secret_post_id', $("#form-id").html(), { expires: 9999, path: '/' });
      $.post(form.attr('action'), form.serialize());
    }
  });

  if ($.cookie('sb_name')) {
    var secret_post_id = $("#form-id").html();
    if ($.cookie('sb_secret_post_id') && secret_post_id && $.cookie('sb_secret_post_id')!=secret_post_id) {
      $.cookie('sb_name', null, { expires: 9999, path: '/' });
      $.cookie('sb_secret_post_id', null, { expires: 9999, path: '/' });
      $.cookie('sb_back', null, { expires: 9999, path: '/' });
    } else {
      $("#download-hilite").hide();
      if ($.cookie('sb_back')) {
        var msg = $(".welcome-back").html().replace(/{}/,$.cookie('sb_name'));
      } else {
        var msg = $(".download-form-success").html().replace(/{}/,$.cookie('sb_name'));
        $.cookie('sb_back', 'true', { expires: 9999, path: '/' });
      }
      $(".download-box").html(msg);
    }
  }
  // remove cookie if new post-id

  // pagination
  $(".paginate").each(function(){
    var $pag = $(this);
    var num_entries = $pag.next().children().length;
    var ipp = 9;
    function handlePaginationClick(page_index, pagination_container) {
      var offset = page_index * ipp;
      var new_content = $pag.next().children().slice(offset, offset + ipp).clone();
      $pag.prev().empty().append(new_content);
      return false;
    };
    $pag.pagination(num_entries, {
      items_per_page: ipp,
      callback: handlePaginationClick,
      prev_text:"",
		  next_text:""
    });
    if (num_entries < ipp) {
      $pag.hide();
    };
  });

  // contact form
  //$("#contact-form .success").next().hide();

  // youtube resize
  $("ul.posts li object, ul.posts li embed").each(function(){
    $(this).attr("width","436px");
    $(this).attr("height","346px");
  });

  // external links new window
  $("a[@href^='http']").attr('target','_blank');

  //$("a").swoosh({ selector: "aswoosh" });
  //$(".tabs a").swoosh({ selector: "tabswoosh" });
  $(".menubar a").swoosh();

});
