/*jslint indent: 2 */
/*globals window: false */
/* based on jquery.noisy */

(function ($) {
  "use strict";
  $.fn.extend({
    noisy: function (params) {
      return $.extend({
        noiseMaker: $.extend({
          opacity: 0.1,
          width: 100,
          amount: 120,
          // particulate width: percent of width to which the particulate should be extended
          p_width: 0,
          // is monochrome: should we add gray
          //                (i.e., use the same random offset for R, G, and B)
          //                to the color?
          is_monochrome: false,
          color: function () {
            return this.caller.css("background-color");
          },
          bringNoise: function () {
            var x, y,
              canvas = $("<canvas>", {width: this.width, height: this.width })[0],
              ctx = canvas.getContext("2d"),
              colorArr = (typeof (this.color) === "function" ?  this.color() : this.color).split(","),
              r = colorArr[0].replace("rgb(", "").trim(), g = colorArr[1].trim(), b = colorArr[2].replace(")", "").trim(),
              h = Math.floor(this.width * this.p_width) + 1,
              offset;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            for (x = 0; x < canvas.width; x += 1) {
              for (y = 0; y < canvas.height; y += 1) {
                if (this.is_monochrome) {
                  offset = Math.random();
                  ctx.fillStyle = "rgba(" + [
                    Math.floor(offset * r + this.amount), Math.floor(offset * g + this.amount), Math.floor(offset * b + this.amount),
                    this.opacity
                  ].join(",") + ")";
                } else {
                  ctx.fillStyle = "rgba(" + [
                    Math.floor(Math.random() * r + this.amount), Math.floor(Math.random() * g + this.amount), Math.floor(Math.random() * b + this.amount),
                    this.opacity
                  ].join(",") + ")";
                }
                ctx.fillRect(x, y, h, 1);
                if ((x + h) > canvas.width + 1) {
                  ctx.fillRect(0, y, ((x + h) - canvas.width), 1);
                }
              }
            }
            return canvas.toDataURL("image/png");
          },
          go: function (caller) {
            this.caller = caller;
            var noise = this.bringNoise();
            return caller.css("background-image", function (i, val) {
              return "url(" + noise + ")" + ", " + val;
            });
          }
        }, params)
      }).noiseMaker.go(this);
    }
  });

  $(window.document).ready(function () {
    var Modernizr = window.Modernizr;
    /* texture */
    if (Modernizr.canvas) {
      $('body').noisy({amount: 30, opacity: 0.02, p_width: 0.2, is_monochrome: true});
      $('article').noisy();
    } else {
      $('body').css({'background-image': 'url(/static/thin-stripe.gif)'});
    }
    /* form placeholders/labels */
    if (!Modernizr.input.placeholder) {
      // no placeholder support :(
      $('input[type!="submit"], textarea').each(function () {
        var $self = $(this),
          label_for = $self.attr('id'),
          label_txt = $self.attr('placeholder');
        $self.before('<label for="' + label_for + '">' + label_txt + '</label>');
      });
    }
    /* portfolio nav */
  //  $('aside nav.secondary a').css({'outline':0});
    $('aside nav.secondary p').text('Show');
    function show_section($el) {
      if ($el.not('.selected').length) {
        var target = $el.attr('href');
        if (target === undefined) {
          target = '';
        }
        $el.siblings('a').removeClass('selected');
        $('section').hide();
        $('section' + target).fadeIn('slow');
        $el.addClass('selected');
        if ($("#dialog").length !== 0) {
          $('#dialog').dialog('option', 'position', ['center', 300]);
        }
      }
    }
    $('aside nav.secondary p').after('<a class="selected">All</a>');
    $('aside nav.secondary a').click(function () {
      show_section($(this));
      return false;
    });
    /* portfolio modals */
    $('body.portfolio section a').click(function () {
      var anchor = $(this),
        url = this.href + '.json',
        dialog = $("#dialog");
      if ($("#dialog").length === 0) {
        dialog = $('<div id="dialog" style="display:hidden"></div>').appendTo('body');
      }
      $.get(url, function (data) {
        dialog.html('');
        $('<a />', {
          'class': 'new-window',
          target: '_blank',
          href: data.new_window,
          text: 'open in new window'
        }).appendTo(dialog);
        $('<a />', {
          'class': 'preview',
          target: '_blank',
          href: data.new_window
        }).appendTo(dialog);
        $('<img />', {
          src: data.preview,
          title: data.title
        }).appendTo($('#dialog a.preview'));
        $(data.description).appendTo(dialog);
        dialog.dialog({
          'close': function () {
            anchor.focus();
          },
          'position': ['center', 300],
          'title': data.title,
          'width': 400
        });
        $('#dialog a.preview').focus();
      });
      return false;
    });
  });
}(window.jQuery));

