﻿// namespace
$.VS = {
    global: {}
};

//jQuery.event.add(window, "load", repositionNav);
jQuery.event.add(window, "resize", repositionNav);

var isIe6 = $.browser.msie && $.browser.version == "6.0";

var rootPath = "";
var workImageFadeTime = 2000;
function repositionNav() {
    var width = $(window).width();
    var contentWidth = $("#main").width();
    var remainder = width - contentWidth;
    var left = (remainder / 2) - 5;
    if (!isIe6) {
        $("#leftNav").css("left", left < 0 ? 0 : left);
    }
}

$(function() {
    $("#submit").hover(
    function() {
    $(this).addClass("contactussubmitActive");
    },
    function() {
    $(this).removeClass("contactussubmitActive");
    }
    );
});

$(function() {
    $(".socialswap").hover(
    function() {
        $(this).attr("src", $(this).attr("src").replace(/-off./, "-over."));
    },
    function() {
        $(this).attr("src", $(this).attr("src").replace(/-over./, "-off."));
    }
    );
});

$(function() { $(".hoverswap").hover(
    function () {
        $(this).attr("src", $(this).attr("src").replace(/_inactive./, "_hover."));        
        },
    function () {
        $(this).attr("src", $(this).attr("src").replace(/_hover./, "_inactive."));
        }
    );
    });
    
$(function() { $(".hoverswapactive").hover(
    function() {
        $(this).attr("src", $(this).attr("src").replace(/_active./, "_hover."));
    },
    function() {
        $(this).attr("src", $(this).attr("src").replace(/_hover./, "_active."));
    }
    );
});

$(function() {
    $(".workBucket h4").hover(
        function() {
            var $outer = $(this).parent().parent().find('.outerFrame');
            var $inner = $outer.find('.innerFrame');
            var $slideshow = $(this).parent().parent().find('.slideshow');
            $outer.attr("style", "width: 255px;	height: 107px; border: 1px solid #fff;");
            $inner.attr("style", "border: 1px solid #000;");
            $(this).attr("style", "color: #ff0000;");
            $(this).find("a").attr("style", "color: #ff0000;");
            var classes = $(this).attr("class").split(' ');
            var lis = $("#WorkLegend ul li");
            $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
            for (var i = 0; i < classes.length; i++) {
                $(lis[classes[i]]).fadeTo('slow', 1.0, function() { });
            }
            $slideshow.cycle('next');
            $slideshow.cycle('toggle');
        },
        function() {
            $(this).attr("style", "color: #fff;");
            $(this).find("a").attr("style", "color: #fff;");
            var $outer = $(this).parent().parent().find('.outerFrame');
            var $inner = $outer.find('.innerFrame');
            var $slideshow = $(this).parent().parent().find('.slideshow');

            $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });

            $slideshow.cycle('toggle');
            $outer.attr("style", "width: 257px; height: 109px;border: 0px solid #fff;");
            $inner.attr("style", "border: 0px solid #000;");
        }
    );
});


if ($.browser.msie) {

    $(function() {
        $(".workBucket .slideshow").hover(
        function() {
            var $outer = $(this).parent().find('.outerFrame');
            var $inner = $outer.find('.innerFrame');
            var $slideshow = $(this);
            var $h4 = $(this).parent().find('h4');
            $h4.attr("style", "color: #ff0000;");
            $($h4).find("a").attr("style", "color: #ff0000;");
            $outer.attr("style", "width: 255px;	height: 107px; border: 1px solid #fff;");
            $inner.attr("style", "border: 1px solid #000;");
            var classes = $slideshow.find('img:first').attr("class").split(' ');
                        
            var lis = $("#WorkLegend ul li");
            $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
            for (var i = 0; i < classes.length; i++) {
                $(lis[classes[i]]).fadeTo('slow', 1.0, function() { });
            }
            $slideshow.cycle('next');
            $slideshow.cycle('toggle');

        },
        function() {
            var $outer = $(this).parent().find('.outerFrame');
            var $inner = $outer.find('.innerFrame');
            var $slideshow = $(this);
            $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
            var $h4 = $(this).parent().find('h4');
            $h4.attr("style", "color: #fff;");
            $($h4).find("a").attr("style", "color: #fff;");
            $slideshow.cycle('toggle');
            $outer.attr("style", "width: 257px; height: 109px;border: 0px solid #fff;");
            $inner.attr("style", "border: 0px solid #000;");
        }
    );
    });

}
else {
    $(function() {
        $(".workBucket .outerFrame").hover(
        function() {
            var $outer = $(this);
            var $inner = $(this).find('.innerFrame');
            var $slideshow = $(this).parent().find('.slideshow');
            var $h4 = $(this).parent().find('h4');
            $h4.attr("style", "color: #ff0000;");
            $($h4).find("a").attr("style", "color: #ff0000;");
            $outer.attr("style", "width: 255px;	height: 107px; border: 1px solid #fff;");
            $inner.attr("style", "border: 1px solid #000;");
            var classes = $slideshow.find('img:first').attr("class").split(' ');
           
            var lis = $("#WorkLegend ul li");
            $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
            for (var i = 0; i < classes.length; i++) {
                $(lis[classes[i]]).fadeTo('slow', 1.0, function() { });
            }
            $slideshow.cycle('next');
            $slideshow.cycle('toggle');

        },
        function() {
            var $outer = $(this);
            var $inner = $(this).find('.innerFrame');
            var $slideshow = $(this).parent().find('.slideshow');
            $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
            var $h4 = $(this).parent().find('h4');
            $h4.attr("style", "color: #fff;");
            $($h4).find("a").attr("style", "color: #fff;");
            $slideshow.cycle('toggle');
            $outer.attr("style", "width: 257px; height: 109px;border: 0px solid #fff;");
            $inner.attr("style", "border: 0px solid #000;");
        }
    );
    });

}

