﻿var resetForm;
var fxspeed = 200;
var pagetitle = document.title;
var defaultnav;
var activenav;
var nicescroll;
// Hash
var hashArr = window.location.hash.substring(1).split('#');
var activeHash = hashArr[0].toLowerCase();

$(window).load(function () {
    // Navigation Hnadlers
    if ($('#navigation .active').length < 1) {
        $('#logo').addClass('active');
    }
    var underline = $('#header #underline');
    var parentOffset = $('#header .shell').offset();
    defaultnav = $('#header .active');
    activenav = defaultnav;
    var activeOffset = activenav.offset();
    underline.css({ 'left': activeOffset.left - parentOffset.left, 'width': activenav.outerWidth() });
    $('#navigation a').mouseover(function () {
        var offset = $(this).offset();
        parentOffset = $('#header .shell').offset();
        activeOffset = activenav.offset();
        underline.stop(true, true).fadeIn(0).animate({
            left: offset.left - parentOffset.left,
            width: $(this).outerWidth()
        }, 200);
    }).mouseout(function () {
        underline.delay(200).animate({
            left: activeOffset.left - parentOffset.left,
            width: activenav.outerWidth()
        }, 400);
    }).not('#contact').click(function () {
        $('#navigation a').removeClass('active');
        activeOffset = $(this).offset();
        $(this).addClass('active');
        activenav = $(this);
    });
    underline.show();
});

$(document).ready(function () {
    // Nice Scroll
    //nicescroll = $("html").niceScroll({ cursorwidth: '8px', cursorcolor: '#999', scrollspeed: 0 });

    // Init Page
    $('#rightcol .cb:not(:first-child)').hide();

    // History Function
    function loadContent(hash) {
        var elem = $('#cb_' + hash);
        if (elem.hasClass('workitem')) {
            // Work Item
            openItem(elem);
        } else {
            // Content Block
            $('#rightcol .cb').stop(true, true).hide();
            $('.menuitem.active .color').stop(true, true).hide();
            $('.cbtrigger').removeClass('active');
            if (hash != "") {
                elem.addClass('active').find('.color').show();
                $('#c_' + hash).fadeIn(300);
                var str = '';
                var urlArr = hash.split('-');
                for (x in urlArr) {
                    var word = urlArr[x];
                    var wordCap = word.charAt(0).toUpperCase() + word.slice(1);
                    str += wordCap + ' ';
                }
                document.title = "Innovah - " + str;
            } else {
                $('.cb:first').fadeIn(300);
                document.title = pagetitle;
                closeItems();
            }
        }
        //nicescroll.resize();
    }

    // CB Handlers
    $('.cbtrigger').hover(function () {
        $(this).addClass('hover').animate({ backgroundPosition: '0 0' }, 300)
    }, function () {
        $(this).removeClass('hover').stop().css('backgroundPosition', '500px 0');
    }).click(function () {
        var url = $(this).attr('id').substring(3);
        if ($(this).hasClass('active')) {
            url = '';
        }
        $.history.load(url);
        return false;
    });
    // Work Handlers
    $('.workitem').hover(function () {
        $(this).find('.heading').stop(true, true).animate({
            marginTop: 0
        }, fxspeed);
    }, function () {
        var heading = $(this).find('.heading');
        heading.stop(true, true).delay(fxspeed / 2).animate({
            marginTop: '-' + heading.outerHeight() + 'px'
        }, fxspeed);
    }).find('.heading .button.more').click(function () {
        var url = $(this).parents('.workitem').attr('id').substring(3);
        $.history.load(url);
        return false;
    });
    // Open Close Work
    function openItem(elem) {
        if (elem == null) { elem = $('#c_' + activeHash); }
        closeItems();
        var bigitem = elem.clone().attr('id', 'bigitem').addClass('big').append('<div class="button x"><span class="label"></span></div>');
        var workoverlay = $('<div></div>').attr('id', 'workoverlay').height($('body').height());
        $('#midshell').append(workoverlay);
        $('body').append(bigitem);
        bigitem.center();
        workoverlay.fadeIn(fxspeed, function () {
            bigitem.slideDown(fxspeed).find('.button.x').click(function () {
                $.history.load('');
                return false;
            });
        });
        return false;
    }
    function closeItems() {
        $('#workoverlay, .workitem.big').fadeOut(fxspeed, function () {
            $(this).remove();
        });
    }

    // Social Handlers
    $('.socialitem').hover(function () {
        $(this).stop(true, false).animate({
            width: '170px'
        }, 200);
    }, function () {
        $(this).stop(true, false).animate({
            width: '33px'
        }, 200);
    });

    // Contact Form
    $('#contact, #contactform .button.x').click(function () {
        $('#contactform').stop(true, false).slideToggle();
        $('#contact').toggleClass('active');
        if (!$('#contact').hasClass('active')) {
            defaultnav.trigger('click').trigger('mouseover');
        }
        return false;
    })
    jQuery.support.cors = true;
    $('.textbox').focus(function () {
        if ($(this).hasClass('watermark')) {
            $(this).removeClass('watermark').val('');
        }
        $(this).nextAll('.validator').fadeOut(fxspeed);
    }).blur(function () {
        validate($(this));
    });

    // Contact Submit
    $('#submit').click(function (event) {
        $('.validate > :first').not('.label').each(function () {
            validate($(this));
        });
        if (!$(this).hasClass('disabled') && $('#contactform .invalid').length < 1) {
            $(this).addClass('disabled');
            $.ajax({
                type: "POST",
                url: "/ws/contact.asmx/add",
                data: '{"fullname": "' + $('#fullname').val() + '", "email": "' + $('#email').val() + '", "comments": "' + encodeURIComponent($('#comments').val()) + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d == "Invalid Email") {
                        validate($('#email'), { 'type': 'email' });
                        $('#submit').removeClass('disabled');
                    } else if (response.d == "Success") {
                        $('#thanks').fadeIn();
                    } else {
                        $('#error').text(response.d).fadeIn(fxspeed);
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $('#error').text('Did Not work! ' + xhr.statusText).fadeIn();
                }
            });
        }
        return false;
    });

    // Validate Form
    function validate(elem, args) {
        if (typeof (args) != 'undefined') {
            // Overwrite Invalid
            elem.addClass('invalid').nextAll('.validator[data-type="' + args.type + '"]').fadeIn(fxspeed);
        } else {
            // Validate Element
            var isvalid = true;
            elem.nextAll('.validator').each(function () {
                var type = $(this).attr('data-type');
                var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                if (type == 'required' && ($.trim(elem.val()) == "" || elem.val() == elem.attr('title'))) {
                    // Is Empty
                    elem.addClass('watermark invalid').val(elem.attr('title'));
                    $(this).fadeIn(fxspeed);
                    isvalid = false;
                    return false;
                } else if (type == 'email' && !reg.test(elem.val())) {
                    $(this).fadeIn(fxspeed);
                    isvalid = false;
                    return false;
                }
            });
            if (isvalid) {
                elem.removeClass('watermark invalid').nextAll('.validator').fadeOut(fxspeed);
            }
        }
    }
    // Reset
    $('.reset').click(function () {
        resetForm();
    });
    resetForm = function () {
        $('.textbox').each(function () {
            $(this).addClass('watermark').val($(this).attr('title'));
        });
        $('#submit').removeClass('disabled');
        $('#error, #thanks').hide();
    };
    resetForm();

    // Count Strokes
    $('#message').keyup(function () {
        limitChars('message', 800, 'countinfo');
    })

    // Client Logos
    $('#clientlogos').mouseover(function () {
        $(this).stop(true, true).delay(200).animate({
            height: '500px'
        }, 400);
        $(this).unbind('mouseover');
    });

    // About Us Quote
    $('.teammember').hover(function () {
        $(this).find('.quotecontainer').stop(true, true).delay(100).animate({
            width: '270px'
        }, 400);
    }, function () {
        $(this).find('.quotecontainer').stop(true, true).delay(100).animate({
            width: '0'
        }, 400);
    });

    // Center
    jQuery.fn.center = function () {
        this.css("position", "absolute");
        this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
        this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
        return this;
    }

    $.history.init(loadContent);

});


