// scribble-it - scribbleIt.js v0.1

// Copyright by Manuel Berger, Christian Hemetsberger and Lukas Rammelmüller
// More information on http://scribble-it.at

document.write('<div id="loading" class="shaddowBox css3 center"><h1>Lade...</h1><p>Bin gleich soweit! Einen kleinen Moment noch, bitte ;)</p><p><img src="style/default/img/loadingAnimation.gif" alt="Loading..." /></p></div>');

if(!console)
{
	var console = {
	  log: function(logMsg) {}
	}
}

// This script initializes the ScribbleIt-UI
var si = {
  Version: '0.1',
  require: function(libraryName) {
	// inserting via DOM fails in Safari 2.0, so brute force approach
	document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
  }
}


// DataAccess-Layer
// This script handles all data-requests and switches between the DataLayers

si.Data = {

	switchLayer: function() {
		var path = "script/data/";
		if (!window.google || !google.gears)
			si.require(path+'server_0001.js');
		else
			si.require(path+'gears_0001.js');
	},
	
	loadUi: function(name, container, insertCode, onSuccess, onFailture) {
		this.Layer.loadUi(name, container, insertCode, onSuccess, onFailture);
	},
	
	GetUserId: function(onSuccess, onFailure){
		si.Data.Layer.getUserId(onSuccess, onFailure);
	},
	
	logout: function(onSuccess, onFailure){
		si.Data.Layer.logout(onSuccess, onFailure);
	}
	

}

si.Data.switchLayer();

// CORE
// This script contains the global-library for scribble-it
si.Core = {
    loadUi: function(uiName, container, insertCode, onSuccess, onFailture) {
        window.location.hash = uiName;
        //TODO: wenn objekt schon vorhanden, lieber sichtbar machen...
        si.Data.loadUi(uiName, container, insertCode, function() {
            if(onSuccess)
                onSuccess();
        }, onFailture);
    },
    loading: function(show) {
        try {
            if (!$('loading'))
                document.write('<div id="loading" class="shaddowBox"><div class="helperTop"><span class="helperMiddle"/></div><div class="content"><div class="helper"><div class="helper"><div class="content"><h1>Lade...</h1><p>Bin gleich soweit! Einen kleinen Moment noch, bitte ;)</p><p><img src="style/default/img/loadingAnimation.gif" alt="Loading..." /></p></div></div></div></div><div class="helperBottom"><span class="helperLeft"><span class="helperMiddle"/></span></div></div>');
            if (show == null)
                show = !$('loading').visible();
            if (show)
                $('loading').show();
            else
                $('loading').hide();
        }
        catch (exception) {
        }
    },
    valueLabel: function(element) {
		var label = element.parentNode.select('label[for="'+element.name+'"]')[0];
		element.onfocus = function() {
			label.addClassName('active');
		}
		element.onblur = function() {
			label.removeClassName('active');
		}
		element.onkeyup = function() {
			if(element.value == '')
				label.removeClassName('text');
			else
				label.addClassName('text');
		}
		/*
        if (label) {
            element.value = label;
            //TODO: label updaten
            //if(element.previous(0).tagName == label)
			//	element.previous(0).update(label);
			//else
			//	element.insert(new Element('label', {'for': element.id }).update(label), { position: before });
        }
        var text = element.value;
        var isPass = (element.type == "password");
        if (isPass)
            element.type = "text";
        element.onfocus = function() {
            if (this.value == text) {
                this.value = "";
                if (isPass)
                    this.type = "password";
            }
        }
        element.onblur = function() {
            if (this.value == "") {
                this.value = text;
                if (isPass)
                    this.type = "text";
            }
        }*/
    },

    cleanUp: function() {
        //TODO: HTML aufräumen
    },

    bind: function(hClass, handler) {
        $$('#Content .h-' + hClass).each(function(h) {
            h.onclick = handler;
        });
    },

    setNavPath: function(elements, links, clickHandlers) {
        $('ProjectLabel').getElementsByTagName('ul')[0].update('');
        if (elements) {
            try{
                for (var i = 0; i < elements.length; i++)
                    si.Core.addNavPath(elements[i], links[i], clickHandlers[i]);
            }catch(err){
                si.Core.addNavPath(elements, links, clickHandlers);
            }
        }
    },

    addNavPath: function(element, link, clickHandler) {
        if (link)
            var linkElem = new Element('a', { 'href': link }).insert(element);
        else
            var linkElem = document.createTextNode(element);
        if (clickHandler)
            linkElem.onclick = clickHandler;
        $('ProjectLabel').getElementsByTagName('ul')[0].insert(new Element('li').insert(linkElem));
    },

    setTitle: function(title) {
        document.title = title + ' : scribble-it';
        try {
            $('ProjectLabel').getElementsByTagName('h1')[0].update(title);
        } catch (err) { }
    }

}

