/***************************************************************************
 *                            Dolphin Web Community Software
 *                              -------------------
 *     begin                : Mon Mar 23 2006
 *     copyright            : (C) 2007 BoonEx Group
 *     website              : http://www.boonex.com
 *
 *
 *
 ****************************************************************************/

/***************************************************************************
 *
 *   This is a free software; you can modify it under the terms of BoonEx
 *   Product License Agreement published on BoonEx site at http://www.boonex.com/downloads/license.pdf
 *   You may not however distribute it for free or/and a fee.
 *   This notice may not be removed from the source code. You may not also remove any other visible
 *   reference and links to BoonEx Group as provided in source code.
 *
 ***************************************************************************/
/**
* Checks/unchecks all tables
*
* @param   string   the form name
* @param   boolean  whether to check or to uncheck the element
*
* @return  boolean  always true
*/
function setCheckboxes(the_form, do_check) {
	var elts  = document.forms[the_form].getElementsByTagName('input');
    var elts_cnt  = elts.length;

    for( i = 0; i<elts_cnt; i++ ) {
        elts[i].checked = do_check;
		if ( elts[i].type == "submit" ) { elts[i].disabled = !do_check; }
    }
}

function setCheckbox(the_form) {
    var elts      = document.forms[the_form].getElementsByTagName('input');
    var elts_cnt  = elts.length;

    var allUnchecked = true;

    for( i = 0; i < elts_cnt; i++ ) {  if( elts[i].checked ) { allUnchecked = false; }  }

    for( i = 0; i < elts_cnt; i++ ) {  if( elts[i].type=="submit" ) { elts[i].disabled = allUnchecked; }  }
}

function tell_friend( id ) {
    
    url = "/tellfriend.php";
    
    if( id !== undefined ) url += "?ID="+id;

    window.open(url, "tell_friend", "width=300,height=300,left=200,top=100,copyhistory=no,directories=no,menubar=no,location=no,resizable=no,scrollbars=no");
    
    return false;
    
}

function charCounter(field,maxLength,countTarget) {

	field = document.getElementById(field);
	countTarget = document.getElementById(countTarget);
	var inputLength=field.value.length;

	if( inputLength >= maxLength ) { field.value=field.value.substring(0,maxLength); }
    
	countTarget.innerHTML = maxLength-field.value.length;
    
}

function getHtmlData( elemID, url, show_only ) {
    
	var elem = $( '#'+elemID );

	if( !elem || !url ) { return false;	}
    
    request = $.get( 
                    url, 
                    { "show_only" : show_only, "r" : Math.random() }, 
                    function( sNewText ) {                        
                        elem.html(sNewText);
                        aScrMatches = sNewText.match(/<script[^>]*javascript[^>]*>([^<]*)<\/script>/ig);
                        if( aScrMatches ) {
                            for( ind = 0; ind < aScrMatches.length; ind++ ) {
                                sScr = aScrMatches[ind];
                                iOffset = sScr.match(/<script[^>]*javascript[^>]*>/i)[0].length;
                                sScript = sScr.substring( iOffset, sScr.length - 9 );
                                eval( sScript );
                            }
                        }
                        
                    }
                   );
}

function moveScrollRightAuto( el_id, b ) {
	if( b ) {
		scrollTimerId = setInterval("moveScrollRight('"+el_id+"')", 100);
	} else {
		clearInterval(scrollTimerId);
	}
}

function moveScrollLeftAuto( el_id, b ) {
	if( b ) {
		scrollTimerId = setInterval("moveScrollLeft('"+el_id+"')", 100);
	} else {
		clearInterval(scrollTimerId);
	}
}

function moveScrollRight( el_id ) {
	var step = 5;
	var e = document.getElementById( el_id );
	var left  = e.style.left ? parseInt( e.style.left, 10 ) : 0;

	minLeft = e.parentNode.clientWidth - parseInt( e.clientWidth, 10 );

	if( (left-step) > minLeft ) {
		e.style.left = left - step + "px";
	} else {
		e.style.left = minLeft + "px";
		moveScrollRightAuto ( el_id, false);
	}
}

