﻿function encodeXml(input) {
    if (input == undefined) {
        alert("error in xmlEncode: input undefined");
        return;
    }
    //input	=	trim(input.toString());

    var replace_with = '&amp;';
    // The 'g' in the first argument is used to tell the function 'replace' 
    // that all occurences (g = global)
    // of the character in between slashes have to be replaced.
    input = input.replace(/&/g, replace_with);

    replace_with = '&lt;';
    input = input.replace(/</g, replace_with);

    replace_with = '&gt;';
    input = input.replace(/>/g, replace_with);

    replace_with = '&apos;';
    input = input.replace(/'/g, replace_with);

    replace_with = '&quot;';
    input = input.replace(/"/g, replace_with);

    return input;
}

function encodeHtml(input) {
    if (input == undefined) {
        alert("error in htmlencode: input undefined");
        return;
    }
    //input	=	trim(input.toString());

    var replace_with = '&amp;';
    // The 'g' in the first argument is used to tell the function 'replace' 
    // that all occurences (g = global)
    // of the character in between slashes have to be replaced.
    input = input.replace(/&/g, replace_with);

    replace_with = '&lt;';
    input = input.replace(/</g, replace_with);

    replace_with = '&gt;';
    input = input.replace(/>/g, replace_with);

    replace_with = '&quot;';
    input = input.replace(/"/g, replace_with);

    return input;

}

// C# style String.Format
function sformat() {
    var formatted = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var regexp = new RegExp('\\{' + (i-1) + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
}; 


function isSet(variable){
    if(typeof(variable) == "undefined" || variable == null){
        return false;
    }
    return true;
}

function toStr(variable) {
    if (!isSet(variable)) {
        return "";
    }

    return "" + variable;
}

function left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function Hashmap(){
    this.values = new Array();
    this.keys = new Array();
    this.objects = new Array();
}

Hashmap.prototype = {

    getCount:function(){
        return this.keys.length;
    },
    
    getKey:function(index){
        return this.keys[index];
    },
    
    getValue:function(index){
        return this.values[index];
    },
    
    getObject:function(index){
        return this.objects[index];
    },
    
    get:function(key){
        var index = this.findIndex(key);
        if(index > -1){
            return [this.values[index], this.objects[index]];
        }
        return null;
    },
    
    getValueByKey:function(key){
        var arr = this.get(key);
        if(arr != null){
            return arr[0];
        }
        return null;
    },
    
    getObjectByKey:function(key){
        var arr = this.get(key);
        if(arr != null){
            return arr[1];
        }
        return null;
    },
    
    findIndex:function(key){
        for(var i = 0; i < this.keys.length; i++){
            if(this.keys[i] == key){
                return i;
            }
        }
        return -1;
    },
    
    set:function(key, value, obj){
        var index = this.findIndex(key);
        if(index > -1){
            this.values[index] = value;
            this.objects[index] = obj;
        }else{
            this.values.push(value);
            this.objects.push(obj);
            this.keys.push(key);
        }
    },
    
    clear:function(){
        for( var i = 0; i < this.keys.length; i++ ){
            this.keys.pop(); this.values.pop(); this.objects.pop();
        }
    },
    
    remove:function(key){
        var index = this.findIndex(key);
        if(index > -1){
            this.values.splice(index, 1);
            this.keys.splice(index, 1);
            this.objects.splice(index, 1);
        }
    },
    
    removeAt:function(index){
        if(index > -1 && index < keys.length){
            this.values.splice(index, 1);
            this.keys.splice(index, 1);
            this.objects.splice(index, 1);
        }
    } 
}


/*
MessageQueue Object manages outgoing messages to the server
it contains a a queue that holds messages to be sent.
This queue will be periodically read by the SimpleConnection object and its messages sent
to the server.

it contains the following methods:
enqueue(message): adds an xml message to the queue
dequeue(): pulls a message out of the queue and returns it to the caller
getCount(): returns the number messages in the queue

*/
function MessageQueue(parent) {
    this.parent = parent;
    this.queue = new Array();
}

MessageQueue.prototype = {
    enqueue: MessageQueue_Enqueue,
    dequeue: MessageQueue_Dequeue,
    getCount: MessageQueue_GetCount,
    clear: function(){
        this.queue.length = 0;
    }
};

function MessageQueue_Enqueue(message) {
    this.queue.push(message);
}

function MessageQueue_Dequeue() {
    if (this.queue.length > 0) {
        return this.queue.shift();
    }
    return null;
}

function MessageQueue_GetCount() {
    return this.queue.length;
}


/*
MessageListener object maps a Message and its Type to a listener represented by the func pointer 
and the targetObject that contains this function
*/
function MessageListener(msgName, msgType, msgCommand, msgSchema, func, targetObject) {
    this.messageName = msgName;
    this.messageType = msgType;
    this.messageCommand = msgCommand;
    this.messageSchema = msgSchema;
    this.callbackFunc = func;
    this.targetObject = null;
    if (typeof (targetObject) != "undefined") {
        this.targetObject = targetObject;
    }
}

/*
MessageListeners object manages the listeners

methods:
addListener(listener): adds a listener to the MessageListeners object
removeListerner(listener): removes the listener from the MessageListeners object
fireMessageReceived(message): calls the callbackFunc of the listeners which messageName and messageType 
                              matches with the message parameter
*/
function MessageListeners(parent) {
    this.parent = parent;
    this.listeners = new Array();
}

MessageListeners.prototype = {
    addListener: MessageListeners_AddListener,
    removeListerner: MessageListeners_RemoveListener,
    fireMessageReceived: MessageListeners_FireMessageReceived,
    clear: function() {
        this.listeners.length = 0;
    }
};

function MessageListeners_AddListener(listener) {
    this.listeners.push(listener);
}

function MessageListeners_RemoveListener(listener) {
    for (var i = 0; i < this.listeners.length; i++) {
        if (this.listeners[i] == listener) {
            this.listeners.splice(i, 1);
            return;
        }
    }
}

function MessageListeners_FireMessageReceived(message) {
    for (var i = 0; i < this.listeners.length; i++) {
        if (this.listeners[i].messageName == message.tagName &&
            (this.listeners[i].messageType == message.type || this.listeners[i].messageType == "*")) {
            
            if(this.listeners[i].messageCommand == message.command || this.listeners[i].messageCommand == "*"){  
                if(typeof(message.schema) != "undefined" && this.listeners[i].messageSchema != null 
                   && this.listeners[i].messageSchema != "" && this.listeners[i].messageSchema != "*"){
                    if (this.listeners[i].messageSchema != message.schema) {
                        continue;
                    }
                }
                
                var obj = this.listeners[i].targetObject;
                var func = this.listeners[i].callbackFunc;
                //            if (obj != null) {
                //                obj.func(this.parent, message);
                //            } else {
                //                func(this.parent, message);
                //            }
                func(this.parent, message, obj);
                //this.listeners[i].callbackFunc(this.parent, message, this.listeners[i].targetObject);
            }
        }
    }
}

/*
EventListeners object manages events like connected, disconnected

methods:
addListener(callbackFunc): adds a callback function "callbackFunc" to the EventListeners object
removeListerner(listener): remoces the callback function "callbackFunc" from the EventListeners object
fireEvent(message): calls the callbackFunc of the listeners which messageName and messageType 
matches with the message parameter
*/
function EventListeners(parent) {
    this.parent = parent;
    this.listeners = new Array();
}

EventListeners.prototype = {
    fireEvent: function(args) {
        var obj = null;
        var func = null;
        for (var i = 0; i < this.listeners.length; i++) {
            obj = this.listeners[i][1];
            func = this.listeners[i][0];
            //            if (obj != null) {
            //                obj.func(this.parent, args);
            //            } else {
            //                func(this.parent, args);
            //            }
            func(this.parent, args, obj);
            //this.listeners[i](this.parent, args);
        }
    },

    addListener: function(callbackFunc, targetObject) {
        var obj = null;
        if (typeof (targetObject) != "undefined") {
            obj = targetObject;
        }
        this.listeners.push([callbackFunc, obj]);
    },

    removeListener: function(callbackFunc, targetObject) {
        var obj = null;
        if (typeof (targetObject) != "undefined") {
            obj = targetObject;
        }
        for (var i = 0; i < this.listeners.length; i++) {
            if (this.listeners[i][0] == callbackFunc && this.listeners[i][1] == obj) {
                this.listeners.splice(i, 1);
                return;
            }
        }
    },
    clear: function() {
        this.listeners.length = 0;
    }
}



function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function saveCookie(cookieName, cookieValue) {
    var strCookie = "";
    if (cookieName != null && cookieName != "") {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + 14);
        var str = cookieName + "=" + escape(cookieValue) + "; " +
                    "expires=" + exdate.toGMTString() + "; path=/";
        document.cookie = str;
    }
}

function loadUUID() {
    var uuid = getCookie("SimpleUUID");
    return uuid;
}

function saveUUID(uuid) {
    saveCookie("SimpleUUID", uuid);
}

function addAjaxLoader(elem_id, type) {
    var jquery_elem = $("#" + elem_id);
    var imgName = "ajax-loader-indicator.gif";
    if (typeof (type) != "undefined") {
        if (type == "snake") {
            imgName = "ajax-loader-snake.gif";
        }
        else if (type == "bigcircleball") {
            imgName = "ajax-loader-bigcircleball.gif";
        }
        else if (type == "indicator") {
            imgName = "ajax-loader-indicator.gif";
        }
    }
    jquery_elem.append("<div class='ajax_loader_container'> <div class = 'ajax_loader_content'> <img src= 'images/" + imgName +"'  /> </div> </div>");
}

function removeAjaxLoader(elem_id) {
    var jquery_elem = $("#" +elem_id +">.ajax_loader_container");
    jquery_elem.remove();
}

function detectUrl(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.match(urlRegex);
}

function htmlUrl(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    var strUrls = text.match(urlRegex);

    if (strUrls != null) {
        for (var i = 0; i < strUrls.length; i++) {
            text = text.replace(strUrls[i], "<a class='stream_text_Link' href='" + strUrls[i] + "' target='_blank' >" + strUrls[i] + "</a>");
        }
    }

    return text;
}
