$(function () {
    /* Toggle Search */
    $("#search").focus(function () {
        if ($("#search").val() == $("#search").data("hint")) {
            $("#search").val("");
        }
        tt.refreshAutocomplete();
        $("#autocomplete").show();
    }).blur(function () {
        if ($("#search").val() == "") {
            $("#search").val($("#search").data("hint"));
        }
        setTimeout(function () {
            $("#autocomplete").hide();
        }, 200);
    }).keypress(function (event) {
        switch (event.keyCode) {
            case 40: // down
                
                break;
            case 38: // up
                
                break;
        }
    }).keyup(function () {
        tt.refreshAutocomplete();
    });
    $("#autocomplete").hide();
    $("#search").val($("#search").data("hint"));
    /* Toggle Subscribe */
    $("#subscribe").focus(function () {
        if ($("#subscribe").val() == $("#subscribe").data("hint")) {
            $("#subscribe").val("");
            $("#subscribe").removeClass("blur");
        }
    }).blur(function () {
        if ($("#subscribe").val() == "") {
            $("#subscribe").val($("#subscribe").data("hint"));
            $("#subscribe").addClass("blur");
        }
    });
    $("#subscribe").val($("#subscribe").data("hint"));
    $("#subscribe").addClass("blur");
    // Hover Navigation for Solutions
    $("#Solutions").mouseenter(function () {
        if ($("header").height() == 104
            && !$("body").hasClass("template-solution-index")
            && !$("body").hasClass("template-solution-page")) {
            $("nav.main .selected").css({ lineHeight: "34px", paddingTop: "2px", height: "34px" });
            $("header").stop().animate({ height: 130 }, 200);
        }
    });
    $("header").mouseleave(function () {
        if (!$("body").hasClass("template-solution-index")
            && !$("body").hasClass("template-solution-page")) {
            $("header").stop().animate({ height: 104 }, 200);
            $("nav.main .selected").css({ lineHeight: "38px", paddingTop: "0", height: "38px" });
        }
    });
});
// Reusable tt object.
var tt = {
    overlay: function (o) {
        o.shadeClose = typeof (o.shadeClose) == "undefined" ? true : o.shadeClose;
        var view = $("body").append('<div class="overlay" id="overlay_close"><div class="overlay-center"><div class="overlay-content" id="overlay"></div></div></div>');
        $("#overlay").css({
            "width": o.width + "px",
            "height": o.height + "px",
            "marginLeft": (-1 * Math.round(o.width / 2)) + "px",
            "top": (-1 * Math.round(o.height / 2)) + "px"
        });
        if (o.shadeClose) {
            $("#overlay_close").click(function (event) {
                if (event.target == this) {
                    $(this).remove();
                }
            });
        }
        o.content.call({
            container: "#overlay",
            close: function () {
                $("#overlay_close").remove();
            }
        });
    },
    removeOverlay: function () {
        $("#overlay_close").remove();
    },
    quickSearch: [
        { keyword: "About", url: "/about" },
        { keyword: "Blog", url: "/blog" },
        { keyword: "Contact", url: "/contact" },
        { keyword: "Address", url: "/contact" },
        { keyword: "Location", url: "/contact" },
        { keyword: "Email,E-Mail", display: "Email", url: "/contact" },
        { keyword: "Outsourcing", url: "/about/outsourcing-options" },
        { keyword: "Partners", url: "/about/founders" },
        { keyword: "Founders", url: "/about/founders" },
        { keyword: "George Walker", url: "/about/founders" },
        { keyword: "Carl Franklin", url: "/about/founders" },
        { keyword: "Henry Schwenk", url: "/about/founders" },
        { keyword: "Solutions", url: "/solutions" },
        { keyword: "Solutions Sharepoint", display: "Solutions - SharePoint", url: "/solutions/sharepoint" },
        { keyword: "Solutions Mobile", display: "Solutions - Mobile", url: "/solutions/mobile" },
        { keyword: "Solutions E-Commerce", display: "Solutions - E-Commerce", url: "/solutions/e-commerce" },
        { keyword: "Solutions Custom Development", display: "Solutions - Development", url: "/solutions/e-commerce" },
        { keyword: "Solutions Hosting Solutions", display: "Solutions - Hosting", url: "/solutions/e-commerce" },
        { keyword: "Solutions Internet Strategy", display: "Solutions - Strategy", url: "/solutions/e-commerce" }
    ],
    refreshAutocomplete: function () {
        $("#autocomplete").empty();
        var c = 0;
        if ($("#search").val().length >= 2) {
            for (var i in tt.quickSearch) {
                if (tt.quickSearch[i].keyword.toLowerCase().indexOf($("#search").val().toLowerCase()) != -1) {
                    c++;
                    $("#autocomplete").append('<li><a href="'
                                              + tt.quickSearch[i].url
                                              + '" id="autocomplete_'
                                              + c
                                              + '">'
                                              + (typeof (tt.quickSearch[i].display) == "undefined"
                                                ? tt.quickSearch[i].keyword
                                                : tt.quickSearch[i].display)
                                              + '</a></li>');
                }
                if (c == 3) {
                    break;
                }
            }
        }
    }
};

tt.email = {
    overlay: function (title, selected, list) {
        tt.overlay({
            width: 400,
            height: 400,
            shadeClose: false,
            content: function () {
                $(this.container).empty();
                $(this.container).addClass("inquiry");

                $(this.container).append('<div class="title">' + title + '<a href="" id="overlay_x">X</a></div>');
                $(this.container).append('<form id="formcontact"></form>');

                var items = '<label>Reason for inquiry <select id="reason" name="reason">';
                for (var i in list) {
                    s = i == selected ? ' selected="selected"' : "";
                    items += '<option value="' + list[i] + '"' + s + '>' + list[i] + '</option>';
                }
                items += '</select></label>';

                $("#formcontact").append(items);
                $("#formcontact").append('<label>Name<input id="name" name="name" /></label>');
                $("#formcontact").append('<label>Email<input id="email" name="email" /></label>');
                $("#formcontact").append('<label>Message<textarea id="body" name="body"></textarea></label>');

                $("#formcontact").append('<button>Send</button>');

                $("#formcontact").submit(function () {
                    if (!(/^[^@]+@[^\.]+\./.test($("#email").val()))) {
                        alert("Invalid Email");
                    }
                    else if ($("#name").val() == "") {
                        alert("Name cannot be empty");
                    }
                    else if ($("#body").val() == "") {
                        alert("Message cannot be empty");
                    }
                    else {
                        $.ajax({
                            type: "POST",
                            url: "/email",
                            data: $(this).serialize(),
                            success: function (data) {
                                if (data == "true") {
                                    $("#formcontact").html('<p>Message sent. We will get back to you as quickly as possible.</p>');
                                }
                                else {
                                    alert(data);
                                }
                            }
                        });
                    }
                    return false;
                });

                $("#overlay_x").click(function () {
                    tt.removeOverlay();
                    return false;
                });
            }
        });
    }
};

/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
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 : cookie_encode(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 cookie_encode(string) {
    //full uri decode not only to encode ",; =" but to save uicode charaters
    var decoded = encodeURIComponent(string);
    //encod back common and allowed charaters {}:"#[] to save space and make the cookies more human readable
    var ns = decoded.replace(/(%7B|%7D|%3A|%22|%23|%5B|%5D)/g, function (charater) { return decodeURIComponent(charater); });
    return ns;
}
