var PopupManager = {
	_popup:null
,	_loader_div:null
,	_base_popup_tpl : '<div id="popup" %popupParam%><div class="section">%inner_html%</div></div>'
,	_base_loading_tpl : '<div class="loading"><h4>%headline%</h4></div>'
,	_base_loaded_tpl : '<div class="loaded"><h4>%headline%</h4><p class="instructions">%instructions%</p></div>'
, 	_base_confirm_tpl : '<div class="confirm_popup">%confirm_text%</div>'
,	_get_popup_html : function(obj) {
		obj.popupParam = (obj.popupParam) ? obj.popupParam : "";
		return simpleTemplateParser.parseTemplate(this._base_popup_tpl,{	
			inner_html : obj.html
		,	popupParam : obj.popupParam
		});
	}
,	_get_loading_html : function(_headline) {
		return this._get_popup_html({	
			html : simpleTemplateParser.parseTemplate(this._base_loading_tpl,{headline : _headline})
		});
	}
,	_get_loaded_html : function(_headline,_instructions) {
		if(!_instructions)	_instructions = " ";
		return this._get_popup_html({	
			html : simpleTemplateParser.parseTemplate(this._base_loaded_tpl, { headline : _headline ,instructions : _instructions })
		});
	}
,	_create_popup:function(html) {
		if (this._popup) {
			this._popup.setContent(html);
			this._popup.showWindow();
		} else {
			this._popup = new OverlayPopupWindow({ htmlSource : html });
		}
		return this._popup;
	}
,	show_loader_div:function(args) {
		var inner_html = '';
		if (args.html) {
			inner_html = args.html;	
		} else {
			var loader_id = args.loaderId || 'loader_1f1f1f_small';
			inner_html = $(loader_id).innerHTML;
		}
		if (this._loader_div) {
			this._loader_div.setParams({
				hAlign : args.hAlign || "leftOf",
				vAlign : args.vAlign || "centerOf",
				hMargin : args.hMargin || 20,
				vMargin : args.vMargin || 0,
				snapTarget : args.snapTarget,
				useIframeShim : args.useIframeShim || false
			});
			this._loader_div.setContent(inner_html);
			this._loader_div.showWindow();
		} else {
			this._loader_div = new RelativePopupWindow({
				htmlSource : inner_html,
				hAlign : args.hAlign || "leftOf",
				vAlign : args.vAlign || "centerOf",
				hMargin : args.hMargin || 20,
				vMargin : args.vMargin || 0,
				snapTarget : args.snapTarget,
				useIframeShim : args.useIframeShim || false
			});
		}
}
,	hide_loader_div:function() {
		if (this._loader_div) this._loader_div.hideWindow();
}
,	create_popup:function(obj) {
		if(obj["template_override"]) {
			return (this._popup = this._create_popup(obj.html));
		} else { 
			return (this._popup = this._create_popup(this._get_popup_html(obj)));
		}
}

,	close_popup:function() {
		if (this._popup) this._popup.hideWindow();
}

,	create_confirm_popup:function(_str) {
		var str 	= "<center>"
				+ _str 
				+ "\n<br/>\n"
				+ '<p class="submit"><input type="button" class="cancel" value="OK" onclick="PopupManager.close_popup()"/>'
				+ '</p>'
				+ '</center>';
		this._popup = 	this.create_popup({html : str});
	}
,	loader_popup:function(headline) {
		if(headline) {
			this._popup =  this._create_popup(this._get_loading_html(headline));
		} else	{
			this._popup.hideWindow();
		}
		return this;
	}
,	hide_loader_popup:function(message,instructions) {
		if (!this._popup) {
			this._popup = this._create_popup(this._get_loaded_html(message,instructions));
		} else {
			this._popup.setContent(this._get_loaded_html(message,instructions));
			this._popup.showWindow();
		}
		var me = this;
		setTimeout(function(){ me._popup.hideWindow(); }, 2000);
	}
,   refresh_position: function() {
		if (this._popup)
			this._popup.positionWindow();
	}
,	show_message_and_hide:function(resp) {	
		PopupManager.hide_loader_popup(resp.message);
	}
,	bookmark_window:function(asset_type,id,sn) {
		var title = 'Post a Takkle Something';
		var ntwk = (sn) ? sn : 'fb';
		switch(asset_type) {
			case 'battle': 
			case 'throwdown':
				title = document.title.replace('on Takkle - High School Sports', 'Throwdown from Takkle.com');
			break;
			case 'photo':
				title = document.title.replace('on Takkle - High School Sports', '');
			break;
		}
		var link = '';
		switch(ntwk) {
			case 'fb':
				link = 'http://www.facebook.com/sharer.php?src=bm&v=4&i=1201721723&u='+encodeURIComponent('http://www.takkle.com/bookmark_it?type=' + asset_type + '&id=' + id) +'&t='+encodeURIComponent(title);
				var sn_win = window.open(link,'sharer','toolbar=0,status=0,resizable=0,width=626,height=436');
				sn_win.focus();
			break;
		}
	}
};
App = ( function() {
	//Private
	var loader = null;
	var issue_popup = null;
	var popup_html = null;
	var message_showing = '';
	var _aff = null;
	var _t = {};
	if(Cookie.get('t'))	_t = eval('('+B.d(unescape(Cookie.get('t')))+')');
	
	function _large_popup(code_div) {
		if($(code_div).innerHTML)	popup_html = $(code_div).innerHTML;
		$(code_div).innerHTML = "";
		return PopupManager.create_popup({ 
			html : popup_html
		,	template_override : true	
		});
	}
	function _report_issue(args) {
		issue_popup = _large_popup((!args || args.type == 'standard') ? 'reportWrapper' : 'issueWrapper');
		issue_popup.type = (args && args.type) ? args.type : 'standard';
		issue_popup.id = (args && args.id) ? args.id : '';
		issue_popup.error_box_id = 'validation_error';
		return issue_popup;
	}
	function _send_issue(obj) {
		API.report().issue(obj,{ onComplete : destroy } );
	}
	function _send_report(obj) {
		API.report().bug(obj,{ onComplete : destroy } );
	}
	function destroy() {
		issue_popup.hideWindow();
	}
//Public	
return {
	showMessage: function ( msg, type, el ) {
		var _styles = {	"border": "solid 1px #0c2b4a", "background": "#151515", "padding": "10px", "marginTop": "10px" };
		var html = "<p class=\"" + ( type || "error" ) + "\">" + msg + "</p>";
		if (this.message_showing) {
			for (var i = 0; i < this.message_showing.length; i++) {
				if (this.message_showing[i] == msg) return;
			}
			this.message_showing.push(msg);
		} else {
			this.message_showing = [ msg ];
		}
		var container = new Element ("div",{
			styles: _styles}).setHTML(html).injectAfter($(el));
			(function() {
				container.effect('opacity', { onComplete: function() { container.remove(); }}).start(0);
			}).delay(10000);
		var me = this;
		setTimeout(function() {
			me.message_showing.pop(msg);
		},11000);
	},
	logged_in: function(params) {
		if(!params)	params = {};
		if(Cookie.get('uli')) {
			return true;
		}
		else {
			if(!params["no_redirect"]) {
				this.redirect_to_login(params);
			}
		return false;
		}
	},
	redirect_to_login: function(params) {
		if(!params)	params = {};
		var obj = {	referrer: window.location.href,	js: (params["js"] || "") };
		Cookie.set('after_login',Json.toString(obj),{path : "/" });
		// Save the hash cookie.
		window.location = "/login";
	},
	get_aff: function() {
		if(!_aff) {
			if(Cookie.get('aff')) {
				_aff = eval('('+B.d(unescape(Cookie.get('aff')))+')');
			} else {
				_aff = {};
			}
		}
		return _aff;
	},
	get_aff_video_id: function() {
		if(_aff && _aff["fk_video_id"]) return _aff.fk_video_id;
		else return 351;
	},
	get_errors: function(el) {
		el = $(el);
		var errors = 0;
		el.getFormElements().each(	function(inp) {
			if(inp.getAttribute('required') && !inp.getValue()) {	// a requred field isn't filled out.
				inp.parentNode.getElementsByTagName('span')[0].style.display = "inline";
				errors++;
			}
		});
		return errors;
	},
	get_t: function() {
		return ( (_t) ? _t : { z : "" } );
	},
	get_user: function() {
		return eval('('+Cookie.get('user')+')');
	},
	loading: function(str) {
		if(str) PopupManager.loader_popup(str);
	},
	large_popup: function(el) {
		return _large_popup(el);
	},
	get_filter_url: function(current_url, type, value) {
		if (!value) return false;
		var final_url = current_url;
		var repl = '/' + type + '/' + value;
		switch (type) {
			case 'sport':
				if (value == 'all') repl = '';
				if (current_url.match(/\/sport\/[^/]+/)) {
					final_url = final_url.replace(/\/sport\/[^/]+/, repl);
				} else {
					final_url = final_url.replace(/\/$/,'');
					final_url += repl; 
				}
			break;
			case 'gender':
				re = new RegExp(/\/gender\/[^/]+/);
			break;
			case 'range':
				if (value == 'all') repl = '';
				if (current_url.match(/\/range\/[^/]+/)) {
					final_url = final_url.replace(/\/range\/[^/]+/, repl);
				} else if (current_url.match(/\/sport\/[^/]+/)) {
					final_url = final_url.replace(/(\/sport\/[^/]+)/,repl + '$1');
				} else {
					final_url = final_url.replace(/\/$/,'');
					final_url += repl; 
				}
			break;
		} 
		
		window.location = final_url;
	},
	send_invites: {
		emails: [],
		email_clone: null,
		invite_html: 	"<div class=\"header\"><h3>Invite your friends</h3></div>"
		+	"<form id=\"invite\" action=\"javascript:App.send_invites.parse()\">"
		+   "<div class=\"formWrapper\">"
		+	"<span id=\"invite_email_wrapper\">"
		+	"<input type=\"text\" value=\"email address\" class=\"text invite_email default\"/>"
		+	"<input type=\"text\" value=\"email address\" class=\"text invite_email default\"/>"
		+	"<input type=\"text\" value=\"email address\" class=\"text invite_email default\"/>"
		+	"</span>"
		+	"<p class=\"actions\"><a href=\"javascript:App.send_invites.add_more()\" class=\"button\" />Add more</a></p>"
		+	"<textarea id=\"custom_message\" class=\"default\">add a personalized message (optional)</textarea>"
		+	"</div>"
		+	"<p class=\"submit\">"
		+	"<input type=\"reset\" value=\"cancel\" class=\"cancel\" onclick=\"javascript:PopupManager.close_popup()\" />"
		+	"<input type=\"submit\" class=\"submit\" value=\"Send\" />"
		+   "</p>"
		+	"</form>",
		popup: null,
		add_more : function() {
			this.emails = $$("#invite .invite_email");
			var br = new Element('br');
			var new_email = this.email_clone.clone();
			new_email.injectInside($('invite_email_wrapper'));
			new_email.addEvent("focus",function(){
				if(new_email.hasClass("default")){
					new_email.value = "";
					new_email.removeClass('default');
				}
			});
		},
		form_id: "invite",
		parse: function() {
			var els = $$("#invite .invite_email");
			els = els.filter(function(item,index){
				return (item.value != "" && !item.hasClass('default'));
			});
			var emails = els.map(function(item,index){
				return item.value;	
			});
			var custom_message = $('custom_message').hasClass('default') ? "": $('custom_message').getValue();
			var obj = {emails : emails, custom_message : custom_message};
			PopupManager.close_popup();
			API.user().send_invites(obj,{ onComplete : PopupManager.show_message_and_hide });
			PopupManager.loader_popup("Sending invitations...");
		},
		show: function() {
			if(!App.logged_in({js:"App.send_invites.show()"}))	return false;
			this.popup = PopupManager.create_popup({html : this.invite_html, popupParam : 'class="form invitePopup" style="width: 360px"' });
			var els = $ES(".default",$('invite').getFormElements());
			els.each(function(el){
				el.addEvent("focus",function(){
					if(el.hasClass("default")){
						el.value = "";
						el.removeClass('default');
					}
				});
			});
			this.email_clone = $E(".default",els).clone();
		}
	},
	report_issue: {
		show: function(args) {
			if(args)	if(!App.logged_in())	return false;
			issue_popup = _report_issue(args);
		},
		close: function() {
			destroy();
			return false;
		},
		parse_form: function() {
			if (issue_popup.type == 'standard') {
				var rep = {		
					issue_type: issue_popup.type,
					bug_description: issue_popup.win.getElementsByTagName('textarea')[0].value,
					bug_suggestion: issue_popup.win.getElementsByTagName('textarea')[1].value,
					bug_url: window.location.href
				}
				_send_report(rep);	
			} else {
				if (issue_popup.win.getElementsByTagName('select')[0].value == '0') {
					var error_box = issue_popup.win.getElementById(issue_popup.error_box_id);
					error_box.innerHTML = 'Please Choose a Reason';
					error_box.className = 'error';
					return false;
				}
				var rep = {		
					issue_type: issue_popup.type,
					report_reason : issue_popup.win.getElementsByTagName('select')[0].value,
					report_description : issue_popup.win.getElementsByTagName('textarea')[0].value,
					report_id: issue_popup.id
				}
				_send_issue(rep);
			}
		}
	},
	nominate_face: {
		popup: null,
		show: function() {
			this.popup = _large_popup('siNominationPopupWrapper');
			$$('#siNominationPopup .errorMessage')
				.each(function(err) { err.style.display = "none"; });
		},
		submit: function() {
			$$('#siNominationPopup .errorMessage')
				.each(function(err) { err.style.display = "none"; });
			var obj = $('si_nominate_face_form').toObject();
			if(App.get_errors($('si_nominate_face_form')))	return;
			this.popup.hideWindow();
			API.si().nominate_face(obj,{ onComplete: PopupManager.show_message_and_hide });
			PopupManager.loader_popup("Saving nomination...");
		}
	},

	registration: {
		pop: null,
		registration_popup_tpl: '',
		popup: function() {
			this.registration_popup_tpl = this.registration_popup_tpl ? this.registration_popup_tpl : $('registrationPopupWrapper').innerHTML;
			this.pop = PopupManager.create_popup({html: this.registration_popup_tpl, popupParam : 'class="registrationPopup"'});
			if($('registrationPopupWrapper')) $('registrationPopupWrapper').remove();
			this.autoComplete();
		},
		autoComplete: function() {
			var completer = new Autocompleter.Ajax.Json(
				$('schoolName'),
				'/api/-/json/school_search',{
					postVar: 'school',
					postDataEval: "({ city : $('city').value , state : $('state').value  })",
					onRequest: this.indicatorShow,
					onComplete: this.indicatorHide,
					zIndex: 15000
				}
			);
		},
		indicatorShow: function(){
			$('schoolField').className = 'loading';
		},
		indicatorHide: function(){
			$('schoolField').className = '';
		},
		popup_close: function() {
			this.pop.hideWindow();
			window.fireEvent('doFirstRegistrationEvents');
		}
	},
	set_primary_photo: function(photo_id) {
		API.user().set_primary_photo(photo_id,{no_cache:1},{onComplete : App.set_primary_photo_resp});
		PopupManager.loader_popup("Setting primary photo...");
	},
	set_primary_photo_resp:function(resp) {
		PopupManager.hide_loader_popup(resp.message);
		window.location = "/people/-/my/profile/landing";
		return false;
	},
	show_wendys_coupon : function() {
		this.popup = PopupManager.create_popup({html : $('wendysPopupWrapper').innerHTML,template_override : 1});
		$('wendysPopupWrapper').innerHTML = "";
		$$('.errorMessage').each(function(err) { err.style.display = "none"; });
	},
	submit_wendys_coupon : function() {
		var obj = $('contestPopup').toObject();
		if(App.get_errors($('contestPopup')))	return;
		this.popup.hideWindow();
		API.contest(8).submit_wendys_coupon(obj,{ onComplete : PopupManager.show_message_and_hide });
		PopupManager.loader_popup("Saving...");
	
	},
	close_wendys_popup:function() {
		this.popup.hideWindow();
	},
	contest: {
		vote: function(param_obj) {
	    	if(!App.logged_in()) return false;
			API.contest().vote(param_obj,{onComplete:App.contest.handle_resp});
			PopupManager.loader_popup("Voting...");
		},
		handle_resp: function(resp) {
			var el_id = "video_item_" + resp.fk_video_id;
			var count = $E('.count',el_id);
			if(resp.votes)	count.setText("Votes: " + resp.votes);
			$$('.vote').each(function(el){
				$E('a',el).onclick = null;
				el.addClass("disabled");
			});
			PopupManager.show_message_and_hide(resp);
		}
	}
}
})();


