

/* Iphone redirection */
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
    }
    return null;
}
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+escape(value)+expires+"; path=/";
}
var agent=navigator.userAgent.toLowerCase();

var is_iphone = (agent.indexOf('iphone')!=-1);
// startseite,kein iphone cookie und iphone dann frag ob mobile version benutzt werden soll
if (is_iphone &&  readCookie('askiphone')==null && /trader.de\/?$/.test( document.location) ) {
    createCookie("askiphone",1,7);
    location.href="http://iphone.godmode-trader.de/switch/index.html";
}

/* random cookie for ajaxpush dispatching */
if ( readCookie('bg_rnd')==null)  {

    var date = new Date();
    date.setTime(date.getTime()+(7*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();

    document.cookie = "bg_rnd="+escape(Math.floor(Math.random()*100000+1))+expires+"; path=/; domain=.godmode-trader.de";
}






var documentReady = false;
var latestScroll;

if( typeof allHeightAdjustments == 'undefined' ) {
    var allHeightAdjustments = {};
}

var tooltTipChart;

var bgTools =  {


    opacity : function(id, opacStart, opacEnd, millisec) {
        var speed = Math.round(millisec / 100);
        var timer = 0;

        if(opacStart > opacEnd) {
            for(i = opacStart; i >= opacEnd; i--) {
                setTimeout("bgTools.changeOpac(" + i + ",'" + id + "')",(timer * speed));
                timer++;
            }
        } else if(opacStart < opacEnd) {
            for(i = opacStart; i <= opacEnd; i++)
                {
                setTimeout("bgTools.changeOpac(" + i + ",'" + id + "')",(timer * speed));
                timer++;
            }
        }
    },

    changeOpac : function (opacity, id) {
        var object = document.getElementById(id);
        object.style.opacity = (opacity / 100);
        object.style.MozOpacity = (opacity / 100);
        object.style.KhtmlOpacity = (opacity / 100);
        object.style.filter = "alpha(opacity=" + opacity + ")";
    },

    fadeIn : function(id) {
        /*document.getElementById(id).style.display = 'block';*/
        this.opacity(id, 0, 100, 200);
    },

    fadeOut : function(id) {
        this.opacity(id, 100, 0, 200);
        setTimeout('document.getElementById("'+id+'").style.left = "-2000px"',200);
    },


    showTooltip : function(el,instrumentId,exchangeId,quoteSource,instrumentName) {

        infoDiv = document.getElementById('tooltipinfo');
        coordinates = mouseCoords(el);

        sepp = new ChartStyle();
        sepp.chartType = 'mountain';
        sepp.xLabelColor = 'rgba(102,102,102,0.3)';
        sepp.xLabelFontSize = 10;
        sepp.xLabelFontFamily = 'Arial';
        sepp.yLabelColor = '#777777';
        sepp.yLabelFontSize = 12;
        sepp.yLabelFontFamily = 'Arial';
        sepp.gridColor = 'rgba(223,223,223,0.3)';
        sepp.lineColor = 'rgba(200,160,0,1)';
        sepp.lineWidth = 1;
        sepp.markerLineColor = 'rgba(255,225,106,0)';
        sepp.markerBackgroundColor = 'rgba(200,160,0,1)';
        sepp.markerFontSize = 12;
        sepp.markerFontFamily = 'arial';
        sepp.markerBackgroundColorDown = 'rgba(200,0,0,1)';
        sepp.markerBackgroundColorUp = 'rgba(60,200,0,1)';
        sepp.markerColor = 'rgba(255,255,255,1)';
        sepp.markerPadding = [2, 4, 2, 4];
        sepp.infoLabelColor = 'rgba(200,160,0,1)';
        sepp.infoLabelFontSize = 18;


        if( infoDiv ) {
             infoDiv.style.left = coordinates.x + 15 + 'px';
             infoDiv.style.top = coordinates.y -50 + 'px';
             tooltTipChart = new Chart('tooltipChart',instrumentId,exchangeId,quoteSource);
             tooltTipChart.setSpanSimple(ESpans.DAY);
             //tooltTipChart._source._instrumentName = instrumentName;
             tooltTipChart.setStyle(sepp);
             this.changeOpac(0,"tooltipinfo");
        } else {
             body = document.getElementById('bgo');

             div = document.createElement('div');
             div.id = "tooltipinfo";
             div.className = 'shadow';
             div.style.position = 'absolute';
             div.style.left = coordinates.x + 15 + 'px';
             div.style.top = coordinates.y -50 + 'px';
             div.style.zIndex = 100000;
             div.id = "tooltipinfo";

             div2 = document.createElement('div');
             div2.className = 'shadow2';
             div.appendChild(div2);

             divfin = document.createElement('div');

             divfin.innerHTML = document.getElementById('dummy').innerHTML + '<div id="tooltipChart"></div>';
             divfin.style.background = '#fff';

             div.appendChild(divfin);

             body.appendChild(div);

             this.changeOpac(0, "tooltipinfo");

             tooltTipChart = new Chart('tooltipChart',instrumentId,exchangeId,quoteSource);
             tooltTipChart.setSpanSimple(ESpans.DAY);
             tooltTipChart.addChart(150);
             //tooltTipChart._source._instrumentName = instrumentName;
             tooltTipChart.setStyle(sepp);

             bgTools.removeChildrenFromNode(document.getElementById('dummy'));
        }

        this.fadeIn('tooltipinfo');

    },



    popup : function(theURL,winName,features) {
		window.open(theURL,winName,features);

	},


    /*getElementsByClassName : function(a,b,c) {
        return getElementsByClassName(a,b,c);
    },  */




    removeChildrenFromNode : function(node) {
       if(node !== undefined && node !== null) {
          return;
       }

       var len = node.childNodes.length;

       while (node.hasChildNodes()) {
          node.removeChild(node.firstChild);
       }
    },

    createCollapsible: function(imgIdentifier, contentIdentifier) {
       var img = document.getElementById(imgIdentifier);
       if (img == null) {
           return;
       }
       var content = document.getElementById(contentIdentifier);

       img.onmouseover = function() {if (img.src.lastIndexOf('min.gif') > 0) {
                                        img.src = img.src.replace(/_min\.gif/g,'_min_off.gif');
                                     } else {
                                        img.src = img.src.replace(/_max\.gif/g,'_max_off.gif');
                                     }};
       img.onmouseout = function() {if (img.src.lastIndexOf('min_off.gif') > 0) {
                                        img.src = img.src.replace(/_min_off\.gif/g,'_min.gif');
                                     } else {
                                        img.src = img.src.replace(/_max_off\.gif/g,'_max.gif');
                                     }};
       img.onclick = function() {if (img.src.lastIndexOf('min_off.gif') > 0) {
                                   content.style.display = 'none';
                                   img.src = img.src.replace(/_min_off\.gif/g,'_max_off.gif');
                                } else {
                                   content.style.display = '';
                                   img.src = img.src.replace(/_max_off\.gif/g,'_min_off.gif');
                                }}
    },

    createTabbedBox : function(identifier, behavior, callback) {
        var context = document.getElementById('tabbox_' + identifier);
        var tabs = bgTools.getElementsByClassName('tab_' + identifier, 'a', context);

        var contentIdentifier   = tabs[0].rel.replace(/.*\/(.*?)$/,'$1');
        document.getElementById(contentIdentifier).style.display = 'block';

        bgTools.activate(tabs[0], context);

        for( var i=0;i<tabs.length;i++ ) {
             if (behavior == 'onClick') {
                 tabs[i].onclick = function() {
                    if( callback ) {
                        callback(this);
                    }
                    bgTools.activate(this, context);
                    return false;
                 }
             } else {
                 tabs[i].onmouseover = function() {
                    bgTools.activate(this, context);
                    //this.blur();
                 }

                 tabs[i].onmousemove = function() {
                     //this.blur();
                 }

                 tabs[i].onclick = function() {
                    //return false;
                 }
             }

        }
    },

    checkAll : function(className) {
        var elements = bgTools.getElementsByClassName(className);

        for( var i=0; i<elements.length; i++ ) {
            elements[i].checked = true;
        }
    },

    uncheckAll : function(className) {
        var elements = bgTools.getElementsByClassName(className);

        for( var i=0; i<elements.length; i++ ) {
            elements[i].checked = false;
        }
    },

    activate : function(activeElement, context) {
        var identifier = activeElement.className.replace('tab_','');
        var tabs = bgTools.getElementsByClassName('tab_' + identifier, 'a', context);

        mySplitResult = identifier.split(" ");
        identifier = mySplitResult[0];
        jQuery('#h_' + identifier).children('div').hide();

        for( var i=0;i<tabs.length;i++ ) {
             contentIdentifier   = tabs[i].rel.replace(/.*\/(.*?)$/,'$1');
             if(activeElement == tabs[i]) {
                  //tabs[i].className = 'tab_'+identifier+' act';
                  jQuery('#'+contentIdentifier).show();
             }
        }

    },

    doXmlHttpRequest : function(callback, url, method, params) {
        var xmlHttp = null;
        if (typeof XMLHttpRequest != 'undefined') {
            xmlHttp = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            if (navigator.userAgent.toLowerCase().indexOf("msie 5") != -1) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } else {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
        }

        xmlHttp.open(method, url, true);
        xmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

        if (method == 'POST') {
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        }

        var urlParams = '';
        if(typeof params != 'string' && typeof params != 'number') {
            for (var name in params) {
                urlParams += name+'='+params[name];
                urlParams += '&';
            }
        } else {
            urlParams = params;
        }

        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4) {
                callback(xmlHttp.responseText, params);
            }
        };

        xmlHttp.send(urlParams);
    },

    heightAdjust : function( cssClassName, itemHeight, cssId, tag ) {

        return;
        //FIXME

        allHeightAdjustments[cssId] = [cssClassName, itemHeight, cssId,tag];



        if(cssId) {
            identifier = cssId;
        } else {
            return;
        }

        tag = tag ? tag : 'a';

        //var adjustArray = bgTools.getElementsByClassName(cssClassName,tag,document.getElementById(identifier));

        adjustArray = jQuery( '#' + identifier + ' ' + tag + '.' + cssClassName );
        var initLength = 0;
        for(i=0;i<adjustArray.length;i++) {
            if( adjustArray[i].scrollHeight > itemHeight ) {
                var text = adjustArray[i].firstChild.nodeValue;
                if (typeof text == 'string') {
                    initLength = text.length;
                    xxx=0;
                    while(adjustArray[i].scrollHeight > itemHeight  && xxx < 100) {
                        var text = text.substr(0,initLength-xxx-3) + '...';
                        adjustArray[i].firstChild.nodeValue = text;
                        xxx++;
                    }
                }
            }
        }
    },

    setCookie : function( name, value, expires, path, domain, secure )
    {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime( today.getTime() );

        /*
        if the expires variable is set, make the correct
        expires time, the current script below will set
        it for x number of days, to make it for hours,
        delete * 24, for minutes, delete * 60 * 24
        */
        if ( expires )
        {
        expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date( today.getTime() + (expires) );

        document.cookie = name + "=" +escape( value ) +
        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
        ( ( path ) ? ";path=" + path : "" ) +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );
    },

    // this fixes an issue with the old method, ambiguous values
    // with this test document.cookie.indexOf( name + "=" );
    getCookie : function ( check_name ) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for ( i = 0; i < a_all_cookies.length; i++ )
        {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split( '=' );


            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if ( cookie_name == check_name )
            {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if ( a_temp_cookie.length > 1 )
                {
                    cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if ( !b_cookie_found ) {
            return null;
        }
    }
};


bgTools.Json = new (function(){
    var useHasOwn = !!{}.hasOwnProperty;

    // crashes Safari in some instances
    //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;

    var pad = function(n) {
        return n < 10 ? "0" + n : n;
    };

    var m = {
        "\b": '\\b',
        "\t": '\\t',
        "\n": '\\n',
        "\f": '\\f',
        "\r": '\\r',
        '"' : '\\"',
        "\\": '\\\\'
    };

    var encodeString = function(s){
        if (/["\\\x00-\x1f]/.test(s)) {
            return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                var c = m[b];
                if(c){
                    return c;
                }
                c = b.charCodeAt();
                return "\\u00" +
                    Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }) + '"';
        }
        return '"' + s + '"';
    };

    var encodeArray = function(o){
        var a = ["["], b, i, l = o.length, v;
            for (i = 0; i < l; i += 1) {
                v = o[i];
                switch (typeof v) {
                    case "undefined":
                    case "function":
                    case "unknown":
                        break;
                    default:
                        if (b) {
                            a.push(',');
                        }
                        a.push(v === null ? "null" : bgTools.Json.encode(v));
                        b = true;
                }
            }
            a.push("]");
            return a.join("");
    };

    this.encodeDate = function(o){
        return '"' + o.getFullYear() + "-" +
                pad(o.getMonth() + 1) + "-" +
                pad(o.getDate()) + "T" +
                pad(o.getHours()) + ":" +
                pad(o.getMinutes()) + ":" +
                pad(o.getSeconds()) + '"';
    };

    this.isArray = function(v){
        return v && typeof v.length == 'number' && typeof v.splice == 'function';
    };

    this.isDate = function(v){
        return v && typeof v.getFullYear == 'function';
    };

    /**
     * Encodes an Object, Array or other value
     * @param {Mixed} o The variable to encode
     * @return {String} The JSON string
     */
    this.encode = function(o){
        if(typeof o == "undefined" || o === null){
            return "null";
        }else if(bgTools.Json.isArray(o)){
            return encodeArray(o);
        }else if(bgTools.Json.isDate(o)){
            return bgTools.Json.encodeDate(o);
        }else if(typeof o == "string"){
            return encodeString(o);
        }else if(typeof o == "number"){
            return isFinite(o) ? String(o) : "null";
        }else if(typeof o == "boolean"){
            return String(o);
        }else {
            var a = ["{"], b, i, v;
            for (i in o) {
                if(!useHasOwn || o.hasOwnProperty(i)) {
                    v = o[i];
                    switch (typeof v) {
                    case "undefined":
                    case "function":
                    case "unknown":
                        break;
                    default:
                        if(b){
                            a.push(',');
                        }
                        a.push(this.encode(i), ":",
                                v === null ? "null" : this.encode(v));
                        b = true;
                    }
                }
            }
            a.push("}");
            return a.join("");
        }
    };

    /**
     * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
     * @param {String} json The JSON string
     * @return {Object} The resulting object
     */
    this.decode = function(json){
        return eval("(" + json + ')');
    };
})();


function loadHistoricPerformance(domObject, instrumentId, targetId) {
    var params = {'instrumentId'        : instrumentId,
                  'date'                : domObject.value,
                  'targetId'            : targetId
                 };
    bgTools.doXmlHttpRequest(loadHistoricPerformanceUpdateHook, '/historicperformance/', 'POST', params);
}

function loadHistoricPerformanceUpdateHook(response, params) {
    document.getElementById(params.targetId).innerHTML = response;
}


document.onmousemove = mouseMove;

function mouseMove(ev){
    ev           = ev || window.event;
    var mousePos = mouseCoords(ev);
}

function mouseCoords(ev){
    if(ev.pageX || ev.pageY){
        return {x:ev.pageX, y:ev.pageY};
    }

    if (!document.body) {
        return;
    }

    return {
        x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y:ev.clientY + document.body.scrollTop  - document.body.clientTop
    };
}


document.onmouseup = mouseUp;
var dragObject     = null;


function mouseUp(ev){
    dragObject = null;
}



document.onmousemove = mouseMove;
document.onmouseup   = mouseUp;

var dragObject  = null;
var mouseOffset = null;

function getMouseOffset(target, ev){
    ev = ev || window.event;

    var docPos    = getPosition(target);
    var mousePos  = mouseCoords(ev);
    return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
    var left = 0;
    var top  = 0;

    while (e.offsetParent){
        left += e.offsetLeft;
        top  += e.offsetTop;
        e     = e.offsetParent;
    }

    left += e.offsetLeft;
    top  += e.offsetTop;

    return {x:left, y:top};
}

function mouseMove(ev){
    ev           = ev || window.event;
    var mousePos = mouseCoords(ev);

    if(dragObject){

        dragObject.style.position = 'absolute';
        dragObject.style.top      = (mousePos.y - mouseOffset.y) + 'px';
        dragObject.style.left     = (mousePos.x - mouseOffset.x) + 'px';
        return false;
    }
}


function mouseUp(){
    dragObject = null;
}


function heightAdjust( cssClassName, itemHeight,cssId ) {
    return;
    //FIXME

    bgTools.heightAdjust(cssClassName, itemHeight,cssId);
}


function changeOverviewChart( imgUrl, link ) {
     document.getElementById('marketOverviewChartImg').src      = imgUrl;
     document.getElementById('marketOverviewChartHref').href    = link;
}


var mlConf_image         = null;
var mlConf_realImgWidth  = null;
var mlConf_realImgheight = null;
var mlConf_growInterval  = null;
var mlConf_curwidth      = null;
var mlConf_widthReady    = false;

var miniLightbox = {

    show : function (url) {

        bgo = document.getElementById('bgo');

        rechts = bgo.getClientRects()[0].right

        var layer           = document.createElement("div");
        lStyle              = layer.style;
        lStyle.position     = 'absolute';
        lStyle.left         = '0px';
        lStyle.top          = window.scrollY + 'px';
        lStyle.height       = window.innerHeight + 'px';
        lStyle.width        = '100%';
        lStyle.background   = '#000000';
        lStyle.zIndex       = 4999;
        layer.id            = 'didyouknowlayer';
        layer.className     = 'transparent';

        layer.onclick = function() {
            document.getElementById('didyouknowlayer').parentNode.removeChild(document.getElementById('didyouknowlayer'))
            document.getElementById('didyouknowlayerimage').parentNode.removeChild(document.getElementById('didyouknowlayerimage'))
            clearInterval( mlConf_growInterval );
        }

        image = document.createElement("img");
        image.src = url;

        mlConf_image = image;

        mlConf_image.style.position     = 'absolute';
        mlConf_image.style.marginLeft   = '30px';
        mlConf_image.style.marginRight  = 'auto';
        mlConf_image.style.zIndex       = 5000;
        mlConf_image.id                 = 'didyouknowlayerimage';

        mlConf_realImgWidth  = image.width;
        mlConf_realImgHeight = image.height;

        mlConf_image.onclick = function() {
            document.getElementById('didyouknowlayer').parentNode.removeChild(document.getElementById('didyouknowlayer'))
            document.getElementById('didyouknowlayerimage').parentNode.removeChild(document.getElementById('didyouknowlayerimage'))
            clearInterval( mlConf_growInterval );
        }

        bgo.appendChild(mlConf_image);

        bgo.appendChild(layer);

        imageReal = document.getElementById('didyouknowlayerimage');
        imageReal.width  = 10;

        mlConf_growInterval = setInterval('miniLightbox.growImage();',10);

    },

    growImage : function () {

        mlConf_image.style.left = window.innerWidth/2 - mlConf_image.width/2 + 'px';
        mlConf_image.style.top  = window.innerHeight/2 - mlConf_image.height/2 + 'px';

        layerImg = document.getElementById('didyouknowlayerimage');

        if( !mlConf_widthReady ) {
            mlConf_growRate = mlConf_realImgWidth/25;
            layerImg.width  += mlConf_growRate;
            layerImg.height = 5;
        }

        if( layerImg.width + mlConf_growRate >= mlConf_realImgWidth ) {
            mlConf_widthReady = true;
        }

        if( mlConf_widthReady ) {
            mlConf_growRate = mlConf_realImgWidth/15;
            mlConf_image.style.opacity = 0.2;
            layerImg.height  += mlConf_growRate;
        }

        if( layerImg.height + mlConf_growRate >= mlConf_realImgHeight ) {
            layerImg.width  = mlConf_realImgWidth;
            layerImg.height = mlConf_realImgHeight;

            clearInterval( mlConf_growInterval );
            mlConf_widthReady = false;
            mlConf_image.style.opacity = 1.0;
            mlConf_image.style.left = window.innerWidth/2 - mlConf_image.width/2 + 'px';
            mlConf_image.style.top  = window.scrollY + window.innerHeight/2 - mlConf_image.height/2 + 'px';
        }

    }

}

/*
    Developed by Robert Nyman, http://www.robertnyman.com
    Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
bgTools.getElementsByClassName = function (className, tag, elm){
    if (document.getElementsByClassName) {
        bgTools.getElementsByClassName = function (className, tag, elm) {
            elm = elm || document;
            var elements = elm.getElementsByClassName(className),
                nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
                returnElements = [],
                current;
            for(var i=0, il=elements.length; i<il; i+=1){
                current = elements[i];
                if(!nodeName || nodeName.test(current.nodeName)) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    else if (document.evaluate) {
        bgTools.getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = "",
                xhtmlNamespace = "http://www.w3.org/1999/xhtml",
                namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
                returnElements = [],
                elements,
                node;
            for(var j=0, jl=classes.length; j<jl; j+=1){
                classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
            }
            try    {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
            }
            catch (e) {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
            }
            while ((node = elements.iterateNext())) {
                returnElements.push(node);
            }
            return returnElements;
        };
    }
    else {
        bgTools.getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
                classesToCheck = [],
                elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
                current,
                returnElements = [],
                match;
            for(var k=0, kl=classes.length; k<kl; k+=1){
                classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
            }
            for(var l=0, ll=elements.length; l<ll; l+=1){
                current = elements[l];
                match = false;
                for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
                    match = classesToCheck[m].test(current.className);
                    if (!match) {
                        break;
                    }
                }
                if (match) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    return bgTools.getElementsByClassName(className, tag, elm);
};



function MouseMoved(ev,delta) {

	if( !delta) { delta = 0; }
    var div = document.getElementById('mouseFollower');

    if( div != null ) {

	    ev = ev || window.event;

	    coords = mouseCoords(ev);

	    ieOffsetRel = document.all ? document.documentElement.scrollTop : 0;

	    div.style.left = (coords.x + 25 ) + 'px';
	    div.style.top  = (coords.y + ieOffsetRel + 25 - delta*50) + 'px';
    }
}

function handle(delta,event) {
	MouseMoved(event,delta);
}



function wheel(event){
	var delta = 0;
	if (!event) {
		event = window.event;
	}
	if (event.wheelDelta) {
		delta = event.wheelDelta/120;
		if (window.opera) {
			delta = -delta;
		}
	} else if (event.detail) { /** Mozilla case. */
			delta = -event.detail/3;
	}
	if (delta) {
		handle(delta,event);
	}
}