function moveScrollLeft( el_id ) {
	var step = 5;
	var e = document.getElementById( el_id );
	var left = parseInt( (e.style.left ? e.style.left : 0), 10);

	if( left + step < 0 ) {
		e.style.left = left + step + "px";
	} else {
		e.style.left = "0px";
		moveScrollLeftAuto (false);
	}
}

function checkAll( formName, _pref, doCheck ) {
	_form = document.forms[formName];
	
	if( !_form ) { return false; }
	
	for( ind = 0; ind < _form.length; ind ++ ) {
		_elem = _form[ind];

		if( _elem.type != 'checkbox' ) { continue; }

		if( _elem.name.substr( 0, _pref.length ) != _pref ) { continue;	}

		_elem.checked = doCheck;
	}
}

function emailCheck( str ) {
    return ( str.search( /^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/i ) != -1 );
}

function unset_reminder() {
    request = $.get( "/profile.php", { "unset_reminder" :  1 } );
}

function BxDolVoting(sSystem, iObjId, sId, sIdSlider, iSize, iMax) {
    
    this._sSystem = sSystem;
    this._iObjId = iObjId;
    this._sId = sId;
    this._sIdSlider = sIdSlider;
    this._iSize = iSize;
    this._iMax = iMax;
    this._iSaveWidth = -1;
    
    this.over = function(i) { var e = document.getElementById(this._sIdSlider); this._iSaveWidth = parseInt(e.style.width,10); e.style.width = i*this._iSize+'px'; };

    this.setRate = function(fRate) { var e = document.getElementById(this._sIdSlider); e.style.width = fRate*this._iSize+'px'; };

    this.setCount = function(iCount) { var e = document.getElementById(this._sId); var eb = e.getElementsByTagName('b')[0]; eb.innerHTML = eb.innerHTML.replace( eb.innerHTML.match(/(\d+)/)[1], iCount ); };

    this.out = function() { var e = document.getElementById(this._sIdSlider); e.style.width = parseInt(this._iSaveWidth,10)+'px'; };

    this.vote = function(i) {
                            $this = this;
                            request = $.get( 
                                            '/vote.php', 
                                            { "vote_send_result" : i, "id" : this._iObjId, "sys": this._sSystem }, 
                                            function( s ) {
                                                    a = s.match(/([0-9\.]+),([0-9\.]+)/);
                                                    if( a ) {
                                                        $this._iSaveWidth = i*$this._iSize;
                                                        $this.setRate(a[1]);        
                                                        $this.setCount(a[2]);
                                                        $this.onvote(a[1], a[2]);
                                                    } else { 
                                                        alert( s.substr(1,s.length-2) );
                                                    }
                                            }                                                           
                                           );
                           };

    this.onvote = function (fRate, iCount) {};
    
}

/*function vote( system, objId, id, size ) {
    
    //this.reset = function() {};
    
    var $sl = $('#'+id+'Slider');
    var orig_width = parseInt($sl.css('width'),10);

    $('#'+id+' a').each( function(index) {
        
        $(this).mouseenter( function() {
            $sl.css('width', (index+1)*size+'px');
        } );
        
        $(this).click( function() {
            request = $.get( '/vote.php', { "vote_send_result" : index+1, "id" : objId, "sys": system }, 
                             function( s ) {
                                    a = s.match(/([0-9\.]+),([0-9\.]+)/);
                                    if( a ) {
                                        orig_width = parseInt(a[1]*size,10);
                                        $sl.css('width', orig_width+'px');
                                        text = $("#"+id+" b").html();
                                        $("#"+id+" b").html( $text.replace( $text.match(/(\d+)/)[1], a[2] ) );
                                        vote.onvote(objId);
                                    } else { 
                                        alert( s.substr(1,s.length-2) );
                                    }
                             } 
                             );
        } );

    } );
    
    $('#'+id).mouseleave( function() {
        $sl.css('width', orig_width+'px');
    } );
    
};*/

function iscriviti() {
	alert("Per poter accedere a tutti i contenuti devi fare il login (in alto a destra).\nSe non sei ancora registrato ricorda che la registrazione è GRATUITA!");
	top.location = 'http://www.amando.it/login/registrazione.htm';
}

