
function pair(nombre)
{
   if(nombre/2 == Math.round(nombre/2))
   {
      return 1;
   }
   else
   {
      return 0;
   }
}

function AttachEvent(obj,evt,fnc,useCapture)
{
    if (!useCapture) useCapture=false;
    
    if (obj.addEventListener)
    {
        obj.addEventListener(evt,fnc,useCapture);
        return true;
    }
    else if (obj.attachEvent)
    {
        return obj.attachEvent("on"+evt,fnc);
        return true;
    }
    else
    {
        if(!obj['on'+evt])
        {
            obj['on'+evt] = fnc;
            return true;
        }
        else
        {
            var oldfnc = obj['on'+evt];
            obj['on'+evt] = function() {
                oldfnc(); fnc();
            }
            return true;
        }
    }
}

function file(fichier)
{
    if (window.XMLHttpRequest) // FIREFOX
        httpRequest = new XMLHttpRequest();
    else if (window.ActiveXObject) // IE
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    else
        return(false);
    
    httpRequest.open("GET", fichier, false);
    httpRequest.send(null);
    
    if (httpRequest.readyState == 4)
        return(httpRequest.responseText);
    else
        return(false);
}

function request(url,onResponseComplete,that)
{
    if (window.XMLHttpRequest) // FIREFOX
        httpRequest = new XMLHttpRequest();
    else if (window.ActiveXObject) // IE
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    else
        return(false);

    if (that)
    {
        if (httpRequest.addEventListener)
        {
            httpRequest.addEventListener('load',function(event){
                onResponseComplete(event.target.responseText,that);
            },false);
        }
        else
        {
            httpRequest.onreadystatechange = function()
            {
                if (this.readyState == 4)
                {
                    onResponseComplete(this.responseText,that);
                }
            };
        }
    }
    else
    {
        if (httpRequest.addEventListener)
        {
            httpRequest.addEventListener('load',function(event){
                onResponseComplete(event.target.responseText);
            },false);
        }
        else
        {
            httpRequest.onreadystatechange = function()
            {
                if (this.readyState == 4)
                {
                    onResponseComplete(this.responseText);
                }
            };
        }
    }
    
    httpRequest.open("GET", url, true);
    httpRequest.send(null);
}

function scroll()
{
    var preload = this.attributes.getNamedItem('preload').value * 1.0;
    var scroll_height = this.attributes.getNamedItem('scroll.height').value * 1.0;
    var box_height = this.attributes.getNamedItem('box.height').value * 1.0;
    if (this.attributes.getNamedItem('box.size'))
        var box_size = this.attributes.getNamedItem('box.size').value;
    
    var childs = this.getElementsByTagName('div');
    
    var total = childs.length;
    
    // first load the displayed elements
    
    var start = Math.floor(this.scrollTop / box_height);
    var end   = Math.ceil((this.scrollTop + scroll_height) / box_height);
    for (var i = Math.max(start,0) ; i < Math.min(total,end) ; i++)
    {
        if (pair(i) == 1)
            var even = 1;
        else
            var even = 0;
        var div = childs[i];
        if (div && !div.loaded && div.id != 'nogame')
        {
            div.innerHTML = file('game-minibox.php?even='+even+'&game='+div.id.substr(4, div.id.length - 4)+(box_size?'&size='+box_size:'')+(category?'&category='+category:'')+(order?'&order='+order:''));
            div.loaded = true;
        }
        //if (div && !div.loaded && !div.loading && div.id != 'nogame')
        //{
        //    request('game-minibox.php?even='+even+'&game='+div.id.substr(4, div.id.length - 4)+(box_size?'&size='+box_size:'')+(category?'&category='+category:'')+(order?'&order='+order:''),function(response,element){
        //        element.innerHTML = response;
        //        element.loaded = true; element.loading = false;
        //    },div);
        //    div.loading = true;
        //}
    }
    
    // then, preload what's requested
    
    var preload_start = Math.floor(this.scrollTop / box_height) - preload;
    var preload_end   = Math.ceil((this.scrollTop + scroll_height) / box_height) + preload;
    
    for (var i = Math.max(preload_start,0) ; i < Math.min(total,preload_end) ; i++)
    {
        if (pair(i) == 1)
            var even = 1;
        else
            var even = 0;
        var div = childs[i];
        if (div && !div.loaded && !div.loading && div.id != 'nogame')
        {
            div.loading = true;
            request('game-minibox.php?even='+even+'&game='+div.id.substr(4, div.id.length - 4)+(box_size?'&size='+box_size:'')+(category?'&category='+category:'')+(order?'&order='+order:''),function(response,element){
                element.innerHTML = response;
                element.loaded = true; element.loading = false;
            },div);
        }
    }
}