function rmEl(id) {
    if( document.getElementById(id) ) {
        document.getElementById(id).parentNode.removeChild(document.getElementById(id));
    }
}

function backgroundLayer( url, width, height, options ) {

    body = document.getElementById('bgo');

    div = document.createElement('div');
    div.id = 'message_bg_div';
    div.style.position = 'absolute';
    div.style.height = window.innerHeight + 'px';
    div.style.top   = window.scrollY + 'px';
    div.style.width = body.offsetWidth + 'px';
    div.style.background = 'black';
    div.style.zIndex = 25000;
    div.style.opacity = 0.8;
    div.onclick = function() { rmEl(this.id); rmEl('message_fg_div');  }
    body.appendChild(div);

    innerDiv = document.createElement('div');
    innerDiv.id                  = 'message_fg_div';
    innerDiv.style.position      = 'absolute';
    innerDiv.style.textAlign     = 'center';
    //innerDiv.style.height        = height+'px';
    innerDiv.style.width         = width+'px';
    innerDiv.style.top           = window.innerHeight/2-height/2 + 'px';
    innerDiv.style.left          = body.offsetWidth/2-width/2 + 'px';
    innerDiv.style.background    = '#555';
    innerDiv.style.zIndex        = 25001;
    body.appendChild(innerDiv);

    bgTools.doXmlHttpRequest( function( a ) { document.getElementById('message_fg_div').innerHTML = a; }, url, 'POST', options );


}

