var mainToolbar= new Array;
var consoleNewGenId= new Array;
var consoleOldGenId= new Array;
var consoleNewGenIdExt= new Array;
var consoleOldGenIdExt= new Array;
var channel=0;
var channelId="multi";
var tab1Toolbar= new Array;
var tab2Toolbar= new Array;
var fontColor= new Array;
var childToolbarColor = new Array;
var tickerColor = new Array;
var screenRes= new Array;
var newsTab = new Array;
var consoleIdExt=new Array;
var urlForum=new Array;
var hp=0;
var sfondoOff;
var pulsantiera; // se 0 disabilita lagestione della main toolbar da javascript
var bgActive = 1; //immagini
var keyBg = 0;
var idusr = 0;
var apuser = false;
var bgContest = 0;
var hpBorderLink="";
var sf = 0; //spaziofilm


function setVar() {
    addEvent($obj('txtSearch'),'keypress',Search);
    addEvent($obj('txtSearch'), 'keyup', AutoSearch);
    addEvent($obj('a_search'),'click',Search);
    addEvent($obj('txtSearch'), 'focus', ClearTxtSearch);
    
    if($obj('txt_user')!=null)addEvent($obj('txt_user'), 'focus', ClearTxt);    
    //addEvent($obj('txtSearch'), 'keyup', AutoSearch);
    //addEvent($obj('a_search'),'click',Search);
    
    if($obj('exit')!=null)addEvent($obj('exit'),'click',EsciAP);
    if($obj('a_enter')!=null)addEvent($obj('a_enter'),'click',EnterCommunity);
    if ($obj('btn_enter') != null) addEvent($obj('btn_enter'), 'click', EnterCommunity2);
    
    addEvent($obj('a_play'), 'mouseover', OpenPlay2);
    addEvent($obj('a_play'), 'click', OpenPlay);
    addEvent($obj('a_my'), 'mouseover', OpenMy2);
    addEvent($obj('a_my'), 'click', OpenMy);
    if(idusr!=0 && $obj('pagpersonale')!=null) $obj('pagpersonale').href = "/utenti/index.aspx?i=" + idusr;
    if (idusr != 0 && $obj('a_my') != null)
        $obj('a_my').href = "/utenti/index.aspx?i=" + idusr;
    else
        $obj('a_my').href = "/help/info_utenti_registrati.aspx";

    mainToolbar[0] = "multi";
    mainToolbar[1] = "pc";
    mainToolbar[2] = "ps3";
    mainToolbar[3] = "x360";
	mainToolbar[4] = "wii";
	mainToolbar[5] = "wiiu";
	mainToolbar[6] = "n3ds";
	mainToolbar[7] = "nds";
	mainToolbar[8] = "psp";
	mainToolbar[9] = "psvita";
	mainToolbar[10] = "apple";
	mainToolbar[11] = "ps2";
	mainToolbar[12] = "xbox";
	mainToolbar[13] = "cube";
	mainToolbar[14] = "psx";
	mainToolbar[15] = "n64";
	mainToolbar[16] = "gba";
	mainToolbar[17] = "dc";
	mainToolbar[18] = "saturn";
	mainToolbar[19] = "neogeo";
	mainToolbar[20] = "cinema";
	mainToolbar[21] = "my";
	mainToolbar[22] = "tech"; // "community";
	mainToolbar[23] = "play";
	mainToolbar[24] = "shop";  

    consoleNewGenId[0] = "multi";
	consoleNewGenId[1] = "pc";
    consoleNewGenId[2] = "ps3";
    consoleNewGenId[3] = "x360";
    consoleNewGenId[4] = "wii";
    consoleNewGenId[5] = "wiiu";
    consoleNewGenId[6] = "3ds";
    consoleNewGenId[7] = "nds";
    consoleNewGenId[8] = "psp";
    consoleNewGenId[9] = "psvita";
	consoleNewGenId[10] = "apple";	
	consoleNewGenId[11] = "mobile";
	consoleNewGenId[12] = "tech";

    consoleOldGenId[0] = "ps2";
    consoleOldGenId[1] = "xbox";
    consoleOldGenId[2] = "cube";
    consoleOldGenId[3] = "psx";
    consoleOldGenId[4] = "n64";
    consoleOldGenId[5] = "gba";
    consoleOldGenId[6] = "dc";
    consoleOldGenId[7] = "saturn";
    consoleOldGenId[8] = "neogeo";

    consoleIdExt[0] = "multi_piattaforma";
    consoleIdExt[1] = "pc";
    consoleIdExt[2] = "playstation_ps3";
    consoleIdExt[3] = "xbox360";
    consoleIdExt[4] = "nintendo_wii";
	consoleIdExt[5] = "nintendo_wiiu";
	consoleIdExt[6] = "nintendo_3ds";
	consoleIdExt[7] = "nintendo_nds";
	consoleIdExt[8] = "playstation_psp";
	consoleIdExt[9] = "playstation_psvita";
	consoleIdExt[10] = "apple";
	consoleIdExt[11] = "playstation_ps2";
	consoleIdExt[12] = "xbox";
	consoleIdExt[13] = "nintendo_cube";
	consoleIdExt[14] = "playstation_psx";
	consoleIdExt[15] = "nintendo_n64";
	consoleIdExt[16] = "nintendo_gameboy_advance";
	consoleIdExt[17] = "sega_dreamcast";
	consoleIdExt[18] = "sega_saturn";
	consoleIdExt[19] = "neogeo";
	consoleIdExt[20] = "cinema";
	consoleIdExt[21] = "mobile_cellulari";
	consoleIdExt[22] = "tecnologia";

    consoleNewGenIdExt[0] = "multi_piattaforma";
	consoleNewGenIdExt[1] = "pc";
    consoleNewGenIdExt[2] = "playstation_ps3";
    consoleNewGenIdExt[3] = "xbox360";
    consoleNewGenIdExt[4] = "nintendo_wii";
    consoleNewGenIdExt[5] = "nintendo_wiiu";
    consoleNewGenIdExt[6] = "nintendo_3ds";
	consoleNewGenIdExt[7] = "nintendo_nds";
	consoleNewGenIdExt[8] = "playstation_psp";
	consoleNewGenIdExt[9] = "playstation_psvita";
	consoleNewGenIdExt[10] = "apple_iphone";		
	consoleNewGenIdExt[11] = "mobile_cellulari";
	consoleNewGenIdExt[12] = "tecnologia";
	

    consoleOldGenIdExt[0] = "playstation_ps2";
	consoleOldGenIdExt[1] = "xbox";
    consoleOldGenIdExt[2] = "nintendo_cube";
    consoleOldGenIdExt[3] = "playstation_psx";
    consoleOldGenIdExt[4] = "nintendo_n64";				
	consoleOldGenIdExt[5] = "nintendo_gameboy_advance";				
	consoleOldGenIdExt[6] = "sega_dreamcast";				
	consoleOldGenIdExt[7] = "sega_saturn";	
	consoleOldGenIdExt[8] = "neogeo";	

    urlForum[0] = "";
    urlForum[1] = "13";
    urlForum[2] = "115";
    urlForum[3] = "116";
    urlForum[4] = "12";
    urlForum[5] = "131";
    urlForum[6] = "131";
    urlForum[7] = "132";
    urlForum[8] = "14"; 

	tab1Toolbar[0]="news"; 
	tab1Toolbar[1]="recensioni";    
	tab1Toolbar[2]="anteprime";   
	tab1Toolbar[3]="speciali";
	tab1Toolbar[4]="video";   
	tab1Toolbar[5]="trucchi_soluzioni";

	tab2Toolbar[0] = "top_games";
	tab2Toolbar[1] = "top_video";
	tab2Toolbar[2] = "ultimi_aggiornamenti";

	fontColor[0] = "#f00";
	fontColor[1] = "#828282";
	fontColor[2] = "#112db9";
	fontColor[3] = "#26A90B";
	fontColor[4] = "#09bcfe";
	fontColor[5] = "#09bcfe";
	fontColor[6] = "#a800ff";
	fontColor[7] = "#a800ff";
	fontColor[8] = "#0b89ff";
	fontColor[9] = "#0B89FF";
	fontColor[10] = "#828282";
	fontColor[11] = "#f00";
	fontColor[12] = "#f00";
	fontColor[13] = "#f00";
	fontColor[14] = "#f00";
	fontColor[15] = "#ffa200";
	fontColor[16] = "#f00";
	fontColor[17] = "#f00";
	fontColor[18] = "#f00";
	fontColor[19] = "#f00";
	fontColor[20] = "#FBA761";
	fontColor[21] = "#f00";
	fontColor[22] = "#0b89ff";
	fontColor[23] = "#09bcfe";

	childToolbarColor[0] = "#FFD1CD";
	childToolbarColor[1] = "#EAEAEA";
	childToolbarColor[2] = "#C4DBF6";
	childToolbarColor[3] = "#DDFFCD";
	childToolbarColor[4] = "#CDF5FF";
	childToolbarColor[5] = "#CDF5FF";
	childToolbarColor[6] = "#E8D5FF";
	childToolbarColor[7] = "#E8D5FF";
	childToolbarColor[8] = "#C4DBF6";
	childToolbarColor[9] = "#C4DBF6";
	childToolbarColor[10] = "#EAEAEA";
	childToolbarColor[11] = "#FFD1CD";
	childToolbarColor[12] = "#FFD1CD";
	childToolbarColor[13] = "#FFD1CD";
	childToolbarColor[14] = "#FFD1CD";
	childToolbarColor[15] = "#FFD1CD";
	childToolbarColor[16] = "#FFD1CD";
	childToolbarColor[17] = "#FFD1CD";
	childToolbarColor[18] = "#FFD1CD";
	childToolbarColor[19] = "#FFD1CD";
	childToolbarColor[20] = "#FEE39C";
	childToolbarColor[21] = "#EAEAEA";
	childToolbarColor[22] = "#C4DBF6";
	childToolbarColor[23] = "#CDF5FF";
	
	
	tickerColor[0] = "#C94845";
	tickerColor[1] = "#9E9EA2";
	tickerColor[2] = "#3B3A9C";
	tickerColor[3] = "#2CB711";
	tickerColor[4] = "#2380D7";
	tickerColor[5] = "#9E65BB";
	tickerColor[6] = "#9E65BB";
	tickerColor[7] = "#3B3A9C";
	tickerColor[8] = "#9E9EA2";

	screenRes[0]="1024"; 
	screenRes[1]="1280";    
	screenRes[2]="1680";   

    newsTab[0]="articoli";
    newsTab[1]="discussioni_forum";
    newsTab[2]="altre_informazioni";

    fxIE6();
    if (pulsantiera != 1) switchMenu();

     if(arguments.length>0)
        getBg(arguments[0]);
    else
	    getBg();
}

