﻿/// <reference path="~/js/jquery-1.3.2.js" />

var queryString = {};
ParseQueryString();


var stage_lang = "en";

if (navigator.userLanguage) // Explorer
    SetCultureLang( navigator.userLanguage );
else if (navigator.language) // FF
    SetCultureLang( navigator.language );

WithQueryString('lang', SetCultureLang);
//alert( stage_lang );

function SetCultureLang(lang)
{
    if ( !lang || 0 === lang.length )
        lang = "en";
    else if (lang.length>2)
        lang = lang.substr(0,2);

    if (lang != "it")
        lang = "en";
    stage_lang = lang;
};

function LocalizeUri(uri)
{
    if ( !uri || 0 === uri.length )
        return uri;
    return stage_lang + "/" + uri;
};

function ParseQueryString()
{
    var tmp = window.location.search;
    if ( !tmp || 0 === tmp.length )
        return;
    
    var gy = tmp.substring(1).split("&");
    for (i=0; i<gy.length; i++) 
    {
        var ft = gy[i].split("=");
        queryString[ft[0]] = ft[1];
    }    
};

function WithQueryString(key, action)
{
    var value = queryString[key];
    if ( !value || value === undefined )
        return
    action(value, key);
};

OMAA.Stage = function (newUri) {
    //constructor here
    this.URI = newUri || this.URI;

    this.init();

    OMAA.Stage.div = $("div#stage");
    OMAA.Stage.background = $("div#stage-background");
    //OMAA.Stage.progressbar = $("#progressA").progress(0);

    //$("#waiting").center({ w: 16, h: "auto" });
    
    
    
    // BASE EVENT
    OMAA.Stage.RegisterEvent('stage_shown', OMAA.Stage.EventNull);
    // $(document).pngFix();
    OMAA.Stage.RegisterEvent("layout_begin", OMAA.Stage.EventNull);
    OMAA.Stage.RegisterEvent('layout_complete', OMAA.Stage.EventNull); //function (event) { //OMAA.Stage.progressbar.progress(-1); });
}

