var pageid = Math.floor(Math.random()*1000000);
var TMPLVARS = new Object();
var logo_x, logo_y;
var search_it = false;
var slide_menu = new Array();                                                 
var imgf_pics = new Array(66, 49, 71, 33);
var bkg_wnd_h = new Array(400, 250, 250);		// altezze delle finestre di background
                                                                                  
function isIE() {
	return (navigator.userAgent.indexOf("MSIE") > -1);
}

function sci()
{
	if ( self.TMPLVARS && TMPLVARS['sci'] == 'on' )
	{
		var data = new Object();
		data['n'] = 1;
		data['list'] = new Object();
		for( var i=1;i<=20;i++ )
		{
			data = sci_add(data,'Box-ads-'+i);
			data = sci_add(data,'Box-ads-top-'+i);
			data = sci_add(data,'Box-ads-bottom-'+i);
		}
		data = sci_add(data,'Box-ads_video');
		data = sci_add(data,'Box-video_spot_3');
	}
}

function sci_add(data,name)
{
	if ( self.scic && document.getElementById(name) )
	{
		var l = document.getElementById(name);
		var links = l.getElementsByTagName('a');
		if ( links && links.length > 0 )
		{
			for( var i=0;i<links.length;i++ )
			{
				if ( links[i].className && links[i].className.match(/^sci/) )
				{
					if ( !data['list'][links[i].href] )
					{
						data['list'] = new Object();
						data['list'][links[i].href] = (data['n']++);
					}
					links[i].pos = data['list'][links[i].href];
					links[i].onclick = scic;
				}
			}
		}
	}
	return data;
}

function tag_cloud_mng(op)
{
	if ( !op && document.getElementById('tag_cloud_opt') )
	{
		var op = 'on';
		if ( document.getElementById('tag_cloud_opt').innerHTML.match(/ on/) )
			op = 'off';
	}
	setMCookie('peeplo_tag_cloud',op);
	view_tag_cloud(op);
}

function view_tag_cloud(op)
{
	if ( document.getElementById('tag_cloud_opt') )
	{
		if ( !op )
			op = getMCookie('peeplo_tag_cloud');
		if ( op == 'off' )
		{
			if (document.getElementById('flashcontent'))
				document.getElementById('flashcontent').innerHTML = '';
			if ( document.getElementById('tag_cloud_opt') )
				document.getElementById('tag_cloud_opt').innerHTML = document.getElementById('tag_cloud_opt').innerHTML.replace(/ on/,' off');
		}
		else
		{
			if ( document.getElementById('tag_cloud_opt') )
				document.getElementById('tag_cloud_opt').innerHTML = document.getElementById('tag_cloud_opt').innerHTML.replace(/ off/,' on');
			var color = getMCookie('peeplo_color_tag_cloud');
			if (!color)
				color = '#65a5e3';
			change_color_tag_cloud(null,color);
			flashkeys();
		}
	}
}

function closeWnd()
{
	$.facebox.close();
	if (_forceReload)
	{
		var u = parseUrl();
		if (document.location == 'http://'+u['host']+'/')
			document.location.reload(true);
		else
			document.location = 'http://'+u['host']+'/';
	}
}

function flashkeys()
{
	if ( document.getElementById('tag_cloud_opt') )
	{
		var w = 0;
		if ( document.getElementById('flashcontent') )
			w = document.getElementById('flashcontent').offsetWidth;
		var h = document.body.clientHeight;
		if ( document.getElementById('tagcloud') )
		{
			document.getElementById('tagcloud').style.width = w + 'px';
			document.getElementById('tagcloud').style.height = h + 'px';
		}
		if ( document.getElementById('flashcontent') )
			document.getElementById('flashcontent').style.top = (document.body.clientHeight - document.getElementById('flashcontent').offsetHeight) + 'px';
	}
}