function $obj(e){
    return document.getElementById(e);
}
function $t(e){
    return document.getElementsByTagName(e);
}
function $c(e){
    return document.createElement(e);
}

/*play*/
{
    var tempX = 0;
    var tempY = 0;
    //var tmplay = 0;
    //var tmmy = 0;

    function OpenMy2() {
        $obj("menuplay").style.display = "none";
        $obj("menumy").style.display = "block";
        $obj("my").style.backgroundImage = "url('/img/tabs/my.png')";
        $obj("a_my").style.color = "#ff0000";
        $obj("playwin").style.backgroundImage = "";
        $obj("a_play").style.color = "#444";
    }

    function OpenMy() {
        $obj("a_my").blur();
        $obj("menuplay").style.display = "none";
        if ($obj("menumy").style.display == "none") {
            $obj("menumy").style.display = "block";
            $obj("my").style.backgroundImage = "url('/img/tabs/my.png')";
            $obj("a_my").style.color = "#ff0000";
            $obj("playwin").style.backgroundImage = "";
            $obj("a_play").style.color = "#444";
        }
        else {
            $obj("menumy").style.display = "none";
            $obj("my").style.backgroundImage = "";
            $obj("a_my").style.color = "#444";
            $obj("playwin").style.backgroundImage = "";
            $obj("a_play").style.color = "#444";
        }
    }

    function OpenPlay2() {
        $obj("menumy").style.display = "none";
        $obj("my").style.backgroundImage = "";
        $obj("a_my").style.color = "#444";
        $obj("menuplay").style.display = "block";
        $obj("playwin").style.backgroundImage = "url('/img/tabs/play.png')";
        $obj("a_play").style.color = "#ff0000";
    }

    function OpenPlay() {
        $obj("a_play").blur();
        $obj("menumy").style.display = "none";
        if ($obj("menuplay").style.display == "none") {
            $obj("menuplay").style.display = "block";
            $obj("my").style.backgroundImage = "";
            $obj("a_my").style.color = "#444";
            $obj("playwin").style.backgroundImage = "url('/img/tabs/play.png')";
            $obj("a_play").style.color = "#ff0000";
        }
        else {
            $obj("menuplay").style.display = "none";
            $obj("my").style.backgroundImage = "";
            $obj("a_my").style.color = "#444";
            $obj("playwin").style.backgroundImage = "";
            $obj("a_play").style.color = "#444";
        }
    }

    function CloseMy() {
        //clearTimeout(tmmy);
        //tmmy = setTimeout(function() {
            $obj("menumy").style.display = "none";
            $obj("my").style.backgroundImage = "";
            $obj("a_my").style.color = "#444";
            //$obj("playwin").style.backgroundImage = "";
            //$obj("a_play").style.color = "#444";
        //}, 100);
    }

    function ClosePlay() {
        //clearTimeout(tmplay);
        //tmplay = setTimeout(function() {
            $obj("menuplay").style.display = "none";
            //$obj("my").style.backgroundImage = "";
            //$obj("a_my").style.color = "#444";
            
            $obj("playwin").style.backgroundImage = "";
            $obj("a_play").style.color = "#444";
        //}, 100);
    }

    if (typeof window.event == 'undefined')
        document.captureEvents(Event.MOUSEMOVE)

    function getMouseXY(e) {
        if ($obj("menumy") != null && $obj("menuplay") != null) {
            var clientVer=navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
            if(clientVer!=null){
                tempX = window.event.clientX //+ document.body.scrollLeft;
                tempY = window.event.clientY+document.documentElement.scrollTop;
            } else {
                tempX = e.pageX;
                tempY = e.pageY;
            }

            tempX = tempX - $obj("main").offsetLeft;
            tempY = tempY - $obj("main").offsetTop;

            if ($obj("menumy").style.display == "block") {
                //if (tempX < 640 || tempX > 790 tempY<110||tempY>450) { 144
                if (tempX < parseInt($obj("menumy").offsetLeft) || tempX > parseInt($obj("menumy").offsetLeft + $obj("menumy").offsetWidth) || tempY < 100 || (tempY-10 > parseInt($obj("menumy").offsetTop+$obj("menumy").offsetHeight)))
                {
                    CloseMy();
                    return;
                }
                //clearTimeout(tmmy);
            }
        
            if ($obj("menuplay").style.display == "block") {
                //if (tempX < 760 || tempX > 920)
                if (tempX < parseInt($obj("menuplay").offsetLeft) || tempX > parseInt($obj("menuplay").offsetLeft + $obj("menuplay").offsetWidth) || tempY < 100 || (tempY-10 > parseInt($obj("menuplay").offsetTop+$obj("menuplay").offsetHeight))) 
                {
                    ClosePlay();
                    return;
                }
                //clearTimeout(tmplay);
            }
        }
    }
    
    document.onmousemove = getMouseXY;
}
/*end play*/