OMAA.Stage.prototype = {

    cssParser: new OMAA.CSS(),

    baseURI: "stages/",
    baseScriptsURI: "stages/js/",
    URI: "stage.xml",

    init: function () {

        if (!this.baseScriptsURI.endsWith("/"))
            this.baseScriptsURI += "/";

    },

    levels: [],
    levelsSelector: [],

    settings: {
        name: "", visible: true, centered: true, background: "", css: "", fade: "normal", script: "", html: "",
        stage: { w: 1024, h: 640 },
        grid: { w: 64, h: 64 },
        padding: { L: 17, T: 23, R: 17, B: 23 },
        page: { title: "", background: "", css: "" },
        stageBackground: { visible: false, css: "", fade: "normal", html: "" },
        tassels: { w: -1, h: -1 }
    },

    stage_error: function (XMLHttpRequest, textStatus, errorThrown) {
        // typically only one of textStatus or errorThrown will have info
        //this; // the options for this ajax request
        var errs = (textStatus || errorThrown) + "\r\n<br/>" + XMLHttpRequest.responseText;
        console.error(errs);
    },

    beforeLoad: function (XMLHttpRequest) {
        OMAA.UID.reset();
        stage.clear();
        OMAA.Stage.div.hide(10);
        OMAA.Stage.background.hide(10);
        //OMAA.Stage.progressbar.progress(0);
    },

    clear: function () {
        this.content("");
        OMAA.UID.reset();
    },

    content: function (html) {
        OMAA.Stage.div.html(html);
    },

    loadAsync: function (newUri) {

        var currentStage = this;
        currentStage.load(newUri);

    },
    
    loadAsync_WithAjaxLoader: function (newUri) {

        var currentStage = this;
        
        $('<div id="waiting" />')
            .appendTo('body')
            .center({ w: 16, h: 'auto' })
            .fadeIn(500, function () {
            
                currentStage.load(newUri);
            
            });

    },
    
    load: function (newUri) {

        newUri = newUri || this.URI || "stage.xml";
        var currentStage = this;

        $.ajax({
            type: "GET",
            url: this.baseURI + newUri,
            async: true,
            dataType: "xml",
            cache: false, global: false, processData: false,
            beforeSend: this.beforeLoad,
            error: this.stage_error,
            success: function (data, textStatus) {
                var new_stage = $("stage", data);
                currentStage.stage_build(new_stage, newUri);
            }
        });

        //OMAA.Stage.progressbar.progress(10);
    },

    assignGrid: function (grid) {

        //this.settings.padding = { L: 17, T: 23, R: 17, B: 23 };
        this.settings.grid = { w: parseInt(grid.attr("w")), h: parseInt(grid.attr("h")) };
        this.settings.margins = { x: 1, y: 1 };

        this.settings.padding.H = this.settings.padding.L + this.settings.padding.R;
        this.settings.padding.V = this.settings.padding.T + this.settings.padding.B;

        this.settings.margins.H = this.settings.margins.x * 2;
        this.settings.margins.V = this.settings.margins.y * 2;

        var ww = this.settings.stage.w - this.settings.padding.H;
        var hh = this.settings.stage.h - this.settings.padding.V;
        //var hh = OMAA.Stage.div.height() - this.settings.padding.V;

        var numTesselsX = ww / (this.settings.grid.w + this.settings.margins.H);
        var numTesselsY = hh / (this.settings.grid.h + this.settings.margins.V);
        //var numTesselsY = Math.max(5, stage.settings.grid.h || 64);

        this.settings.tassels = {
            //w: (ww - (numTesselsX * (stage.settings.margins.x * 2))) / numTesselsX, h: (hh - (numTesselsY * (stage.settings.margins.y * 2))) / numTesselsY,
            w: this.settings.grid.w, h: this.settings.grid.h,
            nX: numTesselsX, nY: numTesselsY,
            W: (this.settings.grid.w + this.settings.margins.H), H: (this.settings.grid.h + this.settings.margins.V)
        };

    },

    assignStageBackground: function (stageBackground) {
        this.settings.stageBackground.css = OMAA.Stage.GetCss(stageBackground.attr("css"));
        this.settings.stageBackground.fade = OMAA.Stage.GetFade(stageBackground.attr("fade"));
        this.settings.stageBackground.visible = OMAA.Stage.IsTrue(stageBackground.attr("visible"), this.settings.stageBackground.visible, "false");
        
        this.settings.stageBackground.html = OMAA.Stage.GetContent(stageBackground.children("content"));
    },

    assignPage: function (page) {
        this.settings.page.title = page.attr("title") || this.settings.page.title;
        this.settings.page.css = OMAA.Stage.GetCss(page.attr("css"), false);
        this.settings.page.background = page.attr("background");
    },

    assignScripts: function (actions) {

        var currentStage = this;

        actions.children().each(function () {
            switch (this.tagName) {
                case "script":
                    var src = $(this).attr("src");
                    currentStage.addScript(src, false);
                    break;
                case "eval":
                    var active = OMAA.Stage.Bool($(this).attr("active") || true);
                    if (active) {
                        var js = "(function(){" + $(this).text() + "})();";
                        OMAA.Stage.Scripts.push(js);
                    }
                    break;
            }

        });
    },

    addScript: function (src, cache) {

        var src0 = src;
        if (!src0.startsWith("http:") && !src0.startsWith("/")) {
            src0 = this.baseScriptsURI + src0;
            //                else if (src0.startsWith("/") && this.baseScriptsURI.endsWith("/"))
            //                    src0 = src0.substring(1);
        }

        cache = cache || true;
        if (cache)
            src0 += "?" + new Date().getMilliseconds() + getRandomArbitary(1, 100);

        var head = document.getElementsByTagName("head")[0];

        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = src0;
        head.appendChild(script);

    },

    stage_build: function (new_stage, context) {

        //OMAA.Stage.progressbar.progress(15);

        this.URI = context;

        this.name = new_stage.attr("name");
        this.settings.centered = OMAA.Stage.IsTrue(new_stage.attr("centered"), this.settings.centered, "true");
        
        this.settings.background = LocalizeUri( new_stage.attr("background") );
        if ( !this.settings.background || 0 === this.settings.background.length )
        {}
        else
            this.settings.background = " url('" + this.settings.background + "')";

        this.settings.css = OMAA.Stage.GetCss(new_stage.attr("css") + this.settings.background);

        this.settings.visible = OMAA.Stage.IsTrue(new_stage.attr("visible"), this.settings.visible, "true");
        this.settings.fade = OMAA.Stage.GetFade(new_stage.attr("fade"));

        //OMAA.Stage.progressbar.progress(20);

        this.assignGrid(new_stage.children("grid"));
        this.assignStageBackground(new_stage.children("backgroundStage"));
        this.assignPage(new_stage.find("page"));

        //OMAA.Stage.progressbar.progress(30);

        this.assignScripts(new_stage.children("actions"));

        //OMAA.Stage.progressbar.progress(40);

        this.settings.html = OMAA.Stage.GetContent(new_stage.children("content"));

        this.layout();
    },


    layout: function () {

        //OMAA.Stage.progressbar.progress(50);

        /* 
        CONTENT
        */
        OMAA.Stage.background.html(this.settings.stageBackground.html);
        this.content(this.settings.html);

        //OMAA.Stage.progressbar.progress(60);

        /* 
        SCRIPTS
        */
        var debug_scripts = new Array();
        for (var scriptID = 0; scriptID < OMAA.Stage.Scripts.length; scriptID++) {
            try {
                eval(OMAA.Stage.Scripts[scriptID]);
            } catch (e) {
                debug_scripts.push(scriptID + ": " + e);
            }
        }

        if (debug_scripts.length > 0) {
            alert("SCRIPTS:\n\n" + debug_scripts.join("\n"));
        }

        OMAA.Stage.Scripts = null;
        //OMAA.Stage.progressbar.progress(70);

        if (OMAA.Stage.ScriptsLoadErrors.length > 0) {
            alert("AJAX SCRIPTS:\n\n" + OMAA.Stage.ScriptsLoadErrors.join("\n"));
        }

        /* 
        BEGIN LAYOUT
        */
        OMAA.Stage.OnLayoutBegin();

        /* 
        PAGE
        */
        if (this.settings.page.title)
            top.document.title = this.settings.page.title;

        $("body").multiCss([
            { background: this.settings.page.background },
            this.settings.page.css
        ], true);      

        //OMAA.Stage.progressbar.progress(80);

        /* 
        stageBackground 
        */
        if (!this.settings.stageBackground.visible)
            OMAA.Stage.background.hide();
        else
            OMAA.Stage.background.multiCss([ this.settings.stageBackground.css ]);

        //OMAA.Stage.progressbar.progress(90);

        /* 
        STAGE
        */
        OMAA.Stage.div.multiCss([
            { background: this.settings.background  },
            this.settings.css
        ]);
        
        var imgURI;
        if (stage_lang == 'en')
            imgURI = "it";
        else
            imgURI = "en";
        
        $('<img src="images/lang-' + imgURI + '.png" width="16" height="16" />')
            .css({ position: 'relative', left: this.settings.stage.width - 16 - 0, top: -3 - 16 - 2, cursor: 'pointer' })
            .click(function() { window.location = "?lang=" + imgURI; })
            .appendTo(  OMAA.Stage.div );
        
        //OMAA.Stage.progressbar.progress(95);
        this.layout_done();
    },

    layout_done: function () {
        /* 
        SHOW
        */
        
        $("#waiting").fadeOut(2000, function(){ $(this).remove(); });
        
        if (this.settings.stageBackground.fade) {
            OMAA.Stage.background.fadeIn(this.settings.stageBackground.fade); 
        }
        else
            OMAA.Stage.background.show();

        if (!this.settings.visible)
            OMAA.Stage.div.hide();
        else {
            if (this.settings.fade)
                OMAA.Stage.div.fadeIn(this.settings.fade, OMAA.Stage.OnStageShown);
            else
                OMAA.Stage.div.show("normal", OMAA.Stage.OnStageShown);
        }
        
        
        
        OMAA.Stage.OnLayoutComplete();
    },

    Resize: function (cfg) {

        this.settings.stage = OMAA.MergeObjects(this.settings.stage, { width: 1024, height: 640 }, cfg);
        //this.settings.stage = jQuery.extend({ width: 1024, height: 640 }, cfg);
        $("#stage").center(cfg);

    }

}

