﻿// NAMESPACE DEFINITIONs
if (!$defined(GoalCom)) {var GoalCom={};}
if (!$defined(GoalCom.UI)) {GoalCom.UI={};}

// GOALCOM.UI.HELPERS
if (!$defined(GoalCom.UI.Helpers)) {
	GoalCom.UI.Helpers = {
		/* UPDATE CLASSIFICA AJAX */
		updateClassificaAjax : function(sourceEl, entryPointUrl, lingua, lookup) {
			if (!$defined(lingua)) {
				return false;
			}
			
			var el1 = $(sourceEl);
			el1.setProperty('disabled','disabled');
			var el2 = $E('div.Clas',el1.getParent().getParent());
			el2.empty().adopt(new Element('span',{'class':'i-load'}).adopt(new Element('span').setText('attendere...')));
			
			new XHR({
				'method':'get',
				'headers':{
					'x-goalcom-cmd':'partial-render'
				},
				'onSuccess':(function(text){
					this.setHTML(text);
					$ES('tr',this).addEvent('mouseenter',function(){this.addClass('i-hover');}).addEvent('mouseleave',function(){this.removeClass('i-hover');});
					$E('select',this.getPrevious()).removeProperty('disabled');
				}).bind(el2)
			})
			.send(
				entryPointUrl,
				Object.toQueryString({
					'idfase':lookup['g_'+el1.options[el1.selectedIndex].value],
					'lingua':lingua
				})
			);
		},

		/* UPDATE SEZ LIVE SCORES */
		updateSezLiveScores : function(sourceEl, entryPointUrl) {
			var ggLv = $(sourceEl).options[$(sourceEl).selectedIndex].value;
			var el1 = $(sourceEl).getParent().getParent();
			
			el1.empty().adopt(new Element('span',{'class':'i-load'}).adopt(new Element('span').setText('attendere...')));
			
			new XHR({
				'method':'get',
				'headers':{
					'x-goalcom-cmd':'partial-render'
				},
				'onSuccess':(function(text){
					this.setHTML(text);
				}).bind(el1)
			})
			.send(
				entryPointUrl,
				Object.toQueryString({
					'ggLv':ggLv
				})
			);
		},
		
		/* UPDATE MATCH LIST AJAX */
		updateMatchListAjax : function(sourceEl, entryPointUrl) {
			var el1 = $(sourceEl);
			el1.setProperty('disabled','disabled');
			var el2 = $E('div.MatchList',el1.getParent().getParent().getParent());
			el2.empty().setStyle('height',200).adopt(new Element('span',{'class':'i-load'}).adopt(new Element('span').setText('attendere...')));
			
			// "FORCE=true/false" QUERYSTRING PARAMETER
			var forceParam = '';
			try {
				forceParam = (location.search.replace(/^\?/,'').toLowerCase().split('&').some(function(item){return item=='force=true'}))?'true':'false';
			} catch(e) {
				forceParam = 'false';
			}
			
			new XHR({
				'method':'get',
				'headers':{
					'x-goalcom-cmd':'partial-render'
				},
				'onSuccess':(function(text){
					this.empty();
					this.setStyle('height',null);
					this.setHTML(text);
					$E('select',this.getParent()).removeProperty('disabled');
				}).bind(el2)
			})
			.send(
				entryPointUrl,
				Object.toQueryString({
					'competitionid':el1.options[el1.selectedIndex].value,
					'force':forceParam
				})
			);
		}
	
	};
}