//add hover state to work capability x's


//yella
$(function() {
    $(".workCapability .yellow").hover(
    function() {
        $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
        $("#ani").fadeTo('fast', 1.0, function() { });
    },
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
    }
    );
});




//blue
$(function() {
$(".workCapability .blue").hover(
    function() {
$("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
        $("#cms").fadeTo('fast', 1.0, function() { });
    },
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
    }
    );
});

//orange
$(function() {
    $(".workCapability .orange").hover(
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
    $("#eComm").fadeTo('fast', 1.0, function() { });
    },
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
    }
    );
});

//red
$(function() {
    $(".workCapability .red").hover(
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
        $("#seon").fadeTo('fast', 1.0, function() { });
    },
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
    }
    );
});

//green
$(function() {
    $(".workCapability .green").hover(
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
        $("#cp").fadeTo('fast', 1.0, function() { });
    },
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
    }
    );
});

//pink
$(function() {
    $(".workCapability .pink").hover(
   function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
       $("#soc").fadeTo('fast', 1.0, function() { });
   },
    function() {
   $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
    }
    );
});

//turquoise
$(function() {
$(".workCapability .turquoise").hover(
    function() {
$("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
        $("#design").fadeTo('fast', 1.0, function() { });
    },
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
    }
    );
});

//white
$(function() {
    $(".workCapability .white").hover(
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
        $("#brand").fadeTo('fast', 1.0, function() { });
    },
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
    }
    );
});

//purple
$(function() {
    $(".workCapability .purple").hover(
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 0.5, function() { });
        $("#elearn").fadeTo('fast', 1.0, function() { });
    },
    function() {
    $("#WorkLegend li").stop(true, true).fadeTo('fast', 1.0, function() { });
    }
    );
});

function SubmitForm()
{
    //var fname = $(form).firstname.val();
    //alert(form);
    var fname = $('#firstname').val();
    var lname = $('#lastname').val();
    var company = $('#company').val();
    var phone = $('#phone').val();
    var email = $('#email').val();
    var subject = $('#subject').val();
    var message = $('#message').val();
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ContactUs.asmx/SendFormSubmission",
        data: "{firstname:'" + fname.replace("'", "\\'") + "', lastname:'" + lname.replace("'", "\\'") + "',company:'" + company.replace("'", "\\'") + "', email:'" + email.replace("'", "\\'") + "',phone:'" + phone.replace("'", "\\'") + "',subject:'" + subject.replace("'", "\\'") + "',message:'" + message.replace("'", "\\'") + "'}",
        dataType: "json",
        success: function(data, textStatus, XMLHttpRequest) {
        $("#contactForm")[0].reset();
        $("#contactForm").hide()
        $("#ThankYou").html(fname + ", Thank you for submitting an inquiry form!<br />We will be in touch with you shortly. Please call if you need an immediate response.<br /><br />");
        $("#ThankYou").fadeIn();
            var timer = setInterval(function() {
                $("#ThankYou").hide();
                $("#contactForm").fadeIn();
            }, 5000);
        }
    });
}