// Character Count
function limitChars(textid, limit, infodiv) {
    var text = $('#' + textid).val();
    var textlength = text.length;
    if (textlength > limit) {
        $('#' + textid).val(text.substr(0, limit));
        return false;
    }
    else {
        $('#' + infodiv).html('(' + (limit - textlength) + ' characters left)');
        return true;
    }
}

// PLUGINS

/**
 * @author Alexander Farkas
 * v. 1.22
 * animate backgroundPosition
 */
(function (a) { function d(a) { a = a.replace(/left|top/g, "0px"); a = a.replace(/right|bottom/g, "100%"); a = a.replace(/([0-9\.]+)(\s|\)|$)/g, "$1px$2"); var b = a.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/); return [parseFloat(b[1], 10), b[2], parseFloat(b[3], 10), b[4]] } if (!document.defaultView || !document.defaultView.getComputedStyle) { var b = a.curCSS; a.curCSS = function (a, c, d) { if (c === "background-position") { c = "backgroundPosition" } if (c !== "backgroundPosition" || !a.currentStyle || a.currentStyle[c]) { return b.apply(this, arguments) } var e = a.style; if (!d && e && e[c]) { return e[c] } return b(a, "backgroundPositionX", d) + " " + b(a, "backgroundPositionY", d) } } var c = a.fn.animate; a.fn.animate = function (a) { if ("background-position" in a) { a.backgroundPosition = a["background-position"]; delete a["background-position"] } if ("backgroundPosition" in a) { a.backgroundPosition = "(" + a.backgroundPosition } return c.apply(this, arguments) }; a.fx.step.backgroundPosition = function (b) { if (!b.bgPosReady) { var c = a.curCSS(b.elem, "backgroundPosition"); if (!c) { c = "0px 0px" } c = d(c); b.start = [c[0], c[2]]; var e = d(b.end); b.end = [e[0], e[2]]; b.unit = [e[1], e[3]]; b.bgPosReady = true } var f = []; f[0] = (b.end[0] - b.start[0]) * b.pos + b.start[0] + b.unit[0]; f[1] = (b.end[1] - b.start[1]) * b.pos + b.start[1] + b.unit[1]; b.elem.style.backgroundPosition = f[0] + " " + f[1] } })(jQuery)

