﻿/// <reference path="~/Scripts/common.js" />
/// <reference path="~/Scripts/jquery-ui-1.8.14.custom.min.js" />
/// <reference path="~/Scripts/json2.js" />
/// <reference path="~/Scripts/menu.js" />

$(document).ready(function () {

    updateAppUI();
    selectBitness();

    $('#descriptionContainer').html('');
    var sid = getHashValue('sid');

    if (sid != null) {

        var loginService = new LoginService();

        loginService.ValidateSession(sid, function (result) {

            if (!result) {
                setHashValue('sid', null);
                showLoginUI();
                goHome();
                return;
            }
        }, function (result) {
            setHashValue('sid', null);
            showLoginUI();
            goHome();
            return;

        });

        hideLoginUI();
    }

    var page = getHashValue('page');

    if (isNullOrEmpty(page)) {
        goHome();
        return;
    }

    switch (page) {
        case 'apps':
            showApps()
            break;
        case 'login':
            $('#sectionDiv').text('Home');
            $('#descriptionContainer').hide();
            $('#productDownloader').hide();
            setHashValue('page', 'home');
            DoLogin();
        default:
            goHome();
            break;
    }
});

function goHome() {
    $('#sectionDiv').text('Home');
    $('#descriptionContainer').hide();
    $('#productDownloader').hide();
    $('#productsMenu').hide();
    setHashValue('page', 'home');
}


function showApps() {

    setHashValue('page', 'apps');

    $('#spinner').show();
    $('#productDownloader').hide();
    $('#contentContainer').hide();

    $('#sectionDiv').text('Apps');    
    $('#descriptionContainer').show();
    updateAppUI();
    var productService = new ProductsService();

    productService.GetProducts(getProductsSuccess, getProductsFailed, null);
}

function getProductsSuccess(result) {

    var productService = new ProductsService();

    $('#productsMenu').empty();

    setHashValue('page', 'apps');
    productService.GetCategories(function (categories) {

        $('#productsMenu').show();

        for (var categorIndex = 0; categorIndex < categories.length; categorIndex++) {

            var category = categories[categorIndex];

            $('#productsMenu').append('<li><a href=\'\'>' + category.Name + '</a><ul id=\'' + category.Id + '\'></ul></li>');
        }

        initMenu();

        if (getHashValue("sid") != null && getHashValue("page") == 'apps') {
            $('#productDownloader').show();
            $('#downloadLink').show();
        }

        var products = eval(result);
        var product;

        for (var i = 0; i < products.length; i++) {

            product = eval(products[i]);

            $('#' + product.CategoryId).append('<li><a id=\'' + product.Id + '\'>' + product.Name + '</a></li>');

            $('#' + product.Id).click(function (eventHandlerData) {

                productService.GetProduct(eventHandlerData.srcElement.id, function (data) {

                    var productInfo = eval(data);

                    setHashValue('pid', productInfo.Id);
                    $('#sectionDiv').text('Apps - ' + productInfo.Name);

                    $('#descriptionContainer').html(productInfo.Descrption);

                    $('#spinner').hide();

                }, function (errorInfo) {

                    alert(errorInfo.get_message());
                });
            });
        }

        if (products.length > 0) {
            product = eval(products[0]);
            setHashValue('pid', product.Id);
            $('#sectionDiv').text('Apps - ' + product.Name);
            $('#descriptionContainer').html(product.Descrption);

            setHashValue('pid', product.Id);
            $('#spinner').hide();
        } else {

            $('#descriptionContainer').html('');

        }

    }, function (result) {

        alert(result.get_message());
    });
}


function getProductsFailed(result) {

    $('#spinner').hide();
    alert(result.get_message());
}

function download() {

    $('#spinner').show();

    var loginService = new LoginService();

    loginService.ValidateSession(getHashValue('sid'), function (result) {

        if (!result) {
            alert('You are not currently logged in.');
            return;
        }

        var productsService = new ProductsService();

        productsService.GetProduct(getHashValue('pid'), function (result) {

            var productLocation;
            var product = eval(result);

            var bitness = $('#osSelector').val();

            switch (bitness) {
                case '0': // 64 Bit
                    productLocation = product.Setup64Location;
                    break;
                case '1': // 32 Bit                
                    productLocation = product.Setup32Location;
                    break;
                default:
                    alert('Unsupported operating system.');
                    return;
            }

            $('#spinner').hide();
            if (isNullOrEmpty(productLocation)) {
                alert('There isn\'t currently a download available.  Please check back later or subscribe to this product for notifications.');
                return;
            }

            openWindow(productLocation, 'Download');

        }, function (getProductsFailedResult) {

            alert(getProductsFailedResult);

        }, null);
    });
}
/* Login Methods */

function loginOkClick() {

    $('#spinner').show();
    var userName = $('#userNameTextBox').val();
    var password = $('#passwordTextBox').val();

    $(this).dialog("close");

    var proxy = new LoginService();

    proxy.Login(userName, password, loginSuccess, loginFailed);
}

function loginSuccess(result) {

    var loginResult = eval(result);

    if (!loginResult.IsUser) {
        alert('User name not foud.');
        return;
    }

    if (loginResult.InvalidPassword) {
        alert('Invalid Password.');
        return;
    }

    setHashValue('sid', loginResult.SessionId);

    $("#dialog:ui-dialog").dialog("destroy");
    $('#osSelector').attr('disabled', '');
   
        updateAppUI();  
    hideLoginUI();
    $('#spinner').hide();
}

function updateAppUI() {

    if (getHashValue("sid") != null && getHashValue("page") == 'apps') {
        $('#productDownloader').show();
        $('#downloadLink').show();
        $('#sideMenu').css('top', 135);
        $('#descriptionContainer').css('top', 58);
        $('#descriptionContainer').css('height', 425)
    }
}

function loginFailed(result) {

    $('#spinner').hide();
    alert(result);
}

function onLoginClick() {

    DoLogin(false);
}


function DoLogin() {

    $('#spinner').show();
    $("#dialog:ui-dialog").dialog("destroy");

    $("#dialog-confirm").dialog({
        resizable: false,
        height: 210,
        width: 250,
        modal: true,
        buttons: {
            "Login": loginOkClick,
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });
}

function selectBitness() {

    if (navigator.userAgent.indexOf("WOW64") != -1) {
        $('#osSelector').val('0');
        return;
    }

    switch (navigator.cpuClass) {
        case 'x86':
            $('#osSelector').val('1');
            break;
        case 'x64':
            $('#osSelector').val('0');
            break;
    }
}

function hideLoginUI() {

    $('#messageWindow').hide();

    $('#navDiv').width($('#navDiv').width() - 50);
    $('#loginLink').hide();
}

function showLoginUI() {

    $('#messageWindow').show();

    if ($('#loginLink').css('display') != 'none') {
        return;
    }

    $('#loginLink').show();
    $('#navDiv').width($('#navDiv').width() + 50);

}

function register() {

    openWindow("register.aspx" + window.location.hash, "Register");
}

function resetPassword() {

    var loginService = new LoginService();

    var emailAddress = prompt("Please enter your email address.", '');

    if (isNullOrEmpty(emailAddress)) {
        return;
    }

    loginService.ResetPassword(emailAddress, function (result) {

        alert('Reset message sent.');
        $(this).dialog("close");
        $("#dialog:ui-dialog").dialog("destroy");
    }, function (result) {
        alert(result.get_message());
    }
    );
}

