var Page = null;
$(document).ready(function () {
    Page = new MainPage();
    Page.OnReady()
});

function twitterCallback() {
    Page.twitterCallback()
}
function MainPage() {
    var h = null,
        $Content = null,
        $CDDays = null,
        $CDHours = null,
        $CDMins = null,
        $CDSecs = null,
        $Bg = null;
    $BgContainer = null, BgRatio = [], LastImageLoaded = false, CurrentImage = 0, Resize = false, Reg_Email = /^\w+([\-\.]\w+)*@([a-z0-9]+(\-+[a-z0-9]+)?\.)+[a-z]{2,5}$/i;
    this.OnReady = function () {
        h = $(window);
        $Content = $('#Content');
        InitBackgrounds();
        h.resize(function () {
            OnResize()
        }).trigger("resize");
        Cufon.replace('p,a,#twitter_update_list');
        SetupTwitter(TwitterID, TwitterCount);
        Contact();
        Subscribe();
        SlideLeftContainers();
        SocialLinks();
        Countdown();
        BarAnimation()
    };

    function BarAnimation() {
        var a = $('#ProgressBar .BarRight'),
            $Text = $('#ProgressBar .Text');
        $Text.hide();
        a.width(0);
        a.delay(1000).animate({
            width: PercentDone
        }, 'slow');
        $Text.delay(1500).fadeIn('slow')
    }
    function SlideLeftContainers() {
        var a = $('#contactLink'),
            $SubContainers = $('#LeftContainer .SubContainer'),
            SubContainerW = $SubContainers.eq(0).width(),
            $backLink = $('#Contact .GetBack');
        a.click(function () {
            $SubContainers.eq(0).animate({
                left: -SubContainerW
            }, ContactSlideSpeed);
            $SubContainers.eq(1).animate({
                left: 0
            }, ContactSlideSpeed)
        });
        $backLink.click(function () {
            $SubContainers.eq(0).animate({
                left: 0
            }, ContactSlideSpeed);
            $SubContainers.eq(1).animate({
                left: SubContainerW
            }, ContactSlideSpeed)
        })
    }
    function SocialLinks() {
        var b = $('#Footer .Social li');
        b.each(function (i) {
            var a = $(this),
                $imgs = a.find('img');
            if ($imgs.length < 2) return;
            a.hover(function () {
                $imgs.eq($imgs.length - 1).fadeIn(SocialLinkFadeSpeed)
            }, function () {
                $imgs.eq($imgs.length - 1).fadeOut(SocialLinkFadeSpeed)
            })
        })
    }
    function SetupTwitter(a, b) {
        $('body').append('<script type="text/javascript" src="scripts/blogger.js"></script>' + '<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/' + a + '.json?callback=twitterCallback2&count=' + b + '"></script>')
    }
    this.twitterCallback = function () {
        Cufon.refresh()
    };

    function CompareArray(a, b) {
        var c = true;
        $.each(a, function (i, v) {
            if (v != b) {
                c = false;
                return false
            }
        });
        return c
    }
    function Countdown() {
        $CDDays = $('#CountdownContainer .Days .Inner');
        $CDHours = $('#CountdownContainer .Hours .Inner');
        $CDMins = $('#CountdownContainer .Minutes .Inner');
        $CDSecs = $('#CountdownContainer .Seconds .Inner');
        $.get('lib/launchDate.php', function (a) {
            if (isNaN(parseInt(a))) return;
            $('#LeftContainer .SubContainer').eq(0).append('<div id="DummyCountdown" class="hidden"></div>');
            $('#DummyCountdown').countdown({
                until: a,
                onTick: CountdownTick
            })
        })
    }
    function CountdownDigits(a) {
        var b = '';
        for (i = 0; i < a.length; i++) {
            b += '<div class="d' + a.charAt(i) + '"></div>'
        }
        return b
    }
    function CountdownTick(a) {
        $CDDays.html(CountdownDigits(ZeroPad(a[3], 2)));
        $CDHours.html(CountdownDigits(ZeroPad(a[4], 2)));
        $CDMins.html(CountdownDigits(ZeroPad(a[5], 2)));
        $CDSecs.html(CountdownDigits(ZeroPad(a[6], 2)))
    }
    function ZeroPad(a, b) {
        var s = a + "";
        while (s.length < b) s = "0" + s;
        return s
    }
    function Subscribe() {
        var e = $('#Subscribe'),
            $Form = e.find('form'),
            $Button = $Form.find('.Button'),
            $ButtonImg = $Button.find('img'),
            $Submit = $Button.find('input'),
            $Inputs = $Form.find('input[type="text"]'),
            $EmailError = $Form.find('.NotValidError'),
            $LoadingImg = e.find('.Feedback .Loading'),
            $FeedbackErr = e.find('.Feedback .Error'),
            $FeedbackSuccess = e.find('.Feedback .Success'),
            Action = $Form.attr('action'),
            ValidFields = [$Inputs.length];
        $Submit.hover(function () {
            $ButtonImg.fadeIn(SubmitButtonFadeSpeed)
        }, function () {
            $ButtonImg.fadeOut(SubmitButtonFadeSpeed)
        });
        $FeedbackErr.find('a').click(function () {
            $FeedbackErr.hide();
            $Submit.click();
            return false
        });
        $Submit.click(function () {
            $Inputs.blur();
            if (!CompareArray(ValidFields, true)) return false;
            $Form.hide();
            $LoadingImg.fadeIn('fast');
            var c = $Form.find('input[name="Email"]').val();
            $.ajax({
                type: "POST",
                url: Action,
                data: {
                    action: 'subscribe',
                    email: c
                },
                error: function (a, b) {
                    $LoadingImg.hide();
                    $FeedbackErr.fadeIn('fast')
                },
                success: function (a) {
                    $LoadingImg.hide();
                    if (a === 'OK') $FeedbackSuccess.fadeIn('fast');
                    else $FeedbackErr.fadeIn('fast')
                }
            });
            return false
        });
        $Inputs.each(function (i) {
            var b = $(this);
            var c = b.attr('name');
            var d = b.val();
            b.focus(function () {
                if (b.val() == d) {
                    b.val('')
                }
            });
            b.blur(function () {
                var a = $.trim(b.val());
                if (c == 'Email') {
                    if (a.length < 1) {
                        ValidFields[i] = false
                    } else {
                        if (!Reg_Email.test(a)) {
                            $EmailError.fadeIn('slow');
                            ValidFields[i] = false
                        } else {
                            $EmailError.fadeOut('fast');
                            ValidFields[i] = true
                        }
                    }
                }
                if (a.length < 1) b.val(d)
            })
        })
    }
    function Contact() {
        var f = $('#Contact');
        if (f.length < 1) return;
        var g = $('#Contact form'),
            $Button = g.find('.Button'),
            $ButtonImg = $Button.find('img'),
            $Submit = $Button.find('input'),
            $Inputs = g.find('input[type="text"],textarea'),
            Action = g.attr('action'),
            ValidFields = [$Inputs.length],
            $Loading = g.find('.Feedback .Loading'),
            $FeedbackErr = g.find('.Feedback .Error'),
            $FeedbackSuccess = g.find('.Feedback .Success');
        $FeedbackErr.find('a').click(function () {
            $FeedbackErr.hide();
            $Submit.click();
            return false
        });
        $Submit.hover(function () {
            $ButtonImg.fadeIn(SubmitButtonFadeSpeed)
        }, function () {
            $ButtonImg.fadeOut(SubmitButtonFadeSpeed)
        });
        $Submit.click(function () {
            var c = true;
            $Inputs.blur();
            if (!CompareArray(ValidFields, true)) return false;
            $Loading.fadeIn('fast');
            var d = g.find('input[name="Name"]'),
                $Email = g.find('input[name="Email"]'),
                $Message = g.find('textarea');
            var e = d.val(),
                Email = $Email.val(),
                Message = $Message.val();
            if (!$Submit.hasClass('hidden')) {
                d.addClass('hidden').parent().append('<div class="Replace">' + e + '</div>');
                $Email.addClass('hidden').parent().append('<div class="Replace">' + Email + '</div>');
                $Message.addClass('hidden').parent().append('<div class="Replace">' + Message.replace(/\n/g, '<br/>') + '</div>');
                $Submit.addClass('hidden')
            }
            $.ajax({
                type: "POST",
                url: Action,
                data: {
                    name: e,
                    email: Email,
                    message: Message
                },
                error: function (a, b) {
                    $Loading.hide();
                    $FeedbackErr.fadeIn('fast')
                },
                success: function (a) {
                    $Loading.hide();
                    if (a === 'OK') $FeedbackSuccess.fadeIn('fast');
                    else $FeedbackErr.fadeIn('fast')
                }
            });
            return false
        });
        $Inputs.each(function (i) {
            var b = $(this);
            var c = b.attr('name');
            var d = b.val();
            b.focus(function () {
                if (b.val() == d) {
                    b.val('')
                }
            });
            b.blur(function () {
                var a = $.trim(b.val());
                if (c == 'Email') {
                    if (!Reg_Email.test(a) || a == d) {
                        b.next().fadeIn('fast');
                        ValidFields[i] = false
                    } else {
                        b.next().fadeOut('fast');
                        ValidFields[i] = true
                    }
                } else if (c == 'Name') {
                    if (a.length < 1 || a == d) {
                        b.next().fadeIn('fast');
                        ValidFields[i] = false
                    } else {
                        b.next().fadeOut('fast');
                        ValidFields[i] = true
                    }
                } else if (c == 'Message') {
                    if (a.length < 1 || a == d) {
                        b.next().fadeIn('fast');
                        ValidFields[i] = false
                    } else {
                        b.next().fadeOut('fast');
                        ValidFields[i] = true
                    }
                }
                if (a.length < 1) b.val(d)
            })
        })
    }
    function ImageLoaded(a, b) {
        if (a.complete === true) {
            b();
            return true
        }
        $(a).bind('load', function () {
            b()
        });
        if (a.complete === undefined) {
            var c = a.src;
            a.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
            a.src = c
        }
        return false
    }
    function InitBackgrounds() {
        $BgContainer = $("#BackgroundContainer");
        $Bg = $('#BackgroundContainer img');
        if ($BgContainer.length < 1 || $Bg.length < 1) return;
        $Bg.each(function (i) {
            var a = $(this);
            BgRatio[i] = a.width() / a.height()
        });
        $Bg.hide();
        ImageLoaded($Bg.get(0), function () {
            $Bg.eq(0).fadeIn('slow');
            if ($Bg.length > 1) setTimeout(RotateImages, BgChangeInterval)
        })
    }
    function RotateImages() {
        var a = CurrentImage;
        if (CurrentImage + 1 == $Bg.length) CurrentImage = 0;
        else CurrentImage++;
        ImageLoaded($Bg.get(CurrentImage), function () {
            $Bg.eq(a).hide();
            $Bg.eq(CurrentImage).fadeIn('slow');
            setTimeout(RotateImages, BgChangeInterval)
        })
    }
    function OnResize() {
        var b = h.width() / h.height(),
            BgWidth = 0,
            BgHeight = 0;
        $BgContainer.width(h.width()).height(h.height());
        $Bg.each(function (i) {
            var a = $(this),
                Diff = 0;
            if (isNaN(BgRatio[i]) && a.height() > 0) BgRatio[i] = a.width() / a.height();
            if (b < BgRatio[i]) {
                BgHeight = h.height();
                BgWidth = parseInt(BgHeight * BgRatio[i])
            } else {
                BgWidth = h.width();
                BgHeight = parseInt(BgWidth / BgRatio[i])
            }
            if (BgHeight >= h.height()) {
                Diff = parseInt((BgHeight - h.height()) * 0.5);
                a.css('top', '-' + Diff + 'px')
            } else if (BgHeight < h.height()) {
                Diff = parseInt((h.height() - BgHeight) * 0.5);
                a.css('top', Diff + 'px')
            }
            if (BgWidth >= h.width()) {
                Diff = parseInt((BgWidth - h.width()) * 0.5);
                a.css('left', '-' + Diff + 'px')
            } else if (BgWidth < h.width()) {
                Diff = parseInt((h.width() - BgWidth) * 0.5);
                a.css('left', Diff + 'px')
            }
            a.width(BgWidth).height(BgHeight)
        });
        $BgContainer.width(h.width()).height(h.height());
        Resize = true
    }
}