var sRayUrl = "/ray/";
var aRayApps = [];

aRayApps["global"] = [];
aRayApps["global"]["admin"] = {"params": ['nick', 'password'], "top": 0, "left": 0, "width": 800, "height": 600, "resizable": 0};

aRayApps["im"] = [];
aRayApps["im"]["user"] = {"params": ['sndId', 'password', 'rspId'], "top": 0, "left": 0, "width": 490, "height": 480, "resizable": 1};

aRayApps["video"] = [];
aRayApps["video"]["recorder"]   = {"params": ['id', 'password'], "top": 0, "left": 0, "width": 545, "height": 355, "resizable": 0};
aRayApps["video"]["player"]     = {"params": ['id'], "top": 0, "left": 0, "width": 375, "height": 355, "resizable": 0};
aRayApps["video"]["admin"]      = {"params": ['nick', 'password'], "top": 0, "left": 0, "width": 400, "height": 250, "resizable": 0};

function getCookie(c_name) {

    if( document.cookie.length>0 ) {
    
        c_start = document.cookie.indexOf(c_name + "=");
        
        if( c_start != -1 ) {
        
            c_start = c_start + c_name.length+1;
            c_end   = document.cookie.indexOf(";",c_start);
            
            if( c_end == -1 ) { 
                c_end = document.cookie.length; 
            }
            
            return unescape(document.cookie.substring(c_start,c_end));
            
        }
    }
    
    return "";

}

function updateRayUserStatus( sUserId ) {

	if( sUserId!="" && sUserId!=="deleted" ) {	
			
		d = new Date();
        request = $.get( sRayUrl + "XML.php", { "action" :  "updateOnlineStatus", "id" : sUserId, "_t" : d.getTime() } );
		
	}
    
}

function openRayWidget(sModule, sApp) {

	if( aRayApps[sModule][sApp] == undefined ) { return; }
	
	var aInfo = aRayApps[sModule][sApp];
	var sUrl = sRayUrl + "index.php?module=" + sModule + "&app=" + sApp;			
	for( var i=0; i<arguments.length - 2; i++ ) {
        sUrl += "&" + aInfo["params"][i] + "=" + arguments[i+2]; 
    }
	var args = 'top='+aInfo["top"]+',left='+aInfo["left"]+',width='+aInfo["width"]+',height='+aInfo["height"]+',toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=0,resizable='+aInfo["resizable"];
	var name = 'Ray_'+sModule+'_'+sApp+parseInt((Math.random()*100000),10);	
	
	try {

		window.open(sUrl, name, args);
		
	} catch( err ) {

		window.open(sUrl, name, args);
		/**
        * Inserisco una piccola procedura per riaprire il popup se uso firefox
        * Avverto l'utente che dopo un timeout tenterò di riaprire il popup
        */
		//	alert( "Devi abilitare l'apertura di finestre popup per usare il messenger,\n premendo su ok, dopo 10 secondi tenterò di riaprire il messenger." );
		//	setTimeout(window.open(sUrl, name, args),10000);

	}

}

function GetWidth() {
    
        var x = 0;
        
        if( self.innerHeight ) {
            x = self.innerWidth;
        } else if( document.documentElement && document.documentElement.clientHeight ) {
            x = document.documentElement.clientWidth;
        } else if( document.body ) {
            x = document.body.clientWidth;
        }
        
        return x;
}

var imn_height 	= 200;
var pos_hide 	= -200; //allinea la finestrella
var foo 		= 0;
var food 		= 1;
var gl_sx = 0;
var gl_sy = 0;