function insertAfter(parent, node, referenceNode) {
    parent.insertBefore(node, referenceNode.nextSibling);
}

var heightAdjustInterval = setInterval('heightAdjustIntervalFunction();',200);

function heightAdjustIntervalFunction() {

   var ts = Number(new Date());
   if ( ts-latestScroll < 2500 ) {
   	return;
	}


    if( typeof(jQuery) == 'function' ) {

        documentReady = true;
        for( ii in allHeightAdjustments) {
            config = allHeightAdjustments[ii];
            heightAdjust(config[0],config[1],config[2]);
        }
    }
    clearInterval(heightAdjustInterval);
    heightAdjustInterval = setInterval('heightAdjustIntervalFunction();',2000);

}

function reloadSingleSegment(id,segmentcode) {
    //jQuery('#'+id).load( '/loader?rand='+Math.random(), {'segmentcode':segmentcode,'rand':Math.random()} );
    //console.log('loader');
}

jQuery(document).ready( function() {

    jQuery('.reloadme').each( function() {
        setInterval("reloadSingleSegment( '"+jQuery(this).attr('id')+"','"+jQuery(this).attr('segmentcode') +"');", jQuery(this).attr('reload')*1000 );
        reloadSingleSegment( jQuery(this).attr('id'),jQuery(this).attr('segmentcode') );
    });

	$(window).scroll( function() {
		latestScroll = Number(new Date());
	});


} );