// STYLE

function generateShaddowBoxes(parent) {

    var shaddowBoxes = parent.getElementsByClassName('shaddowBox');

    for (var box in shaddowBoxes) {
        generateShaddowBox(box);
    }

}

function generateShaddowBox(box, type) {
    
    //TODO: test if box is an element or an id

	FF3=Boolean(/a/[-1]&&Object.getPrototypeOf)
	SAF3=Boolean(window.devicePixelRatio)
    if(!(FF3||SAF3))
	{
		box.addClassName('oldCss');
	    // wrap all childs of the box with a new div
	    var content = new Element('div', { 'class': 'content' });

	    while (box.firstChild != null) {
	        content.appendChild(box.firstChild);
	    }
    
	    // wrap with contentHelpers
	    var contentH = new Element('div', { 'class': 'helper' });
	    content.wrap(contentH);
	    var contentHH = new Element('div', { 'class': 'helper' });
	    contentH.wrap(contentHH);
	    var contentP = new Element('div', { 'class': 'content' });
	    contentHH.wrap(contentP);

	    box.appendChild(contentP);

	    // create topHelper
	    var helperTM = new Element('span', { 'class': 'helperMiddle' });
	    var helperT = new Element('div', { 'class': 'helperTop' });
	    helperTM.wrap(helperT);
	    box.insertBefore(helperT, contentP);
    
	    // create bottomHelper
	    var helperBM = new Element('span', { 'class': 'helperMiddle' });
	    var helperBL = new Element('span', { 'class': 'helperLeft' });
	    var helperB = new Element('div', { 'class': 'helperBottom' });
	    helperBM.wrap(helperBL);
	    helperBL.wrap(helperB);
	    box.appendChild(helperB);

	    if (type)
        box.addClassName(type);
	}

	vCenter(box);
}

function vCenter(element){
	var table = new Element('div', {'style':'display: table; height: 100%; width: 100%; top: 0; position: absolute;'});
	var cell = new Element('div', {'style':'display: table-cell; height: 100%; width: 100%; top: 0; vertical-align: middle;'});
	element.wrap(cell);
	cell.wrap(table);
	element.addClassName('center');
}

function generateWindowButton(btn, others) {
    generateShaddowBox($(btn));
    //if(!actions.contains(btn))
    $(btn).hide();

    si.Core.bind(btn, function() {
        /*others.each(function(e){
        if(e!=btn)
        $(e).hide();
        });*/
        //$(btn).style.top = '150px';
        // $(btn).style.z-index = 9999999;
        $(btn).appear();
        new Draggable($(btn), { starteffect: function() { }, endeffect: function() { } });
        return false;
    });
    si.Core.bind('close_' + btn, function() {
        $(btn).fade();
    });
}



// BIND

document.observe('dom:loaded', function() {

    console.log('scribble-it: started...');

    var uiName = window.location.hash.replace('#', '');
    if (!uiName) {
        uiName = "login";

        si.Data.GetUserId(function() {
            console.log('user drin');

            si.Core.loadUi("start", "", function(structure) {
                si.Core.loading(false);
                document.body.insert(structure);
            });
        }, function() {
            si.Core.loadUi(uiName, "", function(structure) {
                si.Core.loading(false);
                document.body.insert(structure);
            });
        });

    }
    else {
        si.Core.loadUi(uiName, "", function(structure) {
            si.Core.loading(false);
            document.body.insert(structure);
        });
    }
});