/**********BG*/
{

function usrScrWidth(){
    if(screen.width<=1024)
        return 0;
    else if(screen.width>1024&&screen.width<=1280) 
        return 1280;
    else (screen.width>1280) 
        return 1680;
}

String.prototype.Trim=function(){
    return this.replace(/\s+$|^\s+/g,"");
}

function Trm(){
	var obj;
	var e = window.event;
    if(typeof e!='undefined')
	    obj=e.srcElement.id;
	else
	    obj=this.id;    
	    
    var s=$obj(obj).value;
    $obj(obj).value=s.Trim();
    if(obj=='commento')CharCount();
}

Array.prototype.firstIndexOf=function(e){
    e=e.toString().toLowerCase();
    var i=this.length;
    
    for(var zArr=0;zArr<i;zArr++){
        if(this[zArr].toString().toLowerCase().indexOf(e)!=-1)return zArr;
    }
    //return 0;
    return -1;
}

Array.prototype.lastIndexOf=function(e){
    e=e.toString().toLowerCase();
    var i=this.length;
    while(--i>-1){
        if(this[i].toString().toLowerCase().indexOf(e)!=-1)return i;
    }
    return i;
}

Array.prototype.MatchIndex=function(e){
    e=e.toString().toLowerCase();
    var i=this.length;
    while(--i>-1){
        if(this[i].toString().toLowerCase()==e)return i;
    }
    if (i<0)
        return 0;
    else
        return i;
}

var objReqBg;
var channelId2;
function getBg(){    
    var k=0;

    if (idusr != 0) k = keyBg;
    
    var loc=0;
    if (location.pathname.lastIndexOf("/recensioni_videogiochi")!=-1) loc=1;
    if (location.pathname.lastIndexOf("/notizie_videogiochi")!=-1) loc=2;
    if (location.pathname.lastIndexOf("/trucchi_videogiochi")!=-1) loc=3;
    if (location.pathname.lastIndexOf("/schede_videogiochi")!=-1) loc=4;
    if (location.pathname.lastIndexOf("/coverage")!=-1) loc=5;

    var k2 = 0;
    if(arguments.length>0){
        k2=arguments[0];
        bgActive=0;
    }

    if(consoleNewGenIdExt.lastIndexOf(channelId)==-1)
        channelId2=consoleNewGenId[0];
    else
        channelId2=consoleNewGenId[consoleNewGenIdExt.lastIndexOf(channelId)];
	if (channelId=="cinema")
		channelId2="cinema";
		

    if (bgContest != 0) {
        objReqBg = objHttp();
        objReqBg.open('get', '/ajax/background_contest.ashx?i=' + bgContest + '&rn=' + genRnd(), true);
        objReqBg.onreadystatechange = getDataBg;
        objReqBg.send(null);
    }
    else {    
        objReqBg = objHttp();
        objReqBg.open('get', '/ajax/background.ashx?k=' + k + '&k2=' + k2 + '&u=' + idusr + '&c=' + channelId2 + '&hp=' + hp + '&ap=' + apuser + '&rn=' + genRnd(), true);
        objReqBg.onreadystatechange = getDataBg;
        objReqBg.send(null);
        
    }
}

function getImgBg()
{
    if(consoleNewGenIdExt.lastIndexOf(channelId2)!=-1)
        bg="url(http://www.spaziogames.it/images/backgrounds/"+consoleNewGenId[consoleNewGenIdExt.lastIndexOf(channelId2)]+".jpg)";
    else
        bg = "url(http://www.spaziogames.it/images/backgrounds/multi.jpg)";

	$obj('bd').style.backgroundRepeat="repeat-x";
	$obj('bd').style.marginBottom="10px";
	$obj('ads_bottom').style.height="10px";
    $obj('bd').style.backgroundImage = bg;
}

var adsAvailable=[];
var bgAvailable=[];
function getDataBg()
{
    var dataBg=[];
    if(objReqBg.readyState == 4 && objReqBg.status == 200)
    {
        dataBg=eval(objReqBg.responseText);
        var l=dataBg.length;
        var index;
        var chkAds=dataBg[0];
        
        if(chkAds[1].lastIndexOf("webads")!=-1)
            index=0;            
        else
            index=bgIndex(l);            
            
        index=0;
        
        var rowData=dataBg[index];    
        if(dataBg[index]==null) return;
        var bg="";

        if (rowData[0].lastIndexOf("utenti") != -1 || rowData[0].lastIndexOf("jpg") != -1) {
            bg = bg.concat('url(http://www.spaziogames.it/images/backgrounds/', rowData[0], ')');
            if (rowData[0].lastIndexOf("utenti") == -1&&rowData[0].lastIndexOf("jpg") != -1) {
                $obj('bd').style.backgroundRepeat = "repeat-x";
                $obj('bd').style.marginBottom = "10px";
                $obj('ads_bottom').style.height = "10px";
                $obj('bd').style.backgroundImage = bg;
            }
        } else {
            if (usrScrWidth() > 0)//bg=bg.concat('url(http://download.spaziogames.eu/backgrounds/',rowData[0]+'_'+usrScrWidth()+'.jpg',')');
                bg = bg.concat('url(http://www.spaziogames.it/images/backgrounds/', rowData[0] + '_' + usrScrWidth() + '.jpg', ')');
            else {
                if (consoleNewGenIdExt.lastIndexOf(channelId) != -1)
                    bg = "url(http://www.spaziogames.it/images/backgrounds/" + consoleNewGenId[consoleNewGenIdExt.lastIndexOf(channelId)] + ".jpg)";
                else
                    bg = "url(http://www.spaziogames.it/images/backgrounds/multi.jpg)";
            }
        }
        if(usrScrWidth()==0)        		
        {
			$obj('bd').style.backgroundRepeat="repeat-x";
			$obj('bd').style.marginBottom="10px";
			$obj('ads_bottom').style.height="10px";
		}

		if (sfondoOff==1) bg="url(http://www.spaziogames.it/images/backgrounds/2009/6/237_1680.jpg)";

        $obj('bd').style.backgroundImage = bg;
                
        if ($obj("ads_a") != null) {
            $obj("ads_a").href = rowData[1];
            $obj("ads_a").target = "_ads";
        } else {
            var objHref=$c('a');
            var objImg = $c('img');
            hpBorderLink = rowData[1];
            objHref.href=rowData[1];
            if(rowData[3]=="1") objHref.target="_ads";
            objImg.src="/img/common/blank.gif";
            objImg.style.width="99%";
            objImg.style.height="99%";
            objHref.appendChild(objImg);
            $obj('ads').appendChild(objHref);
            SetADV();
        }
        
        if(rowData[2]==""){
            var obj=$obj('ads_bottom');
            if(obj!=null)obj.parentNode.removeChild(obj);
        }    
        else
        {
            if($obj('ads_bottom')!=null){
                var objHrefBt=$c('a');
                var objImgBt = $c('img');
                objHrefBt.href=rowData[2];
                if(rowData[3]=="1") objHrefBt.target="_ads";
                objImgBt.src="/img/common/blank.gif";
                objImgBt.style.width="99%";
                objImgBt.style.height="99%";
                objHrefBt.appendChild(objImgBt);
                
                $obj('ads_bottom').appendChild(objHrefBt);
                $obj('bd').style.marginBottom = "0";
            }
        }
    }
}

function bgIndex(index){
    return Math.floor(Math.random()*(index));
}

function SetADV() {
    if ($obj('adv_border') != null) 
    {
        $obj('adv_border').style.position = "absolute";
        $obj('adv_border').style.top = "0px";
        $obj('adv_border').style.left = "0px";
        $obj('adv_border').style.height = "2625px";
        $obj('adv_border').style.width = "99%";


        var objHref = $c('a');
        objHref.href = hpBorderLink; 
        objHref.target = "_bln";
        objHref.style.display = "block";
        objHref.style.width = "100%";
        objHref.style.height = "2625px";
        objHref.style.opacity = "0";

        $obj('adv_border').appendChild(objHref);
    }
}
}
/*******END BG****/

