if(!this.JSON){this.JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}());

(function($){var state={};if(/^\{.*\}$/.test(window.name)){state=JSON.parse(window.name)}else{window.name='{}'}$.namesession={'set':function(n,v){state[n]=v;window.name=JSON.stringify(state)},'get':function(n,dv){if(n in state){return state[n]}return dv}}})(jQuery);

var mailRegExp = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
var cookieid = 'superscommesseMenu';
var options = { path: '/', expires: 100 };

var menudefault = {tennis: ['leftsubmenu_tennis_atp_tornei']};
initSessionState(menudefault);

function redirect(current_page,action,destination)
{
	$.ajax({ url: "/webBeacon.php", data: {cp: current_page, exit: action, target: destination}});
}

function serializeCookie(data)
{
	$.cookie(cookieid, $.JSON.encode(data), options);	
}

function deSerializeCookie(cookie_id)
{
	data = $.cookie(cookie_id);
	return $.JSON.decode(data);
}

function initCookieState(data)
{
	if($.cookie(cookieid)===null)
	{
		$.cookie(cookieid, $.JSON.encode(data), options);
	}else{
		state = deSerializeCookie(cookieid);
		for(properties in menudefault)
		{
			/*console.log(properties);*/
			if(state[properties]==undefined) state[properties] = menudefault[properties];
		}
		serializeCookie(state);
	}		
		
}

function initSessionState(data)
{
	if($.namesession.get(cookieid)==undefined)
	{
		$.namesession.set(cookieid, data);
	}else{
		state = $.namesession.get(cookieid);
		for(properties in menudefault)
		{
			/*console.log(properties);*/
			if(state[properties]==undefined) state[properties] = menudefault[properties];
		}
		$.namesession.set(cookieid, state);
	}	
}

function deleteCookie()
{
	$.cookie(cookieid, null);
}

function addReplaceSelectedLink(link, state)
{
	new_state = removeSelectedLink(state);
	new_state['selected_link'] = link;
	return new_state;
}

function removeSelectedLink(state)
{
	delete state['selected_link'];
	return state;
}

function addCategoryToCookie(category,state)
{
	to_add = true;
	for(properties in state)
	{
		if(properties == category) to_add = false;
	}
	
	if(to_add) state[category] = new Array();
	
	return state;
}

function removeCategoryFromCookie(category,state)
{
	
	for(properties in state)
	{
		if(properties == category)
		{
			delete state[properties];
		}
	}
	return state;
}

function addElementToCookie(category, selected_id, state, current_category)
{
	if(!hasParameter(current_category, selected_id))
	{
		current_category.push(selected_id);
		state[category] = current_category;	
	}	
	return state;
};

function removeElementFromCookie(category, selected_id,state, current_category)
{
	index_to_remove = new Array();			
	for( i=0;i<current_category.length;i++)
	{
		if(selected_id == current_category[i])
		{
			index_to_remove.push(i);			
		}
	}

	if(index_to_remove.length>0)
	{
		for(j=0; j<index_to_remove.length; j++)
		{
			current_category.splice(index_to_remove[j], 1);	
		}
		
	}
	
	state[category] = current_category;
	
	return state;
};

function hasParameter(stack, parameter)
{
	for(i=0;i<stack.length;i++)
	{
		if(stack[i]==parameter)
		{
			return true;	
		}
		
	}
	return false;
}

function highlightsBestQuota(){
	var max_quote = new Object();
	$('tbody[id]').each(function(){
		id = $(this).attr('id');
		position = id.search(/[0-9]+/i);
		num_segni = id.substr(position, (id.length-position)+1);
		$(this).children().filter('tr').children().filter('td[name]').each(function(){
			current_value = parseFloat($(this).text());
			segno_cur = $(this).attr('name');		
			if((max_quote[segno_cur]<current_value)||(max_quote[segno_cur]==undefined)) max_quote[segno_cur] = current_value;				
		});
		for(quota in max_quote)
		{
			$(this).children().filter('tr').children().filter('td[name='+quota+']').each(function(){
				current_value = parseFloat($(this).text());
				if(current_value == max_quote[quota]) $(this).attr('class','quota_migliore');
				
			});
		}
	});
}

function validateEmail(id,repetition_id,feedback_message)
{
	value = $('#'+id).val();
	//console.log(value);
	value_repetition = $('#'+repetition_id).val();
	$field = $('#'+id);
	$field_repetition = (repetition_id!=false)?$('#'+repetition_id):false;
	valid_field = true;
	if((value=='')||(value=='undefined'))
	{
		if(feedback_message) attachErrorMessage($field,stringErrorMessage,false);
		valid_field = false;
	}
	if((valid_field)&&(!mailRegExp.test(value)))
	{				
		if(feedback_message) attachErrorMessage($field,mailErrorMessage,false);
		valid_field = false;
	}
	if(valid_field){
		if(feedback_message)cleanError($field);		
	}		
	if($field_repetition!=false)
	{
		if((value!=value_repetition)&&(valid_field))
		{
			if(feedback_message) attachErrorMessage($field_repetition,mailRepetitionErrorMessage,false);
			valid_field = false;
		}else{if(feedback_message) cleanError($field_repetition);}
	}
	return valid_field;		
}

function getNewsServiceUrl(sport, sq1, sq2)
{
	return '/?action=news_service&sport='+sport+'&team1='+sq1+'&team2='+sq2;
}

function getQuoteServiceUrl()
{
	return '/?action=quote_html';
}

function getBookmakerUrlFormat()
{
	return '/redirect/bookmaker.html?ea=sim';
}

