/** 
 * 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.Ajax2 = {
      request : function(method, url, callback) {
      
        $.get(url, function(data){
          
        });
        
      },
      update : function(method, url, id, callback) {
        GSY.fade(id, 100, 30, 100);
        $.get(url, function(data){
          
          GSY.fade(id, 30, 100, 100);
          GSY.setContent(id, data);
          
        });

        
       
        
      }
      
      
    
    }
    
    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,
        tabs : new Array(),
        
        init : function(shouts) {
          var tbs = new Array(shouts.length);
          for (i=0; i<shouts.length; i++) {
            
            tbs[shouts[i]] = {"position" : 0, "begin" : true, "end" : false};
            
          }
                   
         GSY.Shoutbox.tabs = tbs;
         
         //GSY.Shoutbox.setSize();
          
        },
        refresh : function (lng) {
          
          GSY.fade('shoutbox-message-wrapper'+current_tab, 100, 30, 100);
          
           
          $.get('shoutbox_refresh_'+current_tab+'_'+lng+'.html', function(data){
            
            GSY.fade('shoutbox-message-wrapper'+current_tab, 30, 100, 100);
            if (data.length > 0) {
              //alert(XMLHttpRequest);
              
              $('#shoutbox-messages'+current_tab).html(data);
              
              GSY.Shoutbox.tabs[current_tab]["begin"] = true;
              GSY.Shoutbox.tabs[current_tab]["position"] = 0;
              
              activate_ads();
            }

            
             
          });
          
        },   
        addMsg : function (lng, tab) {
          //On teste le message
          
          if (tab > 0) {
            
            var msg = jQuery.trim($("#what"+tab).val());
            
            if (msg.length > 0) {
              
              GSY.fade('shoutbox-message-wrapper'+tab, 100, 30, 100);  
              msg = encodeURIComponent(msg);
                            
              $.get('shoutbox_ajax_'+lng+'.html?post='+msg+'&tab='+tab, function(data){
                $('#what'+tab).val('');
                GSY.fade('shoutbox-message-wrapper'+tab, 30, 100, 100);
                
                if (data.length > 0) {
                  $('#shoutbox-messages'+tab).html(data);
                  GSY.Shoutbox.tabs[tab]["begin"] = true;
                  GSY.Shoutbox.tabs[tab]["position"] ++; 
                }
                 
              });
              
            }
            
          }
          
          
        
        },
        delMsg : function (lng,msg,tab) {
          //On teste le message
          
          if (tab > 0) {
            
            if (msg > 0) {
              
              GSY.fade('shoutbox-message-wrapper'+tab, 100, 30, 100);  
              
              
                           
              $.get('shoutbox_ajax_'+lng+'.html?IV='+msg+'&tab='+tab, function(data){
                
                GSY.fade('shoutbox-message-wrapper'+tab, 30, 100, 100);
                $('#shoutbox-messages'+tab).html(data);
                //$('#what'+tab).blur(); 
              });
              
            }
            
          }
          
          
        
        },
        next : function(id, lng) {
            
                        
            var tab = GSY.Shoutbox.tabs[id];
            
            if(!tab["end"]) {
                
                GSY.fade('shoutbox-message-wrapper'+id, 100, 30, 100);
                
                $("#shoutnavright"+id).ajaxComplete(function(event, XMLHttpRequest, ajaxOptions) {
                  if (XMLHttpRequest.getResponseHeader('X-Shoutbox-End') == "Yes") {
                    GSY.Shoutbox.tabs[id]["end"] = true;
                  }
                    
                });
                
                $.get('shoutbox_ajax_' + id + '_' + String(tab["position"]+1) + '_' + lng + '.html', function(data, textStatus, XMLHttpRequest){
                  
                  GSY.fade('shoutbox-message-wrapper'+id, 30, 100, 100);
                  if (data.length > 0) {
                    //alert(XMLHttpRequest);
                    
                    $('#shoutbox-messages'+id).html(data);
                    
                    GSY.Shoutbox.tabs[id]["begin"] = false;
                    GSY.Shoutbox.tabs[id]["position"] ++;
                    
                    activate_ads();
                  }
                });
                
                
            } else {
                $("#shoutnavright"+id).addClass("scroller-down-disabled");
                
            }
        },
        prev : function(id, lng) {
            
            var tab = GSY.Shoutbox.tabs[id];
            
            if(!tab["begin"] && tab["position"] > 0) {
                
                GSY.fade('shoutbox-message-wrapper'+id, 100, 30, 100);
                
                $("#shoutnavleft"+id).ajaxComplete(function(event, XMLHttpRequest, ajaxOptions) {
                  if (XMLHttpRequest.getResponseHeader('X-Shoutbox-Begin') == "Yes") {
                    GSY.Shoutbox.tabs[id]["begin"] = true;
                  }
                    
                });
                
                $.get('shoutbox_ajax_' + id + '_' + String(tab["position"]-1) + '_' + lng + '.html', function(data){
                  
                  GSY.fade('shoutbox-message-wrapper'+id, 30, 100, 100);
                  if (data.length > 0) {
                    
                    $('#shoutbox-messages'+id).html(data);
                    GSY.Shoutbox.tabs[id]["end"] = false;
                    GSY.Shoutbox.tabs[id]["position"] --;
                    
                    activate_ads();
                  }
                });
                
                
            } else {
                $("#shoutnavleft"+id).addClass("scroller-down-disabled");
                
            }
        },
        setSize: function () {
          maxHeight = 0;
          for (i=0; i<GSY.Shoutbox.tabs.length; i++) {
            if (GSY.Shoutbox.tabs[i] != null) {
              var height = $('#shout'+i).height();
              if (height > maxHeight)
                maxHeight = height;
            }
          }
          $('.shout').height(maxHeight);
        }
        
    }
    
    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++;
            }
        }
    }
    
})()

