Playtype

/**
 * Playtype.com
 *
 * Functions, plugin calls and animation
 * of the playtype.com site.
 *
 */


$(function() {


  /*
   * The file's functions are devided into code blocks
   * only called if the relevant element is present in
   * the current page.
   * // JCK
   *
   */


  /**
   * Fade in images when they are loaded.
   *
   */
  $('img').each(function() {

    $(this).hide().load(function() {

      $(this).fadeIn(800);

    });

    if (this.complete) $(this).trigger("load");

  });

  /**
   * Top Menu Quick Fix
   *
   */
  $('.pt-container-header-navigation').each(function() {

    var ul = $(this).find('ul');
    var lis = ul.find('li');
    var takes = Math.floor(lis.length / 3);
    var html = $('<ul class="right"></ul>');
    for (i = 1; i <= takes; i++) {
      html.append(lis.eq(lis.length - i));
    }
    $(this).append(html);

    lis.eq(0).addClass('big browse-fonts');
    lis.eq(1).addClass('big the-store');

  });


  /**
   * Frontpage Slideshow
   *
   */
  var frontpageSlideshow = $('.pt-fpss');
  var frontpageSlideshow = $('.pt-fpss, .view-front');
  frontpageSlideshow.each(function() {

    // Variables
    var slidemargin = 20; // px
    var listcontainer = frontpageSlideshow.find('.pt-fpss-list, .view-content');
    var listelements = listcontainer.find('li');
    var listimages = new Array();
    var activeIndex = 0;


    var temp = 0;
    listelements.find('.fpss-cont').each(function() {

      var listslides = listimages;
      var index = listslides.length;
      listslides[index] = temp;

      temp = temp + $(this).width();
      temp = temp + slidemargin;

    });


    var max_left = temp - slidemargin - 1020;

    /*
     * Slideshow Controls
     */
    $leftArrow = $('<li class="left"><a href="#">left</a></li>');
    $rightArrow = $('<li class="right"><a href="#">right</a></li>');

    /*
     * Slide to index in the list of images
     *
     */

    function slideTo(index) {
      // Find new position (negative left)
      var move = -1 * listimages[index];

      // Remove Hands
      if (index == 0) {
        $leftArrow.addClass('inactive');
      } else if (index + 1 == listelements.length) {
        $rightArrow.addClass('inactive');
      } else {
        $leftArrow.removeClass('inactive');
        $rightArrow.removeClass('inactive');
      }

      if (move < -max_left) {
        move = -max_left;
        $rightArrow.addClass('inactive');
      }

      // Move the slideshow
      listcontainer.stop().animate({
        "left": '' + move + 'px'
      }, 1200, 'easeInOutExpo');

    }

    // Design
    listcontainer.css({
      'width': '20000px'
    }); // Make all the boxes fit.
    $(window).resize(function() {
      listcontainer.css({
        'margin-left': $('.pt-container').offset()['left']
      });
    }); // Put the slideshow in grid with design

    // Go left or right?

    function arrowLeft() {
      if (!(activeIndex == 0)) {
        slideTo(activeIndex - 1);
        activeIndex--;
      }
    }

    function arrowRight() {
      if (!(activeIndex + 1 == listelements.length)) {
        slideTo(activeIndex + 1);
        activeIndex++;
      }
    }

    $leftArrow.click(function() {
      arrowLeft();
      return false;
    });

    $rightArrow.click(function() {
      arrowRight();
      return false;
    });

    // Bind slideTo to arrow left and right
    $(document).keydown(function(e) {

      if (e.keyCode == 37) // Left
      {
        arrowLeft();
        return false;
      } else if (e.keyCode == 39) // Right 
      {
        arrowRight();
        return false;
      }

    });

    $controls = $('<ul></ul>');
    $controls.append($leftArrow);
    $controls.append($rightArrow);
    $controls = $('<div class="pt-fpss-controls"></div>').prepend($controls);

    frontpageSlideshow.prepend($controls);

    /*
     * FadeIn the slideshow
     */
    slideTo(++activeIndex);
    frontpageSlideshow.fadeIn('slow');

  });

  /**
   *
   * Show / Hide the hands on the frontpage slider
   *
   */
  $('.pt-fpss-controls').each(function() {

    var hands = $('.pt-fpss-controls ul li');

    $('.view-front').mouseenter(function() {
      hands.fadeIn(300, 'easeInOutCubic');
    }).mouseleave(function() {
      hands.fadeOut(300, 'easeInOutCubic');
    });
  });


  /**
   * Scale Background
   *
   */
  $('.pt-background').scaleBgImage();


  /**
   * init window functions
   *
   */
  $(window).trigger('resize');


  /**
   *
   * Drop Down Menu (font-filters, about, search, etc)
   *
   */
  $('.pt-container-navigation .content > ul > li').each(function() {

    var wait = 200;
    var timer;

    var dad = $(this); // First level LI
    var dad_ul = $(this).find('> ul'); // First UL in dad


    dad.mouseenter(function() {

      if ($(this).hasClass('active')) {
        return;
      }
      clearTimeout(timer);

      timer = setTimeout(function() {

        dad_ul.addClass('active').stop(true, true).slideDown();

      }, wait);

    }).mouseleave(function() {

      clearTimeout(timer);

      dad_ul.removeClass('active').stop(true, true).delay(400).slideUp('easeInOutCubic');
    });



  });


  /**
   * Font Style Navigation - Navigation
   *
   */
  var secmenu = '.pt-container-navigation ul ul';
  $('.pt-container-navigation .fontstyles ,' + secmenu).each(function() {

    var linkscontainer = $(this);
    var links = $(this).children('li');
    var links_activearea = '.styles, ul';
    var timer;
    var currentslide;

    links.mouseenter(function() {

      if ($(this).hasClass('active')) {
        return;
      }

      currentSlide = $(this);

      clearTimeout(timer);

      timer = setTimeout(function() {
        linkscontainer.find('.active').removeClass('active').find(links_activearea).stop(true, true).slideUp();
        currentSlide.addClass('active');
        currentSlide.find(links_activearea).stop(true, true).slideDown();
      }, 200);

    });

    links.mouseleave(function() {
      clearTimeout(timer);
    });

    linkscontainer.mouseenter(function() {

    });

    linkscontainer.mouseleave(function() {

      clearTimeout(timer);
      $(this).find('.active').removeClass('active').find(links_activearea).stop(true, true).slideUp();
    });
  });


  /**
   * Font Specification - Font Weights
   *
   */
  $('.specfont-weightsandstyles').each(function() {

    var content = $(this).find('ul ul');

    $(this).find('ul a').eq(0).mouseenter(function() {
      content.stop(true, true).slideDown(200);
    });

    $(this).mouseleave(function() {
      content.stop(true, true).slideUp(200);
    });

  });


  /**
   * Font Specification - IntroSlider
   *
   */
  var specificfontspec = $('.fontspecifications-opener');
  specificfontspec.each(function() {
    var container = $('.specfont-headinfo-specs');
    $(this).click(function() {
      container.slideToggle(300, 'easeInOutCubic');
      $(this).toggleClass('active');
      return false;
    });
  });


  /**
   * Open/close font details
   *
   */
  $('.specfont-fontlist ul li').each(function() {

    var current = $(this);
    var detailbutton = current.find('.font');
    var detailcontainer = current.find('.fontdetail');
    var textarea = current.find('.editable textarea');
    var textareacontainer = current.find('.editable .textarea');
    var sizechangers = current.find('.editable .font-size a');
    var transitiontime = 500; // millisecond, smooth transition time		

    sizechangers.eq(0).addClass('active');

    sizechangers.click(function() {

      var newclass = $(this).attr('class');
      var currenttext = textarea.val();
      var newtextarea = $('<textarea></textarea>').attr('class', newclass).attr('spellcheck', 'false').val(currenttext);

      sizechangers.removeClass('active');
      textareacontainer.html('').append(newtextarea);
      newtextarea.autogrow();

      $(this).addClass('active');

      return false;

    });


    detailbutton.click(function() {
      current.toggleClass('active');
      detailcontainer.slideToggle(transitiontime, function() {
        textarea.focus().autogrow();
      });
    });

    setTimeout(function() {
      textarea.trigger('keydown');
    }, 2500);

  });


  /**
   * Opens the fontdetails if theres only one weight
   *
   */

  var weight = $('.specfont-fontlist > ul > li').length;

  if (weight == 1) {
    $('.specfont-fontlist > ul > li:first-child').find('.detail').trigger('click');
  }




  /**
   * Basket Functionality
   *
   */
  $('.pt-basket').each(function() {

    /**
     * Basket init()
     *
     */

    /**
     * Initialise scrollbar
     * @todo - http://jscrollpane.kelvinluck.com/dynamic_content.html
     */
    $('.scrollist').jScrollPane({
      showArrows: true,
      autoReinitialise: true
    });

    $list_container = $(this).find('.pt-basket-body-fontlist ul');
    $list = $list_container.find('li');

    $amount_of_fonts = $list.length;
    $amount_of_fonts_container = $('.thereis strong').html(' font(s)').prepend($('<span class="ajax-amount"></span>')).find('.ajax-amount');
    $amount_of_fonts_container.html($amount_of_fonts);

    $basketintro = $('.pt-basket-body-intro');

    $text = new Array();
    $text['notselected'] = "You have not selected any fonts yet";
    $text['selected'] = "You have selected following font(s):";

    // Display if preview basket is empty
    $text['listfiller'] = '<p class="emptyfiller">To find your favourite Playtype fonts, choose “Browse fonts” in the menu.';
    $text['listfiller'] = $text['listfiller'] + '<br />' + "Try using one of the filters available or just do a search.</p>";

    // Empty Field
    if ($list.length < 1) {
      //console.log('true');
      $basketintro.html($text['notselected']);
      $list_container.html($text['listfiller']);
      $('.pt-basket-body-out .remove, .pt-basket-body-out .basket-info .thereis, .pt-basket-body-out .purchasefonts').hide();

    }



    function setFontAmount(amt) {
      $amount_of_fonts_container.html(amt);
    }

    function getFontAmount() {
      //return $('.pt-basket-body-fontlist ul > li').length;
      return parseFloat($amount_of_fonts_container.html());
    }

    function insertFont(font_style, font_name, font_url) {

      // Not Empty
      $list_container.find('.emptyfiller').hide();
      $basketintro.html($text['selected']);
      $('.pt-basket-body-out .remove').show();


      // Jumpt and such
      var new_font = $('<li><a href="' + font_url.replace(/add/, 'remove') + '" class="remove">Remove</a><div class="font" style="' + font_style + '">' + font_name + '</div><div class="priceinfo">Price per font ex. VAT: <span class="price">50.00 €</span></div></li>');

      $list_container.prepend(new_font);
      //updateScrollbar();
      //jScrollPane.data('jsp').reinitialise();
      setFontAmount(getFontAmount() + 1);

    }


    /**
     * Basket - Remove font from basket
     *
     */
    $list_container.find('.remove').live('click', function() {
      // basket/remove/font-id/1

      var li = $(this).parents('li');
      var remove_url = $(this).attr('href');

      if (li.attr('rel') == 'deactive') {
        return false;
      }

      li.attr('rel', 'deactive');

      $.get(remove_url, function() {

        li.fadeOut(200, function() {
          //updateScrollbar();
          setFontAmount(getFontAmount() - 1);
          li.remove();
          setTimeout(updateBasketPreviewFooter, 500);
        });

      });

      return false;
    });


    /**
     * Basket - Remove ALL font from basket
     *
     */
    $(this).find('.pt-basket-body-out .remove').click(function() {

      //$list_container.find('.remove').each(function() {
      //	$(this).click();
      //});

      var reset_url = $(this).attr('href');

      $.get(reset_url, function() {

        $list_container.find('.remove').each(function() {

          var li = $(this).parents('li');

          li.fadeOut(200, function() {

            //updateScrollbar();
            setFontAmount(getFontAmount() - 1);
            li.attr('rel', 'deactive').remove();
            setTimeout(updateBasketPreviewFooter, 500);

          });

        });

      });

      return false;
    });


    /**
     * Basket - Open/close Basket
     *
     */
    $('.pt-basket-container-footer').click(function() {

      var basket = $('.pt-basket');

      if (basket.hasClass('active')) {
        basket.stop().animate({
          'top': '-316px'
        }, 800, 'easeOutExpo', function() {
          basket.removeClass('active');
        });
      } else {
        basket.stop().animate({
          'top': 0 + 'px'
        }, 800, 'easeOutExpo', function() {
          basket.addClass('active');
        });
      }

    });

    $('.pt-background, .pt-container').click(function() {
      $('.pt-basket').stop().animate({
        'top': '-316px'
      }, 800, 'easeOutExpo', function() {
        $(this).removeClass('active');
      });
    });


    /**
     * Basket - Scrollpane for fontlist
     *
     */
    //updateScrollbar();
    //$('.pt-basket-body').hide();


    // Button Variables
    var text_added = 'Already in your basket';
    var text_notadded = 'Add to basket';

    var basket_wrapper = $('.pt-basket');
    var basket_container = $('.pt-basket-container');
    var basket_status = $('.pt-basket-container-footer');
    var basket_height = basket_container.height();


    /**
     * Buttons - Add to Basket
     *
     */
    $('.basketlink:not(.fullfamily, .freefont)').each(function() {

      // Notthing yet

    }).live("click", function() {

      var button = $(this);

      // return false if already added to basket
      if (button.attr('class').indexOf('added') > 0) {
        return false;
      }

      // Button Animation, Fade the button out.
      button.fadeOut(600, 'easeOutExpo', function() {
        button.text(text_added).addClass('added');
      });

      // AJAX Functionality
      var addUrl = $(this).attr('href');
      addUrl = addUrl + '/1';
      $.get(addUrl, function() {

        // SUCCESS!

        //$('.basket-notification').show();
        $('.basket-status').html('Your basket');

        // Put Font in Basket
        var parent = button.siblings('.fontpreview');
        var font_style = parent.attr('style');
        var font_name = parent.find('.fontpreview-title').html();

        if (parent.length < 1) {
          parent = button.parents('li').find('.font');
          var font_style = parent.attr('style');
          var font_name = parent.find('.fontpreview-title').html();
        }

        insertFont(font_style, font_name, addUrl);

        // Basket Animation
        basket_container.stop(true, true).animate({
          height: basket_height + 74 + 'px'
        }, 300, 'easeOutCubic', function() {

        }).animate({
          height: basket_height + 'px'
        }, 1200, 'easeOutBounce', function() {
          updateBasketPreviewFooter();
        });

        // Button Animation, Fade back in.
        button.delay(300).fadeIn(300);

        // Show the hiddens items again that was hidden in the empty basket 
        $('.pt-basket-body-out .remove, .pt-basket-body-out .basket-info .thereis, .pt-basket-body-out .purchasefonts').show();


      });

      return false;

    });


    /**
     * Add Full Family
     *
     */
    $('.basketlink.fullfamily').each(function() {

      $(this).click(function() {

        var button = $(this),
          link = button.attr('href');

        if (button.attr('class').indexOf('added') > 0) {
          return false;
        }

        $.get(link, function(data) {


        });

        $('.basketlink:not(.fullfamily)').each(function() {

          var addButton = $(this),
            addUrl = addButton.attr('href'),
            parent = (addButton.siblings('.fontpreview').length < 1) ? addButton.parents('li').find('.font') : addButton.siblings('.fontpreview'),
            font_style = parent.attr('style'),
            font_name = parent.find('.fontpreview-title').html();

          addButton.fadeOut(600, 'easeOutExpo', function() {
            addButton.text(text_added).addClass('added').fadeIn(600, 'easeOutExpo');
          });

          insertFont(font_style, font_name, addUrl);

        });

        $('.basket-status').html('Your basket');
        $('.pt-basket-body-out .remove, .pt-basket-body-out .basket-info .thereis, .pt-basket-body-out .purchasefonts').show();

        // Button Animation, Fade the button out.
        button.fadeOut(600, 'easeOutExpo', function() {
          button.text(text_added).addClass('added');
          button.fadeIn(500);
        });

        basket_container.stop(true, true).animate({
          height: '70px'
        }, 300, 'easeOutCubic', function() {}).animate({
          height: basket_height + 'px'
        }, 1200, 'easeOutBounce', function() {
          $(this).css('height', 'inherit');
          updateBasketPreviewFooter();
        });

        return false;

      });
    });


  });


  /**
   * Basket View Calculation
   * page-basket
   */
  $('.pt-container-cbasket').each(function() {

    $basket = $(this);

    var subtotalObject = $basket.find('.total.cal .amount'),
      totaldiscountObject = $basket.find('.discount.cal .amount strong'),
      totalamountObject = $basket.find('.sep.grey .amount'),
      totalvatObject = $basket.find('.sep.white .amount'),
      totalamountvatObject = $basket.find('.sep.darkgrey .amount strong'),
      numberOfLicenses = 0;

    function setPrice($ob, int) {
      $ob.html('EUR ' + int.toFixed(2));
    }

    function updatePrices() {
      numberOfLicenses = 0;
      $basket.find('select').each(function() {
        numberOfLicenses = numberOfLicenses + parseFloat($(this).val());
      });

      var subtotal = numberOfLicenses * 50;
      var totalamount = subtotal - parseFloat(totaldiscountObject.html());
      var totalvat = totalamount * 0.25;
      var totalamountvat = totalamount + totalvat;

      setPrice(subtotalObject, subtotal);
      setPrice(totalamountObject, totalamount);
      setPrice(totalvatObject, totalvat);
      totalamountvatObject.html(totalamountvat.toFixed(2));

/*
			console.log('subtotal = '+subtotal.toFixed);
			console.log('discount = '+totaldiscountObject.html());
			console.log('totalVat = '+totalvat);
			console.log('totalAmoutVat = '+totalamountvat);
			*/

    }

    $('#license-form select').change(function() {
      updatePrices();

      // Update license count
      var license_count = $(this).val(),
        font_id = $(this).attr('name'),
        cookie_url = null;

      font_id = font_id.replace('-licenses', '');
      cookie_url = base_path + 'set-license/' + font_id + '/' + license_count;

      $.get(cookie_url, function(data) {
        //console.log(data);
      });

    });


  });


  /**
   * Basket Page - Create License
   */
  $('#btn-create-license').each(function() {

    var container = $(this).parents('.container');
    var form = container.find('.form');

    form.hide();

    $(this).click(function() {
      form.stop().slideToggle();
      return false;
    })


  });


  /**
   * Font List - Infinite Scroll
   *
   */
  $('.view-Font-browser, .view-Font-filter').each(function() {

    $view = $(this);
    $pager_items = $('.pager > li');

    $navigation = $view.children('.item-list').html();
    $view.children('.view-content').before('<div class="item-list copy">' + $navigation + '</div>');

    if ($pager_items.length < 2) {
      $view.children('.item-list').html('');
    }

  });


  /**
   * Search Field - placeholder functionality
   */
  $('#edit-search-block-form-1').each(function() {
    var input = $(this);
    var placeholder = $(this).attr('value');
    $(this).focus(function() {
      if (input.val() == placeholder) {
        input.val('').removeClass('placeholder');
      }
    }).blur(function() {
      if (input.val() == '' || input.val() == placeholder) {
        input.addClass('placeholder').val(placeholder);
      }
    }).blur();
  });


  /**
   * News - Fix images
   */
  $('.news_new').each(function() {
    $(this).find('img').each(function() {
      $(this).load(function() {
        var width = $(this).width();

        // Check if width is higher than 500, then add negmargin
        if (width > 500) {
          var negmargin = (width - 500) / 2;
          $(this).css('margin-left', '-' + negmargin + 'px').css('display', 'block');
        }
      });
      if (this.complete) $(this).trigger("load");
    });
  });


  /**
   * About Frontpage
   *
   */
  $('a#typographers-glossary, a#licensing').hover(function() {
    var hand = $('<span class="hand-left"></span>');
    $(this).append(hand);
  }, function() {
    $('.hand-left').remove();
  });

  $('a#type-designers').hover(function() {
    var hand = $('<span class="hand-right"></span>');
    $(this).append(hand);
  }, function() {
    $('.hand-right').remove();
  });


  /**
   * FAQ Page
   *
   */
  $('.view-FAQ').each(function() {

    //Dirty dirty code
    var title = $(this).find('.view-header h1');
    title.html(title.html().replace(/^(\w+)/, '<strong class="first-word">$1</strong>'));

    /**
     * Show and tell
     *
     */
    $('.faq-header').click(function() {

      // Closes any open elements
      $('.faq-header.active').removeClass('active').next('.faq-content').slideToggle(200);

      // Opens the selected
      $(this).siblings('.faq-content').stop(true, true).slideToggle(200);
      $(this).addClass('active');

    });



  });


  /**
   *
   * Advert Hovering
   *
   */
  $('.footer-advert').each(function() {

    var advert = $('.footer-advert a img.advert');

    $('.footer-advert a').mouseenter(function() {
      advert.fadeOut(300);
    }).mouseleave(function() {
      advert.fadeIn(300);
    });
  });

  // Update basket footer info
  updateBasketPreviewFooter();

  // Initate font labels hovering
  labelToolTip();

  // Arrange font into groups and columns
  modifyFontFamilyList();

  // Report table sorting
  initiateTableSorter();

  // Make whole font-family item clickable
  $('.font-family').live('click', function() {
    var link = $(this).children('a').attr('href');
    window.location = link;
  });

  modifyFooterMenu();

  getLatestTweet();

});