function offLabelDx(){
    for (var i=9; i<=13;i++){
        $obj(mainToolbar[i]).getElementsByTagName('a')[0].style.color="#444";
    }       
}

// Crea un oggetto di tipo XMLHttpRequest
function objHttp(){
    if (typeof XMLHttpRequest != "undefined") //Il browser non è IE
    {
        return new XMLHttpRequest();
    }
    else if (window.ActiveXObject) // E' IE
    {
        var sVersions = [ "MSXML2.XMLHttp.5.0",
        "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
        "MSXML2.XMLHttp","Microsoft.XMLHttp"
        ];

        for (var i = 0; i <sVersions.length; i++)
        {
	        try
	        {
		        var ret = new ActiveXObject(sVersions[i]);
		        return ret;
	        }
	        catch (oException)
	        {
	        }
        }
    }
    window.alert("Per continuare la navigazione e' necessario aggiornare il browser. Si consiglia l'uso di Internet Explorer o FireFox.");
}		

function genRnd(){
    return rdn=Math.floor(Math.random()*10001);
}

function addEvent(obj,evt,fn){
    if(obj.addEventListener)
        obj.addEventListener(evt,fn,false);
    else if (obj.attachEvent)
        obj.attachEvent('on'+evt,fn);
}

function isEmail(s){ 
    var pt = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/; 
    return String(s).search (pt) != -1; 
}

