﻿function TwitterBox() 
{
    /* Set properties */
    this.maxTweets = 1;
    this.data;
    this.div;
    this.stateDiv;
    this.processingTimeout = null;
    
    //Constants
    this.LOADING = "loading";
    this.LOADED = "loaded";
}

/* Functions */
TwitterBox.prototype.InitHTTPRequest = function(path, method) {
    if (path != null && path != "") {
        var data = null;

        if (window.XMLHttpRequest) { data = new XMLHttpRequest(); }
        else if (window.ActiveXObject) {
            var IE_XMLHTTPVER = ["MSXML4.XMLHTTP",
								 "MSXML3.XMLHTTP",
								 "MSXML2.XMLHTTP",
								 "MSXML.XMLHTTP",
								 "Microsoft.XMLHTTP"]
            var i = 0;

            while (data == null && i < IE_XMLHTTPVER.length) {
                try { data = new ActiveXObject(IE_XMLHTTPVER[i]); }
                catch (ex) { }
                i++;
            }
        }

        if (data != null) {
            if (data.overrideMimeType) { data.overrideMimeType("text/html"); }
            data.open(method, path, true);

            var box = this;
            data.onreadystatechange = function() {
                if (data.readyState == 4) {
                    if (data.status == 200) {
                        // box.ParseHTML(data.responseText);
                        //if ready loading...
                        box.SetState(box.LOADED);
                        box.ParseHTML(data.responseText);
                    }
                    else {
                        //Error..
                        //console.log("Show Error");
                    }
                    data = null;
                }
            }
        }
    }

    return data;
}

/**HTML Parser for the TwitterBox
*   
* @param HTML, Loaded HTML
*/
TwitterBox.prototype.ParseHTML = function(html) {
    var twitterHTML = ExtractElementHTMLById(html, "jsTwitterdata");
    if (twitterHTML != "" && twitterHTML != null) {
        var tempDiv = document.createElement("div");
        tempDiv.innerHTML = twitterHTML;

        this.div.appendChild(tempDiv.firstChild);
        tempDiv = null;
    }
}

TwitterBox.prototype.HTTPGet = function(path) {
    var data = this.InitHTTPRequest(path, "GET");
    if (data != null) { data.send(null); }
    
    return data;
}

TwitterBox.prototype.LoadTweets = function() {
    //Add loading tag
    this.SetState(this.LOADING);
   
    var path = "/" + this.data + "/twitterdata.html?max=" + this.maxTweets;
    this.HTTPGet(path);
}

/** Set state
*
* @param state, a String/Constant
*/
TwitterBox.prototype.SetState = function(state) {
    switch (state) {
        case this.LOADING:
            //show loading gif
            this.stateDiv = document.createElement("div");
            AddCssClass(this.stateDiv, "loading");
            this.div.appendChild( this.stateDiv );
            break;
        case this.LOADED:
            //remove loading gif
            //RemoveCssClass(this.stateDiv, "loading");
            this.stateDiv.parentNode.removeChild(this.stateDiv); ;
            break;
    }
}

/**
* Create Twitter obj to load tweets in
*
* @param div, a HTML section
*/
function CreateTwitterObj(div)
{
    if (div.className.indexOf("jsTwitter") > -1) 
    {
        var temp = div.title.split("_");
        var page = temp[0];
        var max = temp[1];
        if (page != "" && page != null) {
            var twitterBox = new TwitterBox();
            twitterBox.div = div;
            twitterBox.maxTweets = (max != null && max != "") ? max : 0;
            twitterBox.data = page;

            //Object created let's load Data
            twitterBox.LoadTweets();
        }
    }
}

/**
* Find Twitter div's
*/
AddEvent(window, "load", function() {
    var div = document.body.getElementsByTagName("div");
    for (var i = 0; i < div.length; i++) {
        CreateTwitterObj(div[i]);
    }
});

/**
Generic functions
*/
/**
* AddEvent
*
* @param el, Eventlistener
* @param evt, Event
* @param func, When event invoked the function to be called
*/
function AddEvent(el, evt, func)
{
    if (el.attachEvent) { el.attachEvent("on" + evt, func); } // IE
    else if (el.addEventListener) { el.addEventListener(evt, func, true); } // Gecko / W3C
    else { el["on" + evt] = func; }
}
/**
* GetMatchCount
*
* @param html, The HTML to search through
* @param substring, The string it has to match
*
* @return number, Returns a number if not found retuns 0
**/
function GetMatchCount(html, substring) {
    var regExp = new RegExp(substring, "gim");
    var matches = html.match(regExp);
    return matches == null ? 0 : matches.length;
}

/**
* ExtractElementHTMLById
*
* @param html, The HTML to search through
* @param id, The id it needs to find
*
* @return htmlElement, Returns a html element
* @bug Als er op het element zowel een class als een id opzit splits de functie de div in tweeen en zoekt ook naar een extra afsluittag die niet bestaat.
**/
function ExtractElementHTMLById(html, id) {
    var elementHTML = "";
    var match = new RegExp("<([^>]*) id=\"" + id + "\"[^>]*>", "i").exec(html);

    if (match != null && match.index > -1) {
        var startIndex = match.Index;
        var tagName = match[1];
        html = html.substring(match.index);

        var endTagExpression = "</" + tagName + ">";
        var endTagIndex = html.search(endTagExpression, "i");
        
        if (endTagIndex > -1) {
            endTagIndex += tagName.length + 3;
            var i = 0;
            elementHTML = html.substring(0, endTagIndex);
            html = html.substring(endTagIndex);

            while (GetMatchCount(elementHTML, "<" + tagName + "[^>]*?>") > GetMatchCount(elementHTML, endTagExpression) && i < 5000) {
                endTagIndex = html.search(endTagExpression, "i");

                if (endTagIndex > -1) {
                    endTagIndex += tagName.length + 3;
                    elementHTML += html.substring(0, endTagIndex);
                    html = html.substring(endTagIndex);
                }

                i++;
            }
        }
    }
    
    return elementHTML;
}
/** 
* AddCssClass
*
* @param el, HTML Element 
* @param className, Class to add as a String
**/
function AddCssClass(el, className) {
    if (el.className == "") { el.className = className; }
    else {
        var classes = el.className.split(" ");
        var found = false;
        var i = 0;

        while (!found && i < classes.length) {
            found = classes[i] == className;
            i++;
        }

        if (!found) { el.className += " " + className; }
    }
}

/**
* RemoveCssClass
*
* @param el, HTML Element
* @param className, Class to remove as a String
*/
function RemoveCssClass(el, className) {
    if (el.className != "") {
        var oldClasses = el.className.split(" ");
        var newClasses = "";
        for (var i = 0; i < oldClasses.length; i++) {
            if (newClasses != "") { newClasses += " "; }
            if (oldClasses[i] != className) { newClasses += oldClasses[i]; }
        }

        el.className = newClasses;
    }
}