// On Ready
jQuery(function ()
{
  // Activate video classes
  jQuery(".video a, a.video").each(function () { jQuery.ip_ActivateVideo(this); });
  
  // Bind site search
  jQuery(".search-form").submit(function (evt)
  {
	
    evt.preventDefault();
    var jQuerythis = jQuery(this);
    var term = encodeURIComponent(jQuery("#search-from").val());

    window.location.href = "/search.html?q=" + term;
  });

  // Quick fix to allow sidebar to be clickable
  jQuery("#sidebar-right span")
    .addClass("clickable")
    .click(function ()
    {
      var target = jQuery(this).find("a:first");
      if(target.length == 1)
      { location.href = target[0].href; }
    });
  
  // The portfolio pages
  if(jQuery("#portfolio").length && jQuery("#portfoliomenu").length)
  {
    // Portfolio: variables & utility functions
    var thumbnails = jQuery("#portfolio > div:not(.portfolio-detail)")
    var closeAllDetails = function (evt) // Bind the opening & closing of the detail
    {
      evt.preventDefault();
      jQuery(".portfolio-detail .video object").remove();
      jQuery(".portfolio-detail .video a").show();
      jQuery(".portfolio-detail").slideUp();
    };

    // Portfolio: setting up the interactions
jQuery("#portfolio > .portfolio-detail").remove();

          thumbnails.filter(":visible").each(function (i, el)
          {
            var jQuerybase = jQuery(el);
            var modulus = i % 3;
            jQuerybase.toggleClass("first-portfolio-thumbnail", modulus == 0);

            var detail = jQuerybase.find(".portfolio-detail").clone();

            jQuerybase.click(function (evt)
            {
			  var currentlyOpen = detail.filter(":visible").length === 1;
              closeAllDetails(evt);
              if(!currentlyOpen) { detail.slideDown(); }
            });
            detail.find("a.close").click(closeAllDetails);

            // Bind video
            detail.find(".video a").click(function (evt)
            {
              evt.preventDefault();
              var id = jQuerybase.attr('id') + '_video';
              var jQuerythis = jQuery(this);
              jQuerythis
                .hide()
                .parent()
                .append("<div class='image video-container' id='" + id + "'><\/div>");
              swfobject.embedSWF(
                jQuery(this).attr('href'),
                id,
                jQuerythis.parent().width(),
                jQuerythis.parent().height(),
                "9",
                null,
                { 'autoplay': 't' },
                { 'wmode': 'transparent', 'allowfullscreen': 'true' }
              );
            });

            // Bind the Mini Slider
            detail.find(".minislider a").click(function (evt)
            {
              evt.preventDefault();
              var jQuerythis = jQuery(this);
              detail.find(".minislider a").removeClass("active");
              jQuerythis.addClass("active");
              var src = jQuerythis.attr("href");
              jQuerythis.closest(".portfolio-detail").find(".image").css('background-image', "url('" + src + "')");
            });

            // Insert the detail view in the correct row
            var nextRowStart = thumbnails.filter(":visible").eq(i + 2 - modulus);
            if (nextRowStart.length === 0)
            { nextRowStart = thumbnails.filter(":visible").last(); }
            nextRowStart.after(detail);
          });
  
  
    // Portfolio: client flyout
    jQuery("#ClientsFlyout").click(function (evt)
    {
      evt.preventDefault();
      var t = jQuery(this).toggleClass("active").text();
      if (t == "- Close This List")
      { jQuery(this).text("+ Clients"); }
      else
      { jQuery(this).text("- Close This List"); }

      jQuery("#clientlist").slideToggle();
    });
  
  
  
    // Portfolio: Client Deeplinking
    if (typeof UrlParams["client"] === "string")
    { 
      var portfolio = thumbnails.filter("#" + UrlParams["client"]);
      if (!portfolio.length) { return false; }

      if (!portfolio.filter(":visible").length) // if the category selected rules out the single client
      { return false; }

      var offset = portfolio
        .click()
        .offset()
          .top - 2;
      
      if(offset > 0)
      { jQuery("html").scrollTop(offset); }
    } 
  }
  
  // Populate the blog snippets
  if(jQuery(".bring-blog-post-inside").length != 0 || jQuery("#footer-right-mid").length != 0)
  {
    jQuery.ajax({
      url: "/our-blog/?json=get_recent_posts&count=3&post_type=post",
      dataType: 'json',
      type: 'get',
      success: function(data, textStatus, jqXHR)
      {
        jQuery("#blog-content").empty();
        jQuery("#footer-right-mid").empty();
        for(var i = 0; i < data.posts.length; i++)
        {
  var now = new Date(data.posts[i].date.substr(0,4), parseInt(data.posts[i].date.substr(5,2))-1,data.posts[i].date.substr(8,2));
 var dt = dateFormat(now,"mmmm dd, yyyy");

          jQuery('<p class="blog-title"><a href="' +
              data.posts[i].url +
              '">' +
              data.posts[i].title +
              ' &raquo;</a></p><span class="blog-written-date">'+dt+'</span><p class="format">' +
              data.posts[i].excerpt + 
              '</p>')
            .appendTo(".bring-blog-post-inside");
          
        }
      },
      error: function(jqXHR, textStatus, errorThrown)
      {
        //debugger;
      }
    });
  }

});

// While rendering
(function() {
  var img = new Image();
  img.src = 'http://www.theideapeople.com/assets/img/btn_play_on.png';
})();

// Activate Video on demand
jQuery.ip_ActivateVideo = function (el)
{
  jQuery(el).fancybox(
  {
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 600,
    'speedOut': 200
  });
};

// Load Typekit
try { Typekit.load(); } catch (e) { }

// URL Parameters (http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript)
window.UrlParams = {};
(function ()
{
  var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

  while (e = r.exec(q))
    window.UrlParams[d(e[1])] = d(e[2]);
})();
jQuery(".backbutton").live("click",function(){
	history.go(-1);
  });