window.addEvent("load",function(){
	var af = App.get_aff();
	if(af["js"])	eval(af["js"]);
	af.js = "";
	var aff_str = B.e(Json.toString(af));
	Cookie.set('aff',aff_str,{path : "/"});
	if(window.showWendysCoupon)	App.show_wendys_coupon();
});
function checkRegistration() {
}
//PROFILE FUNCTIONS
//VIDEO PAGE
CommentManager = {
	check_logged_in:function(){
		if(App.logged_in()) 
			window.location.reload();
	},
	add_comment : function(param_obj) {
	    if(!App.logged_in()) return false;
		PopupManager.loader_popup("Adding Comment");
		var comments = $(param_obj["comment_field"]).value;
		var form_obj = {};
		//VALIDATION, param_obj needs: `type`,`comments`,`fk_id`
		form_obj["type"] = param_obj["type"];
		form_obj["comments"] = comments;
		form_obj["fk_id"] = param_obj["fk_id"];
		API.comment().add_comment(form_obj,{ onComplete: CommentManager.handle_comment });
	}
,	get_comments : function(req_obj) {
		$E('.more_comments').remove();
		PopupManager.loader_popup("Getting more comments...");
		API.comment().get_comments(req_obj,{ onComplete: CommentManager.handle_comment });
	}
,	handle_comment : function(resp) {
		PopupManager.hide_loader_popup(resp.message);
		if(resp.comment != null) {
				if(resp.position == "top")
						$('comment_placeholder').innerHTML = resp.comment + $('comment_placeholder').innerHTML;
				else
						$('comment_placeholder').innerHTML = $('comment_placeholder').innerHTML + resp.comment;
		}
		if($('commentField'))	$('commentField').value = "";
		$('noComments').style.display = "none";
	}
};
var ThrowdownButtonManager = {
	pop: null
,	track_throwdown: function(throwdown_id) {
		if(!App.logged_in()) return false;
		PopupManager.loader_popup("Saving throwdown to your tracked throwdowns");
		API.user().add_throwdown(
			{throwdown_id : throwdown_id},	
			{onComplete: PopupManager.show_message_and_hide}
		);
	}
,	load_embed_popup : function(throwdown_id, chost, network_type) {
		var flashvars = 'bid=' + throwdown_id + '&h=' + chost;
		var title = 'Embed Throwdown';
		if (network_type) { 
			flashvars += '&ntwk=' + network_type;
			title = 'Share Throwdown: ' + String(network_type).capitalize();
		}
		if (typeof(Countdowntimer) != "undefined") { 
			Countdowntimer.stop();
		}
		this.pop = new DesignedOverlay({
			titleText : title,
			outerWidth : 402,
			htmlSource : '<embed allowScriptAccess="always" src="/static/swf/throwdown_embed_wrapper.swf" flashvars="' + flashvars + '" wmode="transparent" type="application/x-shockwave-flash" width="400" height="300"></embed>',
			onClose : function() {
				if (typeof(Countdowntimer) != "undefined") { 
					Countdowntimer.resume();
				}
			}
		});
	}
};