// GOALCOM.UI.MAINHPNAVIGATOR
GoalCom.UI.MainHPNavigator = new Class({
	options : {
		autoplayInterval : 10000,
		autoplayMaxLoops : 0,
		bigListFxTransition : Fx.Transitions.Quint.easeInOut,
		bigListFxDuration : 800
	},
	
	initialize : function(el, autoplay, options) {
		this.setOptions(options);
		this._el = $(el);
		this._elTitle = $E(".i-title", this._el);
		this._bigListContainer = $E("div.i-biglist", this._el).getFirst();
		this._bigList = $ES("div.M1", this._bigListContainer);
		this._sideList = $ES("ul.Thumb li a", this._el);
		this._selIndex = null;
		this._selCount = this._bigList.length;
		this._elAutoplay = $E(".i-autoplay", this._el);
		this._isInProgress = false;
		this._timerId = null;
		this._currentLoop = 0;
		// DOM SETUP
		this._bigListContainer.setStyles({"position" : "absolute", "left" : 0, "top" : 0});
		// NAVIGATORs SETUP
		this._sideList.each(function(item, index) {
			item.addEvent("click", (function(event) {
				event = new Event(event);
				event.preventDefault();
				if (this.nav.isAutoplayInProgress()) {
					// AUTOPLAY IN PROGRESS --> STOP AND RESUME IT (TO AVOID TOO FAST CHANGING)
					this.nav.stopAutoplay();
					this.nav.startAutoplay();
				}
				this.nav.selNews(this.index);
				return false;
			}).bind({
				"nav" : this,
				"index" : index
			}))
		}.bind(this));
		// AUTOPLAY NAVIGATOR SETUP
		this._elAutoplay.addEvent("click", (function(e){new Event(e).preventDefault();this.switchAutoplay()}).bind(this));
		// STARTUP
		this.selNews(0);
		// AUTOPLAY
		if ($pick(autoplay, false)) {
			this.startAutoplay();
		} else {
			this.stopAutoplay();
		}
	},
	
	startAutoplay : function() {
		this._elAutoplay.className = "pause";
		this._currentLoop = 0;
		// TIMER
		if (this._timerId == null) {
			this._timerId = window.setInterval((function(){this.selNextNews()}).bind(this), this.options.autoplayInterval);
		}
	},
	
	stopAutoplay : function() {
		this._elAutoplay.className = "play";
		// TIMER
		if (this._timerId != null) {
			window.clearInterval(this._timerId);
			this._timerId = null;
		}
	},
	
	isAutoplayInProgress : function() {
		return this._timerId != null;
	},
	
	switchAutoplay : function() {
		if (this.isAutoplayInProgress()) {
			this.stopAutoplay();
		} else {
			this.startAutoplay();
		}
	},
	
	selNews : function(i) {
		try {
			// IF ANIMATION IN PROGRESS --> RETURN
			if (this._isInProgress) {
				return false;
			}
			// PARAMETERs CHECK
			i = $pick(i, 0);
			// IF OLD INDEX SAME AS NEW --> RETURN
			if (this._selIndex == i) {
				return false;
			}
			this._isInProgress = true;
			// OUTER TITLE UPDATE
			this._elTitle.innerHTML = $E("h2", this._bigList[i]).innerHTML;
			// SIDE LIST UPDATE
			if (this._selIndex != null) {
				this._sideList[this._selIndex].getFirst().removeClass("sel");
			}
			this._sideList[i].getFirst().addClass("sel");
			// BIG LIST UPDATE
			new Fx.Style(this._bigListContainer, "top", {duration : this.options.bigListFxDuration, transition : this.options.bigListFxTransition}).start(-352 * i).chain((function() {
				this.nav._selIndex = this.index;
				this.nav._isInProgress = false;
			}).bind({
				"nav" : this,
				"index" : i
			}));
		} catch(e) {
			// EMPTY BY DESIGN
		}
	},
	
	selNextNews : function() {
		var nextIndex;
		// DETERMINE NEXT INDEX
		if (this._selIndex >= this._selCount - 1) {
			if ( (this.options.autoplayMaxLoops > 0) && ((this._currentLoop + 1) >= this.options.autoplayMaxLoops) ) {
				this.stopAutoplay();
				return;
			}
			nextIndex = 0;
			this._currentLoop++;
		} else {
			nextIndex = this._selIndex + 1;
		}
		// SELECT NEWS
		this.selNews(nextIndex);
	}
});

GoalCom.UI.MainHPNavigator.implement(new Options);