$(document).ready(function() {
    $.preloadCssImages();

    //$(".workCapability a[title]").tooltip();
    //change to window.load at a later point
    // FADE IN, IE uses a page transition via a meta tag in the conditional comments
    var $container = $("#content");
    var w = $(window).width();
    var h = $(window).height();
    var contentWidth = $("#main").width();
    var remainder = w - contentWidth;

    repositionNav();

    //if (!$.browser.msie) {

    $container.fadeIn(1000);
    $("#leftNav").fadeIn(1000);
    $("#footer").fadeIn(1000);
    //$container.fadeOut(0);


    $(".fadeLink").live('click', function(e) {
        e.preventDefault();
        var link = this;
        var $wrapper = $("#wrapper");
        $wrapper.fadeOut(800, function() {
            document.location = link.href;
        });
    });
    //}

    $(".workCapability a[title]").tooltip('#tooltip');


    //setup cycling work section
    //$(function() {
    var $slideshows = $('.slideshow');

    $slideshows.each(function() {
        $(this).find('img:first').fadeIn(2000, function() {
            $(this).parent().cycle();
            $(this).parent().cycle('toggle');
        });
    });
    var eContainer = $('#cForm');
    var validator = $("#contactForm").validate({
        rules: {
            firstname: { required: true },
            lastname: { required: true },
            email: { required: true, email: true },
            message: { required: true }
        },
        submitHandler: function(form) {
            //form.submit();
            //$('#contactForm').hide();
            SubmitForm();
        }
        //errorPlacement: function(error, element) {element.parent().find('label').next().fadeIn('slow');},


    });

    var $bodyLinkImg = $("#content .section .sectionContainer .bodyNav a img");

    $.VS.global.Nav = new $.VS.Nav();

    $bodyLinkImg.attr("src", "images/arrow_inactive.gif");
    //$($bodyLinkImg[0]).attr("src", "images/arrow_active.gif");


    //$($bodyLinkImg[0]).removeClass("hoverswap");

    //$(window).resize(doResize);

    var 
	    resizeTimer = null,
	    resizeCookie = {
	        key: "pageSize",
	        val: null,
	        opts: {
	            path: "/"
	        },

	        init: function() {
	            this.val = this.get();
	        },

	        //returns null if cookie does not exist
	        get: function() {
	            return $.cookie(this.key);
	        },

	        set: function(val) {
	            this.val = val;
	            $.cookie(this.key, this.val, this.opts);
	        }
	    };
    resizeCookie.init();

    function doResize() {
        //clearTimeout(resizeTimer);
        //resizeTimer = setTimeout(resizeComplete, 200);
    }
    function resizeComplete() {

        var cont = $("#content");
        var $html = $("html");
        var $body = $("body");
        var winWidth = $(window).width();
        var scrollbarWidth = ($(window).height() < $("#content").height() + 148) ? $.ScrollBar.getWidth() : 0;
        var maxWidth = 1528;
        var medWidth = ($.browser.msie ? 1270 : 1280) - scrollbarWidth; //IE adds in extra padding
        var minWidth = 995;
        var cookieval = "";

        $body.css("overflowX", "hidden");

        if (winWidth > maxWidth) {
            cont.removeClass("small").removeClass("medium").addClass("large");
            $html.removeClass("small").removeClass("medium").addClass("large");
            cookieval = "large";
        } else if (winWidth >= medWidth) {
            cont.removeClass("small").removeClass("large").addClass("medium");
            $html.removeClass("small").removeClass("large").addClass("medium");
            cookieval = "medium";
        } else {
            cont.removeClass("large").removeClass("medium").addClass("small");
            $html.removeClass("large").removeClass("medium").addClass("small");
            cookieval = "small";
            $body.css("overflowX", "visible");
        }

        $(document).trigger("resizeComplete");
        resizeCookie.set(cookieval);
    }

    //resizeComplete();


    getTwitters('vsTweets', {
        id: 'vividsites',
        clearContents: false, // leave the original message in place
        count: 3,
        timeout: 10,
        onTimeout: function() {
            this.innerHTML = '<p class="georgia"><i>&nbsp;</i></p><p class="quiet">Twitter is down right now, but you can <a href="http://twitter.com/vividsites">follow us</a> if you like!</p>';
            //$("#leftNav").fadeIn(400);
        },
        callback: function() { //$("#leftNav").fadeIn(400); 
        },
        onTimeoutCancel: true, // don't allow twitter to finsih the job
        ignoreReplies: true,
        template: '<p><span class="georgia golder bottom"><i>%time%</i></span><span class="quiet"> &ndash; %text%</span></p>'
    });




});


$.VS.HideContent = function() {
    //hide as soon as possible for better transition
    //if (!$.browser.msie)
    $("#content").hide();
    $("#leftNav").hide();
    $("#footer").hide();
};

