//
// Class Scroller
//
var Scroller = Class.create();
Scroller.prototype = {
	initialize: function (tabContainer, tabContained, tabBtnNext, tabBtnPrevious) {
		this.tabContainer = tabContainer;
		this.tabContained = tabContained;
		this.tabBtnNext = tabBtnNext;
		this.tabBtnPrevious = tabBtnPrevious;
		
		Event.observe(window, 'load', this.update.bind(this));
	},
	
	update: function () {		
		var liElms = $(this.tabContained).getElementsBySelector('li');

		this.initialX = $(this.tabContained).offsetLeft;
		this.containedLiCount = liElms.length;

		// calcolo la larghezza del singolo tab
		if (liElms.length == 0) {
			return;
		} else if (liElms.length == 1) {
			var aElms = liElms[0].getElementsBySelector('a');
			if (aElms.length == 0) {
				return;
			}
			this.liWidth = aElms[0].offsetWidth;
			this.containedWidth = this.liWidth;
		} else {
			var aElms1 = liElms[0].getElementsBySelector('a');
			if (aElms1.length == 0) {
				return;
			}
			var aElms2 = liElms[1].getElementsBySelector('a');
			if (aElms2.length == 0) {
				return;
			}
			this.liWidth = aElms2[0].offsetLeft - aElms1[0].offsetLeft;
			this.containedWidth = this.liWidth * this.containedLiCount;
		}

		this.visibleLiCount = Math.floor($(this.tabContainer).offsetWidth / this.liWidth);
		
		$(this.tabContained).style.width = this.containedWidth + 'px';
		if ($(this.tabContained).firstDescendant().tagName.toUpperCase() == 'UL') {
			$(this.tabContained).firstDescendant().style.width = this.containedWidth + 'px';
		}
		
		this.finalX = $(this.tabContained).offsetLeft - this.containedWidth +
			$(this.tabContainer).offsetWidth;
		
		// posiziono sul selected
		var selElms = $(this.tabContained).getElementsByClassName('selected');
		if (selElms.length > 0) {
			var selElm = selElms[0];
			var selElmPosition = selElm.previousSiblings().length + 1;
	
			if (selElmPosition > this.visibleLiCount) {
				var newLeft = -1 * (selElmPosition - this.visibleLiCount) * this.liWidth;
				$(this.tabContained).style.left = newLeft + 'px';
			}
		}
		
		Event.observe(this.tabBtnNext, 'click', this.scroll.bind(this, false));
		Event.observe(this.tabBtnPrevious, 'click', this.scroll.bind(this, true));
	},
	
	scroll: function (left) {
		var offset = Position.positionedOffset($(this.tabContained));
	
		var newX = $(this.tabContained).offsetLeft + (left? 1 : -1) * this.visibleLiCount * this.liWidth;
		if (newX > this.initialX) {
			newX = this.initialX;
		}
		if (newX < this.finalX) {
			newX = this.finalX;
		}
		
		$(this.tabContained).style.left = (newX - this.initialX) + 'px';
	}
};