/**
 * Update basket preview footer (font count and item price)
 */

function updateBasketPreviewFooter() {
  var count = $('.pt-basket-body-fontlist ul > li > div.font').length,
    fontPrice;

  switch (count) {
  case 1:
  case 2:
    fontPrice = 50;
    break;
  case 3:
  case 4:
  case 5:
    fontPrice = 45;
    break;
  case 6:
  case 7:
  case 8:
  case 9:
  case 10:
    fontPrice = 42.5;
    break;
  default:
    fontPrice = 40;
  }

  if (count > 0) {
    $('.basket-notification').html('You have added <strong>' + count + ' font(s)</strong> at <strong>&euro;' + fontPrice + '</strong>');
  } else {
    $('.basket-notification').html('');
  }

}

/**
 * Show tooltip while hovering the labes of fonts
 *
 */

function labelToolTip() {
  $('.label-list > ul > li').mouseenter(function() {
    $(this).children('.tooltip').stop(true, true).fadeIn(200);
  }).mouseleave(function() {
    $(this).children('.tooltip').stop(true, true).fadeOut(200);
  });
}

/**
 * Rearrange markup for the font family list
 * Creates letter groupings
 */

function modifyFontFamilyList() {

  var i = 0,
    // Font family counter
    j = 1,
    // Font group counter
    fontFamilyList = $('.font-family-list'),
    fontFamilyWrapper = $('<div id="font-family-list">'),
    families = $('.font-family'),
    familyCount = families.length,
    previousLetter = '',
    typeWrapper = $('<ul class="family-group group-#">'),
    // Default font group
    column1 = $('<div id="column-1">'),
    column2 = $('<div id="column-2">'),
    column3 = $('<div id="column-3">'),
    column4 = $('<div id="column-4">'),
    column5 = $('<div id="column-5">');

  $('<li class="group-title">#</li>').appendTo(typeWrapper);

  for (i; i < familyCount; i++) {
    var family = $(families[i]),
      name = family.children('a').html(),
      firstLetter = name.charAt(0);

    // Start a new group
    if (firstLetter != previousLetter && isNaN(firstLetter)) {
      // Add previous group into a column
      if (j < 5) {
        typeWrapper.appendTo(column1);
      } else if (j >= 5 && j < 10) {
        typeWrapper.appendTo(column2);
      } else if (j >= 10 && j < 15) {
        typeWrapper.appendTo(column3);
      } else if (j >= 15 && j < 20) {
        typeWrapper.appendTo(column4);
      } else {
        typeWrapper.appendTo(column5);
      }
      j++;

      // Reset group
      typeWrapper = $('<ul class="family-group group-' + firstLetter + '">');
      $('<li class="group-title">' + firstLetter + '</li>').appendTo(typeWrapper);
    }

    family.appendTo(typeWrapper);
    previousLetter = firstLetter;
  }

  // Add last group to the 5th column
  typeWrapper.appendTo(column5);

  // Insert the new wrapperd to DOM
  fontFamilyList.after(fontFamilyWrapper);
  fontFamilyList.remove();

  // Insert new columns into new wrapper
  column1.appendTo(fontFamilyWrapper);
  column2.appendTo(fontFamilyWrapper);
  column3.appendTo(fontFamilyWrapper);
  column4.appendTo(fontFamilyWrapper);
  column5.appendTo(fontFamilyWrapper);
}
/**
 *
 */