$.VS.ContactSection = function() {
    _adjust()

    $(window).resize(function() {
        _adjust();
    });

    function _adjust() {
        var $sectionContainer = $("#footer .sectionContainer");
        var $adjustedHeight = $(window).height() - $("#header").height() + 20;

        if ($sectionContainer.height() < $adjustedHeight) {
            $sectionContainer.height($adjustedHeight);
        }
    }

    var sendAMessage = $("#sendAMessageForm");
    var responseMsg = "";
    if (sendAMessage.get(0)) new $.AjaxForm(sendAMessage, {
        onSuccess: function(response) {
            responseMsg = $("#sentSuccessMesssage");
            $("#submit > input").val("Send Again");            
        },
        onError: function(response) {
            responseMsg = $("#sentErrorMesssage");
        },
        onComplete: function(response) {
            responseMsg.fadeIn('fast');
            setTimeout(function() { responseMsg.fadeOut('slow'); }, 5000);
        }
    });

}

$.VS.Nav = function(options) {
    var settings = $.extend({
        mode: ""
    }, options);

    // INITIALIATION
    var $menu = $("#menu");
    var $menuLinks = $("#menu a");
    var $seoLinks = $("#AboutSEOTextLeft a");
    var $content = $("#content");
    var $contentContainer = $("#contentContainer");
    var $bodyLinks = $("#content .section .sectionContainer .bodyNav a");
    var $bodyLinkImgs = $("#content .section .sectionContainer .bodyNav a img");

    $bodyLinks.click(scrollBodyPage);
    $seoLinks.click(scrollSEOPage);
    $menuLinks.click(scrollPage);

    //if we enter a URL containing a hash, make it active and scroll to it
    var $active = $("#menu a[href='" + window.location.hash + "']");
    $active.addClass("active");
    $(window).load(function() {
        $active.click();
    });

    var hash = window.location.hash;
    setInterval(function() {
        if (window.location.hash != hash) {
            hash = window.location.hash;
            $menuLinks.removeClass("active");
            $("#menu a[href='" + window.location.hash + "']").addClass("active");
            if (!$.browser.msie) {
                $("#menu a[href='" + window.location.hash + "']").click();
            }
        }
    }, 100);

    // private functions
    function scrollPage(e) {
        e.preventDefault(e);
        var idx = $(this).parent().index() - 1;

        $menuLinks.removeClass("active");
        $bodyLinkImgs.attr("src", "images/arrow_inactive.gif");
        $bodyLinkImgs.removeClass("hoverswapactive");


        $($bodyLinkImgs[idx]).attr("src", "images/arrow_active.gif");

        $bodyLinkImgs.removeClass("hoverswap");
        $bodyLinkImgs.addClass("hoverswap");
        $($bodyLinkImgs[idx]).removeClass("hoverswap");
        $($bodyLinkImgs[idx]).addClass("hoverswapactive");
        $($bodyLinkImgs[idx]).unbind();
        $($bodyLinkImgs[idx]).hover(
                    function() {
                        $(this).attr("src", $(this).attr("src").replace(/_active./, "_hover."));
                    },
                    function() {
                        $(this).attr("src", $(this).attr("src").replace(/_hover./, "_active."));
                    }
                );
        e.target.className += " active";
        //SCROLL HANDLING
        //get the href value
        var whereTo = $(this).attr("href");
        var targetLink = whereTo.substring(1); //remove hash
        var offset = parseInt($("#header").css("height"));

        //if there is a div on this page where id = whereTo, then scroll to it
        if ($("#" + targetLink).text() != '') {
            $.scrollTo($("#" + targetLink), 1000, { axis: 'y', easing: '',
                onAfter: function(whereTo) {
                    setTimeout(function() {
                        window.location.hash = targetLink;
                        hash = window.location.hash;
                    }, 100);
                }
            });
        } else {
            window.location = rootPath + whereTo;
        }
    }

    // private functions
    function scrollBodyPage(e) {
        e.preventDefault(e);

        $menuLinks.removeClass("active");
        //$($menuLinks[0]).addClass("active");
        $($bodyLinkImgs).attr("src", "images/arrow_inactive.gif");
        //$($bodyLinkImgs[0]).attr("src", "images/arrow_active.gif");
        $($bodyLinkImgs).unbind();
        $($bodyLinkImgs).hover(
                    function() {
                        $(this).attr("src", $(this).attr("src").replace(/_inactive./, "_hover."));
                    },
                    function() {
                        $(this).attr("src", $(this).attr("src").replace(/_hover./, "_inactive."));
                    }
                );


        //SCROLL HANDLING
        //get the href value
        var whereTo = $(this).attr("href");
        var targetLink = whereTo.substring(1); //remove hash
        var offset = parseInt($("#header").css("height"));

        //if there is a div on this page where id = whereTo, then scroll to it
        if ($("#" + targetLink).text() != '') {
            $.scrollTo($("#" + targetLink), 1000, { axis: 'y', easing: '',
                onAfter: function(whereTo) {
                    setTimeout(function() {
                        window.location.hash = targetLink;
                        hash = window.location.hash;
                    }, 100);
                }
            });
        } else {
            window.location = rootPath + whereTo;
        }
    }

    function scrollSEOPage(e) {
        e.preventDefault(e);

        var idx = $("#menu a[href='" + $(this).attr("href") + "']").parent().index() - 1;
        var whereTo = $(this).attr("href");
        var targetLink = whereTo.substring(1); //remove hash
        var offsetHeader = -118; //parseInt($("#header").css("height"));
        var isTargetMainSection = false;

        isTargetMainSection = targetLink == "AboutSEOText" || targetLink == "Work" || targetLink == "Capabilities" || targetLink == "News" || targetLink == "Contact";

        if (!isTargetMainSection && idx == 0) {
            idx = 3;
        }

        $menuLinks.removeClass("active");
        $bodyLinkImgs.attr("src", "images/arrow_inactive.gif");
        $bodyLinkImgs.removeClass("hoverswapactive");


        $($bodyLinkImgs[idx]).attr("src", "images/arrow_active.gif");

        $bodyLinkImgs.removeClass("hoverswap");
        $bodyLinkImgs.addClass("hoverswap");
        $($bodyLinkImgs[idx]).removeClass("hoverswap");
        $($bodyLinkImgs[idx]).addClass("hoverswapactive");
        $($bodyLinkImgs[idx]).unbind();
        $($bodyLinkImgs[idx]).hover(
                    function() {
                        $(this).attr("src", $(this).attr("src").replace(/_active./, "_hover."));
                    },
                    function() {
                        $(this).attr("src", $(this).attr("src").replace(/_hover./, "_active."));
                    }
                );
        $($menuLinks[idx + 1]).addClass("active");
        //SCROLL HANDLING
        //get the href value


        //if there is a div on this page where id = whereTo, then scroll to it
        if (isTargetMainSection) {
            if ($("#" + targetLink).text() != '') {
                $.scrollTo($("#" + targetLink), 1000, { axis: 'y', easing: '',
                    onAfter: function(whereTo) {
                        setTimeout(function() {
                            window.location.hash = targetLink;
                            hash = window.location.hash;
                        }, 100);
                    }
                });
            } else {
                window.location = rootPath + whereTo;
            }
        }
        else {
            if ($("#" + targetLink).text() != '') {
                $.scrollTo($("#" + targetLink), 1000, { axis: 'y', easing: '', offset: offsetHeader });
            } else {
                window.location = rootPath + whereTo;
            }
        }
    }

    var menuTimeout;
    //show all menu options onmouseover
    //only if it is an inner page
    if ($('body').hasClass("inner")) {
        $('#header').hover(function() {
            clearTimeout(menuTimeout);
            menuTimeout = setTimeout(expandMenu, 300);
        }, collapseMenu);
        $menuLinks.css("display", "none");
    }

    var contentContainerCap = parseInt($contentContainer.position().top) + 99;
    //alert(expandCap);

    //function for rollover
    function expandMenu() {
        $menu.stop();
        $menu.animate({ height: "75px" }, 400, function() {
            $menuLinks.css("display", "block");
            $menu.css('visibility', 'visible');
            $menu.animate({ opacity: 1 }, 200);
        });
        $contentContainer.stop();
        $contentContainer.animate({ paddingTop: contentContainerCap + "px" }, 400);
    }

    //function for rollout
    function collapseMenu() {
        clearTimeout(menuTimeout);
        $menu.stop();
        $contentContainer.stop();
        $menu.animate({ opacity: 0 }, 200, function() {
            $menuLinks.css("display", "none");
            $menu.animate({ height: "29px" }, 400);
            $contentContainer.animate({ paddingTop: (contentContainerCap - 46) + "px" }, 400);
        });
    }
};

