/** 
 * Gamersyde Javascript library
*/
var GSY  = {};

(function() {

    var isIE = !!window.ActiveXObject;
    var timeOutObject       = null;
    
    var _getXhrObject = function() {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        }
        if (window.ActiveXObject){
            var names = [
                "Msxml2.XMLHTTP.6.0",
                "Msxml2.XMLHTTP.3.0",
                "Msxml2.XMLHTTP",
                "Microsoft.XMLHTTP"
            ];
            
            for(var i in names) {
                try { 
                    return new ActiveXObject(names[i]); 
                }
                catch(e){}
            }
        }
        return null; // not supported
    }
    
    GSY.getX = function(el) {
        var _fn = function(el) {
            if (el.offsetWidth === 0) { // IE
                return parseInt(el.style.left);
            }
            // if the given element has a parent node
            if (el.offsetParent) {
                return el.offsetLeft + _fn.call(this, el.offsetParent);
            }
            return el.offsetLeft;
        }
        return _fn.apply(this, arguments);
    }
    
    /**
     * Returns element top offset
     *
     * @function getY
     * @return {Int}
    */
    GSY.getY = function(el) {
        var top = el.offsetTop;
        
        while(el.offsetParent) {
            console.info(top);
            el = el.parentNode;
            top += el.offsetTop;
        }
        //console.info(top);
    }
    
    GSY.shoutboxOn = function(e) {
        if(document.getElementById('shoutbox-message-wrapper').className !== 'mouse-on') {
            document.getElementById('shoutbox-message-wrapper').className = 'mouse-on';
        }
    }
    
    GSY.shoutboxOff = function(e) {
        e = e || window.event;
        document.getElementById('shoutbox-message-wrapper').className = '';
    }

    
    GSY.checkImageDimensions = function(im) {
        
        timeOutObject = window.setTimeout(function() {
        
            var _getDivElement = function(node) {
                while(node.parentNode !== 'DIV' && node.parentNode.style.position !== 'relative') {
                    node = node.parentNode;
                }
                return node.parentNode;
            }
            
            var _createHoverImage = function(hover_image, coords) {
                
                coords = coords || null;
                // Get offsets
                hover_image.style.position = "absolute";
                hover_image.style.left   = im.offsetLeft + "px";
                hover_image.style.top    = im.offsetTop + "px";
                hover_image.style.width  = ((coords) ? coords[0] : hover_image.width)  + "px";
                hover_image.style.height = ((coords) ? coords[1] : hover_image.height) + "px";
                hover_image.style.zIndex = 10;
                hover_image.style.maxWidth = ((coords) ? coords[0] : hover_image.width) + "px";
                hover_image.originalImage = im;
                
                var _div = _getDivElement(im);
                _div.style.overflow = 'visible';
                // Get padding dimensions only if IE
                if(isIE) {
                    var paddingLeft = parseInt(_div.parentNode.currentStyle['paddingLeft']);
                    hover_image.style.left  = (im.offsetLeft - paddingLeft) + "px";
                }
                
                hover_image.onmouseout = function() {
                    hover_image.originalImage.removeAttribute('hovering');
                    hover_image.parentNode.removeChild(hover_image);
                    hover_image = null;
                }
                
                _div.appendChild(hover_image);
            }
            
            if(!im.getAttribute('hovering')) {
                var new_image;
                // Checking if image supports naturalWidth 
                if(!!im.naturalWidth) {
                    if(im.width < im.naturalWidth) {
                        new_image = im.cloneNode(false);
                        new_image.onmouseover = null;
                        _createHoverImage(new_image, [im.naturalWidth, im.naturalHeight]);
                        im.setAttribute('hovering','true');
                    }
                } else {
                    new_image = new Image();
                    new_image.src = im.src;
                    if(!new_image.complete) {
                        new_image.onload = function() {
                            if(im.width < this.width) {
                                _createHoverImage(this);
                                im.setAttribute('hovering','true');
                            }
                        }
                    } else {
                        if(im.width < new_image.width) {
                            _createHoverImage(new_image);
                            im.setAttribute('hovering','true');
                        }
                    }
                }
            }
            
        }, 1000);
    }
    
    GSY.uncheckImageDimensions = function() {
        window.clearTimeout(timeOutObject);
    }
    
    GSY.listenHashChange = function() {
        // Get initial state
        if(document.getElementById('top-news')) {
            
            var initialHash = document.getElementById('top-news').name;
            window.setInterval(function () {
                if(!GSY.Ajax.isCalling) {
                    var urlHash = document.location.hash.substr(1);
                    
                    if(urlHash !== document.getElementById('top-news').name) {
                        if(/^news_ajax_([0-9]+)_[a-z]{2}\.html$/.test(urlHash)) {
                            GSY.Ajax.update('get', '/' + urlHash, 'games-news', function() {
                                window.scrollTo(0, 260);
                            });
                            document.getElementById('top-news').name = urlHash;
                        } else {
                            if(initialHash !== document.getElementById('top-news').name) {
                                GSY.Ajax.update('get', '/' + initialHash, 'games-news', function() {
                                    window.scrollTo(0, 260);
                                });
                                document.getElementById('top-news').name = initialHash;
                            }
                        }
                    }
                }
            }, 50);
        }
    }
    
    GSY.addLoadEvent = function(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                oldonload();
                func();
            }
        }
    }
    
    GSY.run = function(root) {
        if (root.nodeType !== 1) return;
        if (root.tagName.toLowerCase() === 'script') {
            eval(root.text);
        }
        else {
            var n = root.firstChild;
            while (n) {
                if (n.nodeType == 1) GSY.run(n);
                n = n.nextSibling;
            }
        }
    }
    
    GSY.Ajax = {
        
        isCalling : false,
        
        request : function(method, url, callback) {
            
            var xhr = _getXhrObject();
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4 && xhr.status == 200) {
                    
                    if(xhr.responseText.match(/<script type="text\/javascript">(.+)<\/script>/m)) {
                        var _script = /<script type="text\/javascript">(.+)<\/script>/m.exec(xhr.responseText);
                        window['scr'] = xhr.responseText;
                        if(!!_script) {
                            eval(_script[1]);
                        }
                    }
                    callback.call(null, xhr);
                    GSY.Ajax.isCalling = false;
                }
            }
            xhr.open(method.toUpperCase(), url, true); 
            GSY.Ajax.isCalling = true;
            xhr.send(null);
        },
        
        update : function(method, url, id, callback) {
            callback = callback || null;
            GSY.fade(id, 100, 30, 100);
            return this.request(method, url, function(xhr) {
                GSY.fade(id, 30, 100, 100);
                GSY.setContent(id, xhr.responseText);
                if(callback) {
                    callback();
                }
            })
        }
    }
    
    GSY.Shoutbox ={
        
        position : 0,
        end      : false,
        begin    : true,

        previous : function(o, lng) {
            if(this.position > 0 && !this.begin) {
                GSY.Ajax.request('get','shoutbox_ajax_' + String(this.position-1) + '_' + lng + '.html', function(xhr) {
                    GSY.Shoutbox.end = false;
                    
                    if(/scroller\-down\-disabled/.test(document.getElementById('scrollnext').className)) {
                        document.getElementById('scrollnext').className = document.getElementById('scrollnext').className.replace(' scroller-down-disabled', '');
                    }
                    GSY.Shoutbox.position--;
                    if(!xhr.getResponseHeader('X-Shoutbox-Begin')) {
                        GSY.setContent('shoutbox-messages', xhr.responseText);
                        GSY.fade('shoutbox-message-wrapper', 30, 100, 100);
                    } else {
                        GSY.setContent('shoutbox-messages', xhr.responseText);
                        GSY.fade('shoutbox-message-wrapper', 30, 100, 100);
                        GSY.Shoutbox.begin = true;
                        o.className = o.className + ' scroller-up-disabled';
                    }
                    activate_ads();
                });
            } else {
                if(!/scroller\-up\-disabled/.test(o.className)) {
                    o.className = o.className + ' scroller-up-disabled';
                }
            }
        },
        
        next : function(o, lng) {
            if(!this.end) {
                GSY.fade('shoutbox-message-wrapper', 100, 30, 100);
                GSY.Ajax.request('get','shoutbox_ajax_' + String(this.position+1) + '_' + lng + '.html', function(xhr) {
                    GSY.Shoutbox.begin = false;
                    
                    if(/scroller\-up\-disabled/.test(document.getElementById('scrollprev').className)) {
                        document.getElementById('scrollprev').className = document.getElementById('scrollprev').className.replace(' scroller-up-disabled', '');
                    }
                    
                    GSY.Shoutbox.position++;
                    if(!xhr.getResponseHeader('X-Shoutbox-End')) {
                        GSY.setContent('shoutbox-messages', xhr.responseText);
                        GSY.fade('shoutbox-message-wrapper', 30, 100, 100);
                    } else {
                        GSY.setContent('shoutbox-messages', xhr.responseText);
                        GSY.fade('shoutbox-message-wrapper', 30, 100, 100);
                        GSY.Shoutbox.end = true;
                        o.className = o.className + ' scroller-down-disabled';
                    }
                    activate_ads();
                });
            } else {
                if(!/scroller\-down\-disabled/.test(o.className)) {
                    o.className = o.className + ' scroller-down-disabled';
                }
            }
        }
    }
    
    GSY.setContent = function(id, content) {
        if(document.getElementById(id) !== null) {
            document.getElementById(id).innerHTML = content;
            return true;
        }
        return false;
    }
    
    GSY.setOpacity = function(id, opacity) {
        var object = document.getElementById(id);
        object.style.opacity = (opacity / 100);
        object.style.MozOpacity = (opacity / 100);
        object.style.KhtmlOpacity = (opacity / 100);
        // Stupid IE
        object.style.zoom = '1';
        object.style.filter = "alpha(opacity=" + opacity + ")";
    }
    
    GSY.fade = function(id, start, end, ms) {
        var speed = Math.round(ms / 100);
        var timer = 0;
        if(start > end) {
            for(var i = start; i >= end; i--) {
                setTimeout(function() {
                    GSY.setOpacity(id,i);
                }, (timer * speed));
                timer++;
            }
        } else if(start < end) {
            for(var i = start; i <= end; i++){
                setTimeout(function(){
                    GSY.setOpacity(id,i);
                },(timer * speed));
                timer++;
            }
        }
    }
    
})()