//
// Class TabSwitcher
//
var TabSwitcher = Class.create();
TabSwitcher.prototype = {
	initialize: function (tabLis, tabSelClass, tabDiv, loadingHTML, initialDiv, errorPage) {
		this.tabSelClass = tabSelClass;
		this.tabDiv = tabDiv;
		this.loadingHTML = loadingHTML;
		this.prevSelDiv = initialDiv;
		this.errorPage = errorPage;
	
		$A(tabLis).each(function (tabLi) {
			var aElm;
			if (tabLi.tagName.toLowerCase() == 'a') {
				aElm = tabLi;
			} else {
				aElm = tabLi.getElementsBySelector('a')[0];
			}
			Event.observe(aElm, 'click', this.tabSwitch.bind(this, tabLi));
		}.bind(this));
		
		this.selLi = $A(tabLis).find(function (tabLi) {
			return tabLi.hasClassName(tabSelClass);
		});
	},
	
	tabSwitch: function (tabLi) {
		if (this.selLi != undefined) {
			this.selLi.removeClassName(this.tabSelClass);
		}
		
		tabLi.addClassName(this.tabSelClass);
		this.selLi = tabLi;
		
		var aElm;
		if (tabLi.tagName.toLowerCase() == 'a') {
			aElm = tabLi;
		} else {
			aElm = tabLi.getElementsBySelector('a')[0];
		}
		
		if (aElm.rel.substring(0,4) == 'tab:') {
			var tabName = aElm.rel.substring(4);
			if (this.prevSelDiv != null) {
				$(this.prevSelDiv).hide();
			}
			$(tabName).show();
			this.prevSelDiv = tabName;
		} else {
			$(this.tabDiv).innerHTML = this.loadingHTML;
				
			new Ajax.Request(aElm.rel, {
				method: 'get',
				onSuccess: function (transport) {
					$(this.tabDiv).update(transport.responseText);
				}.bind(this),
				onFailure: function () {
					if (this.errorPage) {
						new Ajax.Updater({ success: this.tabDiv }, this.errorPage, {
							method: 'get',
							evalScripts: true
						});
					}		
				}.bind(this)
			});						
			
			if (this.prevSelDiv != null && this.prevSelDiv != this.tabDiv) {
				$(this.prevSelDiv).hide();
			}
			
			$(this.tabDiv).show();
			this.prevSelDiv = this.tabDiv;
		}
		
		return false;
	}
};



//
// Tables underliner
//
Event.observe(window, 'load', function() {  
	if (!window.XMLHttpRequest)   {  
		// IE6, older browsers  
		//new HoverBehavior('tr');  
		$$('table.tab_roller tr').each( function(e) {  
			Event.observe(e, 'mouseover', function() {  
				Element.addClassName(e, 'hover');  
			});  
			Event.observe(e, 'mouseout', function() {  
				Element.removeClassName(e, 'hover');  
			});  
		});  
	}  
}); 

//
// Email Check
//

// This script and many more are available free online at 
// The JavaScript Source!! http://javascript.internet.com
function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	//alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    //alert("The username doesn't seem to be valid.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        //alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	//alert("The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   //alert("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   //alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

//
// popup
//

var PopUp = Class.create();
PopUp.prototype = 
{
  initialize: function(options)
  {
    this.options = {
      url: '#',
      pageName: '',
       width: 450,
      height: 270,
	  toolbar:0,
	  resizable:1,
	  scrollbars:1,
	  left:200,
	  top:200
    }
    Object.extend(this.options, options || {});
	if(this.options.pageName=='NotiziaPrint'){this.options.width=765;this.options.height=600;}
	if(this.options.pageName=='NotiziaMail'){this.options.width=450;this.options.height=500;}
	if(this.options.pageName=='InformativaPrivacy'){this.options.height=500;}
	if(this.options.pageName=='CondizioniUtilizzo'){this.options.height=500;}
	if(this.options.pageName=='web2info'){this.options.scrollbars=0;this.options.height=560;}
    window.open(this.options.url, this.options.pageName, 'width='+this.options.width+',height='+this.options.height+',toolbar='+this.options.toolbar+',scrollbars='+this.options.scrollbars+',resizable='+this.options.resizable);
  }
}
function popup(url,width,height,pageName,scroll) {
	if (pageName == undefined) {
		pageName = "_blank";
	} else if (url == "/poker_live.html") {
		width=650;
		height=470;
	}
	var scrollyn = ((typeof scroll != "undefined") && (scroll = "1")) ? "yes":"no";
	var winl = (screen.width - width) / 2;
	var wint = (screen.height - height) / 2;
	window.open(url,pageName,'width='+width+',height='+height+',toolbar=no,scrollbars='+scrollyn+',menubar=no,resizable=no,top='+wint+',left='+winl+'');
}

function popupInviaAmico(link) {
	if (link == undefined) {
		link = '';
	} else {
		link = '?url=' + link;
	}
	return popup('/popupMail.shtml' + link,431,500,'NotiziaMail');
}

function aggiungi_feed_rss(cat) {
	document.location = '/dinamiche/login.jsp?srv=1&rsscat=' + cat + '&rsstitle=&rsslink=';
}
function aggiungi_feed_rss_esterno(title, link) {
	if (link.substring(link.length - 1) == '/') {
		link = link.substring(0, link.length - 1);
	}
	document.location = 'http://www.corrieredellosport.it/dinamiche/login.jsp?srv=1&rsscat=&rsstitle=' +
		encodeURIComponent(title) + '&rsslink=' + encodeURIComponent(link);
}