OMAA.Stage.IsTrue = function (newValue, prevValue, defaultValue) {
    return (newValue || prevValue || defaultValue) == "true";
}

OMAA.Stage.GetFade = function (v) {
    return (!v) ? "" : (isNaN(v) ? v : parseInt(v));
}

OMAA.Stage.Bool = function (v) {
    return (v && (v == true || v == "true" || v == "yes" || v == "on"));
}

OMAA.Stage.GetCss = function (text) {

    return OMAA.CSS.Parser.parse(text);
    
}

OMAA.Stage.GetContent = function (context) {
    if (context.attr("dynamic") == "true")
        return null;

    var url = context.attr("url");
    if (!url)
        return context.text();

    var x = OMAA.Stage.AjaxSync(url, "html");

    return x.responseText;
}

OMAA.Stage.Scripts = new Array();
OMAA.Stage.ScriptsLoadErrors = new Array();

OMAA.Stage.EventNull = function () { };

OMAA.Stage.OnLayoutBegin = function () { $(document).triggerHandler("layout_begin"); };
OMAA.Stage.OnLayoutComplete = function () { $(document).triggerHandler("layout_complete"); };
OMAA.Stage.OnStageShown = function () { try { $(document).triggerHandler("stage_shown"); } catch (e) { console.error(e); } };


OMAA.Stage.RegisterEvent = function (name, callback) {
    $(document).bind(name, callback);
}

OMAA.Stage.RaiseEvent = function (name) {
    $(document).triggerHandler(name);
}

OMAA.Stage.AjaxSync = function (uri, dataType) {

    return $.ajax({
        type: "GET",
        url: uri,
        async: false,
        dataType: dataType || "text",
        cache: false,
        global: false,
        processData: false,
        error: this.stage_error
    });
}

