(function(window){
    var app = {};

    var ServiceLut = {
            "github": {
                url: "/auth/github",
                width: 1000,
                height: 650
            },
            "facebook": {
                url: "/auth/facebook",
                width: 1010,
                height: 580
            },
            "twitter": {
                url: "/auth/twitter",
                width: 800,
                height: 460
            },
            "google": {
                url: "/auth/google",
                width: 800,
                height: 460
            },
            "bitbucket": {
                url: "/auth/bitbucket",
                width: 1050,
                height: 560
            }
        },
        def = "github",
        winSignin;

    app.screenshot = {
        opened : false,
        isopening : false,
        containers : {},
        init : function() {
            this.containers = {
                main    : document.getElementById("screenshot_banner"),
                info    : document.getElementById("ss_info"),
                picture : document.getElementById("ss_picture"),
                overlay : document.getElementById("ss_overlay")
            };

            $(this.containers.info).click(function(e) {
                app.screenshot.openclose(!app.screenshot.opened ? false : true);
            });
            $(this.containers.picture).click(function(e) {
                app.screenshot.openclose(!app.screenshot.opened ? false : true);
            });
        },
        openclose : function(opened) {
            var info = this.containers.info;
            if (!this.isopening) {
//                this.containers.info.className = opened ? "" : "opened";
                if(!opened)
                    $(info).addClass("opened");
                this.isopening = true;

                $('#screenshot_banner').animate({
                    width: opened ? '-=664' : '+=664'
                }, 800, function() {
                    app.screenshot.opened = !opened;
                    app.screenshot.isopening = false;
                    if(opened)
                        $(info).removeClass("opened");
                    else
                        $(info).addClass("opened");
                });
            }
        }
    };

    app.banner = {
        pathToImages : "style/images/logo/",
        banners : [
            {img : "mozilla.png"},
            {img : "arduino.png"},
            {img : "chrome.png"},
            {img : "apple.png"},

            {img : "mozilla2.png"},
            {img : "arduino2.png"},
            {img : "chrome2.png"},
            {img : "apple2.png"},

            {img : "mozilla3.png"},
            {img : "arduino3.png"},
            {img : "chrome3.png"},
            {img : "empty.png"}
        ],
        containersIds : [
            ["b1r1", "b2r1", "b3r1", "b4r1"],
            ["b1r2", "b2r2", "b3r2", "b4r2"]
        ],
        rowsIds : ["bannerr1", "bannerr2"],
        htmlNodes : {
            rows       : [],
            containers : [[], []]
        },
        init : function() {
            var timer      = null,
                currentRow = 0,
                rangeStart = 4, rangeStop = 8,
                _self      = this,
                htmlNodes  = this.htmlNodes;

//            if (this.banners.length < 5)
//                app.showAlert("", "Error:\n Please define more banners");

            //Get rows htmlNodes
            htmlNodes.rows = [document.getElementById(this.rowsIds[0]), document.getElementById(this.rowsIds[1])];

            //Get images htmlNodes
            for (var i = 0; i < 2; i++) {
                for (var j = 0; j < 4; j++) {
                    this.htmlNodes.containers[i][j] = document.getElementById(this.containersIds[i][j]);
                }
            }

            //Load images to next row to prepare them to display
            _self.fillRow(1, rangeStart, rangeStop);

            htmlNodes.rows[currentRow].style.display = "block";

            _self.fillRow(currentRow, 0, 4);

            clearInterval(timer);
            timer = setInterval(function() {
                $(htmlNodes.rows[currentRow]).fadeOut(function(){
                    htmlNodes.rows[currentRow].style.display = "none";

                    rangeStart = rangeStart + 4 >= _self.banners.length ? 0 : rangeStart + 4;
                    rangeStop  = rangeStop + 4 > _self.banners.length ? 4 : rangeStop + 4;

                    _self.fillRow(currentRow, rangeStart, rangeStop);

                    currentRow = currentRow == 1 ? 0 : 1;
                    htmlNodes.rows[currentRow].style.display = "block";
                    $(this).fadeIn()
                });

            }, 7000);
        },

        fillRow : function(index, indexStart, indexStop) {
            var htmlNodes = this.htmlNodes;
            for (var i = indexStart, j = 0; i < indexStop; i++) {
                htmlNodes.containers[index][j].src = this.pathToImages + this.banners[i].img;
                j++;
            }
        }
    };

    app.util = {
        toggleMore : function (el, trigger) {
            $("#" + el).slideToggle("slow");
            $(trigger).text($(trigger).text() == "Show less" ? "Show more" : "Show less");
        },
        setCookie : function(name, value, expires) {
            document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
        },
        getCookie : function(name) {
            var dc = document.cookie;
            var cname = name + "=";

            if (dc.length > 0) {
              begin = dc.indexOf(cname);
              if (begin != -1) {
                begin += cname.length;
                end = dc.indexOf(";", begin);
                if (end == -1) end = dc.length;
                return unescape(dc.substring(begin, end));
                }
              }
            return null;
        },
        delCookie : function(name) {
            document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT" + "; path=/";
        },
        closeErrorbox : function(btnX) {
            btnX.parentNode.parentNode.style.display = "none";
        }
    };

    // login methods
    app.signin = function(service, origin) {
    /*
        var mode    = mnuAuth.visible ? 1 : 2,
            pager   = mode === 1 ? pgAuth : pgReserve,
            sText   = service.charAt(0).toUpperCase() + service.substr(1)
            service = ServiceLut[service || def],
            h4      = document.getElementById("statusMsg" + mode);
        if (h4) {
            if (!h4.origText)
                h4.origText = h4.innerHTML;
            h4.innerHTML = h4.origText.replace("%s", sText);
        }
        pager.set(mode);
        crtOrigin = mode;
    */
        if($.browser.msie && location.href.indexOf("force") == -1) {
            window.location.href = '/notsupported.html';
            return;
        }
        var service = ServiceLut[service || def];
        var screenHeight = screen.height;
        var left = Math.round((screen.width / 2) - (service.width / 2));
        var top = 0;
        if (screenHeight > service.height)
            top = Math.round((screenHeight / 2) - (service.height / 2))

        winSignin = window.open('http://' + window.location.host + service.url + (origin ? "/" + origin : ""), "cloud9signin",
            "left=" + left + ",top=" + top + ",width=" + service.width + ",height=" + service.height +
            ",personalbar=0,toolbar=0,scrollbars=1,resizable=1"
        );

        winListener = setInterval(winCloseCheck, 1000);
        if (winSignin)
            winSignin.focus();
    };

    function winCloseCheck() {
        if (winSignin && !winSignin.closed)
            return;
        clearInterval(winListener);
    };

    app.openSignin = function() {
        window.location.href = "/signin.html";
    };

    app.login = function(username, password, type) {
        if($.browser.msie && location.href.indexOf("force") == -1) {
            window.location.href = '/notsupported.html';
            return;
        }
    //    alert("todo normal signin: <a:auth/> element?");
        var rememberLogin = $('#cbRememberLogin').hasClass('cbx-checked');;
        if (rememberLogin) {
            app.util.setCookie("username", username);
        }
        else {
            app.util.delCookie("username", username);
        }

        var _self = this;
        var data = {
            username: username,
            password: password
        };

        if (!type) {
            $('#btnSignIn').html('Signing in...').addClass('btn-disabled');
        }
        else if (type == "premium") {
            $('#btnSignIn2').html('Signing in...').addClass('btn-disabled');
            data.premiumcheck = true;
        };

        $.ajax({
            type     : "POST",
            url      : "/auth/login",
            data     : data,
            dataType: "text",
            error: function(e){
                if (!type) {
                    $('#btnSignIn').html('Sign in').removeClass('btn-disabled');
                }
                else {
                    $('#btnSignIn2').html('Sign in').removeClass('btn-disabled');
                }
                if(window.location.pathname.match(/\/(signin|activate|dashboard)\.html$/)) {
                    if (e.responseText.indexOf("is not active yet") == -1) {
                        _self.showSignInStatusMsg("Login failed", e.responseText, true);
                    }
                    else {
                        app.signinPage.switchSigninPage("barActivationLink");
                    }
                }
                /* rewrite if used again
                else if(window.location.pathname.match(/\/pricing\.html$/)) {
                    pgPremiumSignIn.set(3);
                    lblPrSiFailMsg.setAttribute("caption", "Login failed<br/><br/>" +
                        (extra.status == 403
                            ? "Username/Password combination does not exist or is incorrect"
                            : extra.message));
                }
                */
                return;
            },
            success: function(res) {
                if (!type)
                    $('#btnSignIn').html('Sign in').removeClass('btn-disabled');
                else
                    $('#btnSignIn2').html('Sign in').removeClass('btn-disabled');
                if (!type)
                    app.redirect();
                else if (type == "premium") {
                    //_self.startPremiumPayment();
                }
            }
        });
    }

    app.signinCallback = function(service, success, projects, blob, activecontext, contexts, members, msg, origin) {
        clearInterval(winListener);
        if (origin && origin == "link") {
            if (!success)
                return alert("There was a problem signing you in: " + msg);
            if (typeof winModalSignIn != "undefined")
                winModalSignIn.hide();

            app.redirect();
        }
        else if (origin && origin == "premium") {
            //app.startPremiumPayment();
        }
        else {
            if (success) {
                var params = app.getUrlParams();
                if (params.redirect)
                    window.location.href = params.redirect;
                else
                    app.redirect();
            }
            else {
                //display error
                if (window.location.pathname.match(/\/(signin|activate)\.html$/))
                    app.showSignInStatusMsg("Sign in failed", msg, true);
                else {
                    $('#errorRegister .errorboxContent span').html(msg);
                    return $('#errorRegister').show();
                }
            }
        }
    };

    app.forgetPassword = function(user) {
        var _self = this;
        $.ajax({
            type     : "POST",
            url      : "/auth/password",
            data     : {user: user},
            error    : function(e) {
                return _self.showSignInStatusMsg("Retrieve password failed", e.responseText, true);
            },
            success  : function(data) {
                _self.showSignInStatusMsg("Password sent", "You will receive an email with your new password soon", false);
            }
        });
    };

    app.sendActivationEmail = function(user) {
        var _self = this;
        $.ajax({
            type     : "POST",
            url      : "/auth/activationemail",
            data     : "user=" + user,
            error    : function(e){
                return _self.showSignInStatusMsg("No activation email sent", e.responseText, true);
            },
            success  : function(data) {
                _self.showSignInStatusMsg("Activation email sent", "You will receive an email with your activation link soon", false);
            }
        });
    };

    app.redirect = function() {
        if ($.browser.msie) {
            window.location.href = '/notsupported.html';
            return;
        }

        var params = app.getUrlParams();
        if (params.redirect)
            window.location.href = params.redirect;
        else if (window.location.pathname == "/" || window.location.pathname.match(/^\/(signin|activate|index)\.html$/))
            window.location.href = "/dashboard.html";
        else
            window.location.reload();
    };

    app.register = function() {
        var data =  {
            email: $('#inpEmail').val(),
            username: $('#inpUsername').val()
        };

        var params = app.getUrlParams();
        if (params.redirect) {
            data.redirect = params.redirect;
        }

        $('#errorRegister').hide();
        $('#registerBtn').html('Registering...').addClass('btn-disabled');
        $.ajax({
            type     : "POST",
            url      : "/auth/create",
            data     : data,
            error: function(e){
                $('#registerBtn').html('REGISTER').removeClass('btn-disabled');
                $('#errorRegister .errorboxContent span').html(e.responseText);
                return $('#errorRegister').show();
            },
            success: function(data) {
                $('#register_form').addClass("success");
                $('#registerBtn').html('REGISTER').removeClass('btn-disabled');
                app.registerPage.switchRegisterPage('barRegistered');
                $('#registrationEmail').html($('#inpEmail').val());
            }
        });
    };

    app.activate = function(callback) {
        var _self = this;
        var data =  "uid=" + activationuid + "&password="    + $('#inpPassword1').val();

        $('#errorRegister').hide();
        $('#activateBtn').html('Activating...').addClass('btn-disabled');
        $.ajax({
            type     : "POST",
            url      : "/api/context/activate",
            data     : data,
            error: function(e){
                $('#activateBtn').html('ACTIVATE').removeClass('btn-disabled');
                $('#errorRegister .errorboxContent span').html(e.responseText);
                return $('#errorRegister').show();
            },
            success: function(data) {
                $('#activateBtn').html('ACTIVATE').removeClass('btn-disabled');
                if (callback)
                    callback();
                else {
                    var params = app.getUrlParams();
                    
                    if (params.redirect)
                        window.location.href = params.redirect;
                    else
                        app.redirect();
                }
            }
        });
    };

    app.registerPage = {
        switchRegisterPage: function(page){
            $("#register_form .page").each(function(){
                $(this)[$(this).attr("id") == page ? "show" : "hide"]();
            });
        }
    };

    app.showSignInStatusMsg = function(title, msg, error) {
        var $barSignInStatusMsg = $('#barSignInStatusMsg'),
            pos = $("#signin_window").offset();

        var top  = pos.top + 5,
            left = pos.left - $barSignInStatusMsg.outerWidth() - 18;

        $('#lblSignInHeader').html(title).addClass(error ? "errorSignin" : "").removeClass(error ? "" : "errorSignin").show();
        $('#lblSignInStatus').html(msg);
        $barSignInStatusMsg.css({"top": top, "left": left}).show();
    };

    app.eventHandle = function(){
        $('body').bind({
            click: function(event){
                var $eventTrigger = $(event.target);
                if($eventTrigger.hasClass('registerBtn') && !$eventTrigger.hasClass('btn-disabled')) {
                    if(app.validateRegister.numberOfInvalids() == 0) {
                        $eventTrigger.html('Please wait...').addClass('btn-disabled');
                        app.register();
                    }
                    return false;
                }
                else if ($eventTrigger[0].id == 'forgetlink'){
                    app.signinPage.switchSigninPage('barForgetPass');
                    return false;
                }
                else if ($eventTrigger[0].id == 'resendactivation'){
                    app.signinPage.switchSigninPage('barActivationLink');
                    return false;
                }
                else if ($eventTrigger[0].id == 'btnRPCancel' || $eventTrigger[0].id == 'btnALCancel'){
                    app.signinPage.switchSigninPage('barSignIn');
                    return false;
                }
                else if ($eventTrigger[0].id == 'btnSignIn'){
                    app.signinPage.doSignIn();
                    if(app.validateSignin.numberOfInvalids() == 0) {
                        app.login($('#inpUsernameEmail').val(), $('#inpPassword').val())
                    }
                    return false;
                }
                else if ($eventTrigger[0].id == 'btnRP'){
                    app.signinPage.doPassReset();
                    if(app.validateForget.numberOfInvalids() == 0) {
                        app.forgetPassword($('#inpResetPassword').val())
                    }
                    return false;
                }
                else if ($eventTrigger[0].id == 'btnAL'){
                    app.signinPage.doResendConfirmation();
                    if(app.validateResendConfirmation.numberOfInvalids() == 0) {
                        app.sendActivationEmail($('#inpResendConfirmation').val());
                    }
                    return false;
                }
                else if ($eventTrigger.closest('.btn-github').length > 0 || $eventTrigger.hasClass('github-signin')){
                    app.signin('github');
                    return false;
                }
                else if ($eventTrigger.closest('.btn-bitbucket').length > 0 || $eventTrigger.hasClass('bitbucket-signin')){
                    app.signin('bitbucket');
                    return false;
                }
                else if ($eventTrigger.closest('.btn-twitter').length > 0 || $eventTrigger.hasClass('twitter-signin')){
                    app.signin('twitter');
                    return false;
                }
                else if ($eventTrigger.closest('.btn-facebook').length > 0 || $eventTrigger.hasClass('facebook-signin')){
                    app.signin('facebook');
                    return false;
                }
                else if ($eventTrigger.closest('.btn-google').length > 0 || $eventTrigger.hasClass('google-signin')){
                    app.signin('google');
                    return false;
                }
                else if ($eventTrigger[0].id == 'btnGotoSignin'){
                    window.location.href = "/signin.html";
                    return false;
                }
                else if($eventTrigger[0].id == 'btnActivate' && !$eventTrigger.hasClass('btn-disabled')) {
                    if(app.validateActivate.numberOfInvalids() == 0) {
                        if($eventTrigger.html() == "Activate and continue"){    
                            //it's a premium account
                            app.activate(function() {
                                $('#p-activate-account').fadeOut(200);
                                $('#p-premium-subscription-payment').fadeIn(200);
                            });
                        } else {                                                
                            //it's a free account
                            //go ahead and activate it
                            $eventTrigger.html('Please wait...').addClass('btn-disabled');
                            app.activate();
                        }
                    }
                    return false;
                }
                else if($eventTrigger[0].id == 'btnAlreadyActiveSignIn') {
                    $.ajax({
                        type     : "POST",
                        url      : "/auth/signout",
                        success: function(res) {
                            window.location.href = "/signin.html";
                        }
                    });
                    return false;
                }
            }
        });
        $('#activationlinkForm').bind({
            submit: function(){
                app.signinPage.doResendConfirmation();
                if(app.validateResendConfirmation.numberOfInvalids() == 0) {
                    app.sendActivationEmail($('#inpResendConfirmation').val());
                }
                return false;
            }
        });
    };

    app.chromeBar = function(){
        $('#chrome-bar').hide();
        if (navigator && navigator.userAgent && navigator.userAgent.indexOf('Chrome') != -1) {
            if ((typeof localStorage != 'object' || !localStorage.getItem('chrome-bar')) && !chrome.app.getDetails()) {
                if(chrome.app.isInstalled)
                    return;

                setTimeout(function() {
                    $('#chrome-bar').show().animate({'margin-top':0});
                    $('#chrome-install').click(function() {
                        window.open('https://chrome.google.com/webstore/detail/nbdmccoknlfggadpfkmcpnamfnbkmkcp');
                        return false;
                    });
                    $('#chrome-close').click(function() {
                        $('#chrome-bar').animate({'margin-top':-30});
                        localStorage.setItem('chrome-bar', false);
                    });
                }, 700);
            }
        }
    };

    app.chromeSuccess = function(){
        $('#chrome-bar').animate({'margin-top':-30});
        localStorage.setItem('chrome-bar', false);
    }

     app.getUrlParams = function() {
        var params = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            params.push(hash[0]);
            params[hash[0]] = decodeURIComponent(hash[1]);
        }
        return params;
    };
    
    app.switchToFree = function() {
        $.ajax({
            type     : "POST",
            url      : "/api/context/switchtofree",
            error: function(jqXHR, textStatus, errorThrown){
                setPremiumCookie();
                app.redirect();
            },
            success: function(data) {
                setPremiumCookie();
                app.redirect();
            }
        });
    };
    
    function setPremiumCookie() {
        var date = new Date();
        date.setDate(date.getDate() + 1);
        app.util.setCookie("premium_already_shown", date);
    };
    
    app.startPremiumPayment = function() {
        var service = {
            width: 1000,
            height: 650
        };
    
        var screenHeight = screen.height;
        var left = Math.round((screen.width / 2) - (service.width / 2));
        var top = 0;
        
        if (screenHeight > service.height) {
            top = Math.round((screenHeight / 2) - (service.height / 2));
        }
    
        winPayment = window.open("/order/step1/?sid=3&qty=1&origin=homepage", "paypalpayment",
            "left=" + left + ",top=" + top + ",width=" + service.width + ",height=" + service.height +
            ",personalbar=0,toolbar=0,scrollbars=1,resizable=1"
        );
    
        winListener = setInterval(winPayCloseCheck, 1000);
        
        if (winPayment) {
            winPayment.focus();
        }
        
        function winPayCloseCheck() {
            if (winPayment && !winPayment.closed)
                return;
            clearInterval(winListener);
        };
    }
    
    app.processPayment = function() {
        winPayment.close();
        var _self = this;
        $.ajax({
            url      : "order/step3",
            error: function(jqXHR, textStatus, errorThrown){
                
            },
            success: function(data) {
                if (!data || data.ack != 'Success') {
                    $("#p-premium-subscription-payment .p-title").html("Payment error");
                    $("#p-premium-subscription-payment .p-content .box1").addClass("error").html("There was an error processing your payment.");
                    $("#p-premium-subscription-payment .p-content .box2").html("<p>Please try again or contact support.</p>");
                    $("#payForPremium").html("Try again");
                    return;
                }

                //window.location.href = "/" + (typeof window.c9_username != "undefined" ? c9_username : "dashboard.html");
                app.redirect();
            }
        });
    }

    $(document).ready(function(){
        if (window.location.pathname == "/" || window.location.pathname == "/home" || window.location.pathname.indexOf("^/index") > -1) {
            $('#inpUsername').focus();
            //app.banner.init();
            app.screenshot.init();
            $("a.fancyimg").colorbox();
        }
        else if(window.location.pathname == '/activate.html') {
            if (activationmode == "password")
                app.activatePage.switchActivatePage("barSetPassword");
            else if (activationmode == "invalid")
                app.activatePage.switchActivatePage("barInvalid");
            else if (activationmode == "active")
                app.activatePage.switchActivatePage("barActive");
        }
        else if (window.location.pathname == '/signin.html') {
            // if remember login
            $("#inpUsernameEmail").removeAttr("disabled");
            $('#inpUsernameEmail').focus();

            var username = app.util.getCookie("username");
            if (username) {
                $('#cbRememberLogin').addClass('cbx-checked');
                $('#inpUsernameEmail').val(username);
            }
        }
        app.eventHandle();
        app.chromeBar();
    });

    // ClickTale event tracking
    $(function () {
        // make sure clicktale is loaded
        if (typeof ClickTaleTag === "function") {
            $("*[data-clicktale-event]").click(function () {
                ClickTaleTag($(this).attr("data-clicktale-event"));
            });
        }
    });

    // Expose app to the global object
    window.app = app;
})(window);