// for IE6 compatibility
function setImageSrc(where, imgSrc, onloadFnct) {
	var imgPreloader = new Image();
	imgPreloader.onload = function () {
		$(where).src = imgPreloader.src;
		imgPreloader.onload = function () {};
		if (onloadFnct) {
			onloadFnct();
		}
	};
	imgPreloader.src = imgSrc;
}

//
// ToggleWithImages
//
function toggleWithImage(idDiv)	{
	$(idDiv).toggle();
	var targetSrc;
	if ($(idDiv).style.display == 'none') {
		targetSrc = $(idDiv + '_Expander').src.replace(/Contract/, 'Expand');
	} else {
		targetSrc = $(idDiv + '_Expander').src.replace(/Expand/, 'Contract');
	}
	setImageSrc(idDiv+'_Expander', targetSrc);
}


// Effettua l'escaping dei caratteri speciali di Lucene nella stringa
function escapeLuceneQuery (query) 
{
	query = query.replace (/([\\\"\+\-\!\(\)\{\}\[\]\^\~\*\?\:])/g, '\\$1');
	query = query.replace (/\&\&/g,'\\&&');
	query = query.replace (/\|\|/g,'\\||');
	query = '"'+query+'"';

	return query;
}

// Check if banner is present
function bannerPresent(divId) {
	var banner = $(divId).descendants().find(function (elm) {
		if (elm.nodeType != 1) { // not an element
			return false;
		}
		if (elm.tagName.toUpperCase() == 'SCRIPT' ||
				elm.tagName.toUpperCase() == 'A') {
			return false;
		}
		
		if (elm.tagName.toUpperCase() == 'IMG') {
			return elm.width > 10 && elm.height > 10;
		}
		
		return true;
	});
	
	if (banner) {
		return true;
	}
	return false;
}

function bannerPresentInIFrame(iFrameId) {
	var docObj = getIFrameDocument(iFrameId);
	var flagObj = docObj.getElementById('banner_present');
	
	if (!flagObj || flagObj.innerHTML == '') {
		return null;
	}
	return flagObj.innerHTML == 'true';
}

// hide void banner on page loaded
function hideVoidBanners() {
	$$('.banner').each(function (banner) {
		if (banner.tagName.toUpperCase() != 'IFRAME' && !bannerPresent(banner)) {
			banner.hide();
		}
	});
}
Event.observe(window, 'load', hideVoidBanners);

// access the iframe internal document element
function getIFrameDocument(iframeId) {
	if ($(iframeId).contentDocument) { // Firefox
		return $(iframeId).contentDocument;
	} else if ($(iframeId).contentWindow.document) { // IE >= 6
		return $(iframeId).contentWindow.document;
	} else if ($(iframeId).document) { // IE <= 5
		return $(iframeId).document;
	}
}

// To avoid background image flickering in IE6
// cfr http://www.hedgerwow.com/360/bugs/dom-fix-ie6-background-image-flicker.html
(function(){ 
	/*Use Object Detection to detect IE6*/ 
	var m = document.uniqueID /*IE*/ && document.compatMode /*>=IE6*/ 
		&& !window.XMLHttpRequest /*<=IE6*/ && document.execCommand ; 
	try { 
		if(!!m) { 
			m("BackgroundImageCache", false, true) /* = IE6 only */ 
		} 
	} catch (e) {
	}; 
})(); 

// String length for db saving
// char count: & -> 5; <, > -> 4; \n -> 5
function dbStringLength(string) {
	var stringLength = string.length;
	string.replace(/[\n&]/g, function () { stringLength += 4 });
	string.replace(/[<>]/g, function () { stringLength += 3 });
	return stringLength;
};

function prepareStringForAttr(string) {
	return string.replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/>/g, '&gt;');
}

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


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 setCookie(c_name,value,expiredays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

//allinea il livescore
function allineaTabellaDiretta(classTabella) {
	$$('.' + classTabella + ' th').each(function (cell) {
		if (cell.style.width == '139px') {
			cell.style.width = '130px';
		}
	});
}

function insertOkNotizie(id) {
  Event.observe(window, 'load', function() {
      new Insertion.Before('articolo-foot', '<iframe src="http://oknotizie.alice.it/go_frametop.html.php?us='+id+'" allowtransparency="true" style="width:98%;height:40px;" scrolling="no" frameborder="0"></iframe>');
  });
}



// Box Feed RSS
var rssFeedOptions = {
	get_feed_url: '/dinamiche/Feed',
	forum_json: '/rss/forum_home.json',
	blog_json: '/rss/blog_home.json',
	max_abstract_length: 90,
	forum_error_message: new Template('<li><h3 class="tit_ForumSection"><a href="#{url}">Errore nel caricamento del feed RSS.</a></h3>'),
	blog_error_message: new Template('<h3 class="tit_BlogSection"><a href="#{url}">Errore nel caricamento del feed RSS.</a></h3>'),
	forum_item_template: new Template(
		'<li>' +
			'<span class="ora_box_forum">12:15</span><span class="titolo_box_forum">#{title}</span>' + 
			'<p class="subtitle_box_forum">Postato da: #{author}</p>' +
			'<p class="leggitutto"><a href="#{link}" title="Leggi tutto">Leggi tutto</a></p>' +
			'<p class="post"><a href="#{link}">#{replies}</a></p>' +
			'</li>' +
			'<li><img src="/res/img/scommesse/line_forum.png"/></li>' +
		'</li>'),
	blog_item_template: new Template(
		'<div class="box_Img" style="width: 185px;">' +
			'<a href="#{link}" title="#{titleNoQuot}">' +
				'<img class="img_blog_entry" style="display: none" src="" alt="#{titleNoQuot}" />' +
			'</a>' +
		'</div>' +
		'<h3 class="tit_BlogSection"><a href="#{linkBlog}" title="#{titleBlogNoQuot}">#{titleBlog}</a></h3>' +
		'<h4 class="tit_News"><a href="#{link}" title="#{titleNoQuot}">#{title}</a></h4>' +
		'<div class="txt_Abstract"><p>#{postAbstract}</p></div>' +
		'<a href="#{linkCommenti}" class="link_Comment" title="Commenti">#{numCommenti}</a>' +
		'<div class="clear">&nbsp;</div>')
};



var RssBox = Class.create();
RssBox.prototype = {
	initialize: function (boxId, url, type, large, fromStatic) {
		this.options = rssFeedOptions;
		this.boxId = boxId;
		this.url = url;
		this.type = type;
		this.large = large;
		
		this.baseElm = $(this.boxId + '_contents');
		
		if (fromStatic) {
			new Ajax.Request(this.type == 'forum' ? this.options.forum_json : this.options.blog_json, {
				onSuccess: this.updateRssContent.bind(this),
				onFailure: this.updateRssError.bind(this) 
			});
		} else {
			new Ajax.Request(this.options.get_feed_url, {
				parameters: { 
					link: this.url, 
					last: '' 
				},
				onSuccess: this.updateRssContent.bind(this),
				onFailure: this.updateRssError.bind(this) 
			});
		}
	},

	updateRssContent: function (transport) {
		// evaluating response -> defines var newContent
		eval(transport.responseText);

		this.baseElm.innerHTML = '';
		if (this.large) {
			$(this.boxId + '_contents_2').innerHTML = '';
			$(this.boxId + '_contents_3').innerHTML = '';
		}
		
		// checking whether link it is allowed
		if (newContent.not_allowed) {
			this.updateRssError();
			return;
		}
		
		if (this.type == 'forum') {
			var num_items = this.large ? 5 : 3;
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var target = this.baseElm;
				/*
				if (i >= 3) {
					target = $(this.boxId + '_contents_2');
				}
				if (i >= 6) {
					target = $(this.boxId + '_contents_3');
				}
				*/
				var entry = newContent.entries[i];
				var linkUrl = entry.link;
				if (!linkUrl || linkUrl == '') {
					linkUrl = newContent.link;
				}
				
				itemText = this.options.forum_item_template.evaluate({
					title: entry.title,
					titleNoQuot: entry.title.replace(/\"/g, "&quot;"),
					category: entry.category,
					link: linkUrl,
					author: entry.author,
					replies: entry.description
				});
			
				new Insertion.Bottom(target, itemText);
			}
		} else if (this.type == 'blog') {
			var num_items = this.large ? 3 : 1;
			for (var i = 0; i < num_items && i < newContent.entries.length; i++) {
				var target = this.baseElm;
				if (i >= 1) {
					target = $(this.boxId + '_contents_2');
				}
				if (i >= 2) {
					target = $(this.boxId + '_contents_3');
				}
				var entry = newContent.entries[i];
				var linkUrl = entry.link;
				if (!linkUrl || linkUrl == '') {
					linkUrl = newContent.link;
				}
				
				var contents = entry.contents;
				var postAbstract = contents.stripTags().truncate(this.options.max_abstract_length);

				var regexp = new RegExp('<img [^>]*src="([^"]+)"[^>]*>');
				var result = regexp.exec(contents);
				var image = result == null ? "" : result[1];
				
				itemText = this.options.blog_item_template.evaluate({
					title: entry.title,
					titleNoQuot: entry.title.replace(/\"/g, "&quot;"),
					category: entry.category,
					link: linkUrl,
					linkBlog: newContent.link,
					titleBlog: newContent.title,
					titleBlogNoQuot: newContent.title.replace(/\"/g, "&quot;"),
					postAbstract: postAbstract,
					linkCommenti: entry.repliesLink,
					numCommenti: entry.repliesCount + ' ' + (entry.repliesCount == 1 ? 'commento' : 'commenti')
				});
			
				new Insertion.Bottom(target, itemText);
				var imgPreloader = new Image(); 
				imgPreloader.onload = this.onImageLoaded.bind(this, imgPreloader, target);
				imgPreloader.src = image;
			}
		}
	},
	
	onImageLoaded: function (imgPreloader, target) {
		var imgElm = target.getElementsByClassName('img_blog_entry')[0];
		$(imgElm).src = imgPreloader.src;
	
		var ratio = imgPreloader.height / imgPreloader.height;
		if (ratio > (185 / 103)) {
			$(imgElm).setStyle({ 
				width: '185px' 
			}); 
		} else {
			$(imgElm).setStyle({ 
				height: '103px' 
			}); 
		}
		$(imgElm).show();
		imgPreloader.onload = function() {};
	},
	
	updateRssError: function () {
		this.baseElm.innerHTML = '';
		var text = this.type == 'blog' ? this.options.blog_error_message.evaluate({ url: this.url }) : this.options.forum_error_message.evaluate({ url: this.url });
		new Insertion.Bottom(this.baseElm, text);
	}	
}


// This function displays the Google AdSense results.
function google_ad_request_done(google_ads) {
	if (google_ads.length < 1 )
	  return;

	var maxAds=google_ads.length>3 ? 3 : google_ads.length;

	document.write("<div class='html_474 AdGoogle'><div class='headerGoogle clearfix'>");
	document.write("<h2><a href=\"" + google_info.feedback_url + "\">Annunci Google</a></h2>");
	document.write("</div>");
							  
	if (google_ads[0].type == 'text') {
	  document.write("<ul class='listGoogle'>");
	  for(i = 0; i < maxAds; ++i) {

		document.write("<li>");
		document.write("<h3><a target='_blank' href='" + google_ads[i].url + "'>" + google_ads[i].line1 + "</a></h3>");
		document.write("<p><a target='_blank' href='" + google_ads[i].url + "'>" + google_ads[i].line2 + " "+google_ads[i].line3 + "</a><br/>");
		document.write("<span><a target='_blank' href='" + google_ads[i].url + "'>" +google_ads[i].visible_url + "</a></span></p>");
		document.write("</li>");
											
	  }
	  document.write("</ul>");
	}
	document.write ("</div>");
}

Event.observe(window, 'load', page_loaded_specialstrip, false);
function page_loaded_specialstrip(evt) {
	try {
		/*divs = $$(".specialstrip_Confederations_Cup");
		if (divs.length>0) {
			tgt = divs[0];
			Event.observe(tgt, 'click', function(){
				document.location.href="http://www.corrieredellosport.it/rubriche/Confederations%20Cup.shtml";
			}, false);		
		}*/
		//add mondiali nuoto
		divs = $$(".specialstrip_Mondiali_Nuoto");
		if (divs.length>0) {
			tgt = divs[0];
			Event.observe(tgt, 'click', function(){
				document.location.href="http://www.corrieredellosport.it/rubriche/Mondiali di Nuoto.shtml";
			}, false);		
		}
		//speciale olimpiadi
		divs = $$(".specialstrip_Vancouver_2010");
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/rubriche/Olimpiadi.shtml";
		  }, false);		
		}
		//speciale seinazioni
		divs = $$(".specialstrip_Sei_Nazioni");
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/sei_nazioni/";
		  }, false);		
		}
		//speciale maratona di roma
		divs = $$(".specialstrip_Maratona_Roma");
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/rubriche/Altri%20Sport/Maratona%20di%20Roma.shtml";
		  }, false);		
		}
		//speciale maratona di roma
		divs = $$(".specialstrip_Roma_Ostia");
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/rubriche/Altri%20Sport/Mezza%20Maratona%20Roma%20Ostia.shtml";
		  }, false);		
		}
		//speciale internaz tennis
		divs=$$('div[class="specialstrip_Internazionali_d\\\'Italia"]'); 		
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/tennis/internazionali_italia/";
		  }, false);		
		}
		//specialstrip_Mondiali_2010
		divs = $$(".specialstrip_Mondiali_2010");
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/calcio/mondiali_2010/";
		  }, false);		
		}
		
		//specialstrip_Mondiali_2010
		divs = $$(".specialstrip_Mondiali_2010");
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/calcio/mondiali_2010/";
		  }, false);		
		}
		
		//.strip_Speciale_derby
		divs = $$(".strip_Speciale_derby");
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/speciale_derby/";
		  }, false);		
		}
		
		//.strip_Coppa_America
		divs = $$(".strip_Coppa_America");
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/calcio/coppa_america/";
		  }, false);		
		}
		
		//.strip_Rugby
		divs = $$(".strip_Rugby");
		if (divs.length>0) {
		  tgt = divs[0];
		  Event.observe(tgt, 'click', function(){
			document.location.href="http://www.corrieredellosport.it/altri_sport/rugby/";
		  }, false);		
		}
	} catch(err) {
	    
		try{ 
			$('.specialstrip_Sei_Nazioni').click( function(ev){document.location.href="http://www.corrieredellosport.it/rubriche/Sei%20Nazioni.shtml"});
			$('.specialstrip_Vancouver_2010').click( function(ev){document.location.href="http://www.corrieredellosport.it/rubriche/Vancouver%202010.shtml"});
			$('.specialstrip_Rugby').click( function(ev){document.location.href="http://www.corrieredellosport.it/altri_sport/rugby/"});
		}
		catch(err_x){}
	}
}

