var selectors = new Array();
var modules = new Array();

window.onload = init;

function init() {
    var StyleElements = document.getElementsByTagName('style');
    for (i=0; i<StyleElements.length; i++) {
        processStylesheet(StyleElements[i].innerHTML);
    }
}

function processStylesheet(styletext) {
    startSnippet = '/*[if js]/'; endSnippet = '/[endif]*/'
    while ((startPos = styletext.indexOf(startSnippet))>-1) {
        endPos = styletext.indexOf(endSnippet, startPos);
        
        JSStyle = styletext.substring(startPos+startSnippet.length, endPos);
        
        // process JSStyle
        processJSStyle(JSStyle);
        
        // delete JSStyle
        styletext = styletext.substring(0, startPos) + styletext.substring(endPos+1, styletext.length);
    }
    
}

function processJSStyle(styletext) {

    // look for imports
    startSnippet = '@import '; endSnippet = ';'
    while ((startPos = styletext.indexOf(startSnippet))>-1) {
        endPos = styletext.indexOf(endSnippet, startPos);
        
        importRule = styletext.substring(startPos+startSnippet.length, endPos);
        
        // process importRule
        processImportRule(importRule);
        
        // delete rule
        styletext = styletext.substring(0, startPos) + styletext.substring(endPos+1, styletext.length);
    }
    
    // parse the CSS    
    var theRules = parseCSS(styletext);
    
    // pass the rules to the modules
    for (var i in modules) {
        modules[i](theRules);
    }
    
}
function parseCSS(styletext) {
    // implement css-syntax
    var modi = new Array('selector', 'property', 'value', 'comment');
    
    var keys = {
        'selector': {
            '/*': 'comment',
            '{' : 'property'
        },
        'property': {
            '/*': 'comment',
            ':' : 'value',
            '}' : 'end'
        },
        'value': {
            '/*': 'comment',
            ';' : 'end'
        },
        'comment': {
            '*/': 'end'
        }
    }
    var inmod = new Array();
    inmod[0] = 'selector';
    
    var curPos = 0;
    var parsedText = new Array();
    while (true) {
        var lNextPos = styletext.length;
        var lKey     = '';
        var nextPart = '';
        for (var i in keys[inmod[0]]) {
            var nextPos = styletext.indexOf(i, curPos-1);
            if (nextPos<0) continue;
            if (nextPos < lNextPos) {
                lNextPos = nextPos;
                lKey     = i;
                nextPart = keys[inmod[0]][i];
            }
        }
        if (lKey=='') break;
        var betweentext = styletext.substring(curPos, lNextPos);
        parsedText[parsedText.length] = new SyntaxPart(inmod[0], betweentext);
        curPos = lNextPos + lKey.length;
        if (nextPart=='end') {
            for (var c=0; c<inmod.length-1; c++) {
                inmod[c] = inmod[c+1];
            }
            inmod.pop();
        } else {
            newlength = inmod.length+1;
            for (var c=newlength-1; c>0; c--) {
                inmod[c] = inmod[c-1];
            }
            inmod[0] = nextPart;
        }
    }
    for (var i=0; i<parsedText.length; i++) {
        if (parsedText[i].name=='comment') parsedText.splice(i, 1);
    }
    for (var i=0; i<parsedText.length-1; i++) {
        if (parsedText[i].name==parsedText[i+1].name) {
            parsedText[i].content += parsedText[i+1].content;
            parsedText.splice(i+1, 1);
        }
    }
    for (var i=0; i<parsedText.length; i++) {
        parsedText[i].content = parsedText[i].content.trim();
        if (parsedText[i].content=='') {
            parsedText.splice(i, 1);
            i--;
        }
    }
    
    var rules = new Array();
    
    var ruleIndex = 0; var propertyName = '';
    
    for (var i=0; i<parsedText.length; i++) {
        name    = parsedText[i].name;
        content = parsedText[i].content;
        switch (name) {
            case 'selector':
                ruleIndex = rules.length;
                rules[ruleIndex] = new Rule(content);
                break;
            case 'property':
                propertyName = content;
                break;
            case 'value':
                rules[ruleIndex].properties[propertyName] = new Property(propertyName, content);
                break;
        }
    }
    return rules;
}
function SyntaxPart(name, content) {
    this.name       = name;
    this.content    = content;
}
function Rule(selector) {
    this.selector   = selector;
    this.properties = new Array();
}
function Property(name, value) {
    this.name       = name;
    this.value      = value;
}
function processImportRule(importRule) {
    filename = '';
    switch(importRule.substr(0,1)) {
        case '"':
            filename = importRule.substring(1, importRule.indexOf('"', 1));
            break;
        case "'":
            filename = importRule.substring(1, importRule.indexOf("'", 1));
            break;
        case "u":
            if (importRule.substring(0, 3)=='url') {
                filename = importRule.substring(4, importRule.indexOf(')'));
                if (filename.substr(0,1)=='"' || filename.substr(0,1)=="'") filename = filename.substring(1);
                fl = filename.length;
                if (filename.substr(fl-1, 1)=='"' || filename.substr(fl-1, 1)=="'") filename = filename.substr(0, fl-1);
            }
            break;
    }
    myRequest(filename, loadNewStylesheet);
    
}
function loadNewStylesheet(theText) {
    processJSStyle(theText);
}



/* A little Ajax from bazzinet.info (slightly changed) */
function myRequest(myUrl, callBackFunction) 
{
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest(); // Gecko (Firefox, Moz), KHTML (Konqueror, Safari), Opera, Internet Explorer 7
    } else if(window.ActiveXObject) {
       try{
        xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); // Internet Explorer 6 
       } catch(e) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer 4,5 
       }
    } else {
        return false;
    }
    xmlhttp.open("GET", myUrl+'?randomid=6351768715', true); // Open a connection. Replace GET with HEAD in order to do a HEAD request.

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4) { // Wait until everything is fetched!
            callBackFunction(xmlhttp.responseText); // Passes the contents of the response to the callback-function.
        }
    }
    xmlhttp.send(null); // send() is used to initiate the transfer. No actual data have to be sent in this case.
}

/* I need to remove Whitespace. */
String.prototype.trim = function() {
  var x=this;
  x=x.replace(/^\s*(.*?)/, "$1");
  x=x.replace(/(.*?)\s*$/, "$1");
  return x;
}

/* Debug-Funktion */
function debugprint(text) {
    document.getElementsByTagName('body')[0].innerHTML += '<!--'+text+'-->';
}