OMAA.Stage.Async = function (callback, timeout) { window.setTimeout(callback, timeout || 50); };

OMAA.Stage.CreateDiv = function (tl, br, options) {

    options = OMAA.MergeObjects(OMAA.Stage.CreateDiv.defaults, options);

    var rect = OMAA.Tessels.OffsetRect(OMAA.Tessels.MakeRect(tl, br, options.rightAlignment), options.margins.h, options.margins.v, options.withPadding);
    
    if (options.fixedWidth == false && options.width == undefined)
        rect.width = "auto";
    else if (options.width != undefined)
        rect.width = options.width;

    if (options.fixedHeight == false && options.height == undefined)
        rect.height = "auto";
    else if (options.height != undefined)
        rect.height = options.height;

    if (options.id != undefined) {
        options.id = options.id.ltrim('#');
        var q = $("#" + options.id);

        if (q.size() > 0)
            q.remove();
        q = null;
    }

    var div = $("<div />").addClass("staged").multiCss([options.css, rect]);

    if (options.content == undefined)
    { }
    else if (options.content == null)
    { }
    else if (options.content.jquery != undefined)    // is jQuery
        options.content.appendTo(div);
    else if (options.content.constructor == String)
        div.html(options.content);

    if (options.id != undefined)
        div.attr("id", options.id);

    if (options.startsHidden == true)
        div.hide();

    if (options.appendTo == true) {
        if (options.parent == undefined)
            return div.appendTo(OMAA.Stage.div);
        else if (options.parent != null)
            return div.appendTo(options.parent);
    }

    return div;
};
OMAA.Stage.CreateDiv.defaults = { margins: { h: 0, v: 0 }, id: undefined, startsHidden: false, withPadding: false, rightAlignment: false, fixedWidth: true, fixedHeight: true, width: undefined, height: undefined, appendTo: true, css: {}, content: null, parent: undefined };

OMAA.Stage.CreateImage = function (options) {

    options = OMAA.MergeObjects(OMAA.Stage.CreateImage.defaults, options);

    var img = $("<img />")
            .attr({
                src: options.src,
                alt: options.alt,
                title: options.title
            })
            .css(options.css);

    if (options.autoresizer != undefined) {
        img.data("autoresizer", options.autoresizer).hide()
            .bind("image.resize", OMAA.Stage.CreateImage.ImageAutoResizer)
            .triggerHandler("image.resize");
    }

    return img;
};
OMAA.Stage.CreateImage.defaults = { src: "", title: "", alt: "", css: {}, autoresizer: undefined };

OMAA.Stage.CreateImage.ImageAutoResizer = function () {
    var el = $(this);
    var datas = el.data("autoresizer");
    if (datas == undefined || datas == null) {
        el.show();
        return;
    }

    var w = el.width();
    if (w == 0) {
        window.setTimeout(function () { el.triggerHandler("image.resize"); }, 100);
        return;
    }
    el.unbind("image.resize");

    var h = el.height();

    w = w * datas.width;
    h = h * datas.height;

    el.css({ display: "inline", width: w, height: h }).fadeIn(300);
};

OMAA.Stage.HoverOn = function () {
    var el = $(this);
    if (el.disabled()) return;
    el.stop(true, false).fadeTo(150, 0.50);
};
OMAA.Stage.HoverOff = function () {
    var el = $(this);
    el.stop(true, false).fadeTo(10, "");
};

OMAA.Stage.CreateTopRightLabel = function (options) {

    options = OMAA.MergeObjects(OMAA.Stage.CreateTopRightLabel.defaults, options);

    var div = null;

    if (options.id != undefined) {
        options.id = options.id.ltrim('#');
        div = $("#" + options.id);

        if (div.size() < 1)
            div = null;
    }

    var img = OMAA.Stage.CreateImage({ src: options.src, css: {}, autoresizer: { width: 0.5, height: 0.5} });

    if (jQuery.isFunction(options.click))
        img.defaultHover().click(options.click);

    if (div == null) {
        
        div = OMAA.Stage.CreateDiv("{home}", "{bottom right}", {
            id: options.id,
            margins: { h: 0, v: 0 }, withPadding: false, rightAlignment: true,
            fixedWidth: false, fixedHeight: false,
            appendTo: options.appendTo, parent: options.parent,
            css: { textAlign: "right" },
            content: img
        });
        
    }
    else {

        div.children().fadeOut(350, function () {
            div.empty();
            img.appendTo(div);
            div.children().show();
        });
        
    }

    //    if (options.id != undefined)
    //        div.attr("id", options.id);

    return div;
};
OMAA.Stage.CreateTopRightLabel.defaults = OMAA.MergeObjects(OMAA.Stage.CreateDiv.defaults, { src: "", click: undefined, css: { zIndex: 200 }, appendTo: true, parent: undefined });