function fxIE6(){
	var clientVer=navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
    if( clientVer!=null&&Number(clientVer[1])<=6){

        if(typeof(arguments[0])!='undefined'){
            var fx = $obj(arguments[0]);
            var toFx = fx.currentStyle.backgroundImage.indexOf(".png");
            var bgImg = fx.currentStyle.backgroundImage;
            bgImg=bgImg.replace("url","").replace("(","").replace(")","")
            fx.style.backgroundImage = 'none';
            fx.style.filter='progid:DXImageTransform.Microsoft.AlphaImageLoader(src='+bgImg+', sizingMethod="crop")';
        }else{
	        var fx=document.getElementsByTagName("div");
            for(var i=0;i<fx.length;i++){
            
            var toFx = fx[i].currentStyle.backgroundImage.indexOf(".png");
            var bgImg = fx[i].currentStyle.backgroundImage;

	            if (toFx>-1){
    	          
	                bgImg=bgImg.replace("url","").replace("(","").replace(")","")
	                fx[i].style.backgroundImage = 'none';
	                fx[i].style.filter='progid:DXImageTransform.Microsoft.AlphaImageLoader(src='+bgImg+', sizingMethod="crop")';
                }            
            }
	    }
	}
}

function DwTxt(){
    if(parseInt($obj('articolo').style.fontSize)>10){
        var size=parseInt($obj('articolo').style.fontSize)-1;
        if ($obj('tab_aggiornamento2') != null) $obj('tab_aggiornamento2').style.fontSize = size + "px";
        if ($obj('finale') != null) $obj('finale').style.fontSize = size + "px";
        $obj('articolo').style.fontSize=size+"px";
        CreateCookie(size);
    }
}

function UpTxt(){
    if(parseInt($obj('articolo').style.fontSize)<16){
        var size = parseInt($obj('articolo').style.fontSize) + 1;
        if ($obj('tab_aggiornamento2') != null) $obj('tab_aggiornamento2').style.fontSize = size + "px";
        if ($obj('finale') != null) $obj('finale').style.fontSize = size + "px";
        $obj('articolo').style.fontSize=size+"px";
        CreateCookie(size);
    }
}

function CreateCookie(value) {
	document.cookie = "spaziogames01=''; path=/";
	var days=10;
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();

	document.cookie = "spaziogames01="+value+expires+"; path=/";
}

function ReadCookie(){
	var cookie = "spaziogames01=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
	    var c = ca[i];
	    if (c.indexOf(cookie)!=-1) return c.substring(cookie.length,c.length).replace("=","")+"px";
    }
	return "13px";
}

function Send(){ 
    var r=document.location;
    var t=(screen.height/2)-270;
    var l=(screen.width/2)-210;
    var wn=window.open('/send_form.aspx?r='+r+'&c='+mainToolbar[cs],'MailTo','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, width=400,height=490,left='+l+',top='+t);
    wn.focus();       
}

function IsImg(e){ 
    var img= new Image;
    img.onerror= function(){ 
        e.src = "/img/common/noimage.jpg";
        e.width="112";
        e.height="150";
    } 
    img.src = e.src;
} 

function IsImg_V(e){ 
    var img= new Image;
    img.onerror= function(){ 
        $obj(e).src = "/img/common/noimage_v.jpg";
        $obj(e).width="112";
        $obj(e).height="71";
    } 
    img.src = e.src;
} 

function IsImg_P2(e){ 
    var img= new Image;
    img.onerror= function(){ 
        e.src = "/img/common/noimage_8057.jpg";
        e.width="80";
        e.height="57";
    } 
    img.src = e.src;
} 

var lenImgScr=0;
function IsImg_P3(e){ 
    var img= new Image;
    img.onerror= function(){ 
    
        if(lenImgScr==0)lenImgScr=$obj('ls_img').getElementsByTagName('img').length;
        if(typeof window.event!='undefined')
            $obj(e).removeNode();
        else
            $obj(e).removeElement;
        
        lenImgScr--;
        if(lenImgScr==0)$obj('pnlScreenshots').className = "invisible";
    }    
    img.src = e.src;
} 

function IsImg_P(e){ 
    if(arguments[0].tagName!='IMG'){
        if(typeof window.event!='undefined')
            e=$obj(e.srcElement.id);
        else
            e=this;
    }
    var img= new Image;
    img.onerror= function(){ 
        e.src = "/img/common/noimage_p.jpg";
        e.width="120";
        e.height="85";
    } 
    img.src = e.src;
} 

function LImg(e){ 
    var img= new Image;
    img.src=$obj(e).src;
    img.onload= function(){ 
        $obj(e).width=img.width;
    } 
} 

function Reload(){
    location.href=$obj('drpTipologia').options[$obj('drpTipologia').selectedIndex].value;
    return false;
}
    
function Search(e){
    var kp;
    
    if(typeof window.event!='undefined')
        kp=window.event.keyCode;
    else
        kp=e.which;

   	if (kp != 0) {
	if(kp==13||kp==0||kp==1){
	    if ($obj('txtSearch').value.Trim().length == 0 || $obj('txtSearch').value=="cerca...") {
	        window.alert("Inserire il titolo del gioco.");
	        $obj('txtSearch').focus();
	        if(typeof e.which=='undefined')
	            return false;
	        else{
	            e.preventDefault();
	            e.cancelBubble=true;
	        }
	    } else {
	        if (sf == 1)
	            window.location = '/cinema/cerca_film/index.aspx?q=' + escape($obj('txtSearch').value.Trim());
	        else
	            window.location = '/cerca_videogiochi/index.aspx?q=' + escape($obj('txtSearch').value.Trim());
	        if(typeof e.which=='undefined')
	            return false;
	        else{
	            e.preventDefault();
	            e.cancelBubble=true;
	        }            
	    }
	}
	}
}

function EnterCommunity(){
    window.location='/underconstruction.aspx';
}

function EnterCommunity2(e){
    if($obj("txt_user").value.Trim().length==0||$obj("txt_password").value.Trim().length==0){
        window.alert("Per accedere all'area privata inserisci il Nome Utente e Password con cui ti sei registrato.\n\nHai dimenticato la Password?\nVai a questo indirizzo http://www.spaziogames.it/registrati/recupera.aspx \nper recuperarla.");
        if(typeof e!= 'undefined'){            
            if(typeof e.which=='undefined')
               return false;
            else{
                e.preventDefault();
                e.cancelBubble=true;
            }    
        }            
    }
}