function parseUrl(url,paramsLess)
{
	var urlData = new Object();
	var i = 0,j = 0;
	var tmp;
	if(!url)
		url = document.location.href;
	urlData['original_url'] = url;
	urlData['sep']='&';
	urlData['original_params'] = null;
	urlData['params'] = null;
	urlData['parts'] = new Array();
	var a = '';
	if(!url.match(/\?/))
	{
		urlData['sep']='?';
		a = url;
	}
	else
	{
		var urlParts = url.split('?');
		a = urlParts[0];
		urlData['original_query'] = urlParts[1];
		tmp = urlParts[1].split('&');
		var regs = null;
		if(paramsLess)
		{
			regs = new Array();
			for(i=0;i<paramsLess.length;i++)
			{
				regs[i] = new RegExp("^"+paramsLess[i]+"\=");
			}
		}
		var query = "";
		var tmp2;
		urlData['original_params'] = new Object();
		urlData['params'] = new Object();
		for(i=0;i<tmp.length;i++)
		{
			tmp2 = tmp[i].split('=');
			urlData['original_params'][tmp2[0]] = tmp2[1];
			if(regs!=null)
			{
				found = false;
				for(j=0;j<regs.length;j++)
				{
					if(tmp[i].match(regs[j]))
						found = true;
				}
				if(found == false)
				{
					if(query!='')
						query+='&';
					query+=tmp[i];
					urlData['params'][tmp2[0]] = tmp2[1];
				}
			}
		}
		url = urlParts[0]+'?'+query;
	}
	tmp = a.split('/');
	var n = 0;
	if( a.match(/^http:\/\//) )
	{
		urlData['host'] = tmp[2];
		n = 3;
	}
	for(i=0;i<tmp.length;i++)
	{
		if(tmp[i] != '' && i>=n)
			urlData['parts'].push(tmp[i]);
	}
	urlData['url'] = url;
	return urlData;
}

function getDirectoryOrientedInputPars()
{
	var urlData = parseUrl();
	var pars = new Array();
	for(i=0;i<urlData['parts'].length;i++)
	{
		if( urlData['parts'][i] )
		{
			if ( i>0 && (i%2) ) //Le altre pagine (p.e. sitemap) hanno il passaggio paramentri "parametro"/"valore"
			{
				pars[urlData['parts'][i]] = decodeUrl(urlData['parts'][i+1]);
			}
		}
	}
	if ( !pars['q'] && in_array(urlData['parts'][0],TMPLVARS['privated_keys']) )
	{
		pars['q'] = decodeUrl(urlData['parts'][0]);
		pars['q'] = pars['q'].replace(/-/g,' ');
	}
	
	if ( urlData['parts'].length == 2 && in_array(urlData['parts'][0],TMPLVARS['page_types']) ) // /sezione/keywords/
	{
		pars['type'] = decodeUrl(urlData['parts'][0]);
		pars['type'] = pars['type'].replace(/-/g,' ');
		pars['q'] = decodeUrl(urlData['parts'][1]);
		pars['q'] = pars['q'].replace(/-/g,' ');
	}
	
	return pars;
}

function MyInputParValue(par)
{
	var value = MyGetInputParValue(par);
	if ( !value )
	{
		var pars = getDirectoryOrientedInputPars();
		if ( pars && pars[par] )
		{
			value = pars[par];
		}
	}
	return value;
}

function in_array(value,array)
{
	if ( array && array.length > 0 )
	{
		for (i=0;i<array.length;i++)
		{
			if( array[i] == value )
			{
				return true;
			}
		}
	}
	return false;
}

function MyGetInputParValue(par)
{
    var reg = new RegExp("[?&]"+par+"=([^&$]*)","i");
    return((location.search.search(reg)>=0)?RegExp.$1:'');
}

function encodeUrl(string)
{
	if(self.encodeURIComponent)
	{
		string = encodeURIComponent(string);
		string = string.replace(/'/g,"%27");
	}
	else
		return escape(string);
	return string;
}

function decodeUrl(string)
{
	if(self.decodeURIComponent)
		return decodeURIComponent(string);
	else
		return unescape(string);
	return string;
}


function randIt()
{
	return Math.floor(Math.random()*1000000);
}

function SearchByForm()
{
	return true;
}

function VideoDetailTo(id,title,supplier)
{
	var form = document.form_detail;
	var action = TMPLVARS['def_domain']+'/';
	var key = form.q.value;
	var type = form.type.value;
	if ( type != 'web' )
		action += type+'/';
	if( key )
	{
		key = cleanKey(key);
		key = key.replace(/ /g,'-');
	}
	action += encodeUrl(key)+'/';
	if( title )
	{
		title = cleanKey(title);
		title = title.replace(/ /g,'-');
	}
	action += encodeUrl(title)+'/'+supplier+'/'+id+'/';
	form.id.value = id;
	form.supplier.value = supplier;
	form.action = action;
	form.method = 'post';
	form.submit();
	return false;
}

function PageTo(page)
{
	var form = document.form_paging;
	var action = TMPLVARS['def_domain']+'/';
	var key = form.q.value;
	var type = form.type.value;
	if ( type != 'post' )
		action += type+'/';
	if( key )
	{
		key = cleanKey(key);
		key = key.replace(/ /g,'-');
	}
	action += encodeUrl(key)+'/'+page+'/';
	form.page.value = page;
	form.action = action;
	form.method = 'post';
	form.submit();
	return false;
}


function clickSection(type)
{
	$('#search_link_'+menu_sel_item).removeClass('sel');
	$('#search_link_'+type).addClass('sel');
	menu_sel_item=type;
	var top = $('.hmtype').css('top').replace('px','') * 1;
	top -= 10;
	$('.hmtype').hide();
	$('.hmtype').html($('#search_link_'+menu_sel_item).html());
	$('.hmtype').css('top',top+'px');
	$('.hmtype').show();
	$('.hmtype').animate({"top": "+=10px"}, 'fast');
	return SearchIt('',type);
}

function SearchIt(form,type,key,suggested)
{
	if ( !form )
		form = document.form_search;

	if ( !type )
		type = form.elements['type'].value;
	else if ( form.elements && form.elements['tmpl'] )
		form.elements['tmpl'].value = '';
	
	if ( !key && form.q.value )
		key = form.q.value;
	if ( !key )
		key = '';
	
	if ( !key || ( TMPLVARS['tmpl'] == 'gmap' && !TMPLVARS['qed'] ) )
	{
		if ( TMPLVARS['tmpl'] != 'index' && TMPLVARS['tmpl'] != 'index2' )
		{
			self.location.href = TMPLVARS['def_domain']+'/?type='+type;
			return false;
		}
		else if ( type )
			form.elements['type'].value = type;
		return false;
	}
	
	var action = TMPLVARS['def_domain']+'/';
	if ( !key && type )
		action += 'section/'+type+'/';
	else if( key )
	{
		if ( type != 'post' )
			action += type+'/';
		form.q.value = key;
		key = cleanKey(key);
		key = key.replace(/ /g,'-');
		action = action + encodeUrl(key)+'/';
	}
	form.elements['type'].value = type;
	if ( suggested && form.elements['suggested'] )
		form.elements['suggested'].value = suggested;
	form.action = action;
	form.method = 'post';
	form.onsubmit = 'return false;';
	form.submit();
	return false;
}

function PageToByPost(page,key,id)
{
	var form = document.form_paging;
	var key = form.q.value;
	if (key)
	{
		form.q.value = key;
		key = cleanKey(key);
		key = key.replace(/ /g,'-');
	}
	form.elements['page'].value = page;
	form.elements['id_extra'].value = id;
	form.action = '/' + encodeUrl(key) +'/'+page+'/';
	form.method = 'post';
	form.submit();
	return false;
}

function SearchItByPost(form,key,url,id)
{
	if ( !form )
		form = document.form_search;
	if ( !key && form.q.value )
		key = form.q.value;
	if ( !key )
		key = '';
	form.q.value = key;
	form.elements['type'].value = 'post';
	form.elements['id_extra'].value = id;
	form.action = url;
	form.method = 'post';
	form.submit();
	return false;
}

function cleanKey(key)
{
	if( key )
	{
		key = trim(key);
		key = key.replace(/\//g,' ');
		key = key.replace(/\s{2,}/g,' ');
	}
	return key;
}

function centra(oggetto,altezza,larghezza)
{
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	}
	else
	{
		if	( document.documentElement &&
			( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	    {
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else
		{
			if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
			{
				//IE 4 compatible
				myWidth = document.body.clientWidth;
				myHeight = document.body.clientHeight;
			}
		}
   }
   document.getElementById(oggetto).style.position="absolute";
   if (myWidth > larghezza)
   {
	   document.getElementById(oggetto).style.left = ((myWidth - larghezza)/2)+'px';
   }
   else
   {
	   document.getElementById(oggetto).style.left = '0px';
   }
   if (myHeight > altezza)
   {
	   document.getElementById(oggetto).style.top = ((myHeight - altezza)/2)+'px';
   }
   else
   {
   	 document.getElementById(oggetto).style.top =  '0px';
   }
}

function Element(id)
{
	return document.getElementById(id);
}

function add_bookmark() {
	if (window.sidebar)
		window.sidebar.addPanel(document.title, location.href, '');		// versione FF
	else if (document.all)
		window.external.AddFavorite(location.href, document.title);		// versione IE
	else if (window.opera)												// versione Opera
	{
		var a = document.createElement("A");
		a.rel = "sidebar";
		a.target = "_search";
		a.title = document.title;
		a.href = location.href;
		a.click();
	}
}

function set_homepage(obj) {
	if( !obj )
	{
		obj = document.getElementsByTagName('body');
		obj = obj[0];
	}
	obj.style.behavior = 'url(#default#homepage)';
	if (isIE())
		obj.setHomePage(location.href);
	else
		open_wnd(2);
	return false;
}

function trim(str) {
    return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function PopUp(url,name,width,height)
{
	var extra="toolbar=0,status=0,location=0,directories=0,menuBar=0,scrollbars=1,resizable=1,width="+width+",height="+height;
	var w=window.open(url,name,extra);
	w.focus();
	return w;
}

function changeView(tmpl)
{
	document.form_search.tmpl.value = tmpl;
	SearchIt();
}

function Peepix()
{
	var pxt_name = 'peeplo_pxt';
	if( !document.getElementById(pxt_name) && document.createElement )
	{
		var tmp=document.createElement('div');
		tmp.id=pxt_name;
		tmp.style.display='none';
		document.body.appendChild(tmp);
	}
	var pxt = document.getElementById(pxt_name);
	if( pxt )
	{
		var str = "<!-- Advertiser 'Dada Peeplo',  Include user in segment 'Peeplo CPA' - DO NOT MODIFY THIS PIXEL IN ANY WAY --><img src=\"http://ad.yieldmanager.com/pixel?id=116759&t=2\" width=\"1\" height=\"1\" /><!-- End of segment tag -->";
		var iframe="<iframe src='/spage.php5?tmpl=empty&by=shared&nocache="+randIt()+"&str="+encodeUrl(str)+"' style='height:1px;width:1px'></iframe>";
		pxt.innerHTML = iframe;
	}
}

function check_search()
{
	var v = trim(document.getElementById('q_head').value);
	if (v != '' && (search_it || v != 'search') )
		return SearchIt();
	else
		return false;
}

function handle_button_fnc(id, num, extra_num, binary)
{
	var b_state = document.getElementById(id).value;
	if (extra_num)
		document.getElementById(id).value = extra_num;
	else
		document.getElementById(id).value =  1 - b_state;
	if (navigator.userAgent.indexOf("MSIE 6") > -1)
		setTimeout('enable_bkg_button('+num+','+(1-b_state)+',0,'+extra_num+')', 300);
	else
		enable_bkg_button(num,(1-b_state),0,extra_num);
	return true;
}

function enable_bkg_button(button, enable, disable_all, extra)
{
	var bkg_button = {0:'bkg_img_color', 1:'bkg_img_pos', 2:'bkg_img_repeat', 3:'bkg_img_clear'};
	var bkg_img = {0:'color_background', 1:'posizione_', 2:'ripeti', 3:'elimina'};
	
	if (disable_all == 1)
		for (i = 0, tot = bkg_button.length; i < tot; i++)
		{
			if (i != button)
			{
				obj = document.getElementById(bkg_button[i]);
				obj.src= TMPLVARS['prefix']['img']+bkg_img[i]+'.png'+TMPLVARS['suffix']['img'] + '?' + Math.random();
			}
		}
	
	if ((button >= 0) && (button <= 3))
	{
		obj = document.getElementById(bkg_button[button]);
		if (extra)
			obj.src= TMPLVARS['prefix']['img']+bkg_img[button]+ extra + '.png'+TMPLVARS['suffix']['img'] + '?' + Math.random();
		else
			obj.src= TMPLVARS['prefix']['img']+bkg_img[button]+ ((enable == 1) ? '1' : '0') + '.png'+TMPLVARS['suffix']['img'] + '?' + Math.random();
	}
}

function change_color(set_obj, force_color)
{
	var old_obj = document.getElementById('selected_color');
	var view_obj = document.getElementById('view_color');
	
	if (old_obj)
		old_obj.id = '';
	if (set_obj)
	{
		set_obj.id = "selected_color";
		var sel_color = set_obj.style.backgroundColor;
	}
	else
		var sel_color = force_color;
	view_obj.style.backgroundColor = sel_color;
	document.getElementById('wrapper').style.backgroundColor = sel_color;
	setMCookie('peeplo_color', sel_color);
}

function change_color_tag_cloud(set_obj, force_color)
{
	if ( document.getElementById('tag_cloud_opt') )
	{
		var old_obj = document.getElementById('selected_color_tag_cloud');
		var view_obj = document.getElementById('view_color_tag_cloud');
		var sel_color = '';
		if (old_obj)
			old_obj.id = '';
		if (set_obj)
		{
			set_obj.id = "selected_color";
			sel_color = set_obj.style.backgroundColor;
		}
		else
			sel_color = force_color;
		view_obj.style.backgroundColor = sel_color;
		var color = sel_color;
		var tmp = new RGBColor(color);
		if (tmp.ok)
			color = tmp.toHex().toUpperCase();
		if ( color.match(/#/) )
			color = color.substr(1);
		so.addVariable("tcolor", "0x"+color);
		setMCookie('peeplo_color_tag_cloud', sel_color);
		so.write("flashcontent");
	}
}

function dec2hex(dec)
{
    var hexArray = new Array( "0", "1", "2", "3", 
                              "4", "5", "6", "7",
                              "8", "9", "A", "B", 
                              "C", "D", "E", "F" );
    var code1 = Math.floor(dec / 16);
    var code2 = dec - code1 * 16;
    var decToHex = hexArray[code2];
    return (decToHex);
}

function set_color()
{
	default_color = getMCookie('peeplo_color');
	if (!default_color)
		return null;
	
	c = document.getElementsByName('bkg_color');
	sel_obj = null;
	for (i = 0; i < c.length; i++)
	{
		color = c[i].style.backgroundColor;
		if (color == default_color)
			sel_obj = c[i];
		c[i].id = '';
	}
	change_color(sel_obj, default_color);
}

function set_position()
{
	logo_x = getMCookie('logo_x');
	logo_y = getMCookie('logo_y');
	var obj = document.getElementById('hp_search');

	if (logo_x)
	{
		obj.style.left = logo_x + 'px';
		obj.style.top = logo_y + 'px';
		obj.style.display = 'block';
	}
	else
		set_resize(true);
}

function set_resize(force)
{
	if (!logo_x || !logo_y || force)
	{
		centra('hp_search', 410, 530);
		obj = document.getElementById('hp_search');
		var x_str = new String(obj.style.left);
		var x = x_str.substr(0, x_str.length-2);
		var y_str = new String(obj.style.top);
		var y = y_str.substr(0, y_str.length-2);
		setMCookie('logo_x', x);
		setMCookie('logo_y', y);
		obj.style.display = 'block';
	}
}

function show_menu(id, num)
{
	for (i = 0; i < opt_menu.length; i++)
	{
		if (opt_menu[i] != id)
		{
			slide_menu[i].slideup();
			if (opt_menu[i] == 'colors_menu' && document.getElementById('colors_img'))
				document.getElementById('colors_img').src = TMPLVARS['prefix']['img_shared']+'arrow_tiny2_d.gif'+TMPLVARS['suffix']['img_shared'];
			else if (opt_menu[i] == 'colors_menu_tag_cloud' && document.getElementById('colors_img_tag_cloud') )
				document.getElementById('colors_img_tag_cloud').src = TMPLVARS['prefix']['img_shared']+'arrow_tiny2_d.gif'+TMPLVARS['suffix']['img_shared'];
		}
	}
	if (id)
	{
		obj = document.getElementById(id);
		if ((obj.style.display == 'none') || (obj.style.height == '0pt') || (obj.style.height == '0px'))
		{
			obj.style.display = 'block';
			if (self.slide_menu[num])
				slide_menu[num].slidedown();
			if (id == 'colors_menu' && document.getElementById('colors_img') )
				document.getElementById('colors_img').src = TMPLVARS['prefix']['img_shared']+'arrow_tiny2_u.gif'+TMPLVARS['suffix']['img_shared'];
			else if (id == 'colors_menu_tag_cloud' && document.getElementById('colors_img_tag_cloud') )
				document.getElementById('colors_img_tag_cloud').src = TMPLVARS['prefix']['img_shared']+'arrow_tiny2_u.gif'+TMPLVARS['suffix']['img_shared'];
		}
		else if (self.slide_menu[num])
			slide_menu[num].slideup();
	}
}	

function open_wnd(wnd_type, msg, title)
{
	if ( document.getElementById('flash_menu') )
		document.getElementById('flash_menu').style.display='none';
	view_tag_cloud('off');
	
	switch(wnd_type) {
		case 1:	if (msg)
					friend_wnd = dhtmlwindow.open("friend_wnd", "ajax", '/index.php5?wnd=friend&link='+msg, TMPLVARS['dict']['SENDFRIEND2'], "width=440px,height=410px,center=1,resize=0,scrolling=1,close=1");
				else
					friend_wnd = dhtmlwindow.open("friend_wnd", "ajax", '/index.php5?wnd=friend', TMPLVARS['dict']['SENDFRIEND2'], "width=440px,height=400px,center=1,resize=0,scrolling=1,close=1");
				break;
		case 2: home_wnd = dhtmlwindow.open("home_wnd", "ajax", "/index.php5?wnd=mozhp",  TMPLVARS['dict']['MAKEHOMEPAGE2'], "width=450px,height=220px,center=1,resize=0,scrolling=1,minimize=0,close=1");
				break;
		case 3: bkg_wnd = dhtmlwindow.open("bkg_wnd", "ajax", "/index.php5?wnd=bkg", TMPLVARS['dict']['BACKIMAGE2'], "width=520px,height=400px,center=1,resize=0,scrolling=0,minimize=0,close=1,nohead=1");
				default_color = getMCookie('peeplo_color');
				if (default_color)
					rgb_color = new RGBColor(default_color);
				else
					rgb_color = new RGBColor('#000000');
				setTimeout('set_config_wnd()', 300);
				setTimeout('loadSV()', 1000);
				break;
		case 4: msg_wnd = dhtmlwindow.open("msg_wnd", "inline", "<div align=center>"+msg+"</div>", title, "width=250px,height=50px,center=1,resize=0,scrolling=0,minimize=0,close=1");
				break;
	}
}

function set_config_wnd()
{
	var peeplo_bkg_src = getMCookie('peeplo_bkg_src');
	if (peeplo_bkg_src == undefined)
	{
		setTimeout('set_config_wnd()', 200);
		return false;
	}
	else if (peeplo_bkg_src == 0)
		peeplo_bkg_src = 1;
	
	var bkg_format = getMCookie('peeplo_format');
	if (!bkg_format) bkg_format = 0;
	var bkg_gallery = getMCookie('peeplo_bkg');
	if (!bkg_gallery)
		bkg_gallery = 0;
	else
	{
		var tmp = bkg_gallery.substring(bkg_gallery.length-8, bkg_gallery.length-4);
		var stop = false;
		bkg_gallery = '';
		for (var i = 0; i < 4; i++)
			if (stop || (tmp.charAt(i) != '0'))
			{
				bkg_gallery += tmp.charAt(i);
				stop = true;
			}
		for (var i = 0; i < bkg_format; i++)
			bkg_gallery -= imgf_pics[i];
		bkg_gallery--;
	}
	
	if (peeplo_bkg_src == 1)
		setTimeout('imgf_check_image_flow('+bkg_format+','+imgf_pics[bkg_format]+','+bkg_gallery+')', 300);
	else
		setTimeout('change_bkg_type('+(peeplo_bkg_src-1)+')', 100);
}

function check_send_form()
{
	var email_reg = /^([a-zA-Z0-9_\.\-\&])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,4})+$/;
	send_name = trim(document.getElementById('send_name').value);
	send_email = trim(document.getElementById('send_email').value);
	send_friend = trim(document.getElementById('send_friend').value);
	send_code = trim(document.getElementById('send_code').value);
	
	if (send_name == '')
	{
		document.getElementById('send_name').focus();
		alert(TMPLVARS['dict']['TYPENAME']);
		return false;
	}
	else if (send_email == '')
	{
		document.getElementById('send_email').focus();
		alert(TMPLVARS['dict']['TYPEEMAIL']);
		return false;
	}
	else if (email_reg.test(send_email) == false)
	{
		document.getElementById('send_email').focus();
		alert(TMPLVARS['dict']['TYPECORRECTEMAIL']);
		return false;
	}
	else if (send_friend == '')
	{
		document.getElementById('send_friend').focus();
		alert(TMPLVARS['dict']['TYPEEFRIEND']);
		return false;
	}
	else if (email_reg.test(send_friend) == false)
	{
		document.getElementById('send_friend').focus();
		alert(TMPLVARS['dict']['TYPECORRECTFRIEND']);
		return false;
	}
	else if (send_code == '')
	{
		document.getElementById('send_code').focus();
		alert(TMPLVARS['dict']['TYPECODE']);
		return false;
	}
	else
		return true;
}

function change_bkg_type(num)
{
	var c, d;
	
	var obj = document.getElementById('bkg_type_img');
	if (!obj)
	{
		setTimeout('change_bkg_type('+ (peeplo_bkg_src-1)+')', 100);
		return;
	}
	obj.src = TMPLVARS['prefix']['img_shared']+'dhtml_tab'+(num+1)+'.png'+TMPLVARS['suffix']['img_shared'];
	for (i = 0; i < 3; i++)
	{
		if (i == num)
		{
			c = 'selected';
			d = 'block';
		}
		else
		{
			c = 'unselected';
			d = 'none';
		}
		document.getElementById('bkg_type_' + i).className = c;
		document.getElementById('type_' + i).style.display = d;
	}
	document.getElementById('drag-contentarea').style.height = bkg_wnd_h[num] + 'px';
	document.getElementById('bkg_type').value = (num+1);
	
	if (num == 0)
	{
		document.getElementById('bkg_format_0').checked = 'checked';
		change_bkg_format(0);
	}
}

function change_bkg_format(num)
{
	for (i = 0; i < 4; i++)
	{
		if (i == num)
			d = 'block';
		else
			d = 'none';
		document.getElementById('type_f' + i).style.display = d;
	}
	setTimeout('imgf_check_image_flow('+num+', '+imgf_pics[num]+', 0)', 300);
}

function sel_bkg(item, num)
{
	c = document.getElementsByName('bkg_item');
	for (i = 1; i < c.length; i++)
	{
		if (c[i] == item)
		{
			c[i].className = 'bkg_item_sel';
			document.getElementById('bkg_gallery').value = num;
		}
		else
			c[i].className = 'bkg_item';
	}
}

function select_color(obj_id)
{
	obj = document.getElementById(obj_id);
	d = obj.style.display;
	if (d == 'block')
		d = 'none';
	else
		d = 'block';
	obj.style.display = d;
}

function RGBColor(color_string)
{
    this.ok = false;

    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
	color_string = color_string.replace(/[+]/g,'');
    color_string = color_string.toLowerCase();

    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            example: ['#00ff00', '336699'],
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            example: ['#fb0', 'f0f'],
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }

    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }
}

function set_txt_color(s)
{
	var color = new RGBColor(s);
	if (color.ok)
		document.getElementById('plugID').style.backgroundColor	= color.toHex().toUpperCase();
	else
		document.getElementById('plugID').style.backgroundColor	= 'rgb(255, 255, 255)';
}

function add_search_engine()
{
	if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function"))
	{
		window.sidebar.addSearchEngine(
			"http://www.peeplo.com/opensearch.src",
			"http://img.adv.dadapro.net/searchit/shared/peeplo.ico",
			"Peeplo.com",
			"Search");
	}
	else if ( navigator.userAgent.indexOf("MSIE 6") == -1  )
		window.external.AddSearchProvider("http://www.peeplo.com/opensearch.xml");
}

function show_download_toolbar()
{
	var alert_tb = getCookie('alert_tb');
	if (alert_tb != 1)
		document.getElementById('download_toolbar').style.display = 'block';
}

function hide_download_toolbar(check)
{
	if (check == 1)
	{
		setCookie('alert_tb', 1, 90);
		window.setTimeout("document.getElementById('download_toolbar').style.display = 'none'", 600);
	}
	else
	{
		setCookie('alert_tb', 1, 1);
		document.getElementById('download_toolbar').style.display = 'none';
	}	
}

function set_startup(need_sayt, is_homepage)
{
	if (is_homepage)
	{
		window.onresize=flashkeys;
		var tmp = document.getElementById('hp_header');
		if ( navigator.userAgent.indexOf("MSIE 6") == -1  )
			tmp.style.minWidth = (document.getElementById('hp_header_dx').offsetWidth+document.getElementById('hp_header_sx').offsetWidth+10)+'px';
		else
			tmp.style.width = (document.getElementById('hp_header_dx').offsetWidth+document.getElementById('hp_header_sx').offsetWidth+10)+'px';
		view_tag_cloud();
		set_position();
		set_color();
		
		show_download_toolbar();
	}
	
	var peeplo_msg = getMCookie('peeplo_msg');
	if (peeplo_msg > 0)
	{
		if (peeplo_msg == 3)
			open_wnd(1);
		else
		{
			var msg = '';
			var title = '';
			switch(peeplo_msg) {
				case '1': 	msg = TMPLVARS['dict']['MESSAGESENT'];
							title = TMPLVARS['dict']['SENDFRIEND'];
							break;
				case '2': 	msg = TMPLVARS['dict']['MESSAGENOTSENT'];
							title = TMPLVARS['dict']['SENDFRIEND'];
							break;
				case '31':	msg = TMPLVARS['dict']['UPLOAD_ERROR_1'];
							title = TMPLVARS['dict']['FILEUPLOAD'];
							break;
				case '32':	msg = TMPLVARS['dict']['UPLOAD_ERROR_2'];
							title = TMPLVARS['dict']['FILEUPLOAD'];
							break;
				case '33':	msg = TMPLVARS['dict']['UPLOAD_ERROR_3'];
							title = TMPLVARS['dict']['FILEUPLOAD'];
							break;
				case '34':	msg = TMPLVARS['dict']['UPLOAD_ERROR_4'];
							title = TMPLVARS['dict']['FILEUPLOAD'];
							break;
				case '35':	msg = TMPLVARS['dict']['UPLOAD_ERROR_5'];
							title = TMPLVARS['dict']['FILEUPLOAD'];
							break;
			}
			open_wnd(4, msg, title);
		}
	}
	clearMCookie('peeplo_msg');
	
	if (need_sayt)
		searchAsYouType.initialize(document.getElementById('q_head'), false);
	
	if (self.opt_menu)
		for (i = 0; i < opt_menu.length; i++)
			slide_menu[i] = new animatedcollapse(opt_menu[i], 200, false);
}


// broken image
function imageError(imgObj)
{
	imgObj.src = "http://img.adv.dadapro.net/searchit/shared/empty.gif";
}

// gestore dei cookie ------------------------------------------------------------------------

// configurazione del nome dei cookie da gestire.
var multiName = 'mName';
var multiValue = 'mValue';
	
function setMCookie(name, value)
{
	if (name == '')
		return;
	
	if (value == '')	// rimuovo il cookie
	{
		clearMCookie(name);
		return;
	}
	
	var tmp;
	var nameList = new Array();
	var valueList = new Array();
	tmp = getCookie(multiName);
	if (tmp)
		nameList = getCookie(multiName).split('|');
	tmp = getCookie(multiValue);
	if (tmp)
		valueList = getCookie(multiValue).split('|');
	var c_index = -1;
	for (var i = 0; i < nameList.length; i++)
		if (nameList[i] == escape(name))
		{
			c_index = i;
			break;
		}
		
	if (c_index == -1)		// se non c'è lo aggiungo
	{
		nameList.push(name);
		valueList.push(value);
	}
	else					// aggiorno il valore
		valueList[c_index] = value;
	
	setCookie(multiName, nameList.join('|'));
	setCookie(multiValue, valueList.join('|'));
}

function getMCookie(name)
{
	if (name == '')
		return '';
	
	var tmp = getCookie(multiName);
	if (!tmp)
		return '';
	
	var nameList = new Array();
	nameList = tmp.split('|');
	
	for (var i = 0; i < nameList.length; i++)
		if (nameList[i] == escape(name))	// c'è!
		{
			var valueList = new Array();
			tmp = getCookie(multiValue);
			if (!tmp)
				return '';
			valueList = tmp.split('|');
			return unescape(valueList[i].replace(/^\s+|\s+$/g, ''));
		}
	
	return '';
}

function clearMCookie(name)
{
	if (name == '')
		return;
	
	var nameList = new Array();
	var valueList = new Array();
	nameList = getCookie(multiName);
	if (nameList)
		nameList = nameList.split('|');
	else
		return;
	valueList = getCookie(multiValue).split('|');
	var newNameList = new Array();
	var newValueList = new Array();
	for (var i = 0; i < nameList.length; i++)
		if (nameList[i] != escape(name))	// c'è!
		{
			newNameList.push(nameList[i]);
			newValueList.push(valueList[i]);
		}
	
	setCookie(multiName, newNameList.join('|'));
	setCookie(multiValue, newValueList.join('|'));
}

function getCookie(name)
{
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for (var i = 0; i < a_all_cookies.length; i++)
	{
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if ( cookie_name == name )
		{
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 )
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
		return null;
}

function setCookie(name, value, new_expire)
{
	var today = new Date();
	var expire = new Date();
	
	if (new_expire)
		expire.setTime(today.getTime() + 1000 * 60 * 60 * 24 * new_expire);
	else
	{
		if (!self.cookies_expire || (cookies_expire == 0))
			cookies_expire = 1;
		expire.setTime(today.getTime() + 1000 * 60 * 60 * 24 * cookies_expire);
	}
	document.cookie = name + "=" + escape(value) + "; expires=" + expire.toGMTString();
}

// gestore dei cookie [fine] -----------------------------------------------------------------

// gestore di animated collapse --------------------------------------------------------------
var uniquepageid=window.location.href.replace("http://"+window.location.href, "").replace(/^\//, "") //get current page path and name, used to uniquely identify this page for persistence feature

function animatedcollapse(divId, animatetime, persistexpand, initstate){
	this.divId=divId
	this.divObj=document.getElementById(divId)
	this.divObj.style.overflow="hidden"
	this.timelength=animatetime
	this.initstate=(typeof initstate!="undefined" && initstate=="block")? "block" : "contract"
	this.isExpanded = "no";
	if (persistexpand)
		this.isExpanded=animatedcollapse.getCookie(uniquepageid+"-"+divId) //"yes" or "no", based on cookie value
	this.contentheight=parseInt(this.divObj.style.height)
	var thisobj=this
	if (isNaN(this.contentheight)){ //if no CSS "height" attribute explicitly defined, get DIV's height on window.load
		animatedcollapse.dotask(window, function(){thisobj._getheight(persistexpand)}, "load")
		if (!persistexpand && this.initstate=="contract" || persistexpand && this.isExpanded!="yes" && this.isExpanded!="") //Hide DIV (unless div should be expanded by default, OR persistence is enabled and this DIV should be expanded)
			this.divObj.style.visibility="hidden" //hide content (versus collapse) until we can get its height
	}
	else if (!persistexpand && this.initstate=="contract" || persistexpand && this.isExpanded!="yes" && this.isExpanded!="") //Hide DIV (unless div should be expanded by default, OR persistence is enabled and this DIV should be expanded)
		this.divObj.style.height=0 //just collapse content if CSS "height" attribute available
	if (persistexpand)
		animatedcollapse.dotask(window, function(){animatedcollapse.setCookie(uniquepageid+"-"+thisobj.divId, thisobj.isExpanded)}, "unload")
}

animatedcollapse.prototype._getheight=function(persistexpand){
	this.contentheight=this.divObj.offsetHeight
	if (!persistexpand && this.initstate=="contract" || persistexpand && this.isExpanded!="yes"){ //Hide DIV (unless div should be expanded by default, OR persistence is enabled and this DIV should be expanded)
		this.divObj.style.height=0 //collapse content
		this.divObj.style.visibility="visible"
	}
	else //else if persistence is enabled AND this content should be expanded, define its CSS height value so slideup() has something to work with
		this.divObj.style.height=this.contentheight+"px"
}

animatedcollapse.prototype._slideengine=function(direction){
	var elapsed=new Date().getTime()-this.startTime //get time animation has run
	var thisobj=this
	if (elapsed<this.timelength){ //if time run is less than specified length
		var distancepercent=(direction=="down")? animatedcollapse.curveincrement(elapsed/this.timelength) : 1-animatedcollapse.curveincrement(elapsed/this.timelength)
	this.divObj.style.height=distancepercent * this.contentheight +"px"
	this.runtimer=setTimeout(function(){thisobj._slideengine(direction)}, 10)
	}
	else{ //if animation finished
		this.divObj.style.height=(direction=="down")? this.contentheight+"px" : 0
		this.isExpanded=(direction=="down")? "yes" : "no" //remember whether content is expanded or not
		this.runtimer=null
		if ( !isIE() && direction == "down" && self.showVideo && this.mymedia && this.mymedia.id )
			showVideo(this.mymedia.id,this.mymedia.supplier);
	}
}

animatedcollapse.prototype.slidedown=function(){
	if (typeof this.runtimer=="undefined" || this.runtimer==null){ //if animation isn't already running or has stopped running
		if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
			alert("Please wait until document has fully loaded then click again")
		else if (parseInt(this.divObj.style.height)==0){ //if content is collapsed
			this.startTime=new Date().getTime() //Set animation start time
			this._slideengine("down")
		}
	}
}

animatedcollapse.prototype.slideup=function(){
	if (typeof this.runtimer=="undefined" || this.runtimer==null){ //if animation isn't already running or has stopped running
		if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
			alert("Please wait until document has fully loaded then click again")
		else if (parseInt(this.divObj.style.height)==this.contentheight){ //if content is expanded
			this.startTime=new Date().getTime()
			this._slideengine("up")
		}
	}
}

animatedcollapse.prototype.slideit=function(){
	if (isNaN(this.contentheight)) //if content height not available yet (until window.onload)
		alert("Please wait until document has fully loaded then click again")
	else if (parseInt(this.divObj.style.height)==0)
		this.slidedown()
	else if (parseInt(this.divObj.style.height)==this.contentheight)
		this.slideup()
}

animatedcollapse.curveincrement=function(percent){
	return (1-Math.cos(percent*Math.PI)) / 2 //return cos curve based value from a percentage input
}

animatedcollapse.dotask=function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
	var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
	if (target.addEventListener)
		target.addEventListener(tasktype, functionref, false)
	else if (target.attachEvent)
		target.attachEvent(tasktype, functionref)
}

animatedcollapse.getCookie=function(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

animatedcollapse.setCookie=function(name, value){
		document.cookie = name+"="+value
}

// gestore di animated collapse [fine] --------------------------------------------------------

// gestore del drag ---------------------------------------------------------------------------

var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

// gestore del drag [fine] --------------------------------------------------------------------