var Page = null;

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

function twitterCallback() {
    Page.twitterCallback();
}

function MainPage() {

    var $Window = null,

        $Content = null,
        $CDDays  = null,//Countdown days
        $CDHours = null,//Countdown Hours
        $CDMins  = null,//Countdown Minutes
        $CDSecs  = null, //Countdown Seconds
        //Background vars
        $Bg = null;
        $BgContainer = null,
        BgRatio = [], //Array of background ratios
        LastImageLoaded = false,
        CurrentImage = 0, 
        Resize  = false,
        Reg_Email = /^\w+([\-\.]\w+)*@([a-z0-9]+(\-+[a-z0-9]+)?\.)+[a-z]{2,5}$/i;


        this.OnReady = function () {

            $Window = $(window);
            $Content = $('#Content');

            InitBackgrounds();

            //Register event for resizing background
            $Window.resize(function () {
                OnResize();
            }).trigger("resize");

            //cufon
            Cufon.replace('p,a,#twitter_update_list');

            SetupTwitter(TwitterID, TwitterCount);
            Contact();
            Subscribe();
            SlideLeftContainers();
            SocialLinks();
            Countdown();
            BarAnimation();
        };

    function BarAnimation() {
        var $Bar  = $('#ProgressBar .BarRight'),
            $Text = $('#ProgressBar .Text');

        $Text.hide();
        $Bar.width(0);
        $Bar.delay(1000).animate({ width: PercentDone }, 'slow');
        $Text.delay(1500).fadeIn('slow');
    }

    function SlideLeftContainers() {

        var $contactLink   = $('#contactLink'),
            $SubContainers = $('#LeftContainer .SubContainer'),
            SubContainerW  = $SubContainers.eq(0).width(),
            $backLink      = $('#Contact .GetBack');

        $contactLink.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 $Links = $('#Footer .Social li');

        $Links.each(function (i) {
            var $me = $(this),
                $imgs = $me.find('img');

            if ($imgs.length < 2)
                return;

            $me.hover(
			function () {
			    $imgs.eq($imgs.length - 1).fadeIn(SocialLinkFadeSpeed);
			},
			function () {
			    $imgs.eq($imgs.length - 1).fadeOut(SocialLinkFadeSpeed);
			});

        });

    }

    function SetupTwitter(username, count) {
        $('body').append('<script type="text/javascript" src="scripts/blogger.js"></script>' + 
		'<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/'+ username +'.json?callback=twitterCallback2&count='+ count +'"></script>');
    }

    this.twitterCallback = function () {
        Cufon.refresh();
    };

    //Compares array with given value
    //and returns true if all indexes match, otherwise false
    function CompareArray(Array, Value) {
        var IsValid = true;
        //Check if all fields are valid
        $.each(Array, function (i, v) {
            if (v != Value) {
                IsValid = false;
                return false;
            }
        });

        return IsValid;
    }

    function Countdown() {

        $CDDays = $('#CountdownContainer .Days .Inner');
        $CDHours = $('#CountdownContainer .Hours .Inner');
        $CDMins = $('#CountdownContainer .Minutes .Inner');
        $CDSecs = $('#CountdownContainer .Seconds .Inner');

        //Use ajax get function to retrive launch date from the server
        $.get('lib/launchDate.php', function (data) {
            //Make sure the returned string is a number
            if (isNaN(parseInt(data)))
                return;

            $('#LeftContainer .SubContainer').eq(0).append('<div id="DummyCountdown" class="hidden"></div>');
            $('#DummyCountdown').countdown({ until: data, onTick: CountdownTick });
        });

    }

    function CountdownDigits(Value) {
        var Html = '';

        for (i = 0; i < Value.length; i++) {
            Html += '<div class="d' + Value.charAt(i) + '"></div>'
        }

        return Html;
    }

    function CountdownTick(periods) {
        $CDDays.html(CountdownDigits( ZeroPad(periods[3], 2) ));
        $CDHours.html(CountdownDigits( ZeroPad(periods[4], 2) ));
        $CDMins.html(CountdownDigits( ZeroPad(periods[5], 2) ));
        $CDSecs.html(CountdownDigits( ZeroPad(periods[6], 2) ));
    }

    function ZeroPad(num, size) {
        var s = num + "";
        while (s.length < size) s = "0" + s;
        return s;
    }

    function Subscribe() {

        var $Subscribe = $('#Subscribe'),
            $Form      = $Subscribe.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 = $Subscribe.find('.Feedback .Loading'),
            $FeedbackErr = $Subscribe.find('.Feedback .Error'),
            $FeedbackSuccess = $Subscribe.find('.Feedback .Success'),
            Action      = $Form.attr('action'),
            ValidFields = [$Inputs.length];

        $Submit.hover(function () {
            $ButtonImg.fadeIn(SubmitButtonFadeSpeed);
        },
        function () {
            $ButtonImg.fadeOut(SubmitButtonFadeSpeed);
        });

        //Retry link
        $FeedbackErr.find('a').click(function () {
            $FeedbackErr.hide();
            $Submit.click();
            return false;
        });

        $Submit.click(function () {
            //Force to validate inputs
            $Inputs.blur();

            //Check if all fields are valid
            if (!CompareArray(ValidFields, true)) return false;

            //Fade out the form
            $Form.hide();
            $LoadingImg.fadeIn('fast');

            var Email = $Form.find('input[name="Email"]').val();

            //Send post request
            $.ajax({

                type: "POST",
                url: Action,
                data: { action:'subscribe', email: Email },

            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 (Value.length < 1) {
                        ValidFields[i] = false;
                    }
                    else {
                        if (!Reg_Email.test(Value)) {
                            //Show error
                            $EmailError.fadeIn('slow');
                            ValidFields[i] = false;
                        }
                        else {
                            $EmailError.fadeOut('fast');
                            ValidFields[i] = true;
                        }
                    }
                }

                if (Value.length < 1)
                    $me.val(DefaultVal);
            }); //$me.blur
        });
    }

    function Contact() {
        var $Contact = $('#Contact');

        if ($Contact.length < 1)
            return;

        var $Form = $('#Contact form'),
            $Button    = $Form.find('.Button'),
            $ButtonImg = $Button.find('img'),
            $Submit    = $Button.find('input'),
            $Inputs       = $Form.find('input[type="text"],textarea'),
            Action        = $Form.attr('action'),
            ValidFields   = [$Inputs.length],
            $Loading      = $Form.find('.Feedback .Loading'),
            $FeedbackErr  = $Form.find('.Feedback .Error'),
            $FeedbackSuccess = $Form.find('.Feedback .Success');

        //Retry link
        $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 IsValid = true;

            $Inputs.blur();

            //Check if all fields are valid
            if (!CompareArray(ValidFields, true)) return false;

            $Loading.fadeIn('fast');

            var $Name = $Form.find('input[name="Name"]'),
                $Email = $Form.find('input[name="Email"]'),
                $Message = $Form.find('textarea');

            var Name = $Name.val(),
                Email = $Email.val(),
                Message = $Message.val();

            if (!$Submit.hasClass('hidden')) {
                $Name.addClass('hidden').parent().append('<div class="Replace">' + Name + '</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>');

                //Hide the submit button to prevent sending multiple requests
                $Submit.addClass('hidden');
            }

            //Send post request
            $.ajax({
                type: "POST",
                url: Action,
                data: { name: Name, email: Email, message: Message },
                error: function (xhr, error) {
                    $Loading.hide();
                    $FeedbackErr.fadeIn('fast');
                },
                success: function (msg) {
                    $Loading.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
                        $me.next().fadeIn('fast');
                        ValidFields[i] = false;
                    }
                    else {
                        $me.next().fadeOut('fast');
                        ValidFields[i] = true;
                    }
                }
                else if (type == 'Name') {
                    if (Value.length < 1 || Value == DefaultVal) {
                        $me.next().fadeIn('fast');
                        ValidFields[i] = false;
                    }
                    else {
                        $me.next().fadeOut('fast');
                        ValidFields[i] = true;
                    }
                }
                else if (type == 'Message') {
                    if (Value.length < 1 || Value == DefaultVal) {
                        $me.next().fadeIn('fast');
                        ValidFields[i] = false;
                    }
                    else {
                        $me.next().fadeOut('fast');
                        ValidFields[i] = true;
                    }
                }

                if (Value.length < 1) 
                    $me.val(DefaultVal);

            }); //$me.blur
        });

    }

    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 || image.complete === false) {
            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.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.get(CurrentImage), function () {
            $Bg.eq(Last).hide();
            $Bg.eq(CurrentImage).fadeIn('slow');
            setTimeout(RotateImages, BgChangeInterval);
        });
    }

    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[i] = $me.width() / $me.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 flag for reseting position in IE6 
        Resize = true;
    }

}