function EsciAP() {
    document.cookie = "spaziogames_forum01=''; path=/;expires=Thu, 01-Jan-70 00:00:01 GMT;";
    document.cookie = "spaziogamessettings=''; path=/;expires=Thu, 01-Jan-70 00:00:01 GMT;";
    document.form1.submit();
}

function LanciaPremio(liv) {
    var arrayPageSize = getPageSize();

    CreateOverlay();
    var objDivP = $c('div');
    objDivP.setAttribute('id', 'imgpremio');
    objDivP.style.position = "absolute";
    objDivP.style.zIndex = "200";
    objDivP.style.backgroundImage = "url(/img/livelli/" + liv + ".png)";
    objDivP.onclick = function() { $obj('imgpremio').style.display = 'none'; $obj('overlay_p').style.display = 'none'; return false; }
    objDivP.style.width = "680px";
    objDivP.style.height = "380px";
    objDivP.style.top = "200px";
    objDivP.style.left = (((arrayPageSize[0] - 20 - 700) / 2) + 'px');
    $obj("bd").insertBefore(objDivP, $obj("overlay_p").nextSibling);
    $obj("overlay_p").style.display = "block";
    $obj("overlay_p").onclick = function() { $obj('imgpremio').style.display = 'none'; $obj('overlay_p').style.display = 'none'; return false; }
    setTimeout(function() { $obj('imgpremio').style.display = 'none'; $obj('overlay_p').style.display = 'none'; return false; }, 10000);
}

function CreateOverlay() {
    var objOvl = document.createElement("div");
    objOvl.setAttribute('id', 'overlay_p');
    objOvl.style.display = 'none';

    $obj("bd").appendChild(objOvl);
}