var setModelloAnnunci = null;

function PopolaModelloAnnunci(idModello) {
	var selMarca = $(document.forms.formAnnunci.marca);
	var idMarca = selMarca.value;
	if (idMarca != '') {
		if (idModello == undefined) {
			setModelloAnnunci = '';
		} else {
			setModelloAnnunci = idModello;
		}
		new Ajax.Request("/annunci/js/modelli_" + idMarca + ".js", {
			onSuccess: PopolaModelloAnnunci_onSuccess
		});
	} else {
		var selModello = $(document.forms.formAnnunci.modello);
		selModello.innerHTML = '<option value="">---</option>';
	}
}


function PopolaModelloAnnunci_onSuccess(transport) {
	eval(transport.responseText);
	var selModello = $(document.forms.formAnnunci.modello);
	selModello.innerHTML = '<option value="">---</option>';
	$A(modelli).each(function (elm) {
		new Insertion.Bottom(selModello, '<option value="' + elm.id_modello + '">' + elm.label + '</option>');
	});
	if (setModelloAnnunci != null) {
		document.forms.formAnnunci.modello.value = setModelloAnnunci;
	}
}

//LM 
if(window.location.pathname.indexOf('calendario')!=-1)
{ 
    var allLinks=document.getElementsByTagName("a");
	for (i=0; i<allLinks.length; i++) {
		if(allHTMLTags[i].className=='bclic') allHTMLTags[i].setAttribute("href",'http://www.betclic.it/partner.aspx?p=CDS3&z=C9'); 
	}
}
