'use strict' // yep
// W3C, y u no like outerHTML ? (屮ಠ益ಠ)屮
$.ender({
    outerHTML: function(d, i) {
        d = d === false ? false : true
        if (d && this[0].outerHTML) return this[0].outerHTML
        i = new Image
        i.appendChild(this[0].cloneNode(d))
        return i.innerHTML
    }
}, true)

$.domReady(function() {

    var $win = $(window)
      , $body = $('body')
      , $main = $('[role=main]')
      , $portfolioLinks = $('section nav a', $main)
      , $footer = $('footer', $main)
      , $textarea = $('textarea', $footer)
      , $autoResize = $textarea.next()
      , $overlay = $('#overlay')
      , $overlayContent = $('div', $overlay)

    // Typography stuffs
    var fontLoaded = function(active) {
        var $header = $('header')
        // If there is a problem with Typekit
        if (!active) {
            alert('It looks like your browser doesn\'t support the fonts that are in use, I deeply apology for this :(')
        }
        if (Modernizr.mq) {
            var transEndEventNames = {
                'WebkitTransition' : 'webkitTransitionEnd'
              , 'MozTransition'    : 'transitionend'
              , 'OTransition'      : 'oTransitionEnd'
              , 'msTransition'     : 'MSTransitionEnd'
              , 'transition'       : 'transitionend'
            }
              , transEndEventName = transEndEventNames[Modernizr.prefixed('transition')]
            $header[0].addEventListener(transEndEventName, function() {
                $header.addClass('shown')
            })
            $('h1', $header).lettering().fitText(.8, { maxFontSize: 96 })
            $('h2', $header).fitText(1.5, { maxFontSize: 36 })
            $('p').first().fitText(1.8, { maxFontSize: 27 })
            $('.ribbon u', $main).first().fitText(1.6, { maxFontSize: 28 })
        } else {
            $header.addClass('shown')
        }
    }
    Typekit.load({
        active: fontLoaded(true)
      , inactive: fontLoaded
    })

    $portfolioLinks.on('click touchstart', function(e) {
        if (this.hash === '#bwong' && $main.width() >= 850) {
            e.preventDefault()

            var inception = this
              , bwong = false
            // OGG > MP3, even if ogg === "maybe" and mp3 === "probably"
            if (Modernizr.audio.ogg) {
                bwong = new Audio('inception.ogg')
            } else if (Modernizr.audio.mp3) {
                bwong = new Audio('inception.mp3')
            } else {
                // alert('You suck.')
            }

            // If the browser `can play through` ogg/mp3
            if (bwong) {
                bwong.addEventListener('canplaythrough', function() {
                    // Do not play on small screen
                    bwong.play()
                    if (Modernizr.cssanimations) {
                        // THANKS MICROSOFT view-source:http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_animations.htm
                        var animationEndName = (Modernizr.prefixed('animation') + "End").replace(/^ms/, "MS").replace(/^Webkit/, "webkit").replace(/^Moz.*/, "animationend")

                        // IE10 doesn't support classList (yet) :(
                        inception.className = 'inception'
                        inception.addEventListener(animationEndName, function() {
                            inception.className = ''
                        }, false)
                    }
                }, false)
            }
        }
        //if (e.type === 'touchend' || $main.width() < 850) {
        if (e.type === 'touchstart' || $main.width() < 850) {
            e.preventDefault()
            var $figcaption = $(this).find('figcaption')
              , title = $('<h3>').append($figcaption.find('h3').html().link(this.href)).outerHTML()
              , p = $figcaption.find('p').outerHTML()

            $overlayContent.html(title+p)

            $body.addClass('overlay')
        }
    })

    // Load the images
    var portfolioLinksLength = $portfolioLinks.length
      , isBig = $main.width() > 450
    /* I can't show the images like a baus because the 3D can be fucked up, but I let it there, we never know, maybe someday
      , i = 0
      , imgLoad = setInterval(function() {
            var portfolioLink = $portfolioLinks[i++]
              , $img = $('img', portfolioLink)
            $img.attr('src', isBig ?
                $img.attr('data-src') :
                $img.attr('data-src').split('/').join('/th/')
            )
            portfolioLink.style.opacity = 1
            i === portfolioLinksLength && clearInterval(imgLoad)
        }, 75)
    */
    for (var portfolioLink, i = 0; portfolioLink = $portfolioLinks[i++];) {
    var $img = $('img', portfolioLink)
        $img.attr('src', isBig ?
            $img.attr('data-src') :
            $img.attr('data-src').split('/').join('/th/')
        )
        portfolioLink.style.opacity = 1
    }

    // If the images are small, make them bigger when the browser is more than ~> 450
    if (!isBig) {
        $win.on('resize.img', function(e) {
            if ($main.width() > 450) {
                for (var i = 0, portfolioLink; portfolioLink = $portfolioLinks[i++];) {
                    var $img = $('img', portfolioLink)
                    $img.attr('src', $img.attr('data-src'))
                }
                $win.unbind('resize.img')
            }
        }).resize()
    }

    $overlay.on('click', function(e) {
        $body.removeClass('overlay')
    })

    $win.on('keydown', function(e) {
        // 27 = echap
        if (e.keyCode === 27 && $body.hasClass('overlay')) {
            $body.removeClass('overlay')
        }
    }).on('scroll', function(e) {
        if ($footer.offset().top - $win.scrollTop() - $win.height() < -100) {
            showContact()
            $win.unbind('scroll')
        }
    }).on('load', function() {
      if (location.hash === '#contact') {
            showContact()
            $win.unbind('scroll')
      }
    })

    // Show the contact text and the the social links
    var showContact = function() {
        if ($textarea.data('hasText')) return false
        var text = (navigator.language === 'fr' || navigator.browserLanguage === 'fr' ? 'Cher' : 'Dear') + ' François, '
        // Reset the value if it's the default text
        $textarea.val() === text && $textarea.val('')
        var i = 0
          , letter
          , $socialLinks = $('li', $footer)
          , socialLinksLength = $socialLinks.length
          , loop = setInterval(function() {
            if (letter = text.charAt(i))
                $textarea.val($textarea.val() + letter)

            if (socialLinksLength > i)
                $socialLinks[i].className += ' shown'

            i++ >= socialLinksLength && !letter && clearInterval(loop)
          }, 75)

        $textarea.data('hasText', true)[0].focus()
    }

    $footer.one('mouseover', showContact)

    // Auto-resize the textarea with its content
    $textarea.on('change keyup keydown', function() {
        $autoResize.html(this.value.replace(/&/g, '&amp;')
                                    .replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/\n$/, '<br/>&nbsp;')
                                    .replace(/\n/g, '<br/>')
                                    .replace(/ {2,}/g, function(spaces) {
                                        // Change the spaces to $nbsp; except the last one
                                        for (var i = 1, fakeSpaces = '', space; space = spaces[i++];) {
                                            fakeSpaces += '&nbsp;'
                                        }
                                        return fakeSpaces + ' '
                                    })
                                )
        $textarea.css('height', $autoResize.height() + 35)
    })

    // Create the mailto link
    var email = location.host.split('.', 2).join('@') + '.com'
    $('li:first-of-type a', $footer).attr({
        href: 'mailto:' + email
      , "data-email": email
    })

    // Google analitycs links
    $('a', $footer).on('click', function(e) {
        console.log(this.firstChild.src.replace(location.href, '').split('.')[0].split('/')[1].split('_')[0])
        _gaq.push(['_trackEvent', 'Social', this.firstChild.src.replace(location.href, '').split('.')[0].split('/')[1].split('_')[0]])
    })

    // Prevent people with shitty browser to contact me
    var form = document.getElementsByTagName('form')[0]
    if ('addEventListener' in form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault()

            if ($textarea.val().length < 50) {
                alert("That's all ?")
                return false
            }

            var xhr = new XMLHttpRequest()
            xhr.open('POST', 'mail.php', true)
            xhr.addEventListener('readystatechange', function(e) {
                if (this.readyState === 4 && this.status === 200) {
                    form.style.position = 'absolute'
                    form.style.opacity = 0
                    form.nextSibling.style.width = '90%'
                    form.nextSibling.style.margin = '0 5%'
                }
            })

            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
            xhr.send('message=' + $autoResize.html())
        }, false)
    } else {
        $(form).on('submit', function(e) {
            e.preventDefault()
            alert('Go away please.')
        })
    }
})