function onScrollHandler() {

    o = $("#flcontainer");
    sx = 0;
    sy = 0;

    if( document.all ) {

		try {
        	if( document.documentElement != undefined ) {
            	scrollPosY = document.documentElement.scrollTop;
                scrollPosX = document.documentElement.scrollLeft;
            }
        } catch (e) {}
        sy = Math.max(document.body.scrollTop, scrollPosY);
        sx = Math.max(document.body.scrollLeft, scrollPosX);

    } else {

        sx = pageXOffset;
        sy = pageYOffset;
    }

    if( gl_sx!=sx || gl_sy!=sy ) {

        if( parseInt(o.css("top"),10) > pos_hide ) {
            
            o.css("top", sy + foo + "px");
            o.css("left", sx + "px");

            gl_sx = sx;
            gl_sy = sy;

            foo += food;
            if( 10 == foo ) { food = -1; }
            if(  0 == foo ) { food = 1; }
        }
    }

    setTimeout('onScrollHandler()', 90);
    
}

function IMInvitationShow(bool, pos) {

        o = $("#flcontainer");
        sx = 0;
        sy = 0;

        if( !pos ) { onScrollHandler(); }

        if( !bool ) { 
            o.css("top", pos_hide+"px");
            o.css("left", ( GetWidth()/2 )+"px");
            o.css("z-index", "-1");
            return; 
        }

        if( document.all ) {

			try {
	        	if( document.documentElement != undefined ) {
	            	scrollPosY = document.documentElement.scrollTop;
	                scrollPosX = document.documentElement.scrollLeft;
	            }
	        } catch (e) {}
	        sy = Math.max(document.body.scrollTop, scrollPosY);
	        sx = Math.max(document.body.scrollLeft, scrollPosX);

        } else {

            sx = pageXOffset;
            sy = pageYOffset;
        }
        
        o.css("top", String(-imn_height + pos + sy)+"px");
        o.css("left", sx+"px");

        pos += 5;

        if( pos <= imn_height ) { setTimeout('IMInvitationShow('+bool+','+pos+')', 30); }
        
}

function inviteShow( bShow ) {

	if( bShow ) {
        o = $("#flcontainer");
        o.css("top", "1200px");
        o.css("left", "500px");
        o.css("z-index", "2000");
	    IMInvitationShow(true, 0);
	} else {
	    IMInvitationShow(false, 0);
	}
    
}

function google_ad_request_done( google_ads ) {

    if( google_ads.length < 1 ) {
        return;
    }
    
    var i;
    //http://pagead2.googlesyndication.com/pagead/abglogo/abg-it-100c-000000.png
    var s = '<a href="'+google_info.feedback_url+'" class="'+google_ad_style_ads_by_google+'" target="_blank">Annunci Google</a><br />';
    
    if( google_ads[0].type==="flash" ) {
        
           s += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+google_ad.image_width+'" height="'+google_ad.image_height+'">' +
             '<param name="movie" value="'+google_ad.image_url+'" />' +
             '<param name="quality" value="high" />' + 
             '<param name="AllowScriptAccess" value="never" />' + 
             '<embed src="'+google_ad.image_url+'" width="'+google_ad.image_width+'" height="'+google_ad.image_height+'" type="application/x-shockwave-flash" allowscriptaccess="never" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>' +
             '</object>';
    
    } else if( google_ads[0].type==="image" ) {

           s += '<a href="'+google_ads[0].url+'" target="_blank" title="Visita '+google_ads[0].visible_url+'" onmouseout="window.status=\'\';" onmouseover="window.status=\'Visita '+google_ads[0].visible_url+'\';return true;">' +
             '<img border="0" src="'+google_ads[0].image_url+'" width="'+google_ads[0].image_width+'" height="'+google_ads[0].image_height+'" alt="" />' +
             '</a>';

    } else {

        var add_style_title = '';
        var add_style_other = '';
        if( google_ads.length==1 && !google_ad_style_vertical ) {
            add_style_title = ' ' + google_ad_style_big_title;
            add_style_other = ' ' + google_ad_style_big_other;        
        }
        
        /*if( google_ad_style_width=='728' && google_ad_style_height=='90' ) {

            style_li = 'height:100%; width:220px;';
            google_ad_style_width = 660;
            
           } else*/ if( !google_ad_style_vertical ) { 
                 
            style_li = 'height:100%; width:'+Math.floor(google_ad_style_width/google_ads.length)+'px;';
        
        } else {

            var height_temp = Math.floor(google_ad_style_height/google_ads.length);
            if( height_temp>60 && google_ads.length>1 ) { height_temp = 60; }
            style_li = 'width:100%; height:'+height_temp+'px;';
                     
        }
    
        s += '<ul>';
        
        for( i=0; i<google_ads.length; ++i ) {
                        
            s += '<li style="'+style_li+'">' + 
                    '<div class="google_ads_ad">' +
                        '<span class="'+google_ad_style_title+add_style_title+google_ad_style_color+'">' +
                            '<a href="'+google_ads[i].url+'" title="Visita '+google_ads[i].visible_url+'" target="_blank">' + google_ads[i].line1 +    '</a>' +
                        '</span><br />' +
                        '<span class="'+google_ad_style_text+add_style_other+'">' +
                            google_ads[i].line2+' '+google_ads[i].line3 +
                        '</span><br />' +
                        '<span class="'+google_ad_style_url+add_style_other+google_ad_style_color+'">' +
                            '<a href="'+google_ads[i].url+'" title="Visita '+google_ads[i].visible_url+'" target="_blank">' + google_ads[i].visible_url + '</a>' +
                        '</span>' +
                    '</div>' +
                '</li>';
            
        }
        
        s += '</ul>';        
    }
    
    s = '<div class="'+google_ad_style_container+'" style="width:'+google_ad_style_width+'px; height:'+google_ad_style_height+'px;">'+s+'</div>';

    document.write(s);
    return;
}// fine google_ad_request_done

