﻿if(typeof Olsk == 'undefined') Olsk = {}
//Dictionary Class
//=========================================================================
Olsk.Dictionary = function(){ this.InnerArray = new Array();}
Olsk.Dictionary.COLUMN_KEY = 0;
Olsk.Dictionary.COLUMN_VALUE = 1;
Olsk.Dictionary.prototype.GetItems = function() { return this.InnerArray; }
Olsk.Dictionary.prototype.Length = function() { return this.InnerArray.length; }
Olsk.Dictionary.prototype.Add = function(key, value){ this.InnerArray.push([key, value]); }
Olsk.Dictionary.prototype.Clear = function(){ this.InnerArray.splice(0, this.InnerArray.length); }
Olsk.Dictionary.prototype.GetKeyByIndex = function(index){ return this.InnerArray[index][Olsk.Dictionary.COLUMN_KEY]; }
Olsk.Dictionary.prototype.GetValueByIndex = function(index){ return this.InnerArray[index][Olsk.Dictionary.COLUMN_VALUE]; }
Olsk.Dictionary.prototype.GetValueByKey = function(key){
    var index = this.GetIndexByKey(key);
    if(index != -1) return this.GetValueByIndex(index);
    return null;
}
Olsk.Dictionary.prototype.GetIndexByKey = function(key){ return this.FindRowIndex(Olsk.Dictionary.COLUMN_KEY, key); }
Olsk.Dictionary.prototype.GetIndexByValue = function(value){ return this.FindRowIndex(Olsk.Dictionary.COLUMN_VALUE, value); }
Olsk.Dictionary.prototype.ContainsKey = function(key){ return this.GetIndexByKey(key) != -1; }
Olsk.Dictionary.prototype.ContainsValue = function(value){return this.GetIndexByValue(value) != -1;}
Olsk.Dictionary.prototype.FindRowIndex = function(columnNo, value) {
    for (var index in this.InnerArray) {
        if (this.InnerArray[index][columnNo] == value) return index;
    }
    return -1;
}
Olsk.Dictionary.prototype.GetValues = function(){
    var values = new Array();
    for(var index in this.InnerArray) values.push(this.GetValueByIndex(index));
    return values;
}
Olsk.Dictionary.prototype.ForEach = function(functor) {
    for (var index in this.InnerArray) {
        var item = this.InnerArray[index];
        functor(item[Olsk.Dictionary.COLUMN_KEY], item[Olsk.Dictionary.COLUMN_VALUE]);
    }
}
Olsk.Dictionary.prototype.ForEachWithResult = function(functor, initValue) {
    var result = initValue;
    for (var index in this.InnerArray) {
        var item = this.InnerArray[index];
        result = functor(result, item[Olsk.Dictionary.COLUMN_KEY], item[Olsk.Dictionary.COLUMN_VALUE]);
    }
    return result;
}