// GOALCOM.UI.OVERFLOWNAVIGATOR
GoalCom.UI.OverflowNavigator = new Class({
	options : {
		"availableNavigators" : ["t","r","b","l"],
		"fadeNavigators" : true,
		"fadeNavigatorsOpacityOut" : 0.3,
		"fadeNavigatorsOpacityIn" : 0.8,
		"scrollStep" : 4,
		"scrollInterval" : 50
	},
	
	initialize : function(el, options) {
		this.setOptions(options);
		
		this._el = $(el);
		try {
			this._el2 = $E("div", this._el);
			this._timerId = null;
			this._scrollInProgress = false;
			this._currentDirection = null;
			// DOM SETUP
			this._el.setStyles({overflow:"hidden",position:"relative"});
			this._el2.setStyles({position:"absolute",left:0,top:0});
		} catch(e) {
			// EMPTY BY DESIGN
		}
		// NAVIGATORs SETUP
		this._createNavigators();
		if (this.options.fadeNavigators) {
			// INITIAL FADING
			this._setOpacityAllNavigators(this.options.fadeNavigatorsOpacityOut);
			// FADING EVENTs
			this._el.addEvent("mouseenter", this._setOpacityAllNavigators.bind(this,this.options.fadeNavigatorsOpacityIn));
			this._el.addEvent("mouseleave", this._setOpacityAllNavigators.bind(this,this.options.fadeNavigatorsOpacityOut));
		}
	},
	
	_createNavigator : function(direction) {
		// PARAMETERs CHECK
		direction = $pick(direction, "b");
		var e1;
		e1 = new Element("a")
			.setProperties({
				"href" : "#",
				"rel" : "nav",
				"navDir" : direction,
				"class" : "i-nav-" + direction
			})
			.addEvent("mouseenter", (function(){this.nav._startScrolling(this.dir);}).bind({nav:this,dir:direction}))
			.addEvent("mouseleave", (function(){this.nav._stopScrolling(this.dir);}).bind({nav:this,dir:direction}))
			.addEvent("click", function(e){e=new Event(e);e.preventDefault();return false;})
		;
		this._el.adopt(e1);
		return e1;
	},
	
	_createNavigators : function(navigatorsToCreate) {
		// PARAMETERs CHECK
		navigatorsToCreate = $pick(navigatorsToCreate, this.options.availableNavigators);
		navigatorsToCreate.each((function(item){this._createNavigator(item);}).bind(this));
		return this;
	},
	
	_scroll : function(direction) {
		if (this._scrollInProgress) {
			return this;
		}
		this._scrollInProgress = true;
		// PARAMETERs CHECK
		direction = $pick(direction, $pick(this._currentDirection, "b"));
		// SETUP MOVEMENT
		var step,minValue,newValue,prop;
		switch(direction) {
			case "t":
			case "b":
				prop = "top";
				step = (direction == "t"?1:-1) * this.options.scrollStep;
				minValue = this._el.getSize().size.y - this._el2.getSize().size.y;
				break;
			case "r":
			case "l":
				prop = "left";
				step = (direction == "l"?1:-1) * this.options.scrollStep;
				minValue = this._el.getSize().size.x - this._el2.getSize().size.x;
				break;
		}
		// STEP SAFETY-CHECK
		newValue = this._el2.getStyle(prop).toInt() + step;
		// MIN VALUE CHECK
		newValue = Math.max(newValue, minValue);
		// MAX VALUE CHECK
		newValue = Math.min(newValue, 0);
		// MOVE IT
		this._el2.setStyle(prop, newValue);
		this._scrollInProgress = false;
		return this;
	},
	
	_startScrolling : function(direction) {
		// PARAMETERs CHECK
		direction = $pick(direction, "b");
		// SAFETY-STOP
		this._stopScrolling();
		// SET CURRENT DIRECTION
		this._currentDirection = direction;
		// START
		this._timerId = window.setInterval((function(){this._scroll();}).bind(this), this.options.scrollInterval);
		
		return this;
	},
	
	_stopScrolling : function() {
		if (this._timerId != null) {
			// STOP
			window.clearInterval(this._timerId);
			// CLEAR CURRENT DIRECTION
			this._currentDirection = null;
		}
		return this;
	},
	
	_showAllNavigators : function() {
		$ES("a[rel=nav]",this._el).each(function(item){item.setStyle("display","block");});
	},
	
	_hideAllNavigators : function() {
		$ES("a[rel=nav]",this._el).each(function(item){item.setStyle("display","none");});
	},
	
	_setOpacityAllNavigators : function(opacity) {
		$ES("a[rel=nav]",this._el).each((function(item){item.setStyle("opacity",this);}).bind(opacity));
	}
});

GoalCom.UI.OverflowNavigator.implement(new Options);

// GOALCOM.UI.SWITCHER
GoalCom.UI.Switcher = new Class({
	options : {
		"initialSwitch" : "",
		"selectedControllerClass" : "sel"
	},
	
	initialize : function(switchers, options) {
		// PARAMETERs CHECK
		switchers = $pick(switchers, []);
		this.setOptions(options);
		// NOTE: SWITCH STRUCTURE -MUST- BE:
		// {
		//		name : "switcher1",
		//		controller : firstElementRef
		//		view : secondElementRef
		//		enabled : true/false
		// }
		this._switchers = $A(switchers);
		// DOM SETUP
		this._switchers.each((function(item){
			item.controller.removeEvents("click");
			item.controller.addEvent("click", (function(){if (this.nav._switchers.some((function(item){return (item.name==this) && (item.enabled==true);}).bind(this.name))){this.nav.switchTo(this.name);}}).bind({"name":item.name,"nav":this}));
		}).bind(this));
		// STARTUP SWITCH
		if (this.options.initialSwitch == "") {
			if (this._switchers.length > 0) {
				this.options.initialSwitch = this._switchers[0].name;
			}
		}
		if (this.options.initialSwitch != "") {
			this.switchTo(this.options.initialSwitch);
		}
	},
	
	switchTo : function(name) {
		try{
			if (!$defined(name)) {
				return this;
			}
			this._switchers.each((function(item){
				if (item.name == this.name) {
					// SELECTED
					item.controller.addClass(this.nav.options.selectedControllerClass);
					item.view.setStyle("display", "block");
				} else {
					// -NOT- SELECTED
					item.controller.removeClass(this.nav.options.selectedControllerClass);
					item.view.setStyle("display", "none");
				}
			}).bind({"name":name,"nav":this}));
		}catch(e1){
		}
		return this;
	}
});