function alert_blacklist() {
	alert('Non puoi comunicare con questo utente in quanto sei nella sua Lista Nera');
}

function mail( name, domain ) {
	document.write(name+'@'+domain);
}

function pwdFocus() {
    $('#fakepassword').hide();
    $('#password').show();
    $('#password').focus();
}

function pwdBlur() {
    if ($('#password').attr('value') == '') {
        $('#password').hide();
        $('#fakepassword').show();
    }
}
                          
function login_data_ok() {
    var password = document.getElementById('password');
    var username = document.getElementById('nick');
    if( password==undefined || username==undefined || password.value.length==0 || username.value.length==0 ) {
        alert('Attenzione!! Inserisci tutti i campi richiesti!!');
        return false;
    } else if( (username.value.length<3) || (username.value.length>24) ) {
        alert('Attenzione!! Il nickname deve essere minimo di 3 caratteri e max di 24 caratteri');    
        return false;
    } else if( password.value.length<5 ) {
        alert('Attenzione!! La password deve essere almeno di 5 caratteri!');    
        return false;
    } else if( username.value.indexOf('@')!=-1 ) {
        alert('Attenzione!! Non puoi usare un indirizzo e-mail come nick!');    
        return false;
    } else {
        return true;
    }
}

function select_status() {
    div = $("#status");
    if( div.css("display") == "none" ) { div.css("display",'inline'); } else { div.css("display",'none'); }
} 

function change_status( usr ) {
   
    privacyValue = parseInt( $("#selprivacy").val(), 10 );
    
    request = $.get( 
                    "/gremlin/privacy.php", 
                    { "id" :  usr, "status" : privacyValue },
                    function( resp ) {
                        alert("Tipo di privacy cambiata, potrebbe essere necessario qualche secondo perché le modifiche abbiano effetto");
                        if( resp == 'SUCCESS' ) {
                            if( privacyValue == 0 ) { imgurl = '/gremlin/resources/visible.gif'; } else { imgurl = '/gremlin/resources/invisible.gif'; }
                            $("#privacy").attr('src', imgurl);
                            $("#status").css("display","none");
                        }
                    }
                    );
   
}

var navBar = {

    init: function( id ) {

        var $parent = $('#'+id);

        // Ciclo tutti i link nella navbar di primo livello
        $('#'+id+'_liv1 a').each(function(){

            // Se non ha id, lo salto
            if($(this).attr('id') == '') {
                return 1;
            }

            // Recupero le navbar di secondo livello associata
            var $navbarLiv2 = $parent.find('div.'+id+'_liv2.'+$(this).attr('id'));

            // Se non lo trovo, continuo col prossimo link
            if($navbarLiv2.length == 0) {
                return 1;
            }

            // Aggiungo tutti gli eventi alla navbar di primo e secondo livello
            $(this).mouseover(function(){
                $navbarLiv2.css({display: 'block'});
            });

            $(this).mouseout(function(){
                $navbarLiv2.css({display: 'none'});
                                
            });

            $navbarLiv2.mouseover(function(){
                $(this).css({display: 'block'});
            });

            $navbarLiv2.mouseout(function(){
                $(this).css({display: 'none'});
            });

        });

    }
    
};