function launchAjaxSearch(order, filter_platform)
{
	var mySearch = document.searchform.searchbox.value;
	if (mySearch == '')
		return false;
	else
	{
		load_page('catalog_table.php?ajax=true&order='+order+'&filter_platform='+filter_platform+'&letter_filter='+mySearch, 'container_catalog_list', '', '', 'fade1');
		return false; 
	}
}

function launchSearch(id,order)
{
    if (id == 0 && order == '')
    {
        var mySearch = document.searchform.searchbox.value;
        if (mySearch == '')
            return false;
        else
        {
            location.href = (typeof rooturl != 'undefined' ? rooturl+'/' : '')+'search.php?letter_filter='+mySearch;
            return false; 
        }
    }
    
    else if(id == 1)
    {
        var mySearch = document.getElementById('searchbox2').value;
        if (mySearch == '')
            return false;
        else
        {
            resp = file('search-action.php?search='+mySearch+'&order='+order);
            var tab = resp.split('|');
            document.getElementById('searchresult').innerHTML = tab[1];
            return false;
        }
    }
}

function getKeyForSearch(key)
{
    if (key == 13)
    {
        launchSearch(1,'');        
    }
    return false;
}

function getSearchResults(search)
{
    resp = file('search-action.php?search='+search);
    var tab = resp.split('|');
   // document.getElementById('searchnb').innerHTML = tab[0];
    document.getElementById('searchresult').innerHTML = tab[1];
}

function move(url)
{
    location.href = url;
}

function reloadCaptcha()
{
    var id = file('captcha.php');
    document.getElementById('captcha_id').value = id;
    document.getElementById('captchadiv').firstChild.src = 'cache/'+id+'.png';
}