GoalCom.UI.Switcher.implement(new Options);


// GOALCOM.UI.RATING
GoalCom.UI.Rating = new Class({
	options : {
		'hoverCssClass' : 'i-hover' ,
		'lbl' : null ,
		'url' : 'VoteCmd.aspx' ,
		'cookieDurationInDays' : 365
	},
	
	initialize : function(el, et, eid, options) {
		if (!$defined(el)){return;}
		this.setOptions(options);
		this._el=$(el);
		this._et = et;//entity type
		this._eid = eid;//entity id
		this._lbl=$(this.options.lbl);
		this._as=$ES('li a',this._el);
		
		this._loadVote();
		this._updateState();
		this.fireEvent('onLoad');
	},
	
	_getCookieKey : function(){
		return '$GoalCom.Vote_'+this._et+'_'+this._eid.toString();
	},
	
	highlight : function(vote){
		var i,_as=this._as;
		for (i=0;i<_as.length;i++){
			_as[i].addClass(this.options.hoverCssClass);
			if (_as[i].vote == vote){
				break;//for
			}
		}
		if (this._lbl!=null){
			this._lastLbl=this._lbl.getText();
			this._lbl.setText(vote.toString());
		}
		return this;
	},
	
	_onME : function(e){
		this.r.highlight.bind(this.r)(this.e.vote);
		this.r.fireEvent('onVoteEnter',this.e.vote);
	},
	
	_onML : function(e){
		var i,_as=this.r._as;
		for (i=0;i<_as.length;i++){
			_as[i].removeClass(this.r.options.hoverCssClass);
			if (_as[i] == this.e){
				break;//for
			}
		}
		if (this.r._lbl!=null){
			this.r._lbl.setText(this.r._lastLbl);
		}
		this.r.fireEvent('onVoteLeave',this.e.vote);
	},
	
	_onVote : function(e){
		new Event(e).preventDefault();
		if (this.r._isEnabled()){
			var _e=encodeURIComponent;
			new XHR({
				method:'get',
				headers:{'X-GOALCOM-CMD':'vote'},
				onSuccess:this.r._onVoteSuccess.bind(this.r),
				onFailure:this.r._onVoteFailure.bind(this.r)
			}).send(
				this.r.options.url,
				'et='+_e(this.r._et)+'&eid='+_e(this.r._eid)+'&v='+_e(this.e.vote.toString())
			);
		}else{
			//alert('Hai già votato!');
			this.r.fireEvent('onAlreadyVoted');
		}
	},
	
	_onVoteSuccess : function(data){
		var r1;
		try{
			r1=eval('('+data+')');
		}catch(e1){
			r1={'res':true,'vote':null};
		}
		if (r1.res){
			this._saveVote(r1.vote);
			this._updateState();
			this.fireEvent('onVote',r1.vote);
		}
	},
	
	_onVoteFailure : function(){
		alert('Ooops! An error has occured, try again later...');
		this.fireEvent('onVoteError');
	},
	
	_isEnabled : function(){
		return this._curVote == null;
	},
	
	_getVote : function(){
		var r1;
		r1 = Cookie.get(this._getCookieKey());
		if (r1 == false)
			return null;
		else
			return parseInt(r1);
	},
	
	_loadVote : function(){
		this._curVote = this._getVote();
		return this;
	},
	
	_saveVote : function(vote){
		vote=$pick(vote,this._curVote);
		this._curVote=vote;
		Cookie.set(this._getCookieKey(),vote,{duration:this.options.cookieDurationInDays});
		return this;
	},
	
	_updateState : function(){
		var _e = this._isEnabled();
		this._as.each((function(i){
			i.vote=i.getProperty('rel').substr(5);
			i.removeEvents('mouseenter');
			i.removeEvents('mouseleave');
			i.removeEvents('click');
			i.addEvent('click',this._onVote.bind({r:this,e:i}));
		}).bind(this));
		if (_e){
			this._as.each((function(i){
				i.addEvent('mouseenter',this._onME.bind({r:this,e:i}));
				i.addEvent('mouseleave',this._onML.bind({r:this,e:i}));
			}).bind(this));
		}
		if (!_e){
			this.highlight(this._curVote);
		}
		return this;
	}
});

GoalCom.UI.Rating.implement(new Options, new Events);