//String Functions
//=========================================================================
Olsk.DeserializeFromJSON = function(jsonString) {
    if (jsonString == null || jsonString == '') return null;
    try {
        eval("var object = " + jsonString);
        return object;
    }
    catch (error) {
        return null;
    }
}
Olsk.GetLocalNumberString = function(number){
    var numberString = new Number(number).toLocaleString();
    return numberString.substr(0, numberString.length - 3);
}
Olsk.ParseToInt = function(str){
    if(str==null || str =='') return '';
    var onlyDigits = Olsk.String.Replace(str,'[^+-0123456789]','')
    return parseInt(onlyDigits);
}
Olsk.String = {}
Olsk.String.Replace = function(text, findString, replaceString){
    var regEx = new RegExp(findString, "g");
    return text.replace(regEx, replaceString);
}
//not tested
//function replace_string(text, findString, replaceString){
//    var findStringLength =  findString.length;
//    for (var replaceIndex = text.indexOf(findString); replaceIndex != -1; replaceIndex = text.indexOf(findString)){ 
//            text = text.substr(0, replaceIndex) + replaceString + text.substr(replaceIndex + findStringLength);
//    }
//    return text;
//}
//RequestXMLHttp Class
//=========================================================================
Olsk.HttpRequest = function(){}
Olsk.HttpRequest.prototype.CreateRequest = function(){
    if (window.XMLHttpRequest) {
        this.Request = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) {
        this.Request = new ActiveXObject('Msxml2.XMLHTTP');
        if(!this.Request) this.Request = new ActiveXObject("Microsoft.XMLHTTP");
    }    
}
Olsk.HttpRequest.prototype.IsLoading = function(){
    return this.Request != null;
}
Olsk.HttpRequest.prototype.Send = function(method, url, callback, parameters){
    if(this.Request) this.Request.abort();
    this.CreateRequest();
    this.Request.onreadystatechange = callback;
    this.Request.open(method, url, true);
    this.Request.send(null);
}
Olsk.HttpRequest.prototype.Receive = function(callbacks, options){
    if(this.Request){
        if (this.Request.readyState == 4){
            if (this.Request.status == 200){
                if(callbacks && callbacks.success!=null){ 
                    callbacks.success(options && options.isJSON ? Olsk.DeserializeFromJSON(this.Request.responseText) : this.Request.responseText);
                }
            } else {
                if(callbacks && callbacks.error != null) callbacks.error();
            }
            this.Request = null;
        }
    }
}
Olsk.HttpRequest.prototype.Get = function(url, callbacks) {
    var thisObject = this;
    if(callbacks && callbacks.loading!=null) callbacks.loading();
    this.Send("GET", url, function(){ thisObject.Receive(callbacks, {isJSON : false}); });
}
Olsk.HttpRequest.prototype.GetJSON = function(url, callbacks) {
    var thisObject = this;
    if(callbacks && callbacks.loading!=null) callbacks.loading();
    this.Send("GET", url, function(){ thisObject.Receive(callbacks, {isJSON : true}); });
}
//Mian.Http Namespace
Olsk.AddQueryParameter = function(queryString, parameterName, parameterValue) {
    if (queryString == null || queryString == undefined) queryString = "";
    if (parameterValue == null || parameterValue == "") return queryString;   
    return queryString
           + (queryString != "" ? "&" : "")
           + parameterName + "=" + escape(parameterValue);
}
//Event Manager Class
//=========================================================================
Olsk.EventManager = function(){
    this.Objects = new Olsk.Dictionary();
}
Olsk.EventManager.prototype.GetEventHandlers = function(eventName, targetObject){
    var objectEventHandlers = this.Objects.GetValueByKey(targetObject);
    if(objectEventHandlers == null) return null;
    return objectEventHandlers.GetValueByKey(eventName);
}
Olsk.EventManager.prototype.GetOrCreateEventHandlers = function(eventName, targetObject){
    if(!this.Objects.ContainsKey(targetObject)) this.Objects.Add(targetObject, new Olsk.Dictionary());
    var objectEventHandlers = this.Objects.GetValueByKey(targetObject);
    if(!objectEventHandlers.ContainsKey(eventName)) objectEventHandlers.Add(eventName, new Array());
    return objectEventHandlers.GetValueByKey(eventName);
}
Olsk.EventManager.prototype.AddEventHandler = function(eventName, targetObject, handler){
    var eventHandlers = this.GetOrCreateEventHandlers(eventName, targetObject);
    eventHandlers.push(handler);
}
Olsk.EventManager.prototype.RemoveEventHandler = function(eventName, targetObject, handler, isRemoveAll) {
    var eventHandlers = this.GetEventHandlers(eventName, targetObject);
    for (index = 0; index < eventHandlers.length; index++) {
        if (handler == eventHandlers[index]) {
            eventHandlers.splice(index, 1);
            if (isRemoveAll != true) return;
        }
    }
}
Olsk.EventManager.prototype.RaiseEvent = function(eventName, targetObject, eventArgs){
    var eventHandlers = this.GetEventHandlers(eventName, targetObject);
    for(var index in eventHandlers) eventHandlers[index](eventArgs);
}
//static
Olsk.EventManager.Instance = new Olsk.EventManager();