function MM_findObj(n, d) { //v4.01
    var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
    if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
    if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_preloadImages() { //v3.0
    var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
        var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
        if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_swapImgRestore() { //v3.0
    var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_swapImage() { //v3.0
    var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
    if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

window.setInterval(function(){request((typeof rooturl != 'undefined' ? rooturl+'/' : '')+'ping.php',function(){})}, 20 * 60 * 1000);

function WriteSWF(str){
    document.write(str);
}
function ActivateSWF(str)
{
    var e = document.getElementById('homeBlogIt');
    if (e)
    {
        var p = e.parentNode;
        var i = p.innerHTML;
                p.innerHTML = '';
                p.innerHTML = i;
        
        return true;
    }
    else
    {
        return false;
    }
}

function cookie_create( 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 + "=" + value + expires + "; path=/";
}

function cookie_read( 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 c.substring( nameEQ.length, c.length );
    }

    return "";
}

function cookie_erase( name ) {
    createCookie( name, "", -1 );
}

function footer_init()
{
    var footer_display = cookie_read( 'fd' );
    
    var ft = document.getElementById('footer_title');
    var fc = document.getElementById('footer_content');
    var al = document.getElementById('arrow_left');
    var ar = document.getElementById('arrow_right');

    if( footer_display == "0" )
    {
        if (fc) fc.style.display = 'none';
        if (ft) ft.style.display = '';
        if (al) al.style.backgroundImage = 'url('+(typeof rooturl != 'undefined' ? rooturl+'/' : '')+'images/fond_fleche.jpg)';
        if (ar) ar.style.backgroundImage = 'url('+(typeof rooturl != 'undefined' ? rooturl+'/' : '')+'images/fond_fleche.jpg)';
    }
    else
    {
        if (ft) ft.style.display = 'none';
        if (fc) fc.style.display = '';
        if (al) al.style.backgroundImage = 'url('+(typeof rooturl != 'undefined' ? rooturl+'/' : '')+'images/fond_fleche_up.jpg)';
        if (ar) ar.style.backgroundImage = 'url('+(typeof rooturl != 'undefined' ? rooturl+'/' : '')+'images/fond_fleche_up.jpg)';
    }
}
function footer_toggle()
{
    var footer_display = cookie_read( 'fd' );

    var ft = document.getElementById('footer_title');
    var fc = document.getElementById('footer_content');
    var al = document.getElementById('arrow_left');
    var ar = document.getElementById('arrow_right');
    
    if( footer_display == "0" )
    {
        if (ft) ft.style.display = 'none';
        if (fc) fc.style.display = '';
        if (al) al.style.backgroundImage = 'url('+(typeof rooturl != 'undefined' ? rooturl+'/' : '')+'images/fond_fleche_up.jpg)';
        if (ar) ar.style.backgroundImage = 'url('+(typeof rooturl != 'undefined' ? rooturl+'/' : '')+'images/fond_fleche_up.jpg)';
        cookie_create( "fd", "1", 150 );
       
    }
    else
    {
        if (fc) fc.style.display = 'none';
        if (ft) ft.style.display = '';
        if (al) al.style.backgroundImage = 'url('+(typeof rooturl != 'undefined' ? rooturl+'/' : '')+'images/fond_fleche.jpg)';
        if (ar) ar.style.backgroundImage = 'url('+(typeof rooturl != 'undefined' ? rooturl+'/' : '')+'images/fond_fleche.jpg)';
        cookie_create( "fd", "0", 150 );
    }
}

// permet de cacher/montrer un block en fct
// @param string_identifiante : un chaine permettant de connaitre l'identite de la ou des zones a traiter
// @param type : permet de savoir s'il s(agit d'un div, d'une class ou autre
// @param force_action : si ce parametre est mentionne, il aura la valeur "show" ou "hide", sinon, la fct affiche si cache, et cache si visible
function show_hide(string_identifiante, type, force_action)
{
    
    switch (type)
    {
        // si on considere que c une classe
        case 'class':
            if (force_action == "show")
                $(string_identifiante).css({'display': 'block'});
            else if (force_action == "show")
                $(string_identifiante).css({'display': 'none'});
            // si force action n'est pas specifie
            else{
                if ($(string_identifiante).css('display') == "none")
                    $(string_identifiante).css({'display': 'block'});
                else
                    $(string_identifiante).css({'display': 'none'});
                    
            }
            break;
            
        // cas par defaut: on considere que c'est un div
        default:
            //alert(string_identifiante);
            //alert($('#'+string_identifiante).css('display'));
            if (force_action == "show")
                $('#'+string_identifiante).css({'display': 'inline'});
            else if (force_action == "hide")
                $('#'+string_identifiante).css({'display': 'none'});
            // si force action n'est pas specifie
            else{
                if ($('#'+string_identifiante).css('display') == "none")
                    $('#'+string_identifiante).css({'display': 'inline'});
                else
                    $('#'+string_identifiante).css({'display': 'none'});
                    
            }
            break;
    }

} 

function htmlspecialchars(ch) {
   ch = ch.replace(/&/g,"&amp;")
   ch = ch.replace(/\"/g,"&quot;")
   ch = ch.replace(/\'/g,"&#039;")
   ch = ch.replace(/</g,"&lt;")
   ch = ch.replace(/>/g,"&gt;")
   return ch
}

function encode_whosegame_ajax(ch) {
   ch = ch.replace(/&/g,"%26")
   ch = ch.replace(/\"/g,"%22")
   ch = ch.replace(/\'/g,"%27")
   ch = ch.replace(/</g,"%3C")
   ch = ch.replace(/>/g,"%3E")
   return ch
}


// fct permettnat de mettre a jour le contenu d'un div
// utile dans load_ajax notamment car elle incopore les animations
function update_div_content (div_dest, content, animation)
{
    if (animation == "fade1")
    {
        $("#"+div_dest).fadeOut("fast",
            function()
            {
                $("#"+div_dest).html(content);
                $(this).fadeIn("fast");
                
            }
        );
    }
    
    else if (animation == "slide1")
    {
        $("#"+div_dest).slideToggle("slow",
            function()
            {
                $("#"+div_dest).html(content);
                $(this).show("slow");
                
            }
        );
    }
    else if (animation == "hide1")
    {
        $("#"+div_dest).hide("slow",
            function()
            {
                $("#"+div_dest).html(content);
                $(this).show("slow");
                
            }
        );
    }
    
    else
        $("#"+div_dest).html(content);
}

function load_page (page, div_dest, params_post, type_params_post, animation)
{

    var data_to_post = "";
    var old_content = $("#"+div_dest).html();
    
    if (params_post){
        if (type_params_post == "form_name")
        {
            $(":input").each(function(){
                var div_type  = $(this).attr("type");
                var div_content  = "";
                var keep_value_in_post = true;
                if ((div_type == "checkbox"))
                    var div_content = $(this).attr("checked");
                else if (div_type == "radio")
                {
                    if($(this).attr("checked"))
                        var div_content = $(this).val();
                    else
                        keep_value_in_post = false;
                }
                else
                    var div_content = $(this).val();
                if (div_content == undefined) div_content="";
                
                // since decodeURIComponent doesn't like %, we replace them with there HTML value
                if (typeof(div_content) == 'string') div_content= div_content.replace(/%/g,"&#37;");
                
                if (keep_value_in_post)
                    data_to_post += $(this).attr("name") + "=" + encode_whosegame_ajax(decodeURIComponent(div_content))+"&";
                    
            });
            
        }
        else
        {
        
            for (i=0; i<params_post.length; i++)
            {
                //alert(params_post[i]);
                var div_id  = params_post[i];
                var div_type = $("#"+ div_id).attr("type");
                var keep_value_in_post = true;
                
                if (div_type == "checkbox")
                    var div_content = $("#"+ div_id).attr("checked");
                    
                else if (div_type == "radio")
                {
                    if($("#"+ div_id).attr("checked"))
                        var div_content = $("#"+ div_id).val();
                    else
                        keep_value_in_post = false;
                }
                else
                    var div_content = $("#"+ div_id).attr("value");
                
                // since decodeURIComponent doesn't like %, we replace them with there HTML value
                if (typeof(div_content) == 'string') div_content= div_content.replace(/%/g,"&#37;");
                
                data_to_post += div_id + "=" + encode_whosegame_ajax(decodeURIComponent(div_content));
                
                if (i < params_post.length-1) 
                    data_to_post +="&";
            }
        }
    }
    
    
    $.ajax({
        type: "POST",
        url: page,
        data: data_to_post,
        //timeout: 200000,
        success: function(msg){
            error_msg = "error while loading, please try again...";
            if (msg.length>0){
                //alert('ok');
                update_div_content(div_dest, msg, animation);
            }
            else {
                //alert('KO : retour vide');
                //$("#"+div_dest).prepend(error_msg);
                old_content ='<div class="bold">'+error_msg+' </div>' +old_content;
                update_div_content(div_dest, old_content, animation);
            }
        },
        beforeSend: function(){
            
            if($("#loading_popup"))
            {
                $("#loading_popup").css('width', $("#"+ div_dest).width());
                $("#loading_popup").css('height', $("#"+ div_dest).height());
                $("#loading_popup").css('padding-top', ($("#"+ div_dest).height()/3));
                $("#loading_popup").css('display', 'block');
                $("#"+div_dest).html("");
            }
        },
        
        error: function(){
            if($("#loading_popup"))
            {
                //alert('KO : error');
                //if timeout, we relaod the initial page with a quick mesage
                // TODO translate the message
                //old_content ='<div class="bold">timeout, please try again</div>' +old_content;
                update_div_content(div_dest, old_content, animation);
            }
        },
        
        complete: function(){
            if($("#loading_popup"))
             {
                $("#loading_popup").fadeOut("fast");
             }
            // something?
        }
    });
 return false;
}
// fct utile permettant de mettre a jour un champ dans un div d'id div_id
// pratique pour mettre a jour rapidement
function change_div_field(div_id, field_to_update, new_value)
{
    $("#"+div_id).attr(field_to_update, new_value);
}

// used to chaec on the size of the form's input fields
// check the size and bring the focus back to the area explored

function max_length(text,length) {
    if(text.value.length>length)
        text.value = text.value.substr(0,length);
    text.focus();
}