/**
 * @author	Flavio Pala
 */
function log_error_js(errore, no_prefix) {
    
    if( no_prefix != true ) { errore = "ERRORE JS 1: " + errore; }
    
    request = $.post( "/tools/ajax.php", { "type" : "error", "errstr" : errore } );
    
    if( request == null ) { return; }
}

/**
 * @author	Flavio Pala
 */
window.onerror = function(err, filename, line) {

			//errore sconosciuto
            if( typeof err === 'object' ) {
				//log_error_js(" ERRORE JS: "+err.message+" tipo: "+err.type, true);
				return;
			}

            // in genere questi sono errori di caricamento
            if( line<=16 ) {
                /* if( err == "Carattere non valido"  || err == "Invalid character"
                  || err == "Errore di sintassi"    || err == "Syntaxfehler"
                  || err == "Syntax error"          || err == "Caractère incorrect"
                  || err == "Ungültiges Zeichen"    || err == "Erreur de syntaxe"
                  || err == "Erro de sintaxe"       || err == "Error de sintaxis"
                  || err == "illegal character"     || err == "Carácter no válido" ) {*/
                    return;
                 //}
            }
					
			//AdBlocker per firefox
			if( ( err=="Previsto oggetto" || err=="Object expected" || err=="Se esperaba un objeto" ) && 
				( (line>=20 && line<=53) || (line>=62 && line<=64) || line>=1024 || (line>=500 && line<=650) || (line>=225 && line<=350) || (line>=360 && line<=495) ) || (line>=660 && line<=790) ) {
				return;
			}
            
            if( line==39 && ( err.indexOf("'}'")!=-1 || err.indexOf('"}"')!=-1 ) ) {
                return;
            }
			
            //dovuti a prg di adblock 
			if( err.indexOf("GA_googleFillSlot is not defined")!=-1 || err.indexOf("GA_googleAddSlot is not defined")!=-1 
                || err.indexOf("GA_googleFetchAds is not defined")!=-1 || err.indexOf("'GS_googleAddAdSenseService' non è definito")!=-1 
                || err.indexOf("GS_googleAddAdSenseService is not defined")!=-1 ) {
				return;
			}
			
			/*if( err=='Errore non specificato.' || err=='Previsto identificatore' ||
				err=='Errore non specificato' ||
				err=='Unbekannter Fehler' ||
				err=='Autorizzazione negata' ||
				err=='Oprávnění byla odepřena.' ||
				err=='Esecuzione del server non riuscito.' ) {
                return;
            }*/
              			
			//errore con la temporizzazione del tinyMce
			if(  filename.indexOf("compose.php") != -1 ||
					filename.indexOf("messages_outbox.php") != -1 ||
					filename.indexOf("messages_inbox.php") != -1 ) { 
				 return; 
			}
			
			if( err.indexOf("tinyMCE")!=-1 || line==31 ) { 
				 return; 
			}
			
			/*if( err=='Errore di sintassi' || line==25 ) { 
				 return; 
			}*/	
					    
            // non logghiamo gli errori di analytics
			if( err.indexOf("'_gat'") != -1 ||
				err.indexOf("_gat") == 0 ||
				err.indexOf('"_gat"') == 0 ||
				err.indexOf("Error loading script") != -1) {
				return;
			}
           
            //non logghiamo gli errori dovuti a script esterni
			if( filename.indexOf("http://incontri.amando.it")==-1 ) {
				return;
			}

            log_error_js("["+filename+" @ linea: "+line+"] - ERRORE JS: "+err, true);
       };
       
var userId = getCookie("memberID");       
updateRayUserStatus( userId );