function fieldOnFocus(field) {
    if (field.value == field.defaultValue) {
        field.value = '';
        field.className = 'light active';
    }
}

function fieldOnBlur(field) {
    if (field.value == '') {
        field.value = field.defaultValue;
        field.className = 'light';
    }
}




    function handleButtons(obj) {
        //console.log(this);
        obj     = jQuery(obj);

        jQuery('a',obj.parent()).each( function() {
                myObj = jQuery(this);
                myObj.removeClass('act');
                myImg   = jQuery('img',myObj);
                if(myImg.attr('src')) {
                    url     = myImg.attr('src').replace('-act','');
                    myImg.attr('src',url);
                }
        } );

        obj.addClass('act');
        if(myImg.attr('src')) {
            myImg   = jQuery('img',obj);
            url     = myImg.attr('src').replace('-act','').replace('.png','-act.png');
            myImg.attr('src',url);
        }
    }


    var indicatorsToggle = {'sma':false,'tma':false,'wma':false,'ema':false,'bb':false};

    function toggleIndicator(indicator,obj) {
        if( !indicatorsToggle[indicator] ) {
            c.getChart(0).addIndicator(indicator);
            indicatorsToggle[indicator] = true;
            jQuery(obj).addClass('act');
        } else {
            allInds = c.getChart(0).ac;
            for( ind in allInds ) {
                if( allInds[ind].type == indicator ) {
                    c.getChart(0).removeIndicator(ind);
                }
            }
            indicatorsToggle[indicator] = false;
            jQuery(obj).removeClass('act');
        }
    }

    function renewIndicators() {
            allInds = c.getChart(0).ac;
            for( ind in allInds ) {
                c.getChart(0).removeIndicator(ind);
            }
    }

