﻿(function() {
    var ajaxActionPage = { "photo": "PhotoJson.aspx", "user": "UserJson.aspx", "game": "GameJson.aspx" }
    var 
    //window = this,
    baseurl = "../",
    $time = function() { return new Date().valueOf() }, // returns the number of MS since the epoch
    ariel = window.ariel = function() { return new ariel.fn.init() };

    // debug

//    if (window.location.href.indexOf("192.168.") >= 0 ||
//        window.location.href.indexOf("localhost") >= 0)
//        baseurl = "/WaterWeb" + baseurl;

    ariel.fn = ariel.prototype = {
        init: function() { return document; },
        alert: function(string) { alert(string); },
        ajaxGet: function(lib, action, querystring, callback, keepalive) {
            this.ajaxRequest(lib, action, querystring, callback, keepalive, null);
        },
        ajaxPost: function(lib, action, querystring, callback, keepalive, data) {
            this.ajaxRequest(lib, action, querystring, callback, keepalive, data);
        },
        ajaxRequest: function(lib, action, querystring, callback, keepalive, data) {
            var ret;
            if (keepalive == undefined || keepalive == null)
                keepalive = true;
            //          if (keepalive)
            //              $("#keepalive").get(0).src = "http://www.elearning.unimi.it/authentication/keepalive.aspx?userid=0&app=betaforumv3&timestamp=" + $time();
            if (data == undefined || data == null)
			{
				//console.debug(lib);
                jQuery.getJSON(baseurl + ajaxActionPage[lib], "action=" + action + querystring + "&tstamp=" + $time(), function(jsonData) { ariel.fn.ajaxCallback(jsonData, callback) });
			}
            else
                jQuery.post(baseurl + ajaxActionPage[lib] + "?action=" + action + querystring + "&tstamp=" + $time(), data, function(jsonData) { ariel.fn.ajaxCallback(jsonData, callback) }, "json");
        },
        ajaxCallback: function(jsonData, callback) {
            if (jsonData.Status) {
                switch (jsonData.Status) {
                    case "Ok":
                        if (callback)
                            callback(jsonData);
                        break;
                    case "Permission":
                        break;
                    case "Nosession": 
                        // bisogna calcolare l'url mediante una chiamata ajax 
                        var data = {};
                        data.url = window.location.toString();
                        jQuery.post(baseurl + ajaxActionPage["user"] + "?action=geturl&tstamp=" + $time(), data, function(jsonData) { window.location = "Login.aspx?url=" + jsonData.Result; }, "json");
                        //window.location = jsonData.Result.replace("@@url", window.location.toString().split("#")[0]);
                        break;
                }
            }
            else {
                alert("Illegal Ariel Request");
            }
        }
    };

    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, "");
    };

    // Simulates PHP's date function
    Date.prototype.format = function(format) {
        var returnStr = '';
        var replace = Date.replaceChars;
        for (var i = 0; i < format.length; i++) {
            var curChar = format.charAt(i);
            if (replace[curChar]) {
                returnStr += replace[curChar].call(this);
            } else {
                returnStr += curChar;
            }
        }
        return returnStr;
    };

    Date.replaceChars = {
        shortMonths: ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'],
        longMonths: ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settambre', 'Ottobre', 'Novembre', 'Dicembre'],
        shortDays: ['Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'],
        longDays: ['Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'],

        // Day
        d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
        D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
        j: function() { return this.getDate(); },
        l: function() { return Date.replaceChars.longDays[this.getDay()]; },
        N: function() { return this.getDay() + 1; },
        S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
        w: function() { return this.getDay(); },
        z: function() { return "Not Yet Supported"; },
        // Week
        W: function() { return "Not Yet Supported"; },
        // Month
        F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
        m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
        M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
        n: function() { return this.getMonth() + 1; },
        t: function() { return "Not Yet Supported"; },
        // Year
        L: function() { return "Not Yet Supported"; },
        o: function() { return "Not Supported"; },
        Y: function() { return this.getFullYear(); },
        y: function() { return ('' + this.getFullYear()).substr(2); },
        // Time
        a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
        A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
        B: function() { return "Not Yet Supported"; },
        g: function() { return this.getHours() % 12 || 12; },
        G: function() { return this.getHours(); },
        h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
        H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
        i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
        s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
        // Timezone
        e: function() { return "Not Yet Supported"; },
        I: function() { return "Not Supported"; },
        O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
        T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result; },
        Z: function() { return -this.getTimezoneOffset() * 60; },
        // Full Date/Time
        c: function() { return "Not Yet Supported"; },
        r: function() { return this.toString(); },
        U: function() { return this.getTime() / 1000; }
    };
})();

var init;
var $$ = function(element) { return $(document.createElement(element)) };

function loginSubmit() {
    var form = $("#auth_form");
    form.css("display", "none");
    form.attr("method", "post");
    form.attr("action", "CreateSession.aspx");

    var tbLogin = document.createElement("input");
    tbLogin.setAttribute("type", "text");
    tbLogin.setAttribute("name", "login");
    tbLogin.setAttribute("value", $("#login").val());
    form.append(tbLogin);

    var tbPassword = document.createElement("input");
    tbPassword.setAttribute("type", "text");
    tbPassword.setAttribute("name", "password");
    tbPassword.setAttribute("value", $("#password").val());
    form.append(tbPassword);

    form.submit();

    return false;
}

function logoutSubmit(evt) {
    evt.preventDefault();
    window.location = "logout.aspx";
}

$(document).ready(function() {
    $("#enter").click(loginSubmit);
    $("#exit").click(logoutSubmit);

    if (typeof (std_init) != "undefined")
        std_init();
});

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}


