//Init object and replace all
var mySLTitles = new SLTITLES();


//Settings
//NO SL, then we replace "myClassName" , "myClassName_plain"
mySLTitles.SetXAP("http://maerlantmwp.schoolwerkplek.nl/Portals/_default/Skins/Maerlant/replace title/ClientBin/SLTitleReplacement.xap");
//mySLTitles.AddClass("head");

//Windows.onload
function _slTitleLoader() {
    mySLTitles.replaceAll();
    mySLTitles = null;
}

if (window.addEventListener) {
    window.addEventListener('load',_slTitleLoader,false);
}
else {
    window.attachEvent('onload',_slTitleLoader);
}


//By putting all functions in an Object, we create our own namespace.
function SLTITLES() {


    //var classnames contains all candidates for replacement
    var classNames = new Array();
    var origional_onload = window.onload;
    var xappath = "";
    
    
    //Adding classes before calling replaceAll();
    this.AddClass = function(aClassname) {
        classNames.push(aClassname);
    }


    //Setting the path to the XAP-file
    this.SetXAP = function(aPath) {
        xappath = aPath;
    }
    
    
    //FF Rbg value to Hex.
    this._convertColor = function(aRgbValue) {
        str = aRgbValue.replace(/rgb\(|\)/g, "").split(",");
        str[0] = parseInt(str[0], 10).toString(16).toLowerCase();
        str[1] = parseInt(str[1], 10).toString(16).toLowerCase();
        str[2] = parseInt(str[2], 10).toString(16).toLowerCase();
        str[0] = (str[0].length == 1) ? '0' + str[0] : str[0];
        str[1] = (str[1].length == 1) ? '0' + str[1] : str[1];
        str[2] = (str[2].length == 1) ? '0' + str[2] : str[2];
        return ('#' + str.join(""));
    }
    
    
    //Find a rendered style-element in an object
    this._getStyle = function(oElm, strCssRule) {

        var strValue = "";
        if (document.defaultView && document.defaultView.getComputedStyle) {
            //Firefox and so..
            stylelem = document.defaultView.getComputedStyle(oElm, null);

            switch (strCssRule) {
                case "fontSize": strValue = stylelem.fontSize; break;
                case "fontFamily": strValue = stylelem.fontFamily; break;
                case "color": strValue = this._convertColor(stylelem.getPropertyValue(strCssRule)); break;
                default: strValue = stylelem.getPropertyValue(strCssRule);
            }
        }
        else if (oElm.currentStyle) {
            strCssRule = strCssRule.replace(/\-(\w)/g, function(strMatch, p1) {
                return p1.toUpperCase();
            });
            strValue = oElm.currentStyle[strCssRule];
        }
        return strValue;
    }


    //Replace the innerHTML of an object with our silverlightobject
    //Place the innerHTML invisible behind our object (SEO)
    this._writer = function(txt, element) {
        element.innerHTML = txt + "<div style='display:none;'>" + element.innerHTML + "</div>";
    }


    //Create a windowless Silverlight object
    //Watch the initParams in this function!
    this._createSLTitle = function(parentObject) {

        if (typeof (parentObject) == 'object') {

            //stripping tags (escape()?)
            var awidth = this._getStyle(parentObject, "width");
            var aheight = this._getStyle(parentObject, "height");
            var params =
                "height=" + aheight +
                ",width=" + awidth +
                ",fontsize=" + this._getStyle(parentObject, "fontSize") +
                ",fontfamily=" + this._getStyle(parentObject, "fontFamily") +
                ",color=" + this._getStyle(parentObject, "color") +
                ",innerhtml=" + parentObject.innerHTML.replace(/<\/?[^>]+>/gi, '');

            if (awidth == "auto") awidth = "100%";
            if (aheight == "auto") aheight = "100%";

            var objScript =
                         '<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="' + awidth + '" height="' + aheight + '">';
            objScript += '<param name="source" value="' + xappath + '"/>';
            objScript += '<param name="onerror" value="onSilverlightError" />';
            objScript += '<param name="windowless" value="true" />';
            objScript += '<param name="background" value="#00000000" />';
            objScript += '<param name="initParams" value="' + params + '" />';
            //objScript += '<a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;">';
            //objScript += '<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>';
            //objScript += '</a>';
            objScript += '</object>';

            //Helper function call -> will add the object to DIV
            this._writer(objScript, parentObject);
        }
    }


    this.getElementsByClassName = function(class_name, object) {

        var all_obj, ret_obj = new Array(), j = 0;
        if (object) {
            all_obj = object.childNodes;
        }
        else {
            if (document.all)
                all_obj = document.all;
            else if (document.getElementsByTagName && !document.all)
                all_obj = document.getElementsByTagName("*");
        }

        for (i = 0; i < all_obj.length; i++) {
            classname = all_obj[i].className;
            if (classname != undefined) {
                if (classname.indexOf(" ") != -1) {
                    classname = classname.split(" ");
                    for (k = 0; k < classname.length; k++) {
                        if (classname[k] == class_name) {
                            ret_obj[j] = all_obj[i];
                            j++;
                        }
                    }
                }
                else {
                    if (classname == class_name) {
                        ret_obj[j] = all_obj[i];
                        j++;
                    }
                }
            }
        }
        return ret_obj;
    }


    //Loop to the selected classnames, find all objects with that classname and try to replace them with our Silvlightobject.
    this.replaceAll = function() {

        var useSL;
        try {
            control = new ActiveXObject('AgControl.AgControl');
            useSL = true;
            control = null;
        }
        catch (e) {
            var plugin = navigator.plugins["Silverlight Plug-In"];
            useSL = (plugin);
            plugin = null;
        }

        for (var i in classNames) {
            var elems = this.getElementsByClassName(classNames[i], null);
            for (var j in elems) {
                var elem = elems[j];
                if (useSL)
                    this._createSLTitle(elem);
                else
                    try {
                    elem.className = elem.className.replace(classNames[i], "");
                } catch (err) {
                    //Object without a style, don't have fonts to begin with.
                }
            }
        }
    }
}