Olsk.GetElementByTagName = function(parent, tagName)
{
    for(var index in parent.childNodes)
    {
        var cur = parent.childNodes[index];
        var child =   Olsk.GetElementByTagName(cur,tagName);  
        if(child!=null && child.tagName == tagName) return child;
        var cur = parent.childNodes[index];
        if(cur.tagName == tagName) return cur;
    
    }
    return null;
}
Olsk.GetElementByID = function(node, id) {
    if (node == null) return null;
    if (node.id == id) return node;
    for (var index in node.childNodes) {
        var findNode = Olsk.GetElementByID(node.childNodes[index], id);
        if (findNode != null) return findNode;
    }
    return null;
}
//метод противоречит уникальности id
//Olsk.GetElementsByID = function (node, id, result) {
//    if (node == null) return new Array();
//    if (node.id == id) {
//        if (result == null) result = [];
//        result.push(node);
//    }
//    for (var index in node.childNodes) {
//        result = Olsk.GetElementsByID(node.childNodes[index], id, result);
//    }
//    return result;
//}
Olsk.Advertise = {}
Olsk.Advertise.Adv = function(objectID) {
    this.Container = document.getElementById(objectID);
}
Olsk.Advertise.Adv.prototype.ResizeBanner = function(width, height) {
    if (this.Container != null) {
        this.Container.style.width = width + 'px';
        this.Container.style.height = height + 'px';
    }
}
//========================================
Olsk.mCurrentClientID = 0;
Olsk.GenerateClientID = function(prefix) { return "_" + prefix + (++Olsk.mCurrentClientID); }

Olsk.ScreenSize = function() {
    var w, h; // Объявляем переменные, w - длина, h - высота
    w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
    h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
    sh = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
    sw = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
    mw = (window.innerWidth ? window.innerWidth : document.body.offsetWidth);
    mh = (window.innerHeight ? window.innerHeight : document.body.offsetHeight);
    return { w: w, h: h, mw: mw, mh: mh, sh: sh, sw: sw };
}

Olsk.EvalScripts = function(node) {
    if (node != null && node.tagName == "SCRIPT") {
        var scriptCode = node.innerHTML;
        eval(scriptCode);
        return;
    }
    for (var i = 0; i < node.childNodes.length; i++) {
        Olsk.EvalScripts(node.childNodes[i]);
    }
}

Olsk.DebugClass = function() {
    this.IsNeedOutput = false;
    this.IsNeedLog = false;
    this.Log = new Olsk.Dictionary();
}
Olsk.DebugClass.prototype.StartOutput = function() { this.IsNeedOutput = true; }
Olsk.DebugClass.prototype.StopOutput = function() { this.IsNeedOutput = false; }
Olsk.DebugClass.prototype.StartLog = function() { this.IsNeedLog = true; }
Olsk.DebugClass.prototype.StopLog = function() { this.IsNeedLog = false; }
Olsk.DebugClass.prototype.SetOutput = function(consoleID) { this.Output = document.getElementById(consoleID); }
Olsk.DebugClass.prototype.Print = function(message) {
    if (this.IsNeedOutput == true && this.Output != null) {
        this.Output.innerHTML += "<p>&gt; " + message + "</p>";

    } 
}
Olsk.DebugClass.prototype.Write = function(message, owner) {
    if (this.IsNeedLog == true) {
        if (owner == null) owner = "";
        if (!this.Log.ContainsKey(owner)) this.Log.Add(owner, new Array());
        var messageArray = this.Log.GetValueByKey(owner);
        messageArray.push(message);
    }
    if (owner != null && owner != "") message = owner + ": " + message;
    this.Print(message);
}
Olsk.DebugClass.prototype.ClearLog = function() { this.Log = new Olsk.Dictionary(); }
Olsk.DebugClass.prototype.ClearOutput = function() { if (this.Output != null) this.Output.innerHTML = ""; }
Olsk.DebugClass.prototype.Clear = function() { this.ClearLog(); this.ClearOutput(); }
Olsk.Debug = new Olsk.DebugClass();

Olsk.AddEventListener = function (element, eventName, handler) {
    if (element == null || eventName == null || handler == null) return;
    if (document.addEventListener) {
        element.addEventListener(eventName, handler, true);
    } else if (document.attachEvent) {
        element.attachEvent("on" + eventName, handler, true);
    }
}