(function($) {

    $.ScrollBar = {

        width: null,

        getWidth: function() {
            if (this.width == null) this.width = this.calculateWidth();

            return this.width;
        },

        calculateWidth: function() {

            var inner = document.createElement('p');
            inner.style.width = "100%";
            inner.style.height = "200px";

            var outer = document.createElement('div');
            outer.style.position = "absolute";
            outer.style.top = "0px";
            outer.style.left = "0px";
            outer.style.visibility = "hidden";
            outer.style.width = "200px";
            outer.style.height = "150px";
            outer.style.overflow = "hidden";
            outer.appendChild(inner);

            document.body.appendChild(outer);
            var w1 = inner.offsetWidth;
            outer.style.overflow = "scroll";
            var w2 = inner.offsetWidth;
            if (w1 == w2) w2 = outer.clientWidth;

            document.body.removeChild(outer);

            return (w1 - w2);
        }
    };

    $.CloseButton = {
        href: "/",
        anchor: "",
        id: "#pageClose",
        indexClasses: ["workIndex", "newsIndex"],
        cookieName: "lastIndex",
        cookieOpts: {
            path: "/"
        },
        init: function() {
            this.button = $(this.id);
            if (this.button.get(0)) {
                this.bindEvents();
            }

            if (this.href == "/") {
                //save the href
                this.href = this.button.attr('href');
            }
            this.setCookie();
        },

        bindEvents: function() {
            this.button.mousedown(function() {
                $(this).addClass("down");
            }).mouseup(function() {
                $(this).removeClass("down");
            }).mouseleave(function() {
                $(this).removeClass("down");
            });
        },

        setCookie: function() {
            var 
                $body = $("body"),
                isIndex = false;

            for (var i = 0; i < this.indexClasses.length; i++) {
                if ($body.hasClass(this.indexClasses[i])) {
                    $.cookie(this.cookieName, window.location.toString(), this.cookieOpts);
                    isIndex = true;
                    break;
                }
            }

            if (!isIndex) this.setHref();
        },

        setHref: function() {
            var 
	            lastIndex = $.cookie(this.cookieName);

            if (lastIndex != null) {
                this.button.attr("href", lastIndex);
                $.cookie(this.cookieName, null);
            }
        }
    };

    $.AjaxForm = function($form, params) {
        this.settings = $.extend({}, this.defaults, params);
        this.fields = $form.find("input:text, input:hidden, select, textarea");
        this.checkboxes = $form.find("input:checkbox");

        var self = this,
			method = this.settings.method || $form.attr("method"),
			url = this.settings.url || $form.attr("action"),
			stripTags = function() {
			    self.fields.each(function() {
			        var val = this.value;
			        this.value = val.replace(/</g, "&lt;").replace(/>/g, "&gt;");
			    });
			}

        $form.submit(function(e) {
            e.preventDefault();
            if (self.validate()) {
                stripTags();
                var datafields = $.param(self.fields);
                if (self.checkboxes.length)
                    datafields += "&" + self.stringifyCheckboxes();

                $.ajax({
                    url: url,
                    type: method,
                    data: datafields,
                    success: function(response) {
                        self.settings.onSuccess(response);
                    },
                    error: function(response) {
                        self.settings.onError(response);
                    },
                    complete: function(response) {
                        self.settings.onComplete(response);
                    }
                });
            }

        });

    };
    $.AjaxForm.prototype = {
        defaults: {
            requiredClass: "required",
            containerSelectors: ".textBox, .dropdown",
            errorSelector: ".error_state",
            errorClass: "error_state_active",
            onSuccess: function() { },
            onError: function() { },
            onComplete: function() { }
        },

        validate: function() {
            var self = this, errs = 0;

            this.fields.each(function() {
                var $this = $(this), err = 1;
                if (!$this.hasClass(self.settings.requiredClass) || self.checkSpecific($this)) {
                    $this.parents(self.settings.containerSelectors).find(self.settings.errorSelector).removeClass(self.settings.errorClass);
                    err = 0;
                }

                if (err) {
                    $this.parents(self.settings.containerSelectors).find(self.settings.errorSelector).addClass(self.settings.errorClass);
                    errs++;
                }
            });

            return errs ? false : true;
        },

        checkDefault: function($field) {
            return !(/[<>]+/.test($field.val()));
        },

        checkSpecific: function($field) {
            return (this.getCheckRegExp($field).test($field.val()));
        },

        getCheckRegExp: function($field) {
            var regExp = /.+/;
            if ($field.hasClass('email')) regExp = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+$/;
            else if ($field.hasClass('alpha')) regExp = /^[a-zA-Z\s-'.]+$/;

            return regExp;
        },

        stringifyCheckboxes: function() {
            var str = "";
            this.checkboxes.each(function() {
                str += this.name + "=" + this.checked + "&";
            });

            return str.replace(/&$/, '');
        }
    };

    $.CheckboxManager = function(params) {
        var self = this, _checkboxes = {}, _count = 0, _liveClass = 'jq-cb';

        this.defaults = {
            checkedClass: 'cb-checked',
            focusedClass: 'cb-focused',
            container: 0,
            changeCallback: false
        }

        var settings = $.extend({}, self.defaults, params),
			liveInput = '.' + _liveClass + ' input';

        //start:events
        $('.' + _liveClass).live('click', function(e) {
            e.preventDefault();

            while (e.target.className.indexOf(_liveClass) == -1) {
                e.target = e.target.parentNode;
            }

            _toggle(_checkboxes[$(e.target).data('Id')]);

        });


        $(liveInput).live('keyup', function(e) {
            e.preventDefault();
            var $this = $(e.target);
            while (!$this.hasClass(_liveClass)) {
                $this = $this.parent();
            }

            if (e.keyCode == 32) {
                _toggle(_checkboxes[$this.data('Id')]);
            } else if (e.keyCode == 13) {
                var $form = $this.parents('form').eq(0);
                if ($form) {
                    $form.submit();
                }
            }
        });
        //end:events

        //start:public
        this.addCheckbox = function(checkbox) {
            checkbox.Id = _count;
            checkbox.settings.container.data("Id", _count);
            checkbox.settings.container.addClass(_liveClass);
            _checkboxes[_count] = checkbox;
            _count++;
        }
        //end:public

        //start:private
        function _toggle(checkbox) {
            if (checkbox.input.checked == true) {
                checkbox.input.checked = false;
                checkbox.settings.container.removeClass(checkbox.settings.checkedClass);
            } else {
                checkbox.input.checked = true;
                checkbox.settings.container.addClass(checkbox.settings.checkedClass);
            }

            checkbox.input.focus();

            if (typeof checkbox.settings.callBack == 'function') {
                checkbox.callBack();
            }
        }
        //end:private
    }

    /*
    params requirements {container:jQueryObj, manager:string}
    settings public to allow use in CheckboxManager
    */
    $.Checkbox = function(params) {

        if (!window[params.manager]) {
            window[params.manager] = new $.CheckboxManager();
        }

        this.settings = $.extend({}, window[params.manager].defaults, params);
        if (!this.settings.container || !this.settings.container.get(0)) return;

        var self = this, input = this.settings.container.find('input');

        this.input = input.get(0);

        if (this.input.checked == true) {
            this.settings.container.addClass(this.settings.checkedClass);
        }

        //Excluded from the manager since live does not currently support focus/blur
        input.focus(function() {
            self.settings.container.addClass(self.settings.focusedClass);
        }).blur(function() {
            self.settings.container.removeClass(self.settings.focusedClass);
        });

        window[params.manager].addCheckbox(this);
    };

    $.Overlay = function(params) {

        var 
			self = this,
			scrollTimeout,
			resizeTimeout;

        this.settings = $.extend({}, this.defaults, params);
        this.window = $(window);
        this.body = $(document.body);
        this.container = $("<div id='overlayContainer' class='overlay'></div>");
        this.open = 0;

        if (this.settings.content) {
            this.content = this.settings.content;
            this.appendContent();
        }

        //Events!
        this.window.resize(function() {
            if (self.open) {
                clearTimeout(resizeTimeout);
                resizeTimeout = setTimeout(function() {

                    if (self.blocker) {
                        self.adjustBlocker();
                    }

                    self.center(self.settings.animate);
                }, 350);
            }
        });

        if (this.settings.followScroll) {
            this.window.scroll(function() {
                if (self.open) {
                    clearTimeout(scrollTimeout);
                    scrollTimeout = setTimeout(function() {
                        self.center(self.settings.animate);
                    }, 350);
                }
            });
        }

        this.settings.initCallback();
    };
    $.Overlay.prototype = {

        defaults: {
            content: 0,
            zIndex: 10000,
            followScroll: 1,
            animate: 1,
            animateDuration: 500,
            animateEasing: "easeout",
            fade: 0,
            fadeDuration: 500,
            blocker: 1,
            blockerColor: "#000000",
            blockerOpacity: 0.35,
            blockerAdjust: {
                width: 0,
                height: 0
            },
            initCallback: function() { },
            showCallback: function() { },
            hideCallback: function() { },
            closeButton: "<a href='javascript:void(0)' class='close_button'>close</a>"
        },

        show: function() {

            if (this.settings.blocker) {
                this.createBlocker();
            }

            this.body.append(this.container);
            this.container.css({ zIndex: this.settings.zIndex, position: "absolute" });
            this.center();

            if (this.settings.fade) {
                this.fadeIn();
            }
            else {
                this.settings.showCallback();
            }

            this.bindCloseButton();
            this.open = 1;
            return this;

        },

        hide: function() {

            if (this.settings.fade) {
                this.fadeOut();

            }
            else {
                this.container.remove();

                if (this.blocker) {

                    this.blocker.remove();

                }

                this.settings.hideCallback();
            }

            this.open = 0;
            return this;

        },

        //accepts html string or $ extended element
        setContent: function(content) {
            this.content = content;
            this.appendContent();

            return this;
        },

        //should be called when overlay is already showing
        //will transition to the new content without dropping the blocker
        updateContent: function(content) {
            var self = this;
            this.content = content;

            if (this.settings.fade) {
                this.fadeOutContainer(function() {
                    self.appendContent();
                    self.bindCloseButton();
                    self.fadeInContainer();
                });
            }
            else {
                this.appendContent();
                this.bindCloseButton();
            }

            return this;
        },

        appendContent: function() {
            var html = "";

            if (typeof (this.content) == "string") {
                html = this.content;
            }
            else {
                html = this.content.html();
            }

            this.container.html(html + this.settings.closeButton);
        },

        center: function(animate) {
            var 
				cWidth = this.container.outerWidth(),
				cHeight = this.container.outerHeight(),
				scrollTop = this.settings.followScroll ? this.window.scrollTop() : 0,
				scrollLeft = this.settings.followScroll ? this.window.scrollLeft() : 0,
				top = (this.window.height() / 2) - (cHeight / 2) + scrollTop,
				left = (this.window.width() / 2) - (cWidth / 2) + scrollLeft,
				cTop = scrollTop, cLeft = scrollLeft;

            if (top > 0) {
                cTop = top;
            }

            if (left > 0) {
                cLeft = left;
            }

            if (animate) {
                this.container.stop();
                this.container.animate({
                    left: cLeft,
                    top: cTop
                }, {
                    duration: this.settings.animateDuration,
                    easing: this.settings.animateEasing
                });
            }
            else {
                this.container.css({
                    left: cLeft,
                    top: cTop
                });
            }
        },

        createBlocker: function() {
            this.body.append("<div id=\"overlayBlocker\"></div>");
            this.blocker = $("#overlayBlocker");
            this.blocker.css({
                backgroundColor: this.settings.blockerColor,
                opacity: this.settings.blockerOpacity,
                position: 'absolute',
                top: 0,
                left: 0,
                zIndex: this.settings.zIndex - 1
            });

            this.adjustBlocker();
        },

        adjustBlocker: function() {
            var 
				bWidth = this.body.outerWidth() + this.settings.blockerAdjust.width,
				bHeight = this.body.outerHeight() + this.settings.blockerAdjust.height,
				width = (bWidth > this.window.width()) ? bWidth : "100%",
				height = (bHeight > this.window.height()) ? bHeight : "100%";

            this.blocker.width(width).height(height);
        },

        fadeIn: function() {
            var self = this;
            this.fadeInContainer(function() {
                self.settings.showCallback();
            });

            if (this.blocker) {
                this.blocker.css({ opacity: 0 }); //using fadeTo, so instead of display:none set opacity to 0
                this.blocker.fadeTo(this.settings.fadeDuration, this.settings.blockerOpacity);
            }
        },

        fadeOut: function() {
            var self = this;
            this.fadeOutContainer(function() {
                self.container.remove();
                self.settings.hideCallback();
            });

            if (this.blocker) {
                this.blocker.fadeOut(this.settings.fadeDurtaion, function() {
                    self.blocker.remove();
                });
            }
        },

        fadeInContainer: function(callback) {
            this.container.css({ display: 'none' }); //hide initially so it can fade in
            this.container.fadeIn(this.settings.fadeDuration, callback);
        },

        fadeOutContainer: function(callback) {
            this.container.fadeOut(this.settings.fadeDuration, callback);
        },

        bindCloseButton: function() {
            var self = this;
            this.container.find('.close_button').click(function(e) {
                e.preventDefault();
                self.hide();
            });
        }

    };


    $.cookie = function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // NOTE Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = $.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };

    $.QueryString = function() {
        this._getQs();
    };
    $.QueryString.prototype = {
        _getQs: function() {
            this.qs = {};
            if (window.location.search.length > 0) {
                var qs = window.location.search.substr(1), pairs = qs.split('&'), kvp = {};
                for (var i = 0; i < pairs.length; i++) {
                    var pair = pairs[i].split('='), key = decodeURIComponent(pair[0]), val = decodeURIComponent(pair[1]);
                    kvp[key] = val;
                }
                this.qs = kvp;
            }
        },
        get: function(key) {
            if (typeof key == "undefined") return this.qs;
            return (typeof this.qs[key] != "undefined") ? this.qs[key] : "";
        },
        set: function(key, val) {
            this.qs[key] = val;
            return this;
        },
        remove: function(key) {
            if (typeof this.qs[key] != "undefined") {
                this.qs[key] = null;
                delete this.qs[key];
            }
            return this;
        },
        stringify: function() {
            var str = "";
            for (var key in this.qs) {
                str += encodeURIComponent(key) + "=" + encodeURIComponent(this.qs[key]) + "&";
            }
            return str.length ? "?" + str.replace(/&$/, '') : "";
        },
        reset: function() {
            this._getQs();
            return this;
        },
        clear: function() {
            this.qs = {};
            return this;
        }
    };
})(jQuery);

