
$(document).ready(function () {
    var Page = new MainPage();
    Page.OnReady();
});

function MainPage() {

    var $Window = null,

        $Overlay = null,
        $Content = null,
        $Debug = null,
        //Background vars
        $Bg = null;
        $BgContainer = null,
        BgRatio = [], //Array of background ratios
        BgChangeInterval = 5000, //Time between changing background images (in milliseconds)
        LastImageLoaded = false,
        CurrentImage = 0, 
        Resize  = false,
        OverlayVisible = false,
        Reg_Email = /^\w+([\-\.]\w+)*@([a-z0-9]+(\-+[a-z0-9]+)?\.)+[a-z]{2,5}$/i;


    this.OnReady = function () {

        $Window = $(window);
        $Overlay = $('#Overlay');
        $Content = $('#Content');

        InitBackgrounds();

        //Register event for resizing background
        $Window.resize(function () {
            OnResize();
        }).trigger("resize");

        //Setup Forms
        InitContact();
        InitMap();

        //Setup cufon
        Cufon.replace('h1', { fontFamily: 'Acens' });
        Cufon.replace('h2,p', { fontFamily: 'TeXGyreAdventor' });
    };

    function ImageLoaded(image, callBack) {

        if (image.complete === true) {
            callBack();
            return true;
        }

        $(image).bind('load', function () {
            callBack();
        });

        // cached images don't fire load sometimes, so we reset src.
        if (image.complete === undefined) {
            var src = image.src;
            // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
            // data uri bypasses webkit log warning (thx doug jones)
            image.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
            image.src = src;
        }

        return false;
    }

    function InitBackgrounds() {
        
        $BgContainer = $("#BackgroundContainer");
        $Bg          = $('#BackgroundContainer img');

        if ($BgContainer.length < 1 || $Bg.length < 1)
            return;

        //Get ratios
        $Bg.each(function (i) {
            var $me = $(this);
            BgRatio[i] = $me.width() / $me.height();
        });

        //Hide all images
        $Bg.hide();

        //Fade in the first image
        ImageLoaded($Bg.eq(0).get(0), function () {
            $Bg.eq(0).fadeIn('slow');

            //Setup image rotator after first image is loaded
            if ($Bg.length > 1)
                setTimeout(RotateImages, BgChangeInterval);
        });
    }

    function RotateImages() {
        var Last = CurrentImage;

        if (CurrentImage + 1 == $Bg.length)
            CurrentImage = 0;
        else
            CurrentImage++;

        ImageLoaded($Bg.eq(CurrentImage).get(0), function () {
            $Bg.eq(Last).hide();
            $Bg.eq(CurrentImage).fadeIn('slow');
            setTimeout(RotateImages, BgChangeInterval);
        });
    }

    function InitMap() {
        var $MapImg     = $('#Identity .Map'),
            $MapOverlay = $Content.find('.Overlay');

        $('#Identity .MapLink').click(function () {
            OverlayVisible = true;
            $MapImg.fadeTo('fast', 0.99);
            $Overlay.show();
            $MapOverlay.show();
            $Overlay.width($Window.width()).height($Window.height());
            //IE6 position fix
            if ($.browser.msie === true && $.browser.version <= 6.0) { $Content.addClass('relative'); }

            return false;
        });

        $(document).click(function (e) {
            if (!OverlayVisible || $(e.target).hasClass('MapImage'))
                return;

            OverlayVisible = false;
            $MapImg.fadeOut('fast');
            $Overlay.hide();
            $MapOverlay.hide();
            //IE6 position fix
            if ($.browser.msie === true && $.browser.version <= 6.0) { $Content.removeClass('relative'); }
        });

    }

    function InitContact() {
        var $Contact = $('#Contact');

        if ($Contact.length < 1)
            return;

        var $Form = $('#ContactForm'),
            $SubmitBtn    = $Form.find('input[type="submit"]'),
            $Inputs       = $Form.find('input[type="text"],textarea'),
            $EmailError   = $Form.find('.EmailError'),
            $NameError    = $Form.find('.NameError'),
            $MessageError = $Form.find('.MessageError'), 
            Action        = $Form.attr('action'),
            ValidFields   = [$Inputs.length],
            $Feedback     = $Contact.find('.Feedback'),
            $LoadingImg   = $Feedback.find('.Loading'),
            $FeedbackErr     = $Feedback.find('.fbError'),
            $FeedbackSuccess = $Feedback.find('.Success');

        //Retry link
        $FeedbackErr.find('a').click(function () {
            $FeedbackErr.hide();
            $SubmitBtn.click();
            return false;
        });

        $SubmitBtn.click(function () {
            var IsValid = true;

            $Inputs.blur();

            //Check if all fields are valid
            $.each(ValidFields, function (i, v) {
                if (v == false) {
                    IsValid = false;
                    return false;
                }
            });

            if (!IsValid) return false;

            //Fade out the form
            $Form.hide();
            //Show progress bar
            $Feedback.show();
            $LoadingImg.fadeIn('fast');

            var Name = $Form.find('input[name="Name"]').val();
            var Email = $Form.find('input[name="Email"]').val();
            var Message = $Form.find('textarea').val();

            //Send post request
            $.ajax({
                type: "POST",
                url: Action,
                data: { name: Name, email: Email, message: Message },
                error: function (xhr, error) {
                    $LoadingImg.hide();
                    $FeedbackErr.fadeIn('fast');
                },
                success: function (msg) {
                    $LoadingImg.hide();
                    if (msg === 'OK')
                        $FeedbackSuccess.fadeIn('fast');
                    else
                        $FeedbackErr.fadeIn('fast');
                }
            });

            return false;
        });

        $Inputs.each(function (i) {
            var $me = $(this);
            var type = $me.attr('name');
            var DefaultVal = $me.val();

            //Control got focus
            $me.focus(function () {
                if ($me.val() == DefaultVal) {
                    $me.val('');
                }
            }); //$me.focus

            //Control lost focus
            $me.blur(function () {
                var Value = $.trim($me.val());

                //Validate by type
                if (type == 'Email') {
                    if (!Reg_Email.test(Value) || Value == DefaultVal) {
                        //Show error
                        $EmailError.fadeIn('fast');
                        ValidFields[i] = false;
                    }
                    else {
                        $EmailError.fadeOut('fast');
                        ValidFields[i] = true;
                    }
                }
                else if (type == 'Name') {
                    if (Value.length < 1 || Value == DefaultVal) {
                        $NameError.fadeIn('fast');
                        ValidFields[i] = false;
                    }
                    else {
                        $NameError.fadeOut('fast');
                        ValidFields[i] = true;
                    }
                }
                else if (type == 'Message') {
                    if (Value.length < 1 || Value == DefaultVal) {
                        $MessageError.fadeIn('fast');
                        ValidFields[i] = false;
                    }
                    else {
                        $MessageError.fadeOut('fast');
                        ValidFields[i] = true;
                    }
                }

                if (Value.length < 1) 
                    $me.val(DefaultVal);

            }); //$me.blur
        });

    }

    function OnResize() {

        var ScreenRatio = $Window.width() / $Window.height(),
            BgWidth  = 0,
            BgHeight = 0;

        $BgContainer.width($Window.width()).height($Window.height());

        $Bg.each(function (i) {
            var $me = $(this),
                Diff = 0;

            //Skip resize function
            //if (!this.complete || this.complete === undefined)
                //return;

            if (isNaN(BgRatio[i]) && $me.height() > 0)
                BgRatio = $Bg.width() / $Bg.height();

            if (ScreenRatio < BgRatio[i]) {
                BgHeight = $Window.height();
                BgWidth = parseInt(BgHeight * BgRatio[i]);
            }
            else {
                BgWidth = $Window.width();
                BgHeight = parseInt(BgWidth / BgRatio[i]);
            }

            //Center the image
            if (BgHeight >= $Window.height()) {
                Diff = parseInt((BgHeight - $Window.height()) * 0.5);
                $me.css('top', '-' + Diff + 'px');
            }
            else if (BgHeight < $Window.height()) {
                Diff = parseInt(($Window.height() - BgHeight) * 0.5);
                $me.css('top', Diff + 'px');
            }

            if (BgWidth >= $Window.width()) {
                Diff = parseInt((BgWidth - $Window.width()) * 0.5);
                $me.css('left', '-' + Diff + 'px');
            }
            else if (BgWidth < $Window.width()) {
                Diff = parseInt(($Window.width() - BgWidth) * 0.5);
                $me.css('left', Diff + 'px');
            }

            $me.width(BgWidth).height(BgHeight);
        });

        $BgContainer.width($Window.width()).height($Window.height());

        //Set overlay size
        if (OverlayVisible)
            $Overlay.width($Window.width()).height($Window.height());

        //Set flag for reseting position in IE6 
        Resize = true;
    }

}