var PhotoManager = {
	pop: null
,	save_photo: function(photo_id) {
		if(!App.logged_in()) return false;
		PopupManager.loader_popup("Saving photo to gallery");
		API.user().add_photo(
			{photo_id : photo_id},	
			{onComplete: PopupManager.show_message_and_hide}
		);
	}
,	load_embed_popup : function(photo_id, user_id, chost, network_type) {
		var flashvars = 'uid=' + user_id + '&pid=' + photo_id + '&h=' + chost;
		var title = 'Embed Photo';
		if (network_type) { 
			flashvars += '&ntwk=' + network_type;
			title = 'Share Photo: ' + String(network_type).capitalize();
		}
		this.pop = new DesignedOverlay({
			titleText : title,
			outerWidth : 402,
			htmlSource : '<embed allowScriptAccess="always" src="/static/swf/photo_embed_wrapper.swf" flashvars="' + flashvars + '" wmode="transparent" type="application/x-shockwave-flash" width="400" height="300"></embed>'
		});
		
	}
};
var Top100RatingManager = {
	asset_type : '',
	asset_id : 0,
	UNDER_RATED_BAR : 'underrated_bar',
	OVER_RATED_BAR : 'overrated_bar',
	VOTE_BUTTON : 'vote_top_100',
	VIEW_RESULTS_BUTTON : 'view_results',
	MESSAGE_ID : 'vote_message',
	under_rating_val : 0,
	over_rating_val : 0,
	rate_entice : '',
	asset_state : 0,
	PIXEL_WIDTH : 180,
	FORM_NAME : 'rate_athlete_form',
	RADIO_FORM_EL : 'rateAthlete',
	CUR_STATUS : 0,

	init : function( ) {
		if (window.USER && window.USER.profile_type == 'top_100') {
			this.asset_type = 'user';
			this.asset_id = USER.id;
		}
		if (this.asset_id) {
			this.rate_entice = 'Rate it!';
			if (document.getElementById(Top100RatingManager.VOTE_BUTTON) ) {
				var me = this;
				$(Top100RatingManager.VOTE_BUTTON).addEvents( {
					'mousedown': function (event) {
						Top100RatingManager.rate_asset(event, me);
					}
				});
				$(Top100RatingManager.VIEW_RESULTS_BUTTON).addEvents( {
					'mousedown': function (event) {
						Top100RatingManager.view_results(event, me);
					}
				});


			}
		}
	},
	show_message : function(o, msg) {
		//show message
		//IMPLEMENT
		if (msg == undefined) {
			var msg = "The results represent the opinion of the TAKKLE community.";
		}
		$(Top100RatingManager.MESSAGE_ID).innerHTML = msg;
	},
	rate_asset : function(e,o) {
	    	if(!App.logged_in()) return false;
		if ( !Top100RatingManager.CUR_STATUS ) {

			Top100RatingManager.CUR_STATUS = 1;
			var rbutts = document.forms[Top100RatingManager.FORM_NAME][Top100RatingManager.RADIO_FORM_EL];
			var rating = (rbutts[0].checked === true) ? 'overrated' : 
					(rbutts[1].checked === true) ? 'underrated' : '';
		
			if (rating != 'overrated' && rating != 'underrated') {
				Top100RatingManager.CUR_STATUS = 0;
				return Top100RatingManager.show_message(o, 'Please choose a rating!');
			}
			if (o.asset_type == 'user') {	
				Top100RatingManager.show_message(o, 'Processing...');
				$(Top100RatingManager.VOTE_BUTTON).removeEvents();
				$(Top100RatingManager.VIEW_RESULTS_BUTTON).removeEvents();
				API.user(o.asset_id).rate_top_100({rating : rating }, {onComplete : function(resp) {Top100RatingManager.handle_rating(resp, o, 'vote') } } );	
			} else {	
				Top100RatingManager.CUR_STATUS = 0;
			}
		}
	},
	mark_rated : function(o) {
		var me = o;
		$(Top100RatingManager.VOTE_BUTTON).addEvents( {
			'mousedown': function (event) {
				Top100RatingManager.show_message(me, 'You can only vote once per day!');
				setTimeout(function(me) { Top100RatingManager.show_message(me); },  3000);
			}
		});
		
		Top100RatingManager.show_message(o);
	},
	view_results : function(e, o) {
		if (o.asset_id && o.asset_type == 'user') {
			Top100RatingManager.show_message(o, 'Retrieving athlete ratings...');
			$(Top100RatingManager.VIEW_RESULTS_BUTTON).removeEvents();
			API.user(o.asset_id).get_top_100_rating({ }, {onComplete : function(resp) {Top100RatingManager.handle_rating(resp, o, 'view') } } );	
		} 
		
	},
	handle_rating : function(resp, o, v_type) {
		var me = o;
		var msg = '';
		if (resp.over_rating >= 0 && resp.over_rating <= 100 && resp.asset_id == o.asset_id ) {
			var over_rating = Math.round(resp.over_rating);
			var under_rating = Math.round(resp.under_rating); 
			var old_u = parseInt( $(Top100RatingManager.UNDER_RATED_BAR).getAttribute('percent_rating') );
			var old_o = parseInt( $(Top100RatingManager.OVER_RATED_BAR).getAttribute('percent_rating') );
			$(Top100RatingManager.UNDER_RATED_BAR).setAttribute('percent_rating', under_rating);
			$(Top100RatingManager.OVER_RATED_BAR).setAttribute('percent_rating', over_rating);

			Top100RatingManager.asset_state++;
			Top100RatingManager.tween_rating(old_o, over_rating, old_u, under_rating);
			
			msg = resp.message;
		} else {
			if (v_type == 'vote') {
				msg = 'Error rating athlete! Please try again later.';
			} else {
				msg = 'Error retrieving results! Please try again later.';
			}
		}

		Top100RatingManager.show_message(me, msg);
		if (v_type == 'vote') {
			setTimeout(function(me) { Top100RatingManager.mark_rated(me); },  3000);
			Top100RatingManager.CUR_STATUS = 0;	
		} else {
			//setTimeout(function(me) { Top100RatingManager.show_message(me); },  3000);
		}
	},
	tween_rating : function(o_start, o_end, u_start, u_end) {

		if (Top100RatingManager.asset_state < 2) {
			o_start = 0;
			u_start = 0;
		}
	
		o_start = Math.round(o_start * Top100RatingManager.PIXEL_WIDTH/100);
		u_start = Math.round(u_start * Top100RatingManager.PIXEL_WIDTH/100);
		
		o_end_p = Math.round(o_end * Top100RatingManager.PIXEL_WIDTH/100);
		u_end_p = Math.round(u_end * Top100RatingManager.PIXEL_WIDTH/100);

		var myElementsEffects = new Fx.Elements($$([Top100RatingManager.OVER_RATED_BAR, 
							Top100RatingManager.UNDER_RATED_BAR, 
							Top100RatingManager.OVER_RATED_BAR + '_text', 
							Top100RatingManager.UNDER_RATED_BAR + '_text']));
		if (o_start == o_end_p) {
		}
			
		myElementsEffects.start({
			'0': { 'width': [o_start, o_end_p] },
			'1': { 'width': [u_start, u_end_p] },
			'2': { 'opacity': [ 0, 1 ] },
			'3': { 'opacity': [ 0, 1 ] }
		} );
	
		setTimeout(function() {
			$(Top100RatingManager.OVER_RATED_BAR + '_text').innerHTML = o_end + '%';
			$(Top100RatingManager.UNDER_RATED_BAR + '_text').innerHTML = u_end + '%';
		}, 300);
		
	}
};

