/*
 * Class: ScriptLoader
 *     Загружает указанные скрипты из директории scripts.
 */
var ScriptLoader = {

    request: null,

    loaded: {},

    load: function() {
        for (var i = 0, len = arguments.length; i < len; i++) {
            var filename = arguments[i];
            if (!this.loaded[filename]) {
                if (!this.request) {
                    this.request = window.XMLHttpRequest ? new XMLHttpRequest : (window.ie ? new ActiveXObject('Microsoft.XMLHTTP') : null);
                }
                if (!this.request) return false;
                this.loaded[filename] = true;
                this.request.open('get', 'scripts/'+filename, false);
                this.request.send(null);
                if (this.request.status == 200) {
                    this.globalEval(this.request.responseText);
                }
            }
        }
    },

    globalEval: function(code) {
        if (window.execScript) window.execScript(code, 'javascript');
        else window.eval(code);
    }
}

// Словарь для хранения языкозависимых констант и их переводов.
var Dictionary = {};

/*
 * Улучшения:
 *   - Проверка уже загруженных стилей;
 *   - Загрузка стилей из директории stylesheets.
 */
Asset.loaded = { css: {} };
Asset.css = function(source, properties) {
    if (!Asset.loaded.css[source]) {
        Asset.loaded.css[source] = true;
        return new Element('link', $merge({
			'rel': 'stylesheet', 'media': 'screen', 'type': 'text/css', 'href': 'stylesheets/'+source
		}, properties)).inject(document.head);
    }
    return false;
}


Object.toQueryString = function(source){
	var queryString = [];
	for (var property in source) {
	    if ($type(source[property]) == 'array') {
	        for (var i = 0; i < source[property].length; i++) {
	            queryString.push(encodeURIComponent(property)+'='+encodeURIComponent(source[property][i]));
	        }
	    }
	    else {
	        queryString.push(encodeURIComponent(property)+'='+encodeURIComponent(source[property]));
	    }
	}
	return queryString.join('&');
};

Element.implement({

    // Для единообразия.
    removeProperty: function(property){
        this.removeAttribute(property);
        return this;
    }
    // Добавлена поддержка multiple select.
    /*toObject: function(){
		var obj = {};
		$$(this.getElementsByTagName('input'), this.getElementsByTagName('select'), this.getElementsByTagName('textarea')).each(function(el){
			var name = $(el).name;
			var value = el.getValue();
			if ((value !== false) && name){
                obj[name] = value;
            }
		});
		return obj;
	}*/
});
    //Объект предназначен для последующей имплементации его в нужных местах
    //отправляет запрос на сервер и обрабатывает результат
    var Request = {
    request : function(uri, data, onSuccess) {
        new Ajax(uri, {
            method: 'post',
            postBody: data,
            onComplete: function(responseText) {
                try {
                    var response = Json.evaluate(responseText);
                }
                catch (e) {
                    var response = {
                        result: false,
                        title: 'Ошибка',
                        errors: [{ message: 'Произошла ошибка. Пожалуйста, обновите страницу.' }]
                    };
                }

                if (response.result) {
                    onSuccess(response);
                }
                else {
                    var msg = (typeof response.title != 'undefined')?response.title:'Произошла ошибка:' + "\n";
                    response.errors.each(function(error) {
                        if (typeof error.field != 'undefined') {
                            msg += error.field + " :\t";
                        }
                        msg += error.message + "\n";
                    });
                    alert(msg);
                }
            }
        }).request();
    }
    }

    //Пердназначен для последующей имплементации
    //Содержит метод setLabel использующийся для привязки кнопки выбора разделов
    var Label = {
        setLabel: function(result) {
            var id = name = '';
            if (typeof (result)!= 'undefined') {
                if (result) {
                    id = result.smap_id;
                    name = result.smap_name;
                }
                $(this.obj.getAttribute('hidden')).value = id;
                $(this.obj.getAttribute('span')).innerHTML = name;
            }
        }        
    }