$(document).ready(function(){
	
	/* init left menu */
	$('#left_menu').load(
		'/?action=leftmenu_ajax',
		function()
		{
			state = $.namesession.get(cookieid);
			selected_link = state['selected_link'];
			delete state['selected_link'];
			$link = $('#leftmenu > div[id] > div > ul[id] > li > a[href='+selected_link+']');
			$link.css('color','#ff6600');
			
			for(category in state)
			{
				$('#leftmenu > span > a[title='+category+']').addClass('active');
				$('#leftsubmenu_'+category).show();
				for(k = 0; k<state[category].length; k++)
				{
					$('#'+state[category][k]).show();
				}		
			}
			
			$('#left_menu').css('visibility','visible');
		}
	
	);
	
	$('#leftmenu > span > a[title]').live('click',function(){
			
			category = $(this).attr('class');
			state = $.namesession.get(cookieid);			
			reference = $(this).attr('title');
			if($(this).attr('class')!='active')
			{						
				$(this).addClass('active');	
				new_state = addCategoryToCookie(reference, state);
			}else{
				$(this).removeClass('active');
				new_state = removeCategoryFromCookie(reference, state);
			}
			$.namesession.set(cookieid,new_state);
			$('#leftsubmenu_'+reference).slideToggle('normal');
			return false;
		});
		
		$('#leftmenu > div[id] > div > p > span[name]').live('click',function(){	
			reference = $(this).attr('name');
			$('#'+reference+'_tornei').slideToggle('normal', function(){
				$parent_node = $(this).parent().parent().filter('div[name]');
				category = $parent_node.attr('name');
				console.log(category);
				selected_id = $(this).attr('id');
				state = $.namesession.get(cookieid);
				console.log(state);
				current_category = state[category];	
				
				if($(this).is(':hidden'))
				{	
					new_state = removeElementFromCookie(category, selected_id,state, current_category);					
					
				}else{
			
					new_state = addElementToCookie(category, selected_id, state, current_category);
				}
				state = $.namesession.set(cookieid, new_state);					
			});
			return false;
		});
		
		$('#leftmenu > div[id] > div > p').live('click',function(){
			reference = $(this).children().filter('a[name]').attr('name');
			$('#'+reference+'_tornei').slideToggle('normal',function(){
				$parent_node = $(this).parent().parent().filter('div[name]');
				category = $parent_node.attr('name');
				selected_id = $(this).attr('id');
				state = $.namesession.get(cookieid);	
				current_category = state[category];	
				
				if($(this).is(':hidden'))
				{	
					new_state = removeElementFromCookie(category, selected_id,state, current_category);					
					
				}else{
			
					new_state = addElementToCookie(category, selected_id, state, current_category);
				}
				state = $.namesession.set(cookieid, new_state);		
			});
			return false;
		});
		
		$('#leftmenu > div[id] > div > ul[id] > li > a[href]').live('click',function(){
			state = $.namesession.get(cookieid);			
			link = $(this).attr('href');
			new_state = addReplaceSelectedLink(link, state);
			state = $.namesession.set(cookieid, new_state);		
		});
		
		$('input.text-input').focus(
			function()
			{
				if(!mailRegExp.test($(this).val()))
				{
					$(this).attr('rel',$(this).val());
					$(this).val('');
				}
			}
		);
		$('input.text-input').blur(
			function()
			{
				if(($(this).val=='')||(!mailRegExp.test($(this).val())))
				{				
					$(this).val($(this).attr('rel'));
					$(this).attr('rel','');
				}
			}
		);
		
		$('.expand').live('click',
				function()
				{
					class_to_expand = $(this).attr('id');
					$(this).hide();
					if(!($('.'+class_to_expand).is(':visible')))
					{
						$close = $(this).next();
						$close.attr('id',class_to_expand);
						$close.show();
						$('.'+class_to_expand).each(
							function()
							{
								$(this).css('display','table-row');
							}
						);
					}else{
					 	$open = $(this).prev();
						$open.attr('id',class_to_expand);
						$open.show();
					 	$('.'+class_to_expand).each(
							function()
							{
								$(this).css('display','none');
							}
						);
					}
				}
			);
		
		$('#newsletter_submit').live('click',
			function()
			{
				$('#feedback_message').hide();
				$('#feedback_message').removeClass();
				if(validateEmail('newsletter_form',false,false))
				{
					email = $('#newsletter_form').val();
					$.ajax(
						{
							type: 'POST',
							url: '/?action=newsletter',
							data: 'email='+email,
							dataType: 'json',
							success: function(data){
										for(message_type in data)
										{
											switch(message_type)
											{
												case 'error':
													$('#feedback_message').addClass('false_message');
													break;
												case 'warning':
													$('#feedback_message').addClass('alert_message');
													break;
												case 'ok':
													$('#feedback_message').addClass('true_message');
													break;
											}
											$('#feedback_message').html(data[message_type]);
											$('#feedback_message').show();
											break;
										}
									}
						}					
					);
				}else{
					$('#feedback_message').addClass('false_message');
					$('#feedback_message').html('please, insert a valid email!');
					$('#feedback_message').show();
				}
			}		
		);

		$('.link_ajax').live('click',function(){
			var par=$(this).attr('title').split('-');
			url='/?action=hub_pronostici&ajax=1&sport='+par[0];
			
			if (typeof (par[1])!='undefined')
				url+='&id_t='+par[1];
			
			$('#content_ajax').load(url,function(){$(window).scrollTop(0);});
			return false;
		});

		$('.link_ajax_page').live('click',function(){
			url=$(this).attr('href');
			
			if (url.indexOf('?')!=-1)
				url+='&ajax=1';
			else
				url+='?ajax=1';

			$('#content_ajax').load(url,function(){$(window).scrollTop(0);});
			return false;
		});
});