var RatingManager = {
	starCurrentRating : 0,
	totalWidth : 74,
	starWidth : 15,
	starHeight : 19,
	asset_type : '',
	asset_id : 0,
	asset_element : '',
	asset_inner_element : '',
	asset_inner_html_element : '',
	rate_entice : '',
	asset_status : 0,

	init : function( ) {
		if (window.VIDEO) {
			this.asset_type = 'video';
			this.asset_id = VIDEO.id;
		} else if (window.PHOTO) {
			this.asset_type = 'photo';
			this.asset_id = PHOTO.id;
		}
		if (this.asset_id) {
			this.asset_status = 0;
			this.rate_entice = 'Rate it!';
			if (document.getElementById('star' + asset_id) ) {
				this.asset_element = 'star' + asset_id;
				this.asset_inner_element = 'starCurr' + asset_id;
				this.asset_inner_html_element = 'starUser' + asset_id;
				var me = this;
				$(this.asset_element).addEvents( {
					'mouseover': function (event) {
						me.asset_status = 1;
						RatingManager.star_move(event, me);
					},
					'mousemove': function (event) {
						RatingManager.star_move(event, me);
					},
					'mouseout': function (event) {
						me.asset_status = 0;
						RatingManager.star_revert(event, me);
					},
					'mousedown': function (event) {
						RatingManager.rate_asset(event, me);
					}
				});
				$(this.asset_inner_html_element).innerHTML = this.rate_entice;	
			}
		}
	},
	rate_asset : function(e,o) {
	    	if(!App.logged_in()) return false;
		if (RatingManager.starCurrentRating) {
			switch (o.asset_type) {
				case 'video' :
					API.video(o.asset_id).rate({rating : RatingManager.starCurrentRating}, {onComplete : function(resp) {RatingManager.handle_rating(resp, o) } } );
				break;
				case 'photo' :
					API.photo(o.asset_id).rate({rating : RatingManager.starCurrentRating}, {onComplete : function(resp) { RatingManager.handle_rating(resp, o) } } );
				break;
			}
			RatingManager.mark_rated(o);
		}
	},
	mark_rated : function(o) {
		$(o.asset_element).removeEvents();
	},	
	handle_rating : function(resp, o) {
		if (resp.rating >= 0 && resp.rating <= 5 && resp.asset_id == o.asset_id ) {
			var showRating = Math.round(resp.rating * RatingManager.starWidth);
			$(o.asset_inner_element).setAttribute('percent_rating', showRating);
			$(o.asset_inner_element).title = 'Current Rating: ' + resp.rating + ' of 5';
			$(o.asset_inner_element).style.width = showRating + 'px';
			var msg = (resp.message != 'thank you') ? 'already rated!' : 'thanks!';
			$(o.asset_inner_html_element).innerHTML = msg;
			setTimeout(function () { $(asset_inner_html_element).innerHTML = ''; }, 3000);
		}
	},
	star_move : function(e,o) {
		if (o.asset_status) {
			e = new Event(e).stop();
			var p=$(o.asset_element).getPosition();
			var eX=e.page.x-p.x;	
			if (eX > 0) {
				if (eX > (RatingManager.totalWidth) ) {
					eX = RatingManager.totalWidth;
				}
				$(o.asset_inner_element).style.width = Math.round(eX-(eX%RatingManager.starWidth) + RatingManager.starWidth) + 'px';
			} else {
				$(o.asset_inner_element).style.width ='0px';
			}
			RatingManager.starCurrentRating = Math.floor(eX/RatingManager.starWidth) + 1;
			if (RatingManager.starCurrentRating > 5) RatingManager.starCurrentRating = 5;
			$(o.asset_inner_html_element).innerHTML = 'Rate a ' + RatingManager.starCurrentRating + ' of 5';
		}
	},
	star_revert: function(e,o) { 
		var v=parseInt($(o.asset_inner_element).getAttribute('percent_rating'));
		$(o.asset_inner_element).style.width = v + 'px';
		$(o.asset_inner_html_element).innerHTML = o.rate_entice;
	}
};
var VideoPlayerManager = ( function () {
	//Private variables, methods:
	var win = null;
	var embedHtml = "";
	
	//public variables, methods:
	return {
		playerId:"MediaPlayer",
		player:null,
		embedId:"VideoPlayer",
		entryPoint:"_level0._app",
		is_primetime: false,
		endCardType: "STANDARD",
		uid:0,
		vid:0,
		pop:null,
        loaded: false,
		swfLoaded:function() {
			loaded = true;
			this.changeVideo(this.vid);
		},
	    init : function(uid,vid,h,autoPlay) {
			this.vid = vid;
			this.uid = uid;
			this.h = h;
			this.autoPlay = autoPlay;
			this.endCardType = 'STANDARD';
		},
		setVars : function(props) {
			for (var i in props) {
				this[i] = props[i];
			}
		},
		getPlayer : function() {
			if (this.player) return this.player;
			this.player = document.getElementById(this.embedId);
			return this.player;
		},
		changeVideo : function(video_id) {
			this.setVariable("newVideoID",video_id);
                        this.vid = video_id;
		},
		setVariable : function(path,value) {
			this.getPlayer().SetVariable(this.entryPoint+"."+path,value);
		},
		embedPlayer : function() {				
			so.addParam('align', 'middle');
			so.addParam('allowFullScreen','true');
			so.addParam('allowNetworking','all');
			so.addParam('allowScriptAccess','always');
			so.addParam('wmode','transparent');

			so.addVariable('h',this.h);
			so.addVariable('autoPlay',this.autoPlay);
			so.addVariable('uid',this.uid);
			var is_ie = (window.ActiveXObject) ? 1 : 0;
			so.addVariable('gteIE5',is_ie);
			so.addVariable('v',this.vid);
			so.write(this.playerId);
		}
	      ,	save_video : function(video_id) {
		      if(!App.logged_in()) return false;
		      PopupManager.loader_popup("Saving video to gallery");
		      API.user().add_video({video_id : video_id}
				      ,	{onComplete : PopupManager.show_message_and_hide});
	      },
		  videoEnded : function() {
		  	if (this.is_primetime && hash < 2) {
				hash++;
				el = els[hash];
		  		segment_accordion.display(hash);
				el.fireEvent("click");
				this.changeVideo(segment_data.segment_videos[hash]);
			} else {
		  		this.showEndCard();	
				s.linkTrackVars="events";
				s.linkTrackEvents="event9";
				s.events = "event9";
				s.tl(this, 'o', 'showEndCard');
			}
		  },
		  showEndCard : function() {
			this.setVariable("showEndCard",this.endCardType); 
		  },
		  clickEndCard : function() {
			s.linkTrackVars="events";
			s.linkTrackEvents="event10";
			s.events = "event10";
			s.tl(this, 'o', 'clickEndCard');
		  }
	}
} )();
recurs = function(f,scope,expr,times) {
	return ( (!times) ? scope[f](expr) : recurs(f,scope,scope[f](expr),times-1) );
}
ProfileManager = {
	nominate_si:function(user_id) {
		if(!App.logged_in())	return false;
		PopupManager.loader_popup("Sending nomination...");
		API.user(user_id).nominate_si( { onComplete:PopupManager.show_message_and_hide } );
	}	
,	validate_stats:function(user_id){
		if(!App.logged_in())	return false;
		PopupManager.show_message_and_hide({message:"Thank you for verifiying stats!"});
	}
,	add_friend:function(user_id){
		if(!App.logged_in({js:"ProfileManager.add_friend("+user_id+")"}))	return false;
		PopupManager.loader_popup("Sending friend request...");
		API.user(user_id).add_friend( { } , { onComplete:PopupManager.show_message_and_hide } );
	}
,	remove_friend:function(user_id){
		if(!App.logged_in({js:"ProfileManager.remove_friend("+user_id+")"}))	return false;
		PopupManager.loader_popup("Removing from friends list...");
		API.user(user_id).remove_friend( { } , { onComplete:(function(){window.location.reload()}) } );
	}
}
battle_select = ( this["battle_select"] || {}  ); //in this[] context js won't give you an error if its undefined
battle_select.user_opponent = function(uid) {
	if(!App.logged_in({js:"battle_select.user_opponent("+uid+")"}))	return false;
	var inp = 	"<input type='hidden' name='fk_opponent_id' value='"+uid+"' />"
	+			"<input type='hidden' name='action' value='pick_opponent' />";
	pseudoform(inp,"/throwdowns/-/my/create");
};
battle_select.join_battle = function(battle_id) {
	var inp = 	"<input type='hidden' name='fk_battle_id' value='"+battle_id+"' />"
	+			"<input type='hidden' name='action' value='join_battle' />";
	pseudoform(inp,"/throwdowns/-/my/create#chooseYourThrowdown");
}
battle_select.decline_battle = function(battle_id) {
	var inp = 	"<input type='hidden' name='fk_battle_id' value='"+battle_id+"' />"
	+			"<input type='hidden' name='action' value='decline_battle' />";
	pseudoform(inp,"/throwdowns/-/my/create");
}
message_center = {
    select_many:function(url,root) {
    var inp = "<input type='hidden' name='"+root.name+"' value='"+root.value+"' />"; 
    $$('.bulk_checkbox').each(function(el){
        if(el.checked) {
            inp = inp + "<input type='hidden' name='"+el.name+"' value='"+el.value+"' />";        
        }
    });
    pseudoform(inp,url);
    }
}
function pseudoform(html,url){
	var pseudo_form = new Element('form');
	pseudo_form.setProperty('method','POST');
	if(url)	pseudo_form.setProperty('action',url);
	pseudo_form.style.display = "none";
	pseudo_form.setHTML(html);
	pseudo_form.injectInside($E('body'));
	pseudo_form.submit();
}
var TrackingManager = {
	events:[],
	addEvent:function(evt){
		this.events.push(evt);
	},
	getEvents:function(){
		return this.events.join(",");
	}
};

function getTimestamp(utc_date) {
	// expcet '2008-05-01 14:34:27'
	var matches = utc_date.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})[^0-9]*([0-9]{2}):([0-9]{2}):([0-9]{2})/);
	if (matches.length != 7) {
		return 1219853719;	
	} else {
		var utc_date = new Date(matches[1],matches[2],matches[3],matches[4],matches[5],matches[6]);
		
	}
	return utc_date.getTime() / 1000;	
}