//INIZIO RICERCA AUTOCOMPLETE
; (function($) {

    $.fn.extend({
        autocomplete: function(urlOrData, options) {
            var isUrl = typeof urlOrData == "string";
            options = $.extend({}, $.Autocompleter.defaults, {
                url: isUrl ? urlOrData : null,
                data: isUrl ? null : urlOrData,
                delay: isUrl ? $.Autocompleter.defaults.delay : 10,
                max: options && !options.scroll ? 10 : 10
            }, options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function(value) { return value; };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            return this.each(function() {
                new $.Autocompleter(this, options);
            });
        },
        result: function(handler) {
            return this.bind("result", handler);
        },
        search: function(handler) {
            return this.trigger("search", [handler]);
        },
        flushCache: function() {
            return this.trigger("flushCache");
        },
        setOptions: function(options) {
            return this.trigger("setOptions", [options]);
        },
        unautocomplete: function() {
            return this.trigger("unautocomplete");
        }
    });

    $.Autocompleter = function(input, options) {

        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

        var timeout;
        var previousValue = "";
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
            mouseDownOnSelect: true
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);

        var blockSubmit;

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        //$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
        //}        
        $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
            // a keypress means the input has focus
            // avoids issue where input had focus before the autocomplete was applied
            hasFocus = 1;
            // track last key pressed
            lastKeyPressCode = event.keyCode;
            switch (event.keyCode) {

                case KEY.UP:                    
                    event.preventDefault();
                    if (select.visible()) {
                        select.prev();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.DOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.next();
                    } else {
                        onChange(0, true);
                    }
                    return false;
                    break;

                case KEY.PAGEUP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageUp();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEDOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageDown();
                    } else {
                        onChange(0, true);
                    }
                    break;

                // matches also semicolon         
                case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
                case KEY.TAB:
                case KEY.RETURN:
                    selectCurrent();
                   
                    break;

                case KEY.ESC:
                    select.hide();
                    break;

                default:
                    clearTimeout(timeout);
                    timeout = setTimeout(onChange, options.delay);
                    break;
            }
        }).focus(function() {
            // track whether the field has focus, we shouldn't process any
            // results if the field no longer has focus
            hasFocus++;
        }).blur(function() {
            hasFocus = 0;
            if (!config.mouseDownOnSelect) {
                hideResults();
            }
        }).click(function() {
            // show select when clicking in a focused field
            if (hasFocus++ > 1 && !select.visible()) {
                onChange(0, true);
	     }
        }).bind("search", function() {
            // TODO why not just specifying both arguments?
            var fn = (arguments.length > 1) ? arguments[1] : null;
            function findValueCallback(q, data) {
                var result;
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].result.toLowerCase() == q.toLowerCase()) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if (typeof fn == "function") fn(result);
                else $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()), function(i, value) {
                request(value, findValueCallback, findValueCallback);
            });
        }).bind("flushCache", function() {
            cache.flush();
        }).bind("setOptions", function() {
            $.extend(options, arguments[1]);
            // if we've updated the data, repopulate
            if ("data" in arguments[1])
                cache.populate();
        }).bind("unautocomplete", function() {
            select.unbind();
            $input.unbind();
            $(input.form).unbind(".autocomplete");
        });


        function selectCurrent() {
            var selected = select.selected();
            if (!selected)
                return false;

            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var words = trimWords($input.val());
                if (words.length > 1) {
                    var seperator = options.multipleSeparator.length;
                    var cursorAt = $(input).selection().start;
                    var wordAt, progress = 0;
                    $.each(words, function(i, word) {
                        progress += word.length;
                        if (cursorAt <= progress) {
                            wordAt = i;
                            return false;
                        }
                        progress += seperator;
                    });
                    words[wordAt] = v;
                    // TODO this should set the cursor to the right position, but it gets overriden somewhere
                    //$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
                    v = words.join(options.multipleSeparator);
                }
                v += options.multipleSeparator;
            }

            $input.val(v);
            hideResultsNow();
            $input.trigger("result", [selected.data, selected.value]);                      
            
            return true;
        }

        function onChange(crap, skipPrevCheck) {
            if (lastKeyPressCode == 8) {
                select.hide();
                return;
            }
            if (lastKeyPressCode == KEY.DEL) {
                select.hide();
                return;
            }

            var currentValue = $input.val();

            if (!skipPrevCheck && currentValue == previousValue)
                return;

            previousValue = currentValue;

            currentValue = lastWord(currentValue);
            if (currentValue.length >= options.minChars) {
                $input.addClass(options.loadingClass);
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value)
                return [""];
            if (!options.multiple)
                return [$.trim(value)];
            return $.map(value.split(options.multipleSeparator), function(word) {
                return $.trim(value).length ? $.trim(word) : null;
            });
        }

        function lastWord(value) {
            if (!options.multiple)
                return value;
            var words = trimWords(value);
            if (words.length == 1)
                return words[0];
            var cursorAt = $(input).selection().start;
            if (cursorAt == value.length) {
                words = trimWords(value)
            } else {
                words = trimWords(value.replace(value.substring(cursorAt), ""));
            }
            return words[words.length - 1];
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue) {
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
                // fill in the value (keep the case the user has typed)
                $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                // select the portion of the value not typed by the user (so the next character will erase)
                $(input).selection(previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults() {
            clearTimeout(timeout);
            timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
            var wasVisible = select.visible();
            select.hide();
            clearTimeout(timeout);
            stopLoading();
            if (options.mustMatch) {
                // call search and run callback
                $input.search(
				function(result) {
				    // if no value found, clear the input box
				    if (!result) {
				        if (options.multiple) {
				            var words = trimWords($input.val()).slice(0, -1);
				            $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
				        }
				        else {
				            $input.val("");
				            $input.trigger("result", null);
				        }
				    }
				}
			);
            }
        };

        function receiveData(q, data) {
            if (data && data.length && hasFocus) {
                stopLoading();
                select.display(data, q);
                autoFill(q, data[0].value);
                select.show();
            } else {
                hideResultsNow();
            }
        };

        function request(term, success, failure) {
            if (!options.matchCase)
                term = term.toLowerCase();
            var data = cache.load(term);
            // recieve the cached data
            if (data && data.length) {
                success(term, data);
                // if an AJAX url has been supplied, try loading the data now
            } else if ((typeof options.url == "string") && (options.url.length > 0)) {

                var extraParams = {
                    timestamp: +new Date()
                };
                $.each(options.extraParams, function(key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                $.ajax({
                    // try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    // limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    url: options.url,
                    data: $.extend({
                        q: lastWord(term),
                        limit: options.max
                    }, extraParams),
                    success: function(data) {
                        var parsed = options.parse && options.parse(data) || parse(data);
                        cache.add(term, parsed);
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure(term);
            }
        };

        function parse(data) {
            var parsed = [];
            var rows = data.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var row = $.trim(rows[i]);
                if (row) {
                    row = row.split("|");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: options.formatResult && options.formatResult(row, row[0]) || row[0]
                    };
                }
            }
            return parsed;
        };

        function stopLoading() {
            $input.removeClass(options.loadingClass);
        };

    };

    $.Autocompleter.defaults = {
        inputClass: "ac_input",
        resultsClass: "ac_results",
        loadingClass: "ac_loading",
        minChars: 2,
        delay: 400,
        matchCase: false,
        matchSubset: true,
        matchContains: true,
        cacheLength: 10,
        max: 10,
        mustMatch: false,
        extraParams: {},
        selectFirst: true,
        formatItem: function(row) { return row[0]; },
        formatMatch: null,
        autoFill: false,
        width: 0,
        multiple: false,
        multipleSeparator: ", ",
        highlight: function(value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        scrollHeight: 300
    };

    $.Autocompleter.Cache = function(options) {

        var data = {};
        var length = 0;

        function matchSubset(s, sub) {
            if (!options.matchCase)
                s = s.toLowerCase();
            var i = s.indexOf(sub);
            if (options.matchContains == "word") {
                i = s.toLowerCase().search("\\b" + sub.toLowerCase());
            }
            if (i == -1) return false;
            return i == 0 || options.matchContains;
        };

        function add(q, value) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = value;
        }

        function populate() {
            if (!options.data) return false;
            // track the matches
            var stMatchSets = {},
			nullData = 0;

            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if (!options.url) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];

            // loop through the array and create a lookup structure
            for (var i = 0, ol = options.data.length; i < ol; i++) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

                var value = options.formatMatch(rawValue, i + 1, options.data.length);
                if (value === false)
                    continue;

                var firstChar = value.charAt(0).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[firstChar])
                    stMatchSets[firstChar] = [];

                // if the match is a string
                var row = {
                    value: value,
                    data: rawValue,
                    result: options.formatResult && options.formatResult(rawValue) || value
                };

                // push the current match into the set list
                stMatchSets[firstChar].push(row);

                // keep track of minChars zero items
                if (nullData++ < options.max) {
                    stMatchSets[""].push(row);
                }
            };

            // add the data items to the cache
            $.each(stMatchSets, function(i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush() {
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            load: function(q) {
                if (!options.cacheLength || !length)
                    return null;
                /* 
                * if dealing w/local data and matchContains than we must make sure
                * to loop through all the data collections looking for matches
                */
                if (!options.url && options.matchContains) {
                    // track all matches
                    var csub = [];
                    // loop through all the data grids for matches
                    for (var k in data) {
                        // don't search through the stMatchSets[""] (minChars: 0) cache
                        // this prevents duplicates
                        if (k.length > 0) {
                            var c = data[k];
                            $.each(c, function(i, x) {
                                // if we've got a match, add it to the array
                                if (matchSubset(x.value, q)) {
                                    csub.push(x);
                                }
                            });
                        }
                    }
                    return csub;
                } else
                // if the exact item exists, use it
                    if (data[q]) {
                    return data[q];
                } else
                    if (options.matchSubset) {
                    for (var i = q.length - 1; i >= options.minChars; i--) {
                        var c = data[q.substr(0, i)];
                        if (c) {
                            var csub = [];
                            $.each(c, function(i, x) {
                                if (matchSubset(x.value, q)) {
                                    csub[csub.length] = x;
                                }
                            });
                            return csub;
                        }
                    }
                }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function(options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

        // Create results
        function init() {
            if (!needsInit)
                return;
            element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);

            list = $("<ul/>").appendTo(element).mouseover(function(event) {
                if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    $(target(event)).addClass(CLASSES.ACTIVE);
                }
            }).click(function(event) {
                $(target(event)).addClass(CLASSES.ACTIVE);
                select();
                // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                input.focus();
                //$("#btnSearch").click();
                if(sf==1)
                    window.location='/cinema/cerca_film/index.aspx?q='+escape($obj('txtSearch').value.Trim());
                else
                    window.location='/cerca_videogiochi/index.aspx?q='+escape($obj('txtSearch').value.Trim());
                return false;
            }).mousedown(function() {
                config.mouseDownOnSelect = true;
            }).mouseup(function() {
                config.mouseDownOnSelect = false;
            });

            if (options.width > 0)
                element.css("width", options.width);

            needsInit = false;
        }

        function target(event) {
            var element = event.target;
            while (element && element.tagName != "LI")
                element = element.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!element)
                return [];
            return element;
        }

        function moveSelect(step) {
            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if (options.scroll) {
                var offset = 0;
                listItems.slice(0, active).each(function() {
                    offset += this.offsetHeight;
                });
                if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                    list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                } else if (offset < list.scrollTop()) {
                    list.scrollTop(offset);
                }
            }
        };

        function movePosition(step) {
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
			? options.max
			: available;
        }

        function fillList() {
            list.empty();
            var max = limitNumberOfItems(data.length);
            for (var i = 0; i < max; i++) {
                if (!data[i])
                    continue;
                var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
                if (formatted === false)
                    continue;
                var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
                $.data(li, "ac_data", data[i]);
            }
            listItems = list.find("li");
            if (options.selectFirst) {
                //listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                //active = 0;
            }
            // apply bgiframe if available
            if ($.fn.bgiframe)
                list.bgiframe();
        }

        return {
            display: function(d, q) {
                init();
                data = d;
                term = q;
                fillList();
            },
            next: function() {
                moveSelect(1);
            },
            prev: function() {
                moveSelect(-1);
            },
            pageUp: function() {
                if (active != 0 && active - 8 < 0) {
                    moveSelect(-active);
                } else {
                    moveSelect(-8);
                }
            },
            pageDown: function() {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect(listItems.size() - 1 - active);
                } else {
                    moveSelect(8);
                }
            },
            hide: function() {
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible: function() {
                return element && element.is(":visible");
            },
            current: function() {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            show: function() {
                var offset = $(input).offset();
                element.css({
                    width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
                    top: offset.top + input.offsetHeight,
                    left: offset.left
                }).show();
                if (options.scroll) {
                    list.scrollTop(0);
                    list.css({
                        maxHeight: options.scrollHeight,
                        overflow: 'auto'
                    });

                    if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                        var listHeight = 0;
                        listItems.each(function() {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
                        }
                    }

                }
            },
            selected: function() {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected && selected.length && $.data(selected[0], "ac_data");
            },
            emptyList: function() {
                list && list.empty();
            },
            unbind: function() {
                element && element.remove();
            }
        };
    };

    $.fn.selection = function(start, end) {
        if (start !== undefined) {
            return this.each(function() {
                if (this.createTextRange) {
                    var selRange = this.createTextRange();
                    if (end === undefined || start == end) {
                        selRange.move("character", start);
                        selRange.select();
                    } else {
                        selRange.collapse(true);
                        selRange.moveStart("character", start);
                        selRange.moveEnd("character", end);
                        selRange.select();
                    }
                } else if (this.setSelectionRange) {
                    this.setSelectionRange(start, end);
                } else if (this.selectionStart) {
                    this.selectionStart = start;
                    this.selectionEnd = end;
                }
            });
        }
        var field = this[0];
        if (field.createTextRange) {
            var range = document.selection.createRange(),
			orig = field.value,
			teststring = "<->",
			textLength = range.text.length;
            range.text = teststring;
            var caretAt = field.value.indexOf(teststring);
            field.value = orig;
            this.selection(caretAt, caretAt + textLength);
            return {
                start: caretAt,
                end: caretAt + textLength
            }
        } else if (field.selectionStart !== undefined) {
            return {
                start: field.selectionStart,
                end: field.selectionEnd
            }
        }
    };
})(jQuery);
	
	var _lettera = '';
	function AutoSearch() {
	    var _val = $("#txtSearch").val();
	    if  (_val.length == 2) {
           if (_val != _lettera) {
	            $("#txtSearch").flushCache();
	            _lettera = _val;	    
       
    	        $.ajax({type:  'GET',
    	            url: 'http://www.spaziogames.it/ajax/ricerca_auto.ashx?q=' + $("#txtSearch").val()+'&sf='+sf,        
                    success: function(html) {     
                        var data = html.split("#");
		                $("#txtSearch").autocomplete(data);
                    }
                });
	        }
	    }
       }
// FINE RICERCA AUTOCOMPLETE

function OpenLogin() {
    $obj('welcome_login').style.display = "none";
    $obj('login_text').style.display = "block";
}

function ClearTxt() {
    if($obj('txt_user').value=="user...")$obj('txt_user').value = "";
}

function ClearTxtSearch() {
    if ($obj('txtSearch').value == "cerca...") $obj('txtSearch').value = "";
}

function NoArea() {
    window.alert("Utente senza Area Privata.");
}

function ViewForm() {
    if ($obj("overlay") == null || $obj("overlay").style.display == "none") {
        CreateOverlay();
        var yScroll = 0;

        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
        } else if (document.body) {// all other Explorers
            yScroll = document.body.scrollTop;
        }

        var clientVer = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
        /*if (clientVer != null && Number(clientVer[1]) <= 7)
        $obj("FormLayer").style.top = 100-yScroll;
        else
        $obj("FormLayer").style.top = 300;
        */

        $obj("bd").insertBefore($obj("FormLayer"), $obj("overlay").nextSibling);
        $obj("overlay").style.display = "block";
        $obj("FormLayer").style.display = "block";
        return true;
    }
}

function CreateOverlay() {
    var arrayPageSize = getPageSize();

    var objBody = $obj('bd');
    var objOverlay = document.createElement("div");
    objOverlay.setAttribute('id', 'overlay');
    objOverlay.onclick = function () { return false; }
    objOverlay.style.display = 'none';
    objOverlay.style.position = 'absolute';
    objOverlay.style.top = '0';
    objOverlay.style.left = '0';
    objOverlay.style.zIndex = '90';
    objOverlay.style.width = '100%';
    objOverlay.style.height = (arrayPageSize[1] + 'px');
    objBody.insertBefore(objOverlay, objBody.firstChild);
}

function getPageSize() {
    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }


    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight)
    return arrayPageSize;
}

