﻿var headItems = [];

// cause reload in HTML4 browsers
if (location.hash.indexOf("/") != -1) {
    window.location = location.hash.replace("#", "");
}

$().ready(function () {

    // used for vanity urls
    var r = getQuerystring('r');
    if (r != '') {
        if (_gaq !== 'undefined') {
            _gaq.push(['_trackPageview', '/'+r]);
        }
    }


    $.ajaxSetup({
        cache: false
    });

    // enable watermark throughout the website in single pageload situations
    function enableWatermark() {
        $('.email-signup-input').watermark('E-mail Address', { useNative: false, className: 'watermark' });
        $('.contact-form input.email').watermark('E-mail Address', { useNative: false, className: 'watermark' });
    }

    var rootUrl = window.History.getRootUrl();

    // enable the watermark out of the gate
    enableWatermark();

    // get the single page load error count
    var errorcount = Number($.cookie('ajaxerrorcount'));

    // if not a number, or less then X errors in loading, and doesn't go to the blog, enable single pageloads
    if ((isNaN(errorcount) || errorcount < 20) && window.History.getRootUrl().indexOf("blog.") < 0) {
        $('a[href^="/"]:not(a[href$=.pdf],a[href$=.vcf]),a[href^="' + rootUrl + '"]:not(a[href$=.pdf],a[href$=.vcf])').live('click', function (e) {
            if (e.which == 2 || e.metaKey) { return true; }
            var $obj = $(this);

            var setNavigationClass = $(this).parents('.mainnav > li').attr('class');
            if (setNavigationClass !== undefined && setNavigationClass !== "") {

                setNavigationItem($(this).parents('.mainnav > li').attr('class'));
            }
            else if ($obj.attr('href') == "/") {
                setNavigationItem(null);
            }


            e.preventDefault();
            History.pushState(null, $obj.attr('title'), $obj.attr('href'));

            if ($(window).scrollTop() > $('#changingcontentwrapper h1').offset().top + $('#changingcontentwrapper h1').height()) {
                $('html,body').animate({ scrollTop: 0 }, 400);
            }

        });
    }


    var History = window.History;
    if (!History.enabled)
        return false;

    // bind to statechange Event
    $(window).bind('statechange', function () {
        $('#loading').addClass('loading');
        $('#changingcontentwrapper').stop(true).animate({ opacity: '0' }, 250);

        // scroll window to top of the user has scrolled so far down on the page
        if ($(window).scrollTop() > $('#changingcontentwrapper h1').offset().top + $('#changingcontentwrapper h1').height()) {
            $('html,body').animate({ scrollTop: 0 }, 400);
        }

        var State = History.getState();
        var relativeUrl = State.url.replace(rootUrl, '');

        // send request for page
        $.ajax({
            type: "GET",
            url: State.url,
            dataType: "xml",
            timeout: 2000
        })
        .success(function (data, textstatus, xhr) {

            var responseHeader = xhr.getResponseHeader('Content-Type');
            if (responseHeader.indexOf('text/xml') == -1 && responseHeader.indexOf('text/html') == -1) {
                document.location = State.url;
                return;
            }
            $output = $(data).find('output');
            $header = $($output.find('header'));

            var content = jQuery.trim($output.find('content').text());

            // make sure we loaded content, if not, load the page manually
            if (content.length <= 0) {
                _gaq.push(['_trackEvent', 'AJAX', 'Error', 'nocontent']);
                document.location = relativeUrl;
                return;
            }

            // force pageview in google analytics
            if (_gaq !== 'undefined') {
                _gaq.push(['_trackPageview', relativeUrl]);
            }

            $('#changingcontentwrapper').html(content);

            $('#changingcontentwrapper').stop(true).animate({ opacity: '1' }, 500);
            $('#loading').removeClass('loading');

            $('#contentwrap').removeClass().addClass(jQuery.trim($output.find('extraclass').text()));
            $('.testimonialwrap p').html(jQuery.trim($output.find('testimonial quote').text()));
            $('.testimonialwrap div.testimonialname').html(jQuery.trim($output.find('testimonial name').text()));
            document.title = jQuery.trim($output.find('title').text());

            // remove all previously loaded items from the <head>
            jQuery.each(headItems, function () {
                $('#' + this, $('head')).remove();
            });

            headItems = [];

            $($output.find('head').text()).each(function () {
                if (this.tagName == "TITLE" || this.tagName == "title") {
                    return true;
                }
                else if (this.id != undefined && this.id != "") {
                    headItems.push(this.id)
                    $("#" + this.id, 'head').remove();
                    $('head').append(this);
                }
                else if (jQuery.trim(this.data) != "") {
                    $('head').append(this);
                }
            });

            triggerNavUpdate();
            checkFacebook();
            checkYoutube();

            enableWatermark();

            // push custom event to analytics knowing we loaded the page completely
            _gaq.push(['_trackEvent', 'AJAX', 'Load']);

        })
        .error(function (jqXHR, textStatus, errorThrown) {
            // this error event will push the event to analytics, increment the cookie
            // by one to disable the loading after X failures and then redirect
            // the end user to the physical page

            _gaq.push(['_trackEvent', 'AJAX', 'Error', textStatus]);
            if ($.cookie('ajaxerrorcount') != null) {
                var errorcount = parseInt($.cookie('ajaxerrorcount'));
                $.cookie('ajaxerrorcount', errorcount + 1, { expires: 3 });
            }
            else {
                $.cookie('ajaxerrorcount', 1);
            }

            document.location = "/" + relativeUrl
        });
    });

    $('.validateemail').live('submit', function () {
        if ($('input[name="ftremail"]').val() == "") {
            alert("Please enter an email address.");
            return false;
        }
        return true;
    });


});


jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}