function initiateTableSorter() {
  $('#sales-report table').tablesorter().tablesorterPager({
    container: $('#sales-report-pager')
  });;
}

function modifyFooterMenu() {
  var footerContent = $('#pt-footer-content'),
    menu = $('#pt-footer-content > .menu > li'),
    aboutType = menu.eq(0).children('ul'),
    aboutFoundry = menu.eq(1).children('ul'),
    aboutInformation = aboutType.children('li:first').children('ul'),
    footerNavigation = $('<div id="footer-navigation"></div>');

  aboutFoundry.addClass('even');

  // Add About in front of each link
  aboutType.find('a').each(function() {
    $(this).prepend('<span>About</span>');
  });
  aboutFoundry.find('a').each(function() {
    $(this).prepend('<span>About</span>');
  });

  aboutType.children('li:first').remove();
  $('#pt-footer-content > .menu').remove();

  footerNavigation.append(aboutType);
  footerNavigation.append(aboutFoundry);
  footerNavigation.append(aboutInformation);
  footerContent.append(footerNavigation);
}

function getLatestTweet() {
  var footerContent = $('#pt-footer-content'),
    //urlAt = 'http://search.twitter.com/search.json?callback=?&rpp=1&q=@playtype',
    urlFrom = 'https://twitter.com/statuses/user_timeline/playtype.json?callback=?&count=1',
    atPlaytype, fromPlaytype, latestTweet = $('<div id="latest-tweet"></div>');

  //

  $.getJSON(urlFrom, function(data) {

    var tweet = data[0].text;
    // Create links to users
    tweet = tweet.replace(/(^|\s|-)+@(\w+)/g, function(str) {
      //str = str.replace(/^\s+|\s+$/g,'');
      str = str.replace(/\s+/g, '');
      str = str.replace(/@/g, '');
      return '&nbsp;<a href="//twitter.com/' + str + '" target="_blank">@' + str + '</a>&nbsp;';
    });
    // Create links for hash tags
    tweet = tweet.replace(/(^|\s|-)+#(\w+)/g, function(str) {
      url = str.replace(/^\s+|\s+$/g, '');
      url = url.replace(/#/g, '');
      return '&nbsp<a href="//twitter.com/search?q=%23' + url + '" target="_blank">' + str + '</a>';
    });

    //tweet = tweet.linkify();

    latestTweet.html('“' + tweet + '” <span>' + relative_time(data[0].created_at) + '</span>');
    footerContent.append(latestTweet);
  });
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  var r = '';
  if (delta < 60) {
    r = 'a minute ago';
  } else if (delta < 120) {
    r = 'couple of minutes ago';
  } else if (delta < (45 * 60)) {
    r = (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if (delta < (90 * 60)) {
    r = 'an hour ago';
  } else if (delta < (24 * 60 * 60)) {
    r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if (delta < (48 * 60 * 60)) {
    r = '1 day ago';
  } else {
    r = (parseInt(delta / 86400)).toString() + ' days ago';
  }

  return r;
}

String.prototype.linkify = function() {
  return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
    m = m.replace(/ /g, "");
    return m.link(m);
  });
};
/**
 * Playtype.com
 * 
 * Functions, plugin calls and animation
 * of the playtype.com site.
 * 
 */

	
$(function() {
	
	
	/*
	 * The file's functions are devided into code blocks
	 * only called if the relevant element is present in
	 * the current page. 
	 * // JCK
	 * 
	 */

	
	/**
	 * Fade in images when they are loaded.
	 * 
	 */
	$('img').each(function() {
		
		$(this).hide().load(function() {
			
			$(this).fadeIn(800);
			
		});
		
		if(this.complete) $(this).trigger("load");
		
	});
	
	/**
	 * Top Menu Quick Fix
	 * 
	 */
	$('.pt-container-header-navigation').each(function() {
		
		var ul = $(this).find('ul');
		var lis = ul.find('li');
		var takes = Math.floor(lis.length/3);
		var html = $('<ul class="right"></ul>');
		for(i=1;i<=takes;i++)
		{
			html.append(lis.eq(lis.length-i));
		}
		$(this).append(html);
		
		lis.eq(0).addClass('big browse-fonts');
		lis.eq(1).addClass('big the-store');
		
	});
	
	
	/**
	 * Frontpage Slideshow
	 * 
	 */
	var frontpageSlideshow = $('.pt-fpss');
	var frontpageSlideshow = $('.pt-fpss, .view-front');
	frontpageSlideshow.each(function() {
			
		// Variables
		var slidemargin = 20; // px
		var listcontainer = frontpageSlideshow.find('.pt-fpss-list, .view-content');
		var listelements = listcontainer.find('li');
		var listimages  = new Array();
		var activeIndex = 0;
		

		var temp = 0;
		listelements.find('.fpss-cont').each(function() {
			
			var listslides = listimages;
			var index = listslides.length;
			listslides[index] = temp;
			
			temp = temp + $(this).width();
			temp = temp + slidemargin;
			
		});


		var max_left = temp-slidemargin-1020;
		
		/*
		 * Slideshow Controls
		 */
		$leftArrow = $('<li class="left"><a href="#">left</a></li>');
		$rightArrow = $('<li class="right"><a href="#">right</a></li>');
		
		/*
		 * Slide to index in the list of images
		 * 
		 */
		function slideTo(index) 
		{
			// Find new position (negative left)
			var move = -1*listimages[index];

			// Remove Hands
			if(index == 0)
			{
				$leftArrow.addClass('inactive');
			}
			else if(index+1 == listelements.length)
			{
				$rightArrow.addClass('inactive');
			}
			else
			{
				$leftArrow.removeClass('inactive');
				$rightArrow.removeClass('inactive');
			}
			
			if(move < -max_left)
			{
				move = -max_left;
				$rightArrow.addClass('inactive');
			}
			
			// Move the slideshow
			listcontainer.stop().animate({"left": ''+move+'px'}, 1200, 'easeInOutExpo');
			
		}
		
		// Design
		listcontainer.css({'width':'20000px'}); // Make all the boxes fit.
		$(window).resize(function() {listcontainer.css({'margin-left':$('.pt-container').offset()['left']});}); // Put the slideshow in grid with design
		
		// Go left or right?
		function arrowLeft() 
		{
			if (!(activeIndex == 0)) 
			{
				slideTo(activeIndex-1);
				activeIndex--;
			}
		}
		
		function arrowRight()
		{
			if(!(activeIndex+1 == listelements.length)) 
			{
				slideTo(activeIndex+1);
				activeIndex++;
			} 
		}
		
		$leftArrow.click(function() {
			arrowLeft();
			return false;
		});
		
		$rightArrow.click(function() {
			arrowRight();
			return false;
		});
		
		// Bind slideTo to arrow left and right
		$(document).keydown(function(e){
			
		    if (e.keyCode == 37) // Left
		    { 
		       arrowLeft();
		       return false;
		    } 
		    else if (e.keyCode == 39) // Right 
		    {
		    	arrowRight();
		    	return false;
		    }
		    
		});
		
		$controls = $('<ul></ul>');
		$controls.append($leftArrow);
		$controls.append($rightArrow);
		$controls = $('<div class="pt-fpss-controls"></div>').prepend($controls);
		
		frontpageSlideshow.prepend($controls);
		
		/*
		 * FadeIn the slideshow
		 */
		slideTo(++activeIndex);
		frontpageSlideshow.fadeIn('slow');

	});
	
	/**
	 * 
	 * Show / Hide the hands on the frontpage slider
	 * 
	 */
	$('.pt-fpss-controls').each(function() {
		
		var hands = $('.pt-fpss-controls ul li');

		$('.view-front').mouseenter(function() {
        hands.fadeIn(300, 'easeInOutCubic');				
			})
			.mouseleave(function() {
        hands.fadeOut(300, 'easeInOutCubic');				
		  });		
	});
	
		
	/**
	 * Scale Background
	 * 
	 */
	$('.pt-background').scaleBgImage();
	
	
	/**
	 * init window functions
	 * 
	 */
	$(window).trigger('resize');
	
	
	/**
	 * 
	 * Drop Down Menu (font-filters, about, search, etc)
	 * 
	 */
	$('.pt-container-navigation .content > ul > li').each(function() {
		
		var wait = 200;
		var timer;
		
		var dad = $(this);					// First level LI
		var dad_ul = $(this).find('> ul');	// First UL in dad
		
		
		dad
			.mouseenter(function() {
				
				if($(this).hasClass('active')) {return;}
				clearTimeout(timer);
				
				timer = setTimeout(function() {
					
					dad_ul
						.addClass('active')
						.stop(true,true).slideDown();	
					
				},wait);
				
			})
			.mouseleave(function() {
				
				clearTimeout(timer);
				
				dad_ul
					.removeClass('active')
					.stop(true,true)
					.delay(400).slideUp('easeInOutCubic');
			});
		
		
		
	});
	
	
	/**
	 * Font Style Navigation - Navigation
	 * 
	 */
	var secmenu = '.pt-container-navigation ul ul';
	$('.pt-container-navigation .fontstyles ,'+secmenu).each(function() {
		
		var linkscontainer = $(this);
		var links = $(this).children('li');
		var links_activearea = '.styles, ul';
		var timer;
		var currentslide;
		
		links.mouseenter(function() {	
			
			if($(this).hasClass('active')) {return;}	
			
			currentSlide = $(this);	
			
			clearTimeout(timer);
			
			timer = setTimeout(function() {			
				linkscontainer.find('.active').removeClass('active').find(links_activearea).stop(true,true).slideUp();
				currentSlide.addClass('active');
				currentSlide.find(links_activearea).stop(true,true).slideDown();			
			},200);
			
		});
		
		links.mouseleave(function() {
			clearTimeout(timer);
		});
		
		linkscontainer.mouseenter(function() {

		});
		
		linkscontainer.mouseleave(function() {

			clearTimeout(timer);
			$(this).find('.active').removeClass('active').find(links_activearea).stop(true,true).slideUp();
		});	
	});
	
	
	/**
	 * Font Specification - Font Weights
	 * 
	 */
	$('.specfont-weightsandstyles').each(function() {
		
		var content = $(this).find('ul ul');
		
		$(this).find('ul a').eq(0).mouseenter(function() {
			content.stop(true,true).slideDown(200);
		});
		
		$(this).mouseleave(function() {
			content.stop(true,true).slideUp(200);
		});
		
	});
	
	
	/**
	 * Font Specification - IntroSlider
	 * 
	 */
	var specificfontspec = $('.fontspecifications-opener');
	specificfontspec.each(function() {
		var container = $('.specfont-headinfo-specs');
		$(this).click(function() {
			container.slideToggle(300, 'easeInOutCubic');
			$(this).toggleClass('active');
			return false;
		});
	});
	
	
	/**
	 * Open/close font details
	 * 
	 */
	$('.specfont-fontlist ul li').each(function() {
		
		var current = $(this);
		var detailbutton = current.find('.font');
		var detailcontainer = current.find('.fontdetail');
		var textarea = current.find('.editable textarea');
		var textareacontainer = current.find('.editable .textarea');
		var sizechangers = current.find('.editable .font-size a');
		var transitiontime = 500; // millisecond, smooth transition time		
		
		sizechangers.eq(0).addClass('active');
		
		sizechangers.click(function () {
			
			var newclass = $(this).attr('class');
			var currenttext = textarea.val();
			var newtextarea = $('<textarea></textarea>').attr('class', newclass).attr('spellcheck', 'false').val(currenttext);

			sizechangers.removeClass('active');
			textareacontainer.html('').append(newtextarea);			
			newtextarea.autogrow();
			
			$(this).addClass('active');
						
			return false;
			
		});

		
		detailbutton.click(function() {
			current.toggleClass('active');
			detailcontainer.slideToggle(transitiontime,function() {				
				textarea.focus().autogrow();				
			});
		});
		
		setTimeout(function(){textarea.trigger('keydown');}, 2500);

	});
	
	
	/**
	 * Opens the fontdetails if theres only one weight
	 * 
	 */
	 
  var weight = 	$('.specfont-fontlist > ul > li').length;
	
	if ( weight == 1 ) {
	 $('.specfont-fontlist > ul > li:first-child').find('.detail').trigger('click');
	 }	

	


	/**
	 * Basket Functionality
	 * 
	 */
	$('.pt-basket').each(function() {
		
		/**
		 * Basket init()
		 * 
		 */
		
		/**
		 * Initialise scrollbar 
		 * @todo - http://jscrollpane.kelvinluck.com/dynamic_content.html
		 */
		$('.scrollist').jScrollPane({showArrows: true, autoReinitialise: true});
		 
		$list_container = $(this).find('.pt-basket-body-fontlist ul');
		$list = $list_container.find('li');
		
		$amount_of_fonts = $list.length;
		$amount_of_fonts_container = $('.thereis strong').html(' font(s)').prepend($('<span class="ajax-amount"></span>')).find('.ajax-amount');
		$amount_of_fonts_container.html($amount_of_fonts);
		
		$basketintro = $('.pt-basket-body-intro');
		
		$text = new Array();
		$text['notselected'] = "You have not selected any fonts yet";
		$text['selected'] = "You have selected following font(s):";
		
		// Display if preview basket is empty
		$text['listfiller'] = '<p class="emptyfiller">To find your favourite Playtype fonts, choose “Browse fonts” in the menu.';
		$text['listfiller'] = $text['listfiller'] + '<br />' +  "Try using one of the filters available or just do a search.</p>";
		
		// Empty Field
		if($list.length < 1)
		{
			//console.log('true');
			$basketintro.html($text['notselected']);
			$list_container.html($text['listfiller']);
			$('.pt-basket-body-out .remove, .pt-basket-body-out .basket-info .thereis, .pt-basket-body-out .purchasefonts').hide();
			
		}

		
		
		function setFontAmount(amt) {
			$amount_of_fonts_container.html(amt);
		}
		
		function getFontAmount() {
			//return $('.pt-basket-body-fontlist ul > li').length;
			return parseFloat($amount_of_fonts_container.html());
		}
		
		function insertFont(font_style,font_name,font_url) {
			
			// Not Empty
			$list_container.find('.emptyfiller').hide();
			$basketintro.html($text['selected']);
			$('.pt-basket-body-out .remove').show();
			
			
			// Jumpt and such
			var new_font = $('<li><a href="'+font_url.replace(/add/,'remove')+'" class="remove">Remove</a><div class="font" style="'+font_style+'">'+font_name+'</div><div class="priceinfo">Price per font ex. VAT: <span class="price">50.00 €</span></div></li>');
			
			$list_container.prepend(new_font);
			//updateScrollbar();
			//jScrollPane.data('jsp').reinitialise();
			setFontAmount(getFontAmount()+1);
   			
		}
			
		
		/**
		 * Basket - Remove font from basket
		 * 
		 */
		$list_container.find('.remove').live('click', function() {
			// basket/remove/font-id/1
			   
			var li = $(this).parents('li');
			var remove_url = $(this).attr('href');
			
			if(li.attr('rel') == 'deactive') {return false;}

			li.attr('rel','deactive');
			
			$.get(remove_url,function() {
								
				li.fadeOut(200, function() {					
					//updateScrollbar();
					setFontAmount(getFontAmount()-1);
					li.remove();
     			setTimeout(updateBasketPreviewFooter, 500);					
				});
				
			});			
			
			return false;
		});
		
		
		/**
		 * Basket - Remove ALL font from basket
		 * 
		 */
		$(this).find('.pt-basket-body-out .remove').click(function() {
			
			//$list_container.find('.remove').each(function() {
			//	$(this).click();
			//});
			
			var reset_url = $(this).attr('href');
			
			$.get(reset_url,function() {
				
				$list_container.find('.remove').each(function() {
					
					var li = $(this).parents('li');
     
     li.fadeOut(200, function() {
						
						//updateScrollbar();
						setFontAmount(getFontAmount()-1);
						li.attr('rel','deactive').remove();
						setTimeout(updateBasketPreviewFooter, 500);
      
					});
					
				});
				
			});
			
			return false;
		});
		
		
		/**
		 * Basket - Open/close Basket
		 * 
		 */
		$('.pt-basket-container-footer').click(function() {
			
			var basket = $('.pt-basket');			
			
			if(basket.hasClass('active')) {
				basket.stop().animate({'top': '-316px'}, 800, 'easeOutExpo', function() { basket.removeClass('active'); });
			} else {
				basket.stop().animate({'top': 0+'px'}, 800, 'easeOutExpo', function() { basket.addClass('active'); });
			}
			
		});
		
		$('.pt-background, .pt-container').click(function() {
			$('.pt-basket').stop().animate({'top': '-316px'}, 800, 'easeOutExpo', function() { $(this).removeClass('active'); });
		});
		
		
		/**
		 * Basket - Scrollpane for fontlist
		 * 
		 */
		//updateScrollbar();
		//$('.pt-basket-body').hide();

		
		// Button Variables
		var text_added = 'Already in your basket';
		var text_notadded = 'Add to basket';
		
		var basket_wrapper = $('.pt-basket');
		var basket_container = $('.pt-basket-container');
		var basket_status = $('.pt-basket-container-footer');
		var basket_height = basket_container.height();
		
		
		/**
		 * Buttons - Add to Basket
		 * 
		 */
		$('.basketlink:not(.fullfamily, .freefont)').each(function() {
			
			// Notthing yet
			
		}).live("click", function() {
			
			var button = $(this);
			
			// return false if already added to basket
			if(button.attr('class').indexOf('added') > 0 ) {return false;}
			
			// Button Animation, Fade the button out.
			button.fadeOut(600, 'easeOutExpo', function() {
				button
				.text(text_added)
				.addClass('added');
			});
			
			// AJAX Functionality
			var addUrl = $(this).attr('href');
			addUrl = addUrl + '/1';
			$.get(addUrl,function() {
				
				// SUCCESS!
				
				//$('.basket-notification').show();
				$('.basket-status').html('Your basket');
				
				// Put Font in Basket
				var parent = button.siblings('.fontpreview');
				var font_style = parent.attr('style');
				var font_name = parent.find('.fontpreview-title').html();
				
				if(parent.length < 1)
				{
					parent = button.parents('li').find('.font');
					var font_style = parent.attr('style');
					var font_name = parent.find('.fontpreview-title').html();
				}

				insertFont(font_style,font_name,addUrl);
				
				// Basket Animation
				basket_container.stop(true,true).animate({height: basket_height+74+'px'}, 300, 'easeOutCubic', function(){
				
				}).animate({height: basket_height+'px'}, 1200, 'easeOutBounce', function(){
			    updateBasketPreviewFooter();
				});

				// Button Animation, Fade back in.
				button.delay(300).fadeIn(300);
				
        // Show the hiddens items again that was hidden in the empty basket 
				$('.pt-basket-body-out .remove, .pt-basket-body-out .basket-info .thereis, .pt-basket-body-out .purchasefonts').show();

				
			});
   			
			return false;
		
		});
		
		
		/**
		 * Add Full Family
		 * 
		 */
		$('.basketlink.fullfamily').each(function() {
			
			$(this).click(function() {
				
				var button = $(this),
				    link = button.attr('href');

				if(button.attr('class').indexOf('added') > 0 ) {return false;}
				
				$.get(link, function(data) {
				  
				  				  
				});
				
				$('.basketlink:not(.fullfamily)').each(function() {					
          
          var addButton = $(this),
              addUrl = addButton.attr('href'),
				      parent = (addButton.siblings('.fontpreview').length < 1) ? addButton.parents('li').find('.font') : addButton.siblings('.fontpreview'),
				      font_style = parent.attr('style'),
				      font_name = parent.find('.fontpreview-title').html();
				      
				  addButton.fadeOut(600, 'easeOutExpo', function() {
    		    addButton.text(text_added).addClass('added').fadeIn(600, 'easeOutExpo');
    			});

				  insertFont(font_style,font_name,addUrl);

				});
				
  			$('.basket-status').html('Your basket');
  			$('.pt-basket-body-out .remove, .pt-basket-body-out .basket-info .thereis, .pt-basket-body-out .purchasefonts').show();
				
				// Button Animation, Fade the button out.
				button.fadeOut(600, 'easeOutExpo', function() {
					button
					.text(text_added)
					.addClass('added');
					button.fadeIn(500);
				});
				
				basket_container.stop(true,true)
				  .animate({height: '70px'}, 300, 'easeOutCubic', function(){})
				  .animate({height: basket_height+'px'}, 1200, 'easeOutBounce', function(){
					  $(this).css('height','inherit');
       updateBasketPreviewFooter();
				  });

				return false;
				
			});
		});
		
		
	});
	
	
	/**
	 * Basket View Calculation
	 * page-basket
	 */
	$('.pt-container-cbasket').each(function() {
		
		$basket = $(this);
		
		var subtotalObject 			= $basket.find('.total.cal .amount'),
			totaldiscountObject		= $basket.find('.discount.cal .amount strong'),
			totalamountObject		= $basket.find('.sep.grey .amount'),
			totalvatObject			= $basket.find('.sep.white .amount'),
			totalamountvatObject  	= $basket.find('.sep.darkgrey .amount strong'),
			numberOfLicenses = 0;
		
		function setPrice($ob,int)
		{
			$ob.html('EUR '+int.toFixed(2));
		}
		
		function updatePrices() 
		{
			numberOfLicenses = 0;
			$basket.find('select').each(function() {
				numberOfLicenses = numberOfLicenses + parseFloat($(this).val());
			});
			
			var subtotal = numberOfLicenses * 50;
			var totalamount = subtotal - parseFloat(totaldiscountObject.html());
			var totalvat = totalamount*0.25;
			var totalamountvat = totalamount + totalvat;
			
			setPrice(subtotalObject,subtotal);
			setPrice(totalamountObject,totalamount);
			setPrice(totalvatObject,totalvat);
			totalamountvatObject.html(totalamountvat.toFixed(2));
			
			/*
			console.log('subtotal = '+subtotal.toFixed);
			console.log('discount = '+totaldiscountObject.html());
			console.log('totalVat = '+totalvat);
			console.log('totalAmoutVat = '+totalamountvat);
			*/			

		}
		
		$('#license-form select').change(function() {
			updatePrices();			
			
			// Update license count
			var license_count = $(this).val(),
			    font_id = $(this).attr('name'),
			    cookie_url = null;
			    		  
		  font_id = font_id.replace('-licenses', '');      
      cookie_url = base_path + 'set-license/' + font_id + '/' + license_count;    
      
      $.get(cookie_url, function(data) {
        //console.log(data);
      });      					
						
		});
		
		
	});
	
	
	/**
	 * Basket Page - Create License
	 */
	$('#btn-create-license').each(function() {
		
		var container = $(this).parents('.container');
		var form = container.find('.form');
		
		form
			.hide();
		
		$(this).click(function() {
			form.stop().slideToggle();
			return false;
		})
		
		
	});
	
	
	/**
	 * Font List - Infinite Scroll
	 * 
	 */
	$('.view-Font-browser, .view-Font-filter').each(function() {
	
    $view = $(this);
    $pager_items = $('.pager > li');	
	 
    $navigation = $view.children('.item-list').html();
    $view.children('.view-content').before('<div class="item-list copy">' + $navigation + '</div>');
	
	  if($pager_items.length < 2) {
      $view.children('.item-list').html('');
	  }
	 		
	});
	
	
	/**
	 * Search Field - placeholder functionality
	 */
	$('#edit-search-block-form-1').each(function() {
		var input = $(this);
		var placeholder = $(this).attr('value');
		$(this)
			.focus(function() {
				if(input.val() == placeholder)
				{
					input
						.val('')
						.removeClass('placeholder');
				}
			})
			.blur(function() {
				if(input.val() == '' || input.val() == placeholder)
				{
					input
						.addClass('placeholder')
						.val(placeholder);
				}
			})
			.blur();
	});
		
	
	/**
	 * News - Fix images
	 */
	$('.news_new').each(function() {
		$(this).find('img').each(function() {
			$(this).load(function() {
				var width = $(this).width();

        // Check if width is higher than 500, then add negmargin
        if (width > 500) { 
  				var negmargin = (width-500)/2;
  				$(this)
  					.css('margin-left','-'+negmargin+'px')
  					.css('display','block');
  				}
			});
			if(this.complete) $(this).trigger("load");
		});
	});
	
	
	/**
	 * About Frontpage
	 * 
	 */
  $('a#typographers-glossary, a#licensing').hover(function () {
      var hand = $('<span class="hand-left"></span>');
      $(this).append(hand);
    }, function () {
      $('.hand-left').remove();
    }
  );

  $('a#type-designers').hover(function () {
      var hand = $('<span class="hand-right"></span>');
      $(this).append(hand);
    }, function () {
      $('.hand-right').remove();
    }
  );


	/**
	 * FAQ Page
	 * 
	 */
	$('.view-FAQ').each(function() {
		
		//Dirty dirty code
		var title = $(this).find('.view-header h1');
		title.html(title.html().replace(/^(\w+)/,'<strong class="first-word">$1</strong>'));
		
		/**
		 * Show and tell
		 * 
		 */
		$('.faq-header').click(function() {

			// Closes any open elements
			$('.faq-header.active').removeClass('active').next('.faq-content').slideToggle(200);
			
			// Opens the selected
			$(this).siblings('.faq-content').stop(true,true).slideToggle(200);
			$(this).addClass('active');
  		
		});
		
		
		
	});

	
	/**
	 * 
	 * Advert Hovering
	 * 
	 */
	$('.footer-advert').each(function() {
		
		var advert = $('.footer-advert a img.advert');

		$('.footer-advert a').mouseenter(function() {
        advert.fadeOut(300);				
			})
			.mouseleave(function() {
        advert.fadeIn(300);				
		  });		
	});
		
 // Update basket footer info
 updateBasketPreviewFooter();
 
 // Initate font labels hovering
 labelToolTip();
 
 // Arrange font into groups and columns
 modifyFontFamilyList();
 
 // Report table sorting
 initiateTableSorter();

 // Make whole font-family item clickable
 $('.font-family').live('click', function() {
   var link = $(this).children('a').attr('href');
   window.location = link;
 });

 modifyFooterMenu();
 
 getLatestTweet();

});


/**
 * Update basket preview footer (font count and item price)
 */
function updateBasketPreviewFooter() {
  var count = $('.pt-basket-body-fontlist ul > li > div.font').length,
      fontPrice;
  
  switch(count) {
    case 1:
    case 2:
      fontPrice = 50;
      break;
    case 3:
    case 4:
    case 5:
      fontPrice = 45;
      break;
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
      fontPrice = 42.5;
      break;
    default:
      fontPrice = 40;    
  }
  
  if(count > 0) {
    $('.basket-notification').html('You have added <strong>'+ count +' font(s)</strong> at <strong>&euro;'+ fontPrice +'</strong>');
  } else {
    $('.basket-notification').html('');    
  }
  
}

/**
 * Show tooltip while hovering the labes of fonts
 * 
 */
function labelToolTip() {
  $('.label-list > ul > li').mouseenter(function() {
    $(this).children('.tooltip').stop(true, true).fadeIn(200);
  }).mouseleave(function() {
    $(this).children('.tooltip').stop(true, true).fadeOut(200);    
  });  
}

/**
 * Rearrange markup for the font family list
 * Creates letter groupings
 */
function modifyFontFamilyList() {
    
  var i = 0, // Font family counter
      j = 1, // Font group counter
      fontFamilyList = $('.font-family-list'),
      fontFamilyWrapper = $('<div id="font-family-list">'),
      families = $('.font-family'),
      familyCount = families.length,
      previousLetter = '',
      typeWrapper = $('<ul class="family-group group-#">'), // Default font group
      column1 = $('<div id="column-1">'),
      column2 = $('<div id="column-2">'), 
      column3 = $('<div id="column-3">'), 
      column4 = $('<div id="column-4">'), 
      column5 = $('<div id="column-5">'); 
  
  $('<li class="group-title">#</li>').appendTo(typeWrapper);  
  
  for(i; i< familyCount; i++) {
    var family = $(families[i]),
        name = family.children('a').html(),
        firstLetter = name.charAt(0);
    
    // Start a new group
    if(firstLetter != previousLetter && isNaN(firstLetter)) {
      // Add previous group into a column
      if(j < 5) {typeWrapper.appendTo(column1);} 
      else if(j >= 5 && j < 10) {typeWrapper.appendTo(column2);} 
      else if(j >= 10 && j < 15) {typeWrapper.appendTo(column3);} 
      else if(j >= 15 && j < 20) {typeWrapper.appendTo(column4);} 
      else {typeWrapper.appendTo(column5);}      
      j++;
      
      // Reset group
      typeWrapper = $('<ul class="family-group group-'+ firstLetter +'">');
      $('<li class="group-title">'+ firstLetter +'</li>').appendTo(typeWrapper);
    }
    
    family.appendTo(typeWrapper);    
    previousLetter = firstLetter;    
  }
  
  // Add last group to the 5th column
  typeWrapper.appendTo(column5); 
  
  // Insert the new wrapperd to DOM
  fontFamilyList.after(fontFamilyWrapper);
  fontFamilyList.remove();
  
  // Insert new columns into new wrapper
  column1.appendTo(fontFamilyWrapper);
  column2.appendTo(fontFamilyWrapper);
  column3.appendTo(fontFamilyWrapper);
  column4.appendTo(fontFamilyWrapper);
  column5.appendTo(fontFamilyWrapper);  
}
/**
 *
 */
function initiateTableSorter() {
	$('#sales-report table').tablesorter().tablesorterPager({container: $('#sales-report-pager')}); ;
}

function modifyFooterMenu() {
	var footerContent = $('#pt-footer-content'),
			menu = $('#pt-footer-content > .menu > li'),	
			aboutType = menu.eq(0).children('ul'),
			aboutFoundry = menu.eq(1).children('ul'),
			aboutInformation = aboutType.children('li:first').children('ul'),
			footerNavigation = $('<div id="footer-navigation"></div>');
	
	aboutFoundry.addClass('even');
		
	// Add About in front of each link
	aboutType.find('a').each(function() {	$(this).prepend('<span>About</span>'); });
	aboutFoundry.find('a').each(function() {	$(this).prepend('<span>About</span>'); });
	
	aboutType.children('li:first').remove();
	$('#pt-footer-content > .menu').remove();
	
	footerNavigation.append(aboutType);
	footerNavigation.append(aboutFoundry);
	footerNavigation.append(aboutInformation);	
	footerContent.append(footerNavigation);
}

function getLatestTweet() {
	var footerContent = $('#pt-footer-content'),
			//urlAt = 'http://search.twitter.com/search.json?callback=?&rpp=1&q=@playtype',
			urlFrom = 'https://twitter.com/statuses/user_timeline/playtype.json?callback=?&count=1',
			atPlaytype, fromPlaytype,
			latestTweet = $('<div id="latest-tweet"></div>');
			
	//
			
	$.getJSON(urlFrom, function(data) {
		
		var tweet = data[0].text;
		// Create links to users
		tweet = tweet.replace(/(^|\s|-)+@(\w+)/g, function(str) {
			//str = str.replace(/^\s+|\s+$/g,'');
			str = str.replace(/\s+/g,'');
			str = str.replace(/@/g, '');
    	return '&nbsp;<a href="//twitter.com/'+ str +'" target="_blank">@' + str + '</a>&nbsp;';
		});
		// Create links for hash tags
		tweet = tweet.replace(/(^|\s|-)+#(\w+)/g, function(str) {
			url = str.replace(/^\s+|\s+$/g,'');
			url = url.replace(/#/g, '');
    	return '&nbsp<a href="//twitter.com/search?q=%23'+ url +'" target="_blank">' + str + '</a>';
		});
		
		//tweet = tweet.linkify();
	
		latestTweet.html('“' + tweet + '” <span>' + relative_time(data[0].created_at) + '</span>');
		footerContent.append(latestTweet);
	});
}

function relative_time(time_value) {
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);

	var r = '';
	if (delta < 60) { r = 'a minute ago'; } 
	else if(delta < 120) { r = 'couple of minutes ago'; }
	else if(delta < (45*60)) { r = (parseInt(delta / 60)).toString() + ' minutes ago'; }
	else if(delta < (90*60)) { r = 'an hour ago'; }
	else if(delta < (24*60*60)) {	r = '' + (parseInt(delta / 3600)).toString() + ' hours ago'; }
	else if(delta < (48*60*60)) { r = '1 day ago'; }
	else { r = (parseInt(delta / 86400)).toString() + ' days ago'; }
	  
  return r;
}

String.prototype.linkify = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
  	m = m.replace(/ /g,"");
  	return m.link(m);
  });
};