function debug_log(x) {
	if(!/^(?:http:\/\/)?(?:en\.|ro\.|www\.)?intactmedia.ro/.test(document.location))
		alert(x);
}


function check_login() {
	if(Cookie.read('do_you_accept_cookies')!='yes' || (Cookie.read('an_sid') && Cookie.read('already_tested')=='yes'))
		return;
	Cookie.write('already_tested', 'yes', {duration:3, path:'/', domain:'.'+TLD});
	window.location.href = 'http://login.all-news.ro/login_check?b=' + escape(window.location.href);
}
if(/^(?:http:\/\/)?(?:en\.|ro\.|www\.)?intactmedia.ro/.test(document.location))
	try {check_login();} catch(e) {debug_log(e)}

/*function check_upload() {
	if(document.supports_required_flash && /^(?:http:\/\/)?[A-z0-9.-_]+\/upload\/?$/.test(document.location) && !Cookie.read('use_old_upload'))
		document.location = '/upload-beta';
}*/


// flowplayer callbacks (can be overwritten)
var onPause= function() {}
var onClipDone = function() {}
var onResume = function() {}
var onPlay = function(clip) {}
var onCuePoint = function(cuePoint) {}


function init_lib() {
	if(!''.trim)
		String.prototype.trim = function() {
			return this.replace(/^\s+|\s+$/, '');
		}

	Array.prototype.in_array = function(x) {
		var i;
		for(i in this)
			if(this[i] == x)
				return true;
		return false;
	}

	Array.prototype.get_index = function(x) {
		var i;
		for(i in this)
			if(this[i] == x)
				return i;
		return -1;
	}

	Array.prototype.remove_item = function(x) {
		var i;
		for(i in this)
			if(this[i] == x) {
				this.splice(i, 1);
				return true;
			}
		return false;
	}

	String.prototype.str2hex = function() { // only for ASCII (no unicode)
		var i, tmp = '', sym = '0123456789abcdef';
		for(i=0; i < this.length; i++)
			tmp += sym.charAt((this.charCodeAt(i) >> 4) & 0xF) + sym.charAt(this.charCodeAt(i) & 0xF);
		return tmp;
	}

	String.prototype.hex2str = function() { // only for ASCII (no unicode)
		var i, tmp = '', sym = '0123456789abcdef';
		var len = (this.length | 1) ^ 1; // this way it will be even (this.length[bit0]=0)
		for(i = 0; i < len; i+=2)
			tmp += String.fromCharCode(((sym.indexOf(this.charAt(i)) & 0xF) << 4) | (sym.indexOf(this.charAt(i+1)) & 0xF));
		return tmp;
	}
}


function print_r(o, ret, level) {
	try {
	var s = "{\n", i;
	if(!level || level < 1)
		level = 1;
	if(level > 20)
		return '';
	for(i in o) {
		s += (new Array(level+1)).join('    ') + '[' + i + '] => ';
		switch(typeof(o[i])) {
			case 'object':
				s += print_r(o[i], ret, level + 1); break;
			case 'string':
				s += '"' + o[i].replace(/"/g, "\\\"") + "\"\n"; break;
			case 'function':
				s += "function()\n"; break;
			default:
				s += o[i] + "\n";
		}
	}
	s += (new Array(level)).join('    ') + "}\n";
	if(!ret && level == 1)
		debug_log(s);
	return s;
	} catch(e) {debug_log('print_r: '+e);}
}
//print_r({a:1, b:2, c:3, d:{x:1, y:2, z:{t:7, u:8, v:9}}, e:10});


function tooltip_show(s, e, t) {
	if(!document.x_tooltip) {
		document.x_tooltip = {
			id: null,
			fx: null,
			setHTML: function(s) {
				document.x_tooltip.id.innerHTML = '<span class="x1">' + s + '</span>';
			},
			init: function() {
				document.x_tooltip.id = new Element('div', {'class':'xtooltip', 'style':'position:fixed;opacity:0;'});
				document.x_tooltip.id.inject($('container'), 'before');
				document.x_tooltip.fx = new Fx.Morph(document.x_tooltip.id, {duration: 300, transition: Fx.Transitions.Sine.easeOut});
			}
		};
		document.x_tooltip.init();
		document.x_tooltip.id.addEvent('mouseover', function() {
			try {clearTimeout(document.x_tooltip.oThread);} catch(e) {}
		});
		document.x_tooltip.id.addEvent('mouseout', function() {
			try {clearTimeout(document.x_tooltip.oThread);} catch(e) {}
			document.x_tooltip.oThread = setTimeout(function() {
				document.x_tooltip.fx.start({'opacity':0});
			}, t ? t : 1000);
		});
	}
	try {clearTimeout(document.x_tooltip.oThread);} catch(e) {}
	document.x_tooltip.id.setStyles({'opacity':0});
	document.x_tooltip.setHTML(s);
	if(e) {
		document.x_tooltip.id.style.position = 'absolute';
		document.x_tooltip.id.style.top = (e.page.y + 20) + 'px';
		document.x_tooltip.id.style.left = (e.page.x - 10) + 'px';
	} else {
		document.x_tooltip.id.style.position = 'fixed';
	}
	document.x_tooltip.fx.start({'opacity':0.8});
	document.x_tooltip.oThread = setTimeout(function() {
		document.x_tooltip.fx.start({'opacity':0});
	}, t ? t : 3000);
}


function update_embed(uu) { // uu = ui update
	var ebox = $('embed_code_text');
	var cfg = {};
	var tmp = ebox.value.match(/[?&]c=([^&'"]*)/)[1];
	tmp.match(/([^:$]+:[^$]*)/g).each(function(x) {
		var tmp = x.match(/^([^:]+):(.*)$/);
		if(tmp)
			cfg[tmp[1]] = tmp[2];
	});
	$$('#embed input[name="embed_wh"]').each(function(x) {
		try {
		if(uu) {
			if(x.value == (cfg.w+'x'+cfg.h)) {
				x.checked = 'checked';
				return;
			}
		} else {
			if(x.checked) {
				var tmp = x.value.split('x');
				cfg.w = tmp[0];
				cfg.h = tmp[1];
				return;
			}
		}
		} catch(e) {debug_log(e)}
	});

	$$('#embed input[name="embed_cb"]').each(function(x) {
		try {
		if(uu) {
			if(x.value == (cfg.c+'x'+cfg.b)) {
				x.checked = 'checked';
				return;
			}
		} else {
			if(x.checked) {
				var tmp = x.value.split('x');
				cfg.c = tmp[0];
				cfg.b = tmp[1];
				return;
			}
		}
		x.getParent('label').removeEvent('click').addEvent('click', function() { // this is an IE workaround
			x.checked = true;
		});
		} catch(e) {debug_log(e)}
	});

	var tmp = $$('#embed input[name="embed_a"]')[0];
	if(uu) {
		tmp.checked = (cfg.a == '1');
	} else {
		cfg.a = (tmp.checked) ? '1' : '0';
	}

	var tmp = $$('#embed input[name="embed_f"]')[0];
	if(uu) {
		tmp.checked = (cfg.f == '0');
	} else {
		cfg.f = (tmp.checked) ? '0' : '1';
	}

	if(!uu) {
		var i;
		tmp = [];
		for(i in cfg)
			tmp.push(i + ':' + cfg[i]);
		tmp = tmp.join('$');
		ebox.value = ebox.value.replace(/[?&]c=[^&'"]*/, ebox.value.match(/([?&]c=)/)[1] + tmp); // js regexp doesn't support lookbehind
		ebox.value = ebox.value.replace(/width\s*=\s*"[0-9]+"/, 'width="' + cfg.w + '"');
		ebox.value = ebox.value.replace(/height\s*=\s*"[0-9]+"/, 'height="' + cfg.h + '"');
		$$('#embed .pw a')[0].href = '/ajax/embed?c=' + tmp + '&pw';
	}
	//print_r(cfg);
}


function init_embed() {
	var ebox = $('embed_code_text');
	if(!ebox)
		return;

	tmp = $$('#embed ul.more')[0];
	if(!tmp.fx_slider) {
		tmp.fx_slider = new Fx.Slide(tmp, {
			onComplete: function() {
				//if(tmp.fx_slider.wrapper['offset' + tmp.fx_slider.layout.capitalize()])
				if(tmp.fx_slider.open)
					$('embed').addClass('vmore');
				else
					$('embed').removeClass('vmore');
			}
		});
		tmp.fx_slider.hide();
	}

	$$('#embed input[type="text"]').each(function(x) {
		x.addEvent('click', function() {
			try {x.focus();} catch(e) {}
			try {x.select();} catch(e) {}
			if(x.id=='embed_code_text')
				$$('#embed ul.more')[0].fx_slider.slideIn();
		});
	});


	try {update_embed(true);} catch(e) {debug_log(e)}
	try {update_embed();} catch(e) {debug_log(e)}
	$$('#embed ul.more')[0].removeEvent('click').addEvent('click', function() {
		update_embed();
	});

	$$('#embed a.togglemore')[0].removeEvent('click').addEvent('click', function(e) {
		(new Event(e)).stop();
		try {this.blur()} catch(e) {}
		$$('#embed ul.more')[0].fx_slider.toggle();
	});

}


function reload_captcha(t) {
	try {
		$('captcha_image').src = '/images/captcha.jpg?rnd=' + escape(Math.random());
		if(t)
			t.blur();
	} catch(e) {debug_log(e)}
	return false;
}


function reactivate(uid) {
	try {
	var loading = $$('#topheader p.center')[0];
	loading.style.display = 'block';
	var captcha = $$('#topheader input[name=captcha]')[0]
	new Request.JSON({
		url: '/ajax/reactivate',
		onComplete: function(jsonObj, text) {
			try {
				loading.style.display = 'none';
				if(!jsonObj) {
					debug_log(text);
					return;
				}
				if(!jsonObj.error)
					$('topheader').style.display = 'none';
				else {
					$('topheader_captcha').src = '/images/captcha.jpg?rnd=' + escape(Math.random());
					captcha.value = '';
					captcha.focus();
				}
				alert(jsonObj.response);
			} catch(e) {debug_log("reactivate: " + e)}
		}
	}).post({'uid':uid, 'captcha':captcha.value});
	} catch(e) {debug_log(e)}
}


function delete_video(id, q) {
	try {
	if(q && !confirm(q))
		return false;
	new Request({
		method: 'post',
		url: '/ajax/admin_video/?action=delete',
		onSuccess: function(r) {
			try {
			if(r)
				alert(r);
			else	{
				if((m = window.location.href.match(/^(?:http\:\/\/)?[A-z0-9.-_]+(\/user|\/useraudio)\/[0-9]+\/?(?:#.*)?$/)) && m.length>1)
					window.location.href = m[1];
				else
					window.location.reload();
			}
			} catch(e) {debug_log(e)}
		},
		oFailure: function() {
			alert('Error');
		}
	//}).send('id=' + escape(id) + '&uid=' + escape(Cookie.read('uid')) + '&sid=' + escape(Cookie.read('sid')));
	}).post({'id':id, 'sid':Cookie.read('an_sid')});
	} catch(e) {debug_log(e)}
	return false;
}


function edit_video(id) {
	try {
	var title = $$('#edit_video [name="title"]')[0].value;
	var description = $$('#edit_video [name="description"]')[0].value;
	var keywords = $$('#edit_video [name="keywords"]')[0].value;
	var section = $$('#edit_video [name="section"]')[0].value;
	var frame = '';
	if($('sel_pw_1').checked) frame = 'a';
	else if($('sel_pw_2').checked) frame = 'b';
	else if($('sel_pw_3').checked) frame = 'c';
	//alert(frame); return;
	new Request({
		url: '/ajax/admin_video/?action=edit',
		method: 'post',
		encoding: 'utf-8',
		onSuccess: function(rh) {
			if(rh)
				alert(rh);
			else
				window.location = '/user';
		},
		oFailure: function() {
			alert('Error');
		}
	}).post({'id':id, 'sid':Cookie.read('an_sid'), 'section':section, 'title':title, 'description':description, 'keywords':keywords, 'frame':frame});
	} catch(e) {debug_log(e)}
}


function add_rating(cfg) { // a little more reusable
	// cfg = {id,grade,onclick[,hsprite,dsprite,starselector]}
	// cfg.onclick = function(vote, event)
	// cfg.dsprite={x:0, y:0}, cfg.hsprite = {x:0, y:0}, cfg.starselector='.n' -> default values

	var id = $(cfg.id);
	var grade = cfg.grade.toString().replace(/[^0-9\.]+/g, '');
	var hsprite = cfg.hsprite ? cfg.hsprite : {x:0, y:-30}; // hover sprite offset
	var dsprite = cfg.dsprite ? cfg.dsprite : {x:0, y:0}; // default sprite offset

	var stars = (id && id.getElements) ? id.getElements(cfg.starselector ? cfg.starselector : '.n') : [];
	if(stars.length != 5) {
		debug_log('add_rating');
		return;
	}
	var size = stars[0].getSize();

	var scroll_to = function(x, y) {
		x = (x!=0) ? x+'px' : '0';
		y = (y!=0) ? y+'px' : '0';
		id.setStyle('background-position', x + ' ' + y);
	};
	var set_grade = function(grade, hover) {
		var grade2 = parseInt(Math.round(grade*2).toString());
		hover = (hover) ? hsprite.y : dsprite.y;
		if(grade2&1)
			scroll_to(dsprite.x + size.x*((grade2>>1) - 4), hover - size.y);
		else
			scroll_to(dsprite.x + size.x*((grade2>>1) - 5), hover);
	};

	set_grade(grade);
	var oThread = null;
	stars.each(function(x, i) {
		x.removeEvents('mouseover');
		x.removeEvents('mouseout');
		x.removeEvents('click');
		x.addEvents({
			'mouseover': function() {
				try {clearTimeout(oThread);} catch(e) {}
				set_grade(i+1, true);
			},
			'mouseout': function() {
				try {clearTimeout(oThread);} catch(e) {}
				oThread = setTimeout(function() {
					set_grade(grade);
				}, 500);
			},
			'click': function(e) {
				try {
					//set_grade(grade);
					clearTimeout(oThread);
				} catch(e) {}
				cfg.onclick(i+1, e);
			}
		});
		x.title = MSG.js_script_grade_desc[i];
	});
}


function init_rating() {
	// r_grade.innerHTML: {grade x.xx}, r_grade.title: sid_{video id}
	var grade = $('r_grade');
	if(!grade)
		return;
	var sid = grade.title.replace(/[^0-9]+/g, '');

	add_rating({
		id: $$('.rating')[0],
		grade: grade.innerHTML,
		onclick: function(vote, e) {
			(new Event(e)).stop();
			if(!sid)
				return;
			document.xloader_show(e);
			var event = e; // IE workaround (this browser should be banned)
			new Request.JSON({
				url: '/ajax/vote',
				onComplete: function(jsonObj) {
					try {
						if(jsonObj && jsonObj.votes > -1 && jsonObj.grade > -1 && jsonObj.views > -1) {
							$('r_votes').innerHTML = jsonObj.votes;
							$('r_grade').innerHTML = jsonObj.grade;
							$('r_views').innerHTML = jsonObj.views;
							init_rating();
						}
						document.xloader_hide();
						if(jsonObj.response)
							tooltip_show(jsonObj.response, event);
					} catch(e) {debug_log(e)}
				},
				onFailure: function() {
					tooltip_show('Sorry, could not connect, please check your network connection.');
					document.xloader_hide();
				}
			}).post({'xsrf':Cookie.read('an_sid'), 'sid':sid, 'vote':vote});
		}
	});

	if(!$$('.pl_rr').length)
		return;

	var xrating = $$('.pl_rr')[0].title;
	if(xrating=='-1') {
		// -1 disables xrating (for mp3's)
		$$('.pl_rr')[0].style.display = 'none';
		return;
	}
	$$('.pl_rr')[0].style.display = 'block';
	$$('.pl_rr a').each(function(x, i) {
		//try{(i==xrating ? x.addClass : x.removeClass)('sel');}catch(e) {debug_log('init_rating3: '+e)}
		x.className = (i==xrating) ? 'sel' : '';
		x.removeEvents('click');
		x.addEvent('click', function(e) {
			(new Event(e)).stop();
			if(!sid)
				return;
			document.xloader_show(e);
			var event = e;
			new Request.JSON({
				url: '/ajax/vote?t=xr',
				onComplete: function(jsonObj) {
					try {
						document.xloader_hide();
						if(jsonObj && jsonObj.xrating > -1) {
							$$('.pl_rr')[0].title = jsonObj.xrating;
							setTimeout(function() {
								init_rating();
							}, 200);
						}
						if(jsonObj.response)
							tooltip_show(jsonObj.response, event);
					} catch(e) {debug_log(e)}
				},
				onFailure: function() {
					tooltip_show('Sorry, could not connect, please check your network connection.', event);
					document.xloader_hide();
				}
			}).post({'xsrf':Cookie.read('an_sid'), 'sid':sid, 'vote':i});
		});
	});
}


function init_login() {
	var x = $('login');
	if(!x)
		return;
	x.set('morph', {duration: 1000, transition: 'expo:out'});

	if($$('#login .loginfail').length) {
		x.setOpacity(1);
	} else {
		x.setOpacity(0);
		x.morph({'opacity':0}); // instead of display:none
	}

	x.makeDraggable({
		handle: x.getChildren('.header_r')[0]
	});

	var myEffects = new Fx.Morph(x, {duration: 500, transition: Fx.Transitions.Sine.easeOut});
	var login_show = function(pos) { // private functions inside init_login function/object or w/e
		//alert(pos.x + ' ' + pos.y)
		if(pos)
			myEffects.start({'top':pos.y, 'left':pos.x+50});
		x.morph({'opacity':1});
		setTimeout(function() {
			try {x.getElement('input').focus();} catch(e) {debug_log(e)}
		}, 200);
	}
	var login_hide = function() {
		x.morph({'opacity':0});
	}

	$$('a[name=login_lnk]').each(function(y) {
		y.addEvent('click', function(e) {
			try {
			(new Event(e)).stop();
			y.blur();
			(x.getOpacity()<0.5 ? login_show : login_hide)(y.getPosition()); // lol this works
			} catch(e) {debug_log(e)}
			return false;
		});
	});


	$$('#login .header_r .xr_')[0].addEvent('click', function() {
		x.morph({'opacity':0});
		return false;
	});

	x.getChildren('.header_r').addEvent('mousedown', function() {
		x.morph({'opacity':.7});
	}).addEvent('mouseup', function() {
		x.morph({'opacity':1});
	});

	if(/#userlogin$/.test(document.location))
		login_show();
}

function init_login2() {
	if(!$('authrequired'))
		return;
	setTimeout(function() {
		$$('#authrequired form input[type="text"]')[0].focus();
	}, 300);
}


function init_sort() { // OBSOLETE
	var x = $$('#topmenu .order select')[0];
	if(!x)
		return;
	x.addEvent('change', function() {
	try {
		var c;
		if(/^(?:http:\/\/)?[A-z0-9.-]+\/audio\/?/.test(window.location.href)) {
			try {c = window.location.href.match(/^(http\:\/\/)?[A-Za-z0-9\.\-]+\/audio\/([A-Za-z0-9\-]+)\//)[2] + "/";} catch(e) {c="";}
			window.location.href = "/audio/" + c + "?sort=" + escape(x.options[x.selectedIndex].value);
		} else {
			try {c = window.location.href.match(/^(http\:\/\/)?[A-Za-z0-9\.\-]+\/video\/([A-Za-z0-9\-]+)\//)[2] + "/";} catch(e) {c="";}
			window.location.href = "/video/" + c + "?sort=" + escape(x.options[x.selectedIndex].value);
		}
	} catch(e) {debug_log(e)}
	});
}


function init_search() {
	try {
		$$('#search input[type=submit]')[0].addEvents({
			'mouseover': function() {
				$('search').addClass('search_hover');
			},
			'mouseout': function() {
				$('search').removeClass('search_hover');
			}
		});
	} catch(e) {debug_log(e)}
	var m = $$('#search input[name="q"]')[0];
	try {
		var q = unescape(document.location.href.match(/(?:\&|\?)q\=([^&]+)(?:\&[A-z0-9=+-\/]*)*$/)[1].replace(/\+/g, '%20'));
		if(q) {
			m.value = q;
			return;
		}
	} catch(e) {}
	m.addEvent('focus', function() {
		if(m.value == m.title && !m.has_been_cleared)
			m.value = '';
		m.has_been_cleared = true;
	});
	/*var form = $('search');
	form.addEvent('mouseover', function() {form.is_mouseover = true;});
	form.addEvent('mouseout', function() {form.is_mouseover = false;});
	document.body.addEvent('click', function() {
		//alert(form.is_mouseover);
	});*/
}


function init_rmenu() {
	m = $('rmenu');
	if(!m)
		return;
	m.set('morph', {duration: 500, transition: 'expo:out'});
	m.setStyle('opacity', 0);
	document.r_menu = {oTimeout:null, show:function() {
		if(document.r_menu.oTimeout) {
			try{clearTimeout(document.r_menu.oTimeout);} catch(e) {}
			document.r_menu.oTimeout = null;
		}
		//m.setStyle('opacity', 0);
		m.style.display = 'block';
		m.morph({'opacity':0.93});
		$('more_button').setStyle('background', 'url(/images/more_h.png)');
	}, hide:function() {
		if(document.r_menu.oTimeout) {
			try{clearTimeout(document.r_menu.oTimeout);} catch(e) {}
			document.r_menu.oTimeout = null;
		}
		m.morph({'opacity':0});
		$('more_button').setStyle('background', 'url(/images/more.png)');
	}};

	$('more_button').addEvent('mouseover', function() {
		document.r_menu.show();
	});
	$('more_button').addEvent('mouseout', function() {
		try{clearTimeout(document.r_menu.oTimeout); document.r_menu.oTimeout = null;} catch(e) {}
		document.r_menu.oTimeout = setTimeout(document.r_menu.hide, 500);
	});

	m.addEvent('mouseover', function() {
		if(document.r_menu.oTimeout) {
			try{clearTimeout(document.r_menu.oTimeout); document.r_menu.oTimeout = null; return;} catch(e) {}
		}
	});

	m.addEvent('mouseout', function() {
		document.r_menu.oTimeout = setTimeout(document.r_menu.hide, 500);
	});
}


function init_tab_buttons() {
	var buttons = $$('#tab_buttons ul li a');
	var content = $$("#tab_content .tab_content");
	if(!buttons || buttons.length < 1 || !content || content.length < 1)
		return;
	buttons.each(function(x, idx) {
		x = $(x);
		var clk = function() {
			try {
			for(i=0; i < buttons.length; i++)
				buttons[i].className = (i==idx) ? 'selected' : '';
			for(i=0; i < content.length; i++)
				content[i].style.display = (i==idx) ? 'block' : 'none';
			} catch(e) {}
		}
		x.addEvent('click', function(e) {
			(new Event(e)).stop();
			clk();
			return false;
		});
		if(idx == 1 && /#comments$/.test(document.location.href))
			clk();
	});
	//buttons[0].className = 'selected';
	//content[0].style.display = 'block';
}


function video_scroll() {
	return;
	var scroll = new Fx.Scroll(window, { wait: false, duration: 700, transition: Fx.Transitions.Quad.easeInOut });
	scroll.toElement('topmenu');
}


/*function play_audio(player, url) {
	var request = new Request.JSON({ // &ajax[]=main.center_menu
		url: '/audio/-/' + url + '/?ajax[]=main.center_tab.videos&ajax[]=main.center_tab.comments&ajax[]=main.center_tab.comments_button&ajax[]=r_views&ajax[]=r_grade&ajax[]=r_votes&ajax[]=r_id&ajax[]=r_hash&ajax[]=url&ajax[]=embed&ajax[]=r_cover&ajax[]=r_name&ajax[]=r_description&ajax[]=r_user&ajax[]=r_date&ajax[]=r_xrating',
		onComplete: function(jsonObj) {
			try {
				try {
						//player.playClip(
						//{
						//	name: 'Playing...',
						//	url: FILESURL + '/audio/' + jsonObj['r_hash'] + '.mp3',
						//	overlay: jsonObj['r_cover']
						//});
				} catch(e) {debug_log("ajaxplay: " + e)}
				//$$("#tab_content .tab_content")[0].empty(); $$("#tab_content .tab_content")[0].innerHTML = jsonObj['main.center_tab.videos'].replace(/^\<div[^\>]*\>|\<\/div\>$/g, '');
				try {
					$('r_name').innerHTML = jsonObj['r_name'];
					$$('.player_right .content span.name')[0].innerHTML = jsonObj['r_name'];
				} catch(e) {debug_log("x1a: " + e)}
				try {$('r_description').innerHTML = jsonObj['r_description'];} catch(e) {debug_log("x1b: " + e)}
				try {$('r_user').href = '/audio/?u=' + ($('r_user').innerHTML = jsonObj['r_user']);} catch(e) {debug_log("x1c: " + e)}
				try {$('r_date').innerHTML = jsonObj['r_date'];} catch(e) {debug_log("x1d: " + e)}
				try {$('comment').empty(); $('comment').innerHTML = jsonObj['main.center_tab.comments'].replace(/^(\<div[^\>]*\>\s*){2}|(\<\/div\>\s*){2}$/g, '');} catch(e) {debug_log("x2: " + e)}
				try {init_comment();} catch(e) {debug_log(e)}
				try {
					var tmp = null;
					tmp = $$('#tab_buttons span');
					tmp = tmp[1] ? tmp[1] : tmp[0];
					tmp.empty();
					tmp.innerHTML = jsonObj['main.center_tab.comments_button'].match(/\<span\>([^\<\>]+)\<\/span\>/)[1];
				} catch(e) {debug_log("x3: " + e)}
				try {
					$('r_grade').innerHTML = jsonObj['r_grade'];
					$('r_grade').set('title', 'sid_' + jsonObj['r_id']);
					$('r_votes').innerHTML = jsonObj['r_votes'];
					$('r_views').innerHTML = jsonObj['r_views'];
					$$('.pl_rr')[0].title = jsonObj['r_xrating'];
					init_rating();
				} catch(e) {debug_log("x4: " + e)}
				try {
					$$('#embed input[type="text"]')[0].value = jsonObj['url'];
					$$('#embed input[type="text"]')[1].value = jsonObj['embed'];
					update_embed();
				} catch(e) {debug_log("x5: " + e)}

				document.title = TITLE + ' - ' + $('r_name').innerHTML;
			} catch(e) {debug_log(e)}
		}
	}).send();
}*/


//function fp_play2(url, start) { //alert(start)
function fp_play2(id, ftype, start) {
	//alert('id:'+id+' ftype:'+ftype+' start:'+start); return;
	var player = $('myFlashContent');

	//if(start) {
	//	return;
	//}

	if(!ftype)
		fype = 'media';

	//try {player.DoStop();} catch(e) {debug_log(e)}

	//if(/^(?:http:\/\/)?[A-z0-9.-]+\/audio/.test(document.location))
	//	return play_audio(player, url);

	try {
	var url = document.location.href.match(/^(?:http:\/\/)?([^\/]+\/playlist\/:[0-9]+:[0-9a-f]{32,40}\/play-[0-9]+\/?(?:\?.*)?)(?:#.*)?$/);
	if(url && url.length == 2)
		url = 'http://' + url[1].replace(/\/play-[0-9]+/, '/play-' + id);
	else if((url = document.location.href.match(/^(?:http:\/\/)?([^\/]+\/(?:video|audio|media)\/[a-z0-9-]+\/[0-9]+\/?(?:\?.*)?)(?:#.*)?$/)) && url.length==2) {
		url = 'http://' + url[1].replace(/\/(video|audio|media)\/[a-z0-9-]+\/[0-9]+/, '/$1/-/'+id);
	} else {
		url = '/media/-/' + id + '/';
	}
	//alert(url); return;
	} catch(e) {debug_log(e);return;}

	var request = new Request.JSON({ // &ajax[]=main.center_menu
		//url: '/' + ftype + '/-/' + id + '/?ajax[]=main.center_tab.videos&ajax[]=main.center_menu&ajax[]=main.center_tab.comments&ajax[]=main.center_tab.comments_button&ajax[]=main.player.playernav&ajax[]=r_views&ajax[]=r_grade&ajax[]=r_votes&ajax[]=r_id&ajax[]=r_hash&ajax[]=r_type&ajax[]=r_cover&ajax[]=url&ajax[]=embed',
		url: url + '?ajax[]=main.center_tab.videos&ajax[]=main.center_tab.comments&ajax[]=main.center_tab.comments_button&ajax[]=main.player.playernav&ajax[]=r_views&ajax[]=r_grade&ajax[]=r_votes&ajax[]=r_id&ajax[]=r_hash&ajax[]=r_type&ajax[]=r_cover&ajax[]=url&ajax[]=embed&ajax[]=r_name&ajax[]=r_description&ajax[]=r_user&ajax[]=r_date&ajax[]=r_xrating&ajax[]=warn18&ajax[]=config&ajax[]=id',
		onComplete: function(jsonObj) {
			try {
				try {
					if(jsonObj.redir) {
						document.location = jsonObj.redir;
						return;
					}
					
					jsonObj.config.playlist.each(function(x, i) {
						if(x.url.match(/(?:audio|video)(?:\/[a-f0-9]{2}){4}\/[a-f0-9]+\.(?:mp3|flv)(?:\?.*)?$/)) {
							jsonObj.config.playlist[i].onPause = function() {
								onPause({id:jsonObj.id});
							}
							jsonObj.config.playlist[i].onResume = function() {
								onResume({id:jsonObj.id});
							}
							jsonObj.config.playlist[i].onFinish = function() {
								onClipDone({id:jsonObj.id});
							}
							nowpl = jsonObj.id;
						}
					});
					/*if(jsonObj['r_type'] == 'flv') {
						player.playClip({
							name: 'Playing...',
							url: FILESURL + '/video/' + jsonObj['r_hash'] + '.flv'
						});
						document.fp_now_playing2.ext = 'flv';
						document.fp_now_playing2.id = id;
					} else if(jsonObj['r_type'] == 'mp3') {
						player.playClip({
							name: 'Playing...',
							url: FILESURL + '/audio/' + jsonObj['r_hash'] + '.mp3',
							overlay: jsonObj['r_cover']
						});
						document.fp_now_playing2.ext = 'mp3';
						document.fp_now_playing2.id = id;*/
					//var warn18 = false;
					//if(jsonObj["warn18"]) {
					//	warn18 = jsonObj['warn18'].replace(/^[, ]|[, ]$/g, '');
					//	eval('warn18 = ' + warn18);
					//}

					if(jsonObj['r_type']=='flv') {
						jsonObj.section_link = '/video/';
						//player.setConfig({showMenu:false, showVolumeSlider:true, controlsOverVideo:"ease", controlBarBackgroundColor:0x555555, timeDisplayFontColor:0xffbbbb, controlBarGloss:"low", autoBuffering:false, initialScale:"fit", usePlayOverlay:true, loop:false, autoPlay:true, autoRewind:true, playList:[warn18 ? warn18 : {url:FILESURL+"/video/shot/b/"+jsonObj['r_hash']+".jpg", overlayId:"play"}, {url:FILESURL+"/video/"+jsonObj['r_hash']+".flv"}]});
					} else if(jsonObj['r_type']=='mp3') {
						jsonObj.section_link = '/audio/';
						//player.setConfig({showMenu:false, showVolumeSlider:true, controlsOverVideo:"ease", controlBarBackgroundColor:0x555555, timeDisplayFontColor:0xffbbbb, controlBarGloss:"low", autoBuffering:false, initialScale:"fit", usePlayOverlay:true, loop:false, autoPlay:true, autoRewind:true, playList:[{url:FILESURL+"/audio/"+jsonObj['r_hash']+"-"+id+".jpg", overlayId:"play"}, {url:FILESURL+"/audio/"+jsonObj['r_hash']+".mp3"}]});
					} else {
						debug_log('unknown type: ' + jsonObj['r_type']); // this happens in playlist mode (if the file is not in the playlist)
						//document.location = '/media/-/' + id + '/';
						return;
					}
					$f('mainplayer', '/script/flowplayer-3.1.1.swf?v='+MSG.lastupdate, jsonObj.config).load();
				} catch(e) {debug_log("ajaxplay: " + e)}
				//$$("#tab_content .tab_content")[0].empty(); $$("#tab_content .tab_content")[0].innerHTML = jsonObj['main.center_tab.videos'].replace(/^\<div[^\>]*\>|\<\/div\>$/g, '');
				try {
					$('r_name').innerHTML = jsonObj['r_name'];
					$$('.player_right .content span.name')[0].innerHTML = jsonObj['r_name'];
				} catch(e) {debug_log("x1a: " + e)}
				try {$('r_description').innerHTML = jsonObj['r_description'];} catch(e) {debug_log("x1b: " + e)}
				try {$('r_user').href = jsonObj.section_link + '?u=' + ($('r_user').innerHTML = jsonObj['r_user']);} catch(e) {debug_log("x1c: " + e)}
				try {$('r_date').innerHTML = jsonObj['r_date'];} catch(e) {debug_log("x1d: " + e)}
				try {$('comment').empty(); $('comment').innerHTML = jsonObj['main.center_tab.comments'].replace(/^(\<div[^\>]*\>\s*){2}|(\<\/div\>\s*){2}$/g, '');} catch(e) {debug_log("x2: " + e)}
				try {init_comment();} catch(e) {debug_log(e)}
				try {
					var tmp = null;
					tmp = $$('#tab_buttons span');
					tmp = tmp[1] ? tmp[1] : tmp[0];
					tmp.empty();
					tmp.innerHTML = jsonObj['main.center_tab.comments_button'].match(/\<span\>([^\<\>]+)\<\/span\>/)[1];
				} catch(e) {debug_log("x3: " + e)}
				try {
					$('r_grade').innerHTML = jsonObj['r_grade'];
					$('r_grade').set('title', 'sid_' + jsonObj['r_id']);
					$('r_votes').innerHTML = jsonObj['r_votes'];
					$('r_views').innerHTML = jsonObj['r_views'];
					$$('.pl_rr')[0].title = jsonObj['r_xrating'];
					init_rating();
				} catch(e) {debug_log("x4: " + e)}
				try {
					$$('#embed input[type="text"]')[0].value = jsonObj['url'];
					$$('#embed input[type="text"]')[1].value = jsonObj['embed'];
					update_embed();
				} catch(e) {debug_log("x5: " + e)}
				try {
					if($$('div.playernav')[0]) {
						$$('div.playernav a[name=pl_nav]').each(function(x, idx) {
							x.removeEvents();
						});
						$$('div.playernav')[0].innerHTML = jsonObj['main.player.playernav'].replace(/^\s*\<div[^>]*\>|\<\/div\>\s*$/, '');
						init_preview3();
					}
				} catch(e) {debug_log("x6: " + e)}

				document.title = TITLE + ' - ' + $('r_name').innerHTML;
				//document.location = '#' + (document.fp_now_playing2.ext=='flv' ? 'video' : 'audio') + '/-/' + document.fp_now_playing2.id;
				document.location = '#media/-/' + jsonObj.id;
			} catch(e) {debug_log(e)}
		}
	}).send();

	//alert($$('div.tab_content_item a').length)

	/*$$('div.tab_content_item a').each(function(x, i) {
		fp_addpw(x, x.getChildren('img')[0]);
		x.getChildren('img')[0].src = 'http://all-news.ro/files/video/shot/a/6192-1.jpg';
	});*/
}


/*function fp_play(url, start) { // OBSOLETE
	var player = $('myFlashContent');

	if(start) {
		return;
		//$('myFlashContent').setConfig({//showPlayButton:false,showScrubber:false,showMuteVolumeButton:false,
		//	showMenu:false, showVolumeSlider:true, controlsOverVideo:'ease', controlBarBackgroundColor:0x555555, timeDisplayFontColor:0xffbbbb, controlBarGloss:'low', autoRewind:false, autoBuffering:false, initialScale:'scale', usePlayOverlay:true, loop:false,
		//	videoFile:url
		//});
		//try {player.setConfig({videoFile:''});} catch(e) {debug_log(e)}
		//try {player.DoPlay(); return;} catch(e) {debug_log(e)}
	}

	url = url.match(/\/([0-9]+).(?:flv|mp3)$/)[1];

	try {player.DoStop();} catch(e) {debug_log(e)}
	//try {player.stopBuffering();} catch(e) {debug_log(e)}

	if(/^(?:http:\/\/)?[A-z0-9.-]+\/audio/.test(document.location))
		return play_audio(player, url);

	var request = new Request.JSON({ // &ajax[]=main.center_menu
		url: '/video/-/' + url + '/?ajax[]=main.center_tab.videos&ajax[]=main.center_tab.comments&ajax[]=main.center_tab.comments_button&ajax[]=r_views&ajax[]=r_grade&ajax[]=r_votes&ajax[]=r_id&ajax[]=r_hash&ajax[]=url&ajax[]=embed',
		onComplete: function(jsonObj) {
			try {
				try {
						player.playClip({
							name: 'Playing...',
							url: FILESURL + '/video/' + jsonObj['r_hash'] + '.flv'
						});
				} catch(e) {debug_log("ajaxplay: " + e)}
				//$$("#tab_content .tab_content")[0].empty(); $$("#tab_content .tab_content")[0].innerHTML = jsonObj['main.center_tab.videos'].replace(/^\<div[^\>]*\>|\<\/div\>$/g, '');
				try {$$('.coloanas .tag_cloud')[0].empty(); $$('.coloanas .tag_cloud')[0].innerHTML = jsonObj['main.center_menu'].replace(/\<br[ \/]*\>$/, '').replace(/^\<div[^\>]*\>|\<\/div\>$/g, '');} catch(e) {debug_log("x1: " + e)}
				try {$('comment').empty(); $('comment').innerHTML = jsonObj['main.center_tab.comments'].replace(/^(\<div[^\>]*\>\s*){2}|(\<\/div\>\s*){2}$/g, '');} catch(e) {debug_log("x2: " + e)}
				try {
					var tmp = null;
					tmp = $$('#tab_buttons span');
					tmp = tmp[1] ? tmp[1] : tmp[0];
					tmp.empty();
					tmp.innerHTML = jsonObj['main.center_tab.comments_button'].match(/\<span\>([^\<\>]+)\<\/span\>/)[1];
				} catch(e) {debug_log("x3: " + e)}
				try {
					$('r_grade').innerHTML = jsonObj['r_grade'];
					$('r_grade').set('name', 'sid_' + jsonObj['r_id']);
					$('r_votes').innerHTML = jsonObj['r_votes'];
					$('r_views').innerHTML = jsonObj['r_views'];
					init_rating();
				} catch(e) {debug_log("x4: " + e)}
				try {
					$$('#embed input[type="text"]')[0].value = jsonObj['url'];
					$$('#embed input[type="text"]')[1].value = jsonObj['embed'];
				} catch(e) {debug_log("x5: " + e)}

				document.title = 'VideoBest.eu - ' + $$('.coloanas .tag_cloud .tag_cloud_header')[0].innerHTML;
			} catch(e) {debug_log(e)}
		}
	}).send();

}*/


function fp_addpw(x, y) {
	var def_shot = y.src;
	var start_idx = 0;
	try {start_idx += "abc".indexOf(def_shot.match(/\/files\/video\/shot\/([a-c])\/.*$/)[1].charAt(0));} catch(e) {}
	//try {x.def_shot = x.src.match(/\/files\/video\/shot\/([a-c]{1})\/[0-9]+-1.jpg$/)[1];} catch(e) {x.def_shot='b';}
	x.addEvent('mouseover', function() {
		try {
			document.video_pw.id = y;
			document.video_pw.i = start_idx;
			document.video_pw.sw();
			try {clearInterval(document.video_pw.oInterv)} catch(e) {}
			document.video_pw.oInterv = setInterval(document.video_pw.sw, 600);
		} catch(e) {debug_log('mouseover: ' + e)}
	});
	x.addEvent('mouseout', function() {
		try {
			try {clearInterval(document.video_pw.oInterv);} catch(e) {}
			//document.video_pw.i = 0;
			//document.video_pw.sw();
			y.src = def_shot;
			//alert(x.src);
		} catch(e) {debug_log('mouseout: ' + e)}
	});

	x.click_ev_handler = function(e) {
		try {
			var m = null;
			//if(!document.fp_is_loaded || !(m=$('myFlashContent')))
			//	return;
			try {$$('.playernav .nav_left .count')[0].innerHTML = '<span>'+MSG.js_script_fileloading+'</span>';} catch(e) {}
			/*try {
				if(window.location.href.match(/\/video\/([A-Za-z0-9\-]+\/[0-9]+)\/?/)) {
					window.location = '/#video/' + x.name.replace(/\_/g, '/');
					return false;
				}
			} catch(e) {}*/
			/*m.playClip({
				name: 'Playing...',
				url: FILESURL + '/video/' + x.name.split('_')[1] + '.flv'
			});*/
			var np = x.href ? x.href.match(/^(?:http:\/\/)?[^\/]+\/(video|audio|media)\/[a-z0-9-]+\/([0-9]+)\/?(?:\?.*)?$/) : null;
			if(!np) {
				return;
				//debug_log('regexp: ' + x.href);
			}
			if(e)
				(new Event(e)).stop();
			document.fp_now_playing2 = {ftype:np[1], id:np[2]};
			fp_play2(np[2], np[1]);
		} catch(e) {debug_log('click_ev_handler: '+e)}
		return false;
	}
	x.addEvent('click', x.click_ev_handler);
}


function init_preview() {
	$$('div.tab_content_item a').each(function(x, i) {
		fp_addpw(x, x.getChildren('img')[0]);
	});
	fp_onload();
	//$$('div#playlist a').each(function(x, i) {
	//	fp_addpw(x, x.getChildren('img')[0]);
	//});
}


function init_preview2() {
	var images = $$('.video_list .inner_image img');
	if(!images || images.length < 1)
		return;
	images.each(function(x, idx) {
		fp_addpw(x, x);
	});
}


function init_preview3() {
	var links = $$('div.playernav a[name=pl_nav]');
	if(!links || links.length < 1)
		return;
	links.each(function(x, idx) {
		fp_addpw(x, x.getChildren('img.pw')[0]);
	});

	onClipDone = function() {
		try {
			var next = $$('.playernav .nav_left .nav_r');
			if(!next || !next.length || !(next = next[0]))
				return;
			if(next.click_ev_handler)
				next.click_ev_handler();
		} catch(e) {debug_log(e)}
	}
}


function fp_onload() {
	//try {init_crop()} catch(e) {debug_log(e)}
	try {
	$$('#playlist a').each(function(x,i) {
		fp_addpw(x, x.getChildren('img')[0]);
	});

	/*now_playing = 0;
	start = false;
	try {now_playing = window.location.href.match(/\/(?:video|audio)\/[a-zA-Z0-9\-]+\/([0-9]+)\/?$/)[1]; start=true;} catch(e) {}
	try {now_playing = window.location.href.match(/\#\/?(?:video|audio)\/[a-zA-Z0-9\-]+\/([0-9]+)\/?$/)[1];} catch(e) {}
	if(now_playing)
		fp_play(FILESURL + '/video/' + now_playing + '.flv', start);
	document.fp_now_playing = now_playing;

	document.fp_event_back = {oInterv:null, link:window.location.href, f:function() {
		now_playing = 0;
		try {now_playing = window.location.href.match(/\/(?:video|audio)\/[a-zA-Z0-9\-]+\/([0-9]+)\/?$/)[1];} catch(e) {}
		try {now_playing = window.location.href.match(/\#\/?(?:video|audio)\/[a-zA-Z0-9\-]+\/([0-9]+)\/?$/)[1];} catch(e) {}
		if(!now_playing || document.fp_now_playing == now_playing)
			return;
		try {fp_play(FILESURL + '/video/' + now_playing + '.flv');} catch(e) {}
		document.fp_now_playing = now_playing;
	}};
	document.fp_event_back.oInterv = setInterval(document.fp_event_back.f, 300); */
	now_playing = 0;
	start = false;
	try {now_playing = window.location.href.match(/\/(?:video|audio|media)\/[a-zA-Z0-9\-]+\/([0-9]+)\/?$/)[1]; start=true;} catch(e) {}
	try {now_playing = window.location.href.match(/\#\/?(?:video|audio|media)\/[a-zA-Z0-9\-]+\/([0-9]+)\/?$/)[1];} catch(e) {}
	if(now_playing)
		fp_play2(now_playing, 'media', start);
	else
		if($('mainplayer')) {
			main_player_config.playlist.each(function(x, i) {
				if(x.url.match(/(?:audio|video)(?:\/[a-f0-9]{2}){4}\/[a-f0-9]+\.(?:mp3|flv)(?:\?.*)?$/)) {
					main_player_config.playlist[i].onPause = function() {
						onPause();
					}
					main_player_config.playlist[i].onResume = function() {
						onResume();
					}
					main_player_config.playlist[i].onFinish = function() {
						onClipDone();
					}
				}
			});
			$f('mainplayer', '/script/flowplayer-3.1.1.swf?v='+MSG.lastupdate, main_player_config).load();
		}
	document.fp_now_playing2 = {id:now_playing, ftype:'media'};
	document.fp_event_back = {oInterv:null, link:window.location.href, f:function() {
		var now_playing = 0;
		try {now_playing = window.location.href.match(/\/play-([0-9]+)\/?$/)[1];} catch(e) {}
		try {now_playing = window.location.href.match(/\/(?:video|audio|media)\/[a-zA-Z0-9\-]+\/([0-9]+)\/?$/)[1];} catch(e) {}
		try {now_playing = window.location.href.match(/\#\/?(?:video|audio|media)\/[a-zA-Z0-9\-]+\/([0-9]+)\/?$/)[1];} catch(e) {}
		try {
		if(!now_playing || document.fp_now_playing2.id == now_playing)
			return;
		} catch(e) {return;}
		try {fp_play2(now_playing, 'media');} catch(e) {}
		document.fp_now_playing2.id = now_playing;
	}};
	//document.fp_event_back.oInterv = setInterval(document.fp_event_back.f, 300); // TODO TODO // "back" not working properly
	} catch(e) {debug_log(e)}
}


function onFlowPlayerReady() {
	try {
	if(document.fp_is_half_loaded) {
		document.fp_is_loaded = true;
		fp_onload();
	} else
		document.fp_is_half_loaded = true;
	} catch(e) {}
}



function add_fxscroll(id, sbid) {
	var dbclass = {'top':['sb_top','sb_dtop'], 'bottom':['sb_bottom','sb_dbottom']};

	var sbspace = sbid.getElement('.sb_space');
	var buttons = sbid.getElements('.sb_button');
	var slider = new Slider(sbspace, sbspace.getElement('.sb_knob'), {
		steps: 20,
		//snap: true,
		mode: 'vertical',
		wheel: true,
		onChange: function(val) {
			id.scrollTo(0, (id.getScrollSize().y - id.getSize().y) * (val/this.steps));
			if(val <= 0 || val >= this.steps) {
				buttons[val <= 0 ? 0 : 1].addClass(dbclass[val <= 0 ? 'top' : 'bottom'][1]);
			} else {
				buttons[0].removeClass(dbclass.top[1]);
				buttons[1].removeClass(dbclass.bottom[1]);
			}
		}
	}).set(0);

	var bthread = null;

	buttons.each(function(x, i) {
		x.addEvent('mousedown', function(e) {
			try {
			(new Event(e)).stop();
			var s = '';
			for(j in slider)
				if(typeof(slider[j]) != 'function')
					s += j + ' => ' + slider[j] + '\n';
			//alert(s)
			try {clearInterval(bthread);} catch(e) {}
			bthread = setInterval(function() {
				var n = slider.step + (i ? 1 : -1);
				if(n < 0 || n > slider.steps) {
					try {clearInterval(bthread);} catch(e) {}
					return;
				}
				slider.set(n);
			}, 20);
			} catch(e) {debug_log(e)}
		});
		x.addEvent('mouseup', function() {
			try {clearInterval(bthread);} catch(e) {}
		});
	});

	id.addEvent('mousewheel', function(e) {
		(new Event(e)).stop();
		var n = slider.step - 5*e.wheel;
		if(n < 0 || n > slider.steps)
			n = (n < 0) ? 0 : slider.steps;
		slider.set(n);
	});
}


function init_fxscroll() {
	if(!$('playlist'))
		return;
	var sbid = $$('.wrapplayer .scrollbar')[0];
	var id = $('playlist');
	add_fxscroll(id, sbid);
}


function flash_not_supported(v) {
	$('update_flash').style.display = 'block';
}


function init_flash_check() {
	//var v0 = 9, v1 = 0, v2 = 115;
	var v = '9.0.115';
	try {
		//alert(GetSwfVer());
		//var v = GetSwfVer().split(/[^0-9]+/);
		//if(!v || v.length < 3)
		//	throw false;
		//if((100000*parseInt(v[0]) + 1000*parseInt(v[1]) + parseInt(v[2])) < (100000*v0 + 1000*v1 + v2))
		//	throw false;
		//alert(true);
		if(!swfobject)
			debug_log('swfobject not loaded');
		if(!swfobject.hasFlashPlayerVersion(v))
			throw false;
		document.supports_required_flash = true;
	} catch(e) {
		document.supports_required_flash = false;
		try {flash_not_supported(v);} catch(e) {debug_log(e)}
	}
	Cookie.write('supports_required_flash', document.supports_required_flash ? 'true' : 'false', {domain:'.'+TLD, duration:1, path:'/'});
}


function init_mp3_upload() { // ui autocomplete, OBSOLETE
	if(!$$('#swform_ul_1 input[name="id3_artist"]').length || !$$('#swform_ul_1 input[name="id3_title"]').length || !$$('#swform_ul_1 input[name="title"]').length) {
		return;
	}
	var artist = $$('#swform_ul_1 input[name="id3_artist"]')[0], title = $$('#swform_ul_1 input[name="id3_title"]')[0], album = $$('#swform_ul_1 input[name="id3_album"]')[0], name = $$('#swform_ul_1 input[name="title"]')[0];
	var description = $$('#swform_ul_1 textarea[name="description"]')[0], keywords = $$('#swform_ul_1 textarea[name="keywords"]')[0];
	name.addEvent('change', function() {name.is_changed = true;});
	description.addEvent('change', function() {description.is_changed = true;});
	keywords.addEvent('change', function() {keywords.is_changed = true;});

	var event_change = function(x) {
		if(!name.is_changed || !name.value.trim()) {
			name.is_changed = false;
			if(artist.value.trim() && title.value.trim())
				name.value = artist.value.trim() + ' - ' + title.value.trim();
			else if(title.value.trim())
				name.value = title.value.trim();
			else if(artist.value.trim())
				name.value = artist.value.trim();
		}
		if(!description.is_changed || !description.value.trim()) {
			description.is_changed = false;
			if(artist.value.trim() && title.value.trim())
				description.value = artist.value.trim() + ': ' + title.value.trim() + (album.value.trim() ? ' (' + album.value.trim() + ')' : '');
			else if(title.value.trim())
				description.value = title.value.trim() + (album.value.trim() ? ' (' + album.value.trim() + ')' : '');
			else if(artist.value.trim())
				description.value = artist.value.trim() + (album.value.trim() ? ' (' + album.value.trim() + ')' : '');
		}
		if(!keywords.is_changed || !keywords.value.trim()) {
			keywords.is_changed = false;
			if(artist.value.trim() && title.value.trim())
				keywords.value = artist.value.trim() + (album.value.trim() ? ', '+album.value.trim() : '') + ', ' + title.value.trim().split(/\s+|\s*,\s*/).join(', ');
			else if(title.value.trim())
				keywords.value = (album.value.trim() ? album.value.trim()+', ' : '') + title.value.trim().split(/\s+|\s*,\s*/).join(', ');
			else if(artist.value.trim())
				keywords.value = artist.value.trim();
			keywords.value = keywords.value.toLowerCase();
		}
	}
	artist.addEvents({'change':event_change, 'keyup':event_change, 'click':event_change, 'blur':event_change});
	title.addEvents({'change':event_change, 'keyup':event_change, 'click':event_change, 'blur':event_change});
	album.addEvents({'change':event_change, 'keyup':event_change, 'click':event_change, 'blur':event_change});
}


function init_video_upload() { // ui autocomplete, OBSOLETE
	if(!$$('#swform_ul_0 input[name="title"]').length) {
		return;
	}
	var name = $$('#swform_ul_0 input[name="title"]')[0];
	var description = $$('#swform_ul_0 textarea[name="description"]')[0], keywords = $$('#swform_ul_0 [name="keywords"]')[0];
	keywords.addEvent('change', function() {keywords.is_changed = true;});

	var event_change = function(x) {
		if(!keywords.is_changed || !keywords.value.trim()) {
			keywords.is_changed = false;
			if(name.value.trim() && description.value.trim())
				//keywords.value = name.value.trim() + ', ' + description.value.trim().split(/\s+|\s*,\s*/).join(', ');
				keywords.value = name.value.trim() + ', ' + description.value.trim().match(/[^, ]{3,}/g).join(', ');
			else if(name.value.trim())
				keywords.value = name.value.trim();
			keywords.value = keywords.value.toLowerCase();
		}
	}
	name.addEvents({'change':event_change, 'keyup':event_change, 'click':event_change, 'blur':event_change});
	description.addEvents({'change':event_change, 'keyup':event_change, 'click':event_change, 'blur':event_change});
}


function SwfAjaxForm(id, callback) {
	var this2 = this; // this way public functions can be accessed with this2
	this.init = function() {
		id = $(id);
		if(!callback) callback = {};
		if(!callback.onFileadd) callback.onFileadd = function(){};
		if(!callback.onStart) callback.onStart = function(){return true;};
		if(!callback.progressCallback) callback.progressCallback = function(){};
		if(!callback.onComplete) callback.onComplete = function(){};

		var getDoc = function(x) {
			var fdoc;
			if(x.contentDocument)
				fdoc = x.contentDocument;
			else if(x.contentWindow && x.contentWindow.document)
				fdoc = x.contentWindow.document;
			else
				fdoc = x.document;
			return fdoc;
		}

		if(!document.supports_required_flash || id.getElements('input[type=file]').length>1) {
			var oFrame = 'axswf' + Math.floor(Math.random()*1000000000);
			oFrame = new Element('iframe', {'src':'about:blank', 'id':oFrame, 'name':oFrame, 'width':0, 'height':0, 'style':'border:0;visibility:hidden;', 'frameborder':0});
			oFrame.inject(id, 'after');

			(new Element('input', {'type':'hidden', 'name':'is_ajax_upload', 'value':'js'})).inject(id, 'bottom');

			id.setAttribute('target', oFrame.name);

			oFrame.addEvent('load', function() {
				if(!oFrame.axswf_pending)
					return;
				try {id.getElement('input[type=submit]').disabled = false;} catch(e) {}
				callback.onComplete(getDoc(oFrame).body.innerHTML);
			});

			id.addEvent('submit', function(e) {
				if(!callback.onStart(false, this2.formread(id), e)) {
					(new Event(e)).stop();
					return;
				}
				oFrame.axswf_pending = true;
				id.getElement('input[type=submit]').disabled = true;
			});
		} else {
			this2.swfupload(id.getElement('input[type=file]'), id.getAttribute('action'), id.getElement('input[type=file]').name);
		}
	}

	this.formread = function(id) {
		var data = {};
		id.getElements('input[type=text], input[type=radio], input[type=checkbox], input[type=hidden], textarea, select').each(function(x) {
			if(!x.name)
				return;
			if((x.type=='radio' && x.checked) || x.type!='radio')
				data[x.name] = x.value;
		});
		return data;
	}

	this.swfupload = function(buttonholder, action, filepostname) {
		action = '/ajax/upload.php';
		//if(typeof(action) != 'string') action = action.value;
		var rndid = Math.floor(Math.random()*1000000000);
		var placeholder = new Element('div', {'class':'filequeue'});
		placeholder.innerHTML = '<input type="text" id="queue_' + rndid + '" readonly="readonly"/><div><div id="button_' + rndid + '"></div></div>';
		placeholder.inject(buttonholder, 'after');
		buttonholder.dispose();
		id.getElement('input[type=submit]').disabled = true;
		var settings = {
			flash_url: "/script/swfupload_v2.2.0b5/swfupload.swf",
			upload_url: action,
			file_post_name: filepostname,
			file_size_limit : "2000 MB",
			file_types: "*.*",
			file_types_description: "All Files",
			file_upload_limit: 100,
			file_queue_limit: 0,
			debug: false,

			button_image_url: "/script/swfupload_v2.2.0b5/browse.png",
			button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
			button_width: "75",
			button_height: "29",
			button_placeholder_id: 'button_' + rndid,
			button_text: '<span class="theFont">Browse</span>',
			button_text_style: ".theFont {font-size:16px;text-align:center;color:#ffffff;}",
			//button_text_left_padding: 6,
			button_text_top_padding: 3,


			// The event handler functions are defined in handlers.js
			file_queued_handler : function(file) {
				$('queue_' + rndid).value = file.name;
				id.getElement('input[type=submit]').disabled = false;
				//callback.onFileadd(file);
				//$$('#upload input[name="ulvideo"]')[0].value = file.name;
			}, //fileQueued
			file_queue_error_handler: function(file, errorCode, message) {}, //fileQueueError
			file_dialog_complete_handler: function(numFilesSelected, numFilesQueued) {}, //fileDialogComplete
			upload_start_handler: function(file) {}, //uploadStart,
			upload_progress_handler: function(file, bytesLoaded, bytesTotal) {
				callback.progressCallback(file, bytesLoaded, bytesTotal);
				//$('upload_progress').style.display = 'block';
				//$$('#upload_progress .percent')[0].innerHTML = $$('#upload_progress .border .progress')[0].style.width = Math.floor((bytesLoaded*100)/bytesTotal).toString() + '%';
			}, //uploadProgress
			upload_error_handler: function(file, errorCode, message) {alert(message)}, // uploadError
			upload_success_handler: function(file, serverData) {
				try {
					$('queue_' + rndid).value = '';
					id.getElement('input[type=submit]').disabled = true;
				} catch(e) {debug_log(e)}
				callback.onComplete(serverData);
			}
		}
		var swf_upload2 = new SWFUpload(settings);
		id.addEvent('submit', function(e) {
			(new Event(e)).stop();
			var formdata = this2.formread(id);
			if(!callback.onStart(true, formdata))
				return;
			id.getElement('input[type=submit]').disabled = true;
			formdata['is_ajax_upload'] = 'swf';
			//var s = ''; for(i in formdata) s += i + ' => ' + formdata[i] + "\n"; alert(s);
			swf_upload2.setPostParams(formdata);
			swf_upload2.startUpload();
		});
	}

	// -------------------------------------------------------------------------------------------------------------

	this.init();
}

function init_swform() { // switch forms
	$$('[id^=swform_ul]').each(function(x) {
		x.style.display = 'none';
	});
	var buttons = $$('input[name^=swform_]');
	buttons.each(function(x, idx) {
		if(x.checked) $$('input[name^=' + x.name + ']').each(function(y, idy) {
			$(x.name + '_' + idy).style.display = (idy == idx) ? 'block' : 'none';
		});
		var ev_handler = function() {
			$$('input[name^=' + x.name + ']').each(function(y, idy) {
				$(x.name + '_' + idy).style.display = (idy == idx) ? 'block' : 'none';
			});
		};
		x.addEvents({'change':ev_handler, 'click':ev_handler});
	});
}


function init_upload_tags_autocomplete(form) { // ui autocomplete, form = {name,description,keywords} (optional)
	if(!form && !$$('#swform_ul_0 input[name="title"]').length) {
		return;
	}
	var name = (form && form.name) ? form.name : $$('#swform_ul_0 input[name="title"]')[0];
	var description = (form && form.description) ? form.description : $$('#swform_ul_0 textarea[name="description"]')[0];
	var keywords = (form && form.keywords) ? form.keywords : $$('#swform_ul_0 [name="keywords"]')[0];
	keywords.addEvent('change', function() {keywords.is_changed = true;});

	var event_change = function(x) {
		try {

		if(!keywords.is_changed || !keywords.value.trim()) {
			keywords.is_changed = false;
			var words_n = name.value.trim().match(/[^,;. ]{3,}/g);
			var words_d = description.value.trim().match(/[^,;. ]{3,}/g);
			var words = [];
			var i;
			if(!words_n) words_n = [];
			if(!words_d) words_d = [];
			for(i=0; i < words_n.length && words.length < 2; i++)
				if(!words.in_array(words_n[i]))
					words = words.concat([words_n[i]]);

			for(i=0; i < words_d.length && words.length < 5; i++)
				if(!words.in_array(words_d[i]))
					words = words.concat([words_d[i]]);

			keywords.value = words.join(', ').toLowerCase();
		}
		} catch(e) {debug_log(e)}
	}
	name.addEvents({'change':event_change, 'keyup':event_change, 'click':event_change, 'blur':event_change});
	description.addEvents({'change':event_change, 'keyup':event_change, 'click':event_change, 'blur':event_change});
}


function init_upload_file() {
	if(!$('uploadfile'))
		return;
	//try {init_swform();} catch(e) {debug_log(e)}
	//try {init_mp3_upload();} catch(e) {debug_log(e)}
	//try {init_video_upload();} catch(e) {debug_log(e)}
	try {init_upload_tags_autocomplete();} catch(e) {debug_log(e)}

	if($('swform_ul_0'))
	new SwfAjaxForm('swform_ul_0', { // video upload
		onStart: function(hasprogress, formdata) {//print_r(formdata);return false;
			//var s = '';
			//for(i in formdata)
			//	s += i + ' => ' + formdata[i] + "\n";
			//alert(s);

			//for(i in formdata)
			//	if(!formdata[i].trim()) {
			//		alert(MSG.js_script_upload_requiredfields);
			//		return false;
			//	}
			$('swform_ul_0').setStyles({opacity:0.5});
			return true;
		},
		progressCallback: function(file, bytesLoaded, bytesTotal) {
			$('upload_progress').style.display = 'block';
			$$('#upload_progress .percent')[0].innerHTML = $$('#upload_progress .border .progress')[0].style.width = Math.floor((bytesLoaded*100)/bytesTotal).toString() + '%';
		},
		onComplete: function(serverData) {
			try {
			serverData = serverData.match(/-!!\[\^((?:.|\n)*)\$\]!!-/)[1]; // since serverData also contains html
			$('upload_progress').style.display = 'none';
			//$$('#upload input[name="ulvideo"]')[0].value = '';
			//$$('#upload textarea[name="keywords"]')[0].value = serverData;
			var id;
			if(id = serverData.match(/^OK id=([0-9]+)$/)) {
				id = id[1];
				document.location = '/upload-file/step-2?upload=1&id=' + escape(id);
				/*
				$('upload_pending').style.display = 'block';
				var oInterv = setInterval(function() {
					// here we keep checking if the server has finished encoding the file
					new Request({
						method: 'get',
						url: '/ajax/pending?id=' + escape(id) + '&rnd=' + escape(Math.random()),
						onSuccess: function(r) {
							if(r != '1') {
								clearInterval(oInterv);
								$('upload_pending').style.display = 'none';
							}
							if(r == '0') {
								alert(MSG.js_script_upload_success); // success
								document.location = '/user';
							} else if(r == '2') {
								alert(MSG.js_script_upload_eunknownformat); // error
								document.location = '/upload-file';
							}
						},
						oFailure: function() {
							clearInterval(oInterv);
							alert('Error: connection lost');
						}
					}).send();

				}, 3000);*/

			} else {
				alert(serverData);
				$('swform_ul_0').setStyles({opacity:1});
			}
			} catch(e) {debug_log(e)}
		}
	});



	var show_pending = function(id) {
		document.xloader_hide();
		document.location = '#pending';
		try {$('upload_file_update_shot').empty();} catch(e) {}
		$('upload_pending').style.display = 'block';
			var oInterv = setInterval(function() {
				// here we keep checking if the server has finished encoding the file
				new Request({
					method: 'get',
					url: '/ajax/pending?id=' + escape(id) + '&rnd=' + escape(Math.random()),
					onSuccess: function(r) {
						if(r != '1') {
							clearInterval(oInterv);
							$('upload_pending').style.display = 'none';
						}
						if(r == '0') {
							alert(MSG.js_script_upload_success); // success
							document.location = '/user';
						} else if(r == '2') {
							alert(MSG.js_script_upload_eunknownformat); // error
							document.location = '/upload-file';
						}
					},
					oFailure: function() {
						clearInterval(oInterv);
						alert('Error: connection lost');
					}
				}).send();

			}, 3000);
	}


	if($('upload_file_update_shot')) {
		init_upload_tags_autocomplete({name:$('upload_u_title'), keywords:$('upload_u_keywords'), description:$('upload_u_description')});
		if(document.location.href.match(/#pending$/))
			show_pending();

		if(/[?&]upload=1[^?]*$/.test(document.location.href)) {
			(new Element('input', {'type':'hidden', 'name':'is_ajax', 'value':'1'})).inject($('upload_file_update_shot'), 'bottom');
			$('upload_file_update_shot').addEvent('submit', function(e) {
				(new Event(e)).stop();
				var form = this;
				var id = form.getElement('input[name=id]').value;

				form.set('send', {
					//url: '/ajax/admin_video?action=update_shot',
					onComplete: function(response) {
						show_pending(id);
					},
					onFailure: function() {
						show_pending(id);
					}
				});
				document.xloader_show();
				form.send();
			});
		}
	}
	/*new SwfAjaxForm('swform_ul_1', { // audio upload
		onStart: function(hasprogress, formdata, e) {
			try {
			for(i in formdata)// alert(i + ' => ' + formdata[i].trim()); return;
				if(!['id3_artist', 'id3_album'].in_array(i) && !formdata[i].trim()) {
					alert(MSG.js_script_upload_requiredfields);
					return false;
				}
			$('swform_ul_1').setStyles({opacity:0.5});
			document.xloader_show(e);
			return true;
			} catch(e) {debug_log(e);}
		},
		onComplete: function(serverData) {
			$('swform_ul_1').setStyles({opacity:1});
			document.xloader_hide();
			try {
			serverData = serverData.match(/-!!\[\^(.*)\$\]!!-/)[1]; // since r also contains html
			if(id = serverData.match(/^OK id=([0-9]+)$/)) {
				id = id[1];
				alert(MSG.js_script_upload_mp3success);
				document.location = '/useraudio';
			} else
				alert(serverData);
			$('swform_ul_1').setStyles({opacity:1});
			} catch(e) {alert('no match')}
		}
	});*/
}


/*function init_upload() {
	if(!$('uploadButtonPlaceHolder'))
		return;

	var settings = {
		flash_url: "/script/swfupload/swfupload.swf",
		upload_url: "/upload-beta",	// Relative to the SWF file
		file_post_name : 'ulvideo',
		file_size_limit : "200 MB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : 100,
		file_queue_limit : 0,
		debug: false,

		button_image_url: "/script/swfupload/browse.png",	// Relative to the Flash file
		button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
		button_width: "65",
		button_height: "29",
		button_placeholder_id: "uploadButtonPlaceHolder",
		button_text: '<span class="theFont">' + $('uploadButtonPlaceHolder').innerHTML + '</span>',
		button_text_style: ".theFont { font-size: 16;font-weight:bold; }",
		button_text_left_padding: 6,
		button_text_top_padding: 3,


		// The event handler functions are defined in handlers.js
		file_queued_handler : function(file) {
			$$('#upload input[name="ulvideo"]')[0].value = file.name;
			//alert(file.name + ' ' + file.size);
		}, //fileQueued
		file_queue_error_handler : function(file, errorCode, message) {}, //fileQueueError
		file_dialog_complete_handler : function(numFilesSelected, numFilesQueued) {}, //fileDialogComplete
		upload_start_handler : function(file) {}, //uploadStart,
		upload_progress_handler : function(file, bytesLoaded, bytesTotal) {
			$('upload_progress').style.display = 'block';
			$$('#upload_progress .percent')[0].innerHTML = $$('#upload_progress .border .progress')[0].style.width = Math.floor((bytesLoaded*100)/bytesTotal).toString() + '%';
			//$('upload_progressbar').innerHTML = bytesLoaded + ' / ' + bytesTotal;
		}, //uploadProgress
		upload_error_handler : function(file, errorCode, message) {}, // uploadError
		upload_success_handler : function(file, serverData) {
		try {
			$('upload_progress').style.display = 'none';
			$$('#upload input[name="ulvideo"]')[0].value = '';
			//$$('#upload textarea[name="keywords"]')[0].value = serverData;
			var id;
			if(id = serverData.match(/^OK id=([0-9]+)$/)) {
				id = id[1];
				$('upload_pending').style.display = 'block';
				var oInterv = setInterval(function() {
					// here we keep checking if the server has finished encoding the file
					new Request({
						method: 'get',
						url: '/ajax/pending?id=' + escape(id) + '&rnd=' + escape(Math.random()),
						onSuccess: function(r) {
							if(r != '1') {
								clearInterval(oInterv);
								$('upload_pending').style.display = 'none';
							}
							if(r == '0') {
								alert(MSG.js_script_upload_success); // success
								document.location = '/user';
							} else if(r == '2') {
								alert(MSG.js_script_upload_eunknownformat); // error
								window.location.reload();
							}
						},
						oFailure: function() {
							clearInterval(oInterv);
							alert('Error: connection lost');
						}
					}).send();

				}, 3000);

			} else {
				if(serverData.length < 1024)
					alert(serverData);
				else
					document.location = '/upload'; // the server made a boo boo
			}
		} catch(e) {debug_log(e)}
		}, // uploadSuccess
		upload_complete_handler : function(file) {}, // uploadComplete
		queue_complete_handler : function(numFilesUploaded) {} // queueComplete	// Queue plugin event
	};

	document.swf_upload1 = new SWFUpload(settings);

	document.upload_submit = function(c, m) {
		try {
			if(!$(c).checked) {
				alert(m[0]);
				return;
			}
			var p = {
				'action' : 'upload-beta',
				'xsrf' : Cookie.read('an_sid').trim(),
				'an_sid' : Cookie.read('an_sid').trim(),
				'title' : $$('#upload input[name="title"]')[0].value.trim(),
				'description' : $$('#upload textarea[name="description"]')[0].value.trim(),
				'keywords' : $$('#upload textarea[name="keywords"]')[0].value.trim(),
				'section' : $$('#upload select[name="section"]')[0].value.trim()
			};
			for(i in p)
				if(!p[i]) {
					alert(m[1]);
					return;
				}
			//debug_log(p['xsrf'] + ' - ' + p['title'] + ' - ' + p['description'] + ' - ' + p['keywords'] + ' - ' + p['section']); return;
			document.swf_upload1.setPostParams(p);
			document.swf_upload1.startUpload();
		} catch(e) {debug_log(e)}
	}
}*/


function init_speedlist() {
	document.speedlist_add = function(id, select) { // returns true if id was added
		if(!select)
			select = 'speedlist';
		try {
		var r = false;
		var list = Cookie.read(select);
		list = list ? list.split('|') : [];
		if(id != -1) {
			if(!list.in_array(id)) {
				list.push(id);
				r = true;
			}
			Cookie.write(select, list.join('|'), {domain:'.'+TLD, duration:365, path:'/'});
		}

		if(select == 'speedlist') {
			$$('#topmenu .topmenu a[name="speedlist"]', '.mtoggle a[name="speedlist"]').each(function(l) {
				l.innerHTML = l.innerHTML.replace(/\((?:\<b\>)?[0-9]*(?:\<\/b\>)?\)/i, '(<b>'+list.length+'</b>)');
			});

		}
		} catch(e) {debug_log(e)}
		return r;
	}

	document.speedlist_contains = function(id, select) {
		if(!select)
			select = 'speedlist';
		var list = Cookie.read(select);
		list = list ? list.split('|') : [];
		return list.in_array(id);
	}

	document.speedlist_remove = function(id, select) { // returns true if it has actually removed id
		if(!select)
			select = 'speedlist';
		var list = Cookie.read(select);
		list = list ? list.split('|') : [];
		if(!select)
			document.speedlist_remove(id, 'speedlist_sel'); // remove selected
		if(list.remove_item(id)) {
			Cookie.write(select, list.join('|'), {domain:'.'+TLD, duration:365, path:'/'});
			document.speedlist_add(-1); // updates the counter
			return true;
		}
		return false;
	}

	document.speedlist_select = function(t) { // t = (all | page | unall | unpage)
		try {
		var p = $$('#g_playlist .wrap_item');
		if(p && p.length) p.each(function(x) {
			var sel = x.getElement('input[id^=speedlist_sel_]');
			if(!sel)
				return false;
			var id = sel.id.match(/^speedlist_sel_([0-9]+)$/)[1];
			if(t=='all' || t=='page') {
				x.className = 'wrap_item wrap_sel';
				sel.checked = true;
				if(t=='page')
					document.speedlist_add(id, 'speedlist_sel');
			} else if(t=='unall' || t=='unpage') {
				x.className = 'wrap_item';
				sel.checked = false;
				if(t=='unpage')
					document.speedlist_remove(id, 'speedlist_sel');
			}
		});
		if(t=='unall')
			Cookie.write('speedlist_sel', '', {domain:'.'+TLD, duration:365, path:'/'});
		else if(t=='all')
			Cookie.write('speedlist_sel', Cookie.read('speedlist'), {domain:'.'+TLD, duration:365, path:'/'});

		} catch(e) {debug_log(e)}
		return false;
	}


	var p = $$('.video_list .inner_image a[name="pl_plus"]');
	if(p && p.length) p.each(function(x, i) {
		var id = x.id.match(/^pl_plus_([0-9]+)$/)[1];
		if(document.speedlist_contains(id)) {
			x.parentNode.className = 'inner_image qlist';
			x.className = 'pl_minus';
		}

		x.addEvent('click', function(e) {
			try {
			(new Event(e)).stop();
			if(!document.speedlist_contains(id)) {
				document.speedlist_add(id);
				x.className = 'pl_minus';
				x.parentNode.className = 'inner_image qlist';
			} else {
				document.speedlist_remove(id);
				x.className = 'pl_plus';
				x.parentNode.className = 'inner_image';
				//$('video_list').removeChild(x.parentNode.parentNode);
			}
			if(x.blur)
				x.blur();
			return false;
			} catch(e) {debug_log(e)}
		});
	});

	$$('.audio_list td.corner a.pl_plus').each(function(x) {
		var id = x.id.match(/^pl_plus_([0-9]+)$/)[1];
		if(document.speedlist_contains(id))
			x.getParent('tr').addClass('qlist');
		x.addEvent('click', function(e) {
			try {
				(new Event(e)).stop();
				if(document.speedlist_contains(id)) {
					x.getParent('tr').removeClass('qlist');
					document.speedlist_remove(id);
					if(/[?&]o=sl[^?]*$/.test(document.location.href)) { // order=speedlist
						x.getParent('tr').style.display = 'none';
					}
				} else {
					x.getParent('tr').addClass('qlist');
					document.speedlist_add(id);
				}
				if(x.blur)
					x.blur();
			} catch(e) {debug_log(e)}
		});
	});

	p = $$('#g_playlist div[name="speedlist_item"]');
	if(p && p.length) p.each(function(x) {
		var sel = x.getElement('input[id^=speedlist_sel_]');
		var id = sel.id.match(/^speedlist_sel_([0-9]+)$/)[1];

		if(document.speedlist_contains(id, 'speedlist_sel')) {
			x.className = 'wrap_item wrap_sel';
			sel.checked = true;
		}

		var ev_handler = function() {
			if(sel.checked) {
				x.className = 'wrap_item wrap_sel';
				document.speedlist_add(id, 'speedlist_sel');
			} else {
				document.speedlist_remove(id, 'speedlist_sel');
				x.className = 'wrap_item';
			}
		};
		sel.addEvents({'click':ev_handler, 'change':ev_handler});

		x.getElement('a[name=remove]').addEvent('click', function(e) {
			(new Event(e)).stop();
			document.speedlist_remove(id);
			$('g_playlist').removeChild(x);
			document.location.reload();
		});
	});

	document.speedlist_add(-1); // this updates the counter on domready
	//alert(p);
}


function init_playlist() {
}


function playlist_add(id, values, name) { // if id is 0 a new playlist will be created, if values is not set speedlist will be added
	if(!values)
		values = Cookie.read('speedlist_sel');
	if(!name)
		name = '';
	new Request({
		method: 'post',
		url: '/ajax/playlist?action=' + (id ? 'add' : 'create'),
		onSuccess: function(r) {
			if(r)
				alert(r);
			else
				window.location.reload();
		},
		oFailure: function() {
			alert('Error: connection lost');
		}
	}).post({'xsrf':Cookie.read('an_sid'), 'id':id, 'name':name, 'values':values});
}


function playlist_delete(id, cf) {
	if(cf && !confirm(cf))
		return false;

	new Request({
		method: 'post',
		url: '/ajax/playlist?action=delete',
		onSuccess: function(r) {
			if(r)
				alert(r);
			else
				window.location.reload();
		},
		oFailure: function() {
			alert('Error: connection lost');
		}
	}).post({'xsrf':Cookie.read('an_sid'), 'id':id});
	return false;
}

function playlist_del_item(id, lid, cf) {
	if(cf && !confirm(cf))
		return false;

	new Request({
		method: 'post',
		url: '/ajax/playlist?action=del_item',
		onSuccess: function(r) {
			if(r)
				alert(r);
			else
				window.location.reload();
		},
		oFailure: function() {
			alert('Error: connection lost');
		}
	}).post({'xsrf':Cookie.read('an_sid'), 'id':id, 'lid':lid});
	return false;
}


function open_mplayer(id, p, t) {
	try {
	if(t)
		t.blur();
	} catch(e) {debug_log(e)}
	window.open(
		"/ajax/mplayer?id="+escape(id)+'&p='+escape(p),
		"_blank",
		"width=515, height=312, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes"
	);
	return false;
}


function init_menutoggle() {
	$$('.mtoggle').each(function(x) {
		var idl;
		if(!x.id || !(idl = $('toggle_' + x.id)))
			return;
		var fx = new Fx.Slide(x);
		fx.hide();
		var is_hidden = 1;
		idl.innerHTML = MSG.js_script_toggle_more;
		idl.addEvent('click', function(e) {
			(new Event(e)).stop();
			if(is_hidden) {
				idl.innerHTML = MSG.js_script_toggle_less;
				fx.slideIn();
			} else {
				idl.innerHTML = MSG.js_script_toggle_more;
				fx.slideOut();
			}
			is_hidden ^= 1;
		});
	});
}


function init_xloader() {
	var visible = false;
	document.xloader_show = function(e) {
		if(e) {
			try {
				$('xloader').style.top = (e.page.y + 20) + 'px';
				$('xloader').style.position = 'absolute';
			} catch(e) {}
		} else {
			$('xloader').style.position = 'fixed';
			$('xloader').style.top = '0px';
		}
		$('xloader').style.display = 'block';
		visible = true;
	}
	document.xloader_hide = function() {
		$('xloader').style.display = 'none';
		visible = false;
	}
}


function init_ajaxnav() {
	var lnk = $$('.video_list');
	if(!lnk || !lnk.length)
		return;

	document.vlist_navigate = function(h, e) {
			document.xloader_show(e);
			$$('.video_list')[0].setStyles({'opacity':0.5});
			url = document.location.href.replace(/(\?.*|#.*)$/g, '');
			url = url + '?' + h.hex2str();
			url += /\?.*$/.test(url) ? '&ajax[]=main.video_list' : '?ajax[]=main.video_list';
			document.location.href = '#$' + h;
			//alert(url)
			new Request.JSON({
				//url: /\?.*$/.test(x.href) ? x.href+'&ajax[]=main.video_list' : x.href+'?ajax[]=main.video_list',
				url: url,
				onComplete: function(jsonObj, text) {
					try {
						setTimeout(function() {
							$$('.video_list')[0].setStyles({'opacity':1});
							document.xloader_hide();
						}, 500);
						var list = $$('.video_list')[0];
						//list.clear();
						list.innerHTML = jsonObj['main.video_list'].match(/^\s*\<div class="video_list"\>\s*(.+)\s*\<\/div\>\s*$/)[1];
						init_speedlist();
						init_videolist_rating();
						init_ajaxnav();
						setTimeout(function() {
							init_preview2();
						}, 200);
					} catch(e) {debug_log("ajaxnav: " + e)}
				},
				oFailure: function() {
					$$('.video_list')[0].setStyles({'opacity':1});
					document.xloader_hide();
					alert('Error');
				}
			}).send();
	}



	if(!document.axnav) {
		document.axnav = {
			href: '',
			tick: function() {
				var anchor = document.location.href.match(/#\$([0-9a-f]+)$/);
				/*if(!anchor || !(anchor=anchor[1]))
					anchor = '';*/
				if(!anchor || !(anchor=anchor[1])) {
					anchor = /\?/.test(document.location.href) ? document.location.href.replace(/^.*\?|#.*$/g, '') : '';
					anchor = anchor.str2hex();
					if(!this.href)
						anchor = '';
				}
				if(anchor == this.href)
					return;
				this.href = anchor;
				document.vlist_navigate(anchor);
			},
			init: function() {
				var anchor = document.location.href.match(/#\$([0-9a-f]+)$/);
				if(!anchor || !(anchor=anchor[1]))
					anchor = '';
				this.href = anchor;
				if(anchor)
					document.vlist_navigate(anchor);
				setInterval(function() {
					document.axnav.tick();
				}, 200);
			}
		}
		document.axnav.init();
	}



	lnk = $$('.video_list a.s', '.video_list ul.gl_main li a', '.video_list ul li.user a', '.video_list div.users p a');
	lnk.each(function(x) {
		x.addEvent('click', function(e) {
			try {
			(new Event(e)).stop();
			var m = x.href.match(/\?(.*)$/);
			if(!m || !(m = m[1]))
				m = '';
			document.axnav.href = m.str2hex();
			document.vlist_navigate(document.axnav.href, e);
			} catch(e) {debug_log(e)}
		});
	});
}



function init_preload_images() {
	var images = ['/images/messagebox_info.png', '/images/splistbg.png'];
	for(i=0; i < images.length; i++)
		try {(new Image).src = images[i];} catch(e) {debug_log(e)}
}


function init_suggested_covers() {
	if(!$('suggested_covers'))
		return;

	var update_click = function(remove_ev) {
		$$('#suggested_covers img').each(function(a){
			a.removeEvents('click');
			if(remove_ev)
				return;
			a.addEvent('click',function(e){
				try {
				$$('.ul-s2-cover img').getLast().set('src',this.get('src'));
				$('upload_iv_suggested').set('value',this.get('src'));
				$('upload_iv_album').set('value',this.get('rel'));
				} catch(e) {debug_log(e)}
			});
		});
	}

	var req = null;
	var show_suggestions = function(show) {
		$('suggested_covers').empty();
		if(!show) {
			try{req.cancel();} catch(e) {};
			return;
		}

		var artist = $('upload_iv_artist').value;
		var album = $('upload_iv_album').value;
		update_click(true);
		(new Element('img', {'src':'/images/loading3.gif', 'alt':'Loading...', 'style':'height:31px;width:31px;cursor:default;'})).inject($('suggested_covers'), 'bottom');
		req = new Request.JSON({
			url: '/ajax/suggested_covers',
			onComplete: function(jsonObj, text) {
				try {
					$('suggested_covers').empty();
					if(jsonObj.length)
						for(i=0; i < jsonObj.length; i++) {
							var cover = jsonObj[i];
							(new Element('img', {'alt':cover.artist+' : '+cover.album+' ('+cover.year+')', 'src':cover.cover, 'title':cover.artist+' : '+cover.album+' ('+cover.year+')', 'rel':cover.album})).inject($('suggested_covers'), 'bottom');
						}
					else
						(new Element('p', {text:MSG.js_script_suggestions_none})).inject($('suggested_covers'), 'bottom');
					update_click();
				} catch(e) {debug_log(e)}
			},
			oFailure: function() {
			}
		});
		req.post({'artist':artist, 'album':album, 'xsrf':Cookie.read('an_sid')});
	}

	//(new Element('input', {'type':'button', 'id':'suggested_toggle_button', 'value':''})).inject($('suggested_toggle_button_wrap'), 'bottom');
	var status = /[?&]upload=1[^?]*$/.test(document.location.href) ? 1 : 0;
	show_suggestions(status);
	$('suggested_toggle_button').value = MSG.js_script_suggestions_togglebutton[status];
	$('suggested_toggle_button').addEvent('click', function() {
		status ^= 1;
		show_suggestions(status);
		$('suggested_toggle_button').value = MSG.js_script_suggestions_togglebutton[status];
	});
}



function init_audio_list() {
	if(!$$('.audio_list').length)
		return;
	var songoftheday = audio_of_the_day.id;
	var ids = [];
	var id_list = [];

	var player = new function() {
		var req = null; // private property
		var this2 = this;
		var nowpl = false; // now playing

		this.updatePlayer = function(jsonObj, text) {
			try {
				if(jsonObj.type != 'mp3')
					return;
				jsonObj.fpconfig.playlist.each(function(x, i) {
					if(x.url.match(/audio(?:\/[a-f0-9]{2}){4}\/[a-f0-9]+\.mp3(?:\?.*)?$/)) {
						jsonObj.fpconfig.playlist[i].onPause = function() {
							onPause({id:jsonObj.id});
						}
						jsonObj.fpconfig.playlist[i].onResume = function() {
							onResume({id:jsonObj.id});
						}
						jsonObj.fpconfig.playlist[i].onFinish = function() {
							onClipDone({id:jsonObj.id});
						}
						nowpl = jsonObj.id;
					}
				});
				//print_r(audio_of_the_day.fpconfig)
				$f('audio_player', '/script/flowplayer-3.1.1.swf?v='+MSG.lastupdate, jsonObj.fpconfig).load().play();
				pl = {name:'id = '+nowpl, url:jsonObj.file_url, allowResize:'true'};
				if(jsonObj.cover_url)
					pl.overlay = jsonObj.cover_url;
				if(pl.url) {
					//$('audio_player').playClip(pl);
					//$('audio_player').fp_play(pl);
					//$f(0).play();
					//alert($('audio_player').getInterface().fp_play);
					//var tmp=[]; for(var i in $('audio_player')) if(!document.body[i]) tmp.push(i); alert(tmp.join(' '));
				}
				//print_r(pl);
				$('ap_link').href = jsonObj.link;
				var title = '';
				if(jsonObj.artist && jsonObj.title)
					title = jsonObj.artist + ' - ' + jsonObj.title;
				else if(jsonObj.name && !jsonObj.title)
					title = jsonObj.name;
				else
					title = jsonObj.title;
				//print_r(jsonObj);
				$('ap_link').innerHTML = title;
				$('ap_description').innerHTML = jsonObj.description ? jsonObj.description : '';
				$('ap_album').innerHTML = jsonObj.album ? jsonObj.album : '';
				$('ap_album').getParent('li').style.display = jsonObj.album.trim() ? 'block' : 'none';
				$('ap_description').getParent('li').style.display = jsonObj.description.trim() ? 'block' : 'none';
				$('r_grade').getParent('li').style.display = 'block';
				$('r_grade').innerHTML = jsonObj.grade;
				$('r_grade').title = jsonObj.id;
				$('r_votes').innerHTML = jsonObj.votes;
				$('r_views').innerHTML = jsonObj.views;
				if(pl.url)
					$('audio_player_title').innerHTML = nowpl==songoftheday ? MSG.js_script_player_songoftheday_title : MSG.js_script_player_title;

				init_rating();
				if(jsonObj.embed) { // for the audio of the day it will be undefined
					$('embed_code_text').value = jsonObj.embed;
					update_embed();
				}

			} catch(e) {debug_log(e)}
		}

		this.play = function(id) { // public method
			try {req.cancel();} catch(e) {}
			if(ids[id])
				ids[id].getParent('tr').addClass('nowplaying');
			if(nowpl && nowpl != id && ids[nowpl])
				ids[nowpl].getParent('tr').removeClass('nowplaying').removeClass('paused');
			else if(nowpl == id) {
				if($f(0).isPaused()) {
					$f(0).play();
					ids[id].getParent('tr').removeClass('paused');
				} else {
					$f(0).pause();
					ids[id].getParent('tr').addClass('paused');
				}
				return;
			}
			nowpl = id;
			req = new Request.JSON({
				url: '/ajax/media-info?id=' + escape(id),
				method: 'get',
				onComplete: function(jsonObj, text) {
					this2.updatePlayer(jsonObj, text);
				},
				oFailure: function() {
				}
			});
			req.send();
		};

		/*setTimeout(function() {
			//try{$f(0).onPause = onPause;} catch(e) {debug_log(e)}
			try {
				$f(0).getCommonClip().onPause = function() {
					alert(123)
				}
			} catch(e) {debug_log(e)}
		}, 1000);*/
		onPause = function(clip) {
			//var cid = clip.name.match(/^id = ([0-9]+)$/)[1];
			var cid = nowpl;
			ids[cid].getParent('tr').addClass('paused');
		}
		onResume = function(clip) {
			//var cid = clip.name.match(/^id = ([0-9]+)$/)[1];
			var cid = nowpl;
			ids[cid].getParent('tr').removeClass('paused');
		}
		onClipDone = function(clip) {
			//var cid = clip.name.match(/^id = ([0-9]+)$/)[1];
			var cid = nowpl;
			var i = id_list.get_index(cid);
			if(i < 0)
				//return;
				i = -1;
			i = id_list[(parseInt(i)+1) % id_list.length];
			if(i == nowpl) {
				ids[cid].getParent('tr').removeClass('nowplaying');
				return;
			}
			this2.play(i);
		}

		this.pause = function() {
		};
		onPlay = function(clip) {
			try {
				//if(clip.type != 'mp3')
				//	return;
				//var cid = clip.name.match(/^id = ([0-9]+)$/)[1];
				var cid = nowpl;
				if(!cid)
					return;
				//if(cid == audio_of_the_day.id)
				//	player.play(cid);
				onPlay = function() {}; // a function that overwrites itself :D
			} catch(e) {debug_log(e)}
		}
	};

	$$('.audio_list td.corner a.p').each(function(x) {
		var id = x.href.match(/\/audio\/play\/([0-9]+)\//)[1];
		ids[id] = x;
		id_list.push(id);
		x.addEvent('click', function(e) {
			(new Event(e)).stop();
			player.play(id);
			//alert(id + ': ' + document.speedlist_contains(id));
		});
		x.getParent('tr').addEvent('click', function() {
			player.play(id);
			return false;
		});
		x.getParent('tr').getElements('a.l').each(function(y) {
			y.addEvent('click', function(e) {
				(new Event(e)).stop();
				document.location = y.href;
			});
		});
	});

	audio_of_the_day.type = 'mp3';
	//print_r(audio_of_the_day);
	try {player.updatePlayer(audio_of_the_day);} catch(e) {alert(e)} // audio_of_the_day is defined inline in HTML
}


function init_videolist_rating() {
	$$('.video_list div.details .d_rating').each(function(x) {
		x.empty();
		var i;
		for(i=0; i < 5; i++)
			(new Element('span', {'class':'n'})).inject(x, 'bottom');
		//x.set('class', 'd_rating2');
		add_rating({
			id: x,
			grade: x.get('title'),
			onclick: function(vote, e) {
				sid = x.getParent('.inner_image').getElement('a.lnk').get('href').match(/\/([0-9]+)\/?$/)[1];
				//alert(sid); return;
				(new Event(e)).stop();
				if(!sid)
					return;
				document.xloader_show(e);
				var event = e;
				new Request.JSON({
					url: '/ajax/vote',
					onComplete: function(jsonObj) {
						try {
							if(jsonObj && jsonObj.votes > -1 && jsonObj.grade > -1 && jsonObj.views > -1) {
							//	$('r_votes').innerHTML = jsonObj.votes;
								x.set('title', jsonObj.grade);
							//	$('r_views').innerHTML = jsonObj.views;
							//	init_rating();
							}
							document.xloader_hide();
							init_videolist_rating();

							if(jsonObj.response)
								tooltip_show(jsonObj.response, event);
						} catch(e) {debug_log(e)}
					},
					onFailure: function() {
						tooltip_show('Sorry, could not connect, please check your network connection.');
						document.xloader_hide();
					}
				}).post({'xsrf':Cookie.read('an_sid'), 'sid':sid, 'vote':vote});
			}
		});
	});
}


function init_comment() {
	var form = $('comments_form');
	if(!form)
		return;
	form.removeEvents('submit');

	form.addEvent('submit', function(e) {
		(new Event(e)).stop();
		var event = e;
		var p = {};
		form.getElements('[name]').each(function(x) {
			if(x.name)
				p[x.name] = x.value;
		});
		p.ajax_powered = 1;
		//print_r(p); return;
		document.xloader_show(event);
		new Request.JSON({
			url: '/ajax/vote?t=addcomment',
			onComplete: function(jsonObj) {
				if(jsonObj.error) {
					reload_captcha();
					document.xloader_hide();
					alert(jsonObj.error);
					return;
				}
				new Request.JSON({
					url: '/video/-/' + p.sid + '/?ajax[]=main.center_tab.comments&ajax[]=main.center_tab.comments_button',
					method: 'get',
					onComplete: function(jsonObj) {
						document.xloader_hide();
						try {$('comment').empty(); $('comment').innerHTML = jsonObj['main.center_tab.comments'].replace(/^(\<div[^\>]*\>\s*){2}|(\<\/div\>\s*){2}$/g, '');} catch(e) {debug_log("x2: " + e)}
						try {
							var tmp = null;
							tmp = $$('#tab_buttons span');
							tmp = tmp[1] ? tmp[1] : tmp[0];
							tmp.empty();
							tmp.innerHTML = jsonObj['main.center_tab.comments_button'].match(/\<span\>([^\<\>]+)\<\/span\>/)[1];
						} catch(e) {debug_log("x3: " + e)}
						try {init_comment();} catch(e) {debug_log(e)}
						new Fx.Scroll(window, {duration:700}).toElement($('tab_buttons'));
						setTimeout(function() {
							var c = $$('#comment ul li')[0];
							c.addClass('justadded');
							setTimeout(function() {
								if(c = $(c))
									c.removeClass('justadded');
							}, 2500);
						}, 200);
					}
				}).send();
			},
			onFailure: function() {
				tooltip_show('Sorry, could not connect, please check your network connection.');
			}
		}).post(p);
	});
}



function _set_view(id, w) {
	try {
	id = $(id);
	var links = id.getParent('div').getElements('a');
	links.each(function(x) {
		x.set('class', x.get('class').replace(/view_s_([0-9]+)/, 'view_$1'));
	});

	id.className = 'viewlink view_s_'+w;
	id.blur();
	$$('.video_list .inner_image').each(function(x,i) {
		x.getParent('div').className = (w==1 || (w==2 && i < 3) ? 'wrap_image2' : 'wrap_image'); // somehow this breaks the voting
	});
	setTimeout(function() {
		init_videolist_rating();
	}, 10);
	Cookie.write('_video_view', w, {duration:365, path:'/', domain:'.'+TLD});
	} catch(e) {debug_log(e);}
	return false;
}


function set_fp_crop(player, start, end) {
	onPlay = function(clip) {
		if(!clip || clip.type!='flv')
			return;
		try {
			//print_r(clip);
			/*var i=0, oInt = setInterval(function() {
				if(i++ > 30 || player.getTime()>0) {
					clearInterval(oInt);
					return;
				}
				player.Seek(start);
				if(i==9) {
					player.DoPlay();
					alert('seek:' + start + ' ' + player.getTime());
				}
			}, 100); // workaround // ::Seek() is buggy
			*/
			//setTimeout(function() {
			//	alert(player.getTime());
			//}, 200);
		} catch(e) {debug_log(e)}
	}
	onCuePoint = function(cuePoint) {
		print_r(cuePoint);
	}
	//player.Seek(start);
	//player.addCuePoints({name:'end', time:'end', parameters:{test:123}});
}


function init_crop() {
	if(!$('uploadfile') || !$('uploadfile').hasClass('crop'))
		return;
	//print_r(cropped_clip);
	new Asset.css('/script/slider/slider.css', {});
	var label = {
		min: $$('.slide_container .pm.min p')[0],
		max: $$('.slide_container .pm.max p')[0],
		button: [
			$$('.slide_container .pm.min span.minus')[0],
			$$('.slide_container .pm.min span.plus')[0],
			$$('.slide_container .pm.max span.minus')[0],
			$$('.slide_container .pm.max span.plus')[0]
		]
	};
	var format_seconds = function(pos) {
		return pos*5;
		return pos%10 ? pos/10 : (pos/10 + '.0');
	};
	(cropped_clip.init_min==0 ? label.button[0].addClass('end') : label.button[0].removeClass('end'));
	(cropped_clip.init_max==cropped_clip.limit ? label.button[3].addClass('end') : label.button[3].removeClass('end'));
	var mySlideA = new Slider($('slider_minmax_gutter_m'), $('slider_minmax_minKnobA'), $('slider_bkg_img'), {
		start: 0,
		end: cropped_clip.limit,
		//offset: 8,
		offset: 10,
		//tweak: 341,
		tweak: Browser.Engine.trident ? 0 : 391, // IE fix
		snap: false,
		onChange: function(pos) {
			if(pos.minpos==0 && cropped_clip.min>0)
				label.button[0].addClass('end');
			else if(pos.minpos>0 && cropped_clip.min==0)
				label.button[0].removeClass('end');
			if(pos.maxpos==cropped_clip.limit && cropped_clip.max<cropped_clip.limit)
				label.button[3].addClass('end');
			else if(pos.maxpos<cropped_clip.limit && cropped_clip.max==cropped_clip.limit)
				label.button[3].removeClass('end');
			cropped_clip.min = pos.minpos;
			cropped_clip.max = pos.maxpos;
			label.min.innerHTML = MSG.js_script_crop_start.replace(/@sec/g, format_seconds(pos.minpos));
			label.max.innerHTML = MSG.js_script_crop_end.replace(/@sec/g, format_seconds(cropped_clip.limit-pos.maxpos));
		}
	}, $('slider_minmax_maxKnobA')).setMin(cropped_clip.init_min).setMax(cropped_clip.init_max);


	var oTimeout=0, oInterv=0;
	var clear = function() {
		try {clearTimeout(oTimeout)} catch(e) {}
		try {clearInterval(oInterv)} catch(e) {}
		oTimeout=0; oInterv=0;
	}
	label.button.each(function(x, i) {
		var click = function() {
			if(i < 2) {
				if(i==0 && cropped_clip.min>0)
					mySlideA.setMin(cropped_clip.min-1);
				else if(i==1 && cropped_clip.min<cropped_clip.max)
					mySlideA.setMin(cropped_clip.min+1);
				mySlideA.setMax(cropped_clip.max); // bug workaround
			} else {
				if(i==2 && cropped_clip.min<cropped_clip.max)
					mySlideA.setMax(cropped_clip.max-1);
				else if(i==3 && cropped_clip.max<cropped_clip.limit)
					mySlideA.setMax(cropped_clip.max+1);
			}
		}
		x.addEvents({
			'click': function(e) {
				(new Event(e)).stop();
				click();
			},
			'mousedown': function() {
				oTimeout = setTimeout(function() {
					oInterv = setInterval(function() {
						click();
					}, 50);
				}, 300);
			},
			'mouseup': function() {
				clear();
			},
			'mouseout': function() {
				clear();
			}
		});
	});


	var player = $('cplayer');
	//set_fp_crop(player, 10, 20);
	$f('fp_holder',  '/script/flowplayer-3.1.1.swf', {
		clip: {
			url: cropped_clip.url.replace(/start=[0-9.]+/, 'start='+cropped_clip.min*5).replace(/end=[0-9.]+/, 'end=' + ((cropped_clip.len - 5*(cropped_clip.limit - cropped_clip.max)))),

			scaling: 'fit',
			seekableOnBegin: true,
			onStart: function() {
				this.seek(parseInt(cropped_clip.min/10));
				//alert(parseInt(cropped_clip.min/10));
			}
		},
		plugins: {
			/*h264streaming: {
				url: '/script/flowplayer.h264streaming-3.0.5.swf'
			}//*/
			/*,
			controls: {
				url: '/script/flowplayer.controls-3.1.1.swf',
				play: false,
				fullscreen: true,
				scrubber: true
			}//*/
		},
		logo: {
			url: '/images/alert.png',
			fullscreenOnly: false,
			displayTime: 10
		},

		onLoad: function() {
			//$f('fp_holder').startBuffering();
			//$f('fp_holder').play();
		}
	}).load();

	$('crop_test').onclick = function() {

		//$f('fp_holder').play();
		//$f('fp_holder').play();
		/*$f('fp_holder').stop();
		$f('fp_holder').play({
			url: cropped_clip.url.replace(/start=[0-9.]+/, 'start='+cropped_clip.min*5).replace(/end=[0-9.]+/, 'end=' + ((cropped_clip.len - 5*(cropped_clip.limit - cropped_clip.max)))),
			//start: cropped_clip.min/10,
			//duration: cropped_clip.max/10,
			scaling: 'fit',
			seekableOnBegin: true,
			autoBuffering: true
		});*/
		$f('fp_holder',  '/script/flowplayer-3.1.1.swf', {
			clip: {
				url: cropped_clip.url.replace(/start=[0-9.]+/, 'start='+cropped_clip.min*5).replace(/end=[0-9.]+/, 'end=' + ((cropped_clip.len - 5*(cropped_clip.limit - cropped_clip.max)))),

				scaling: 'fit',
				seekableOnBegin: true,
				onStart: function() {
					this.seek(parseInt(cropped_clip.min/10));
					//alert(parseInt(cropped_clip.min/10));
				}
			},
			plugins: {
				/*h264streaming: {
					url: '/script/flowplayer.h264streaming-3.0.5.swf'
				}//*/
				/*,
				controls: {
					url: '/script/flowplayer.controls-3.1.1.swf',
					play: false,
					fullscreen: true,
					scrubber: true
				}//*/
			},
			logo: {
				url: '/images/alert.png',
				fullscreenOnly: false,
				displayTime: 10
			},

			onLoad: function() {
				//$f('fp_holder').startBuffering();
				//$f('fp_holder').play();
			}
		}).load();
		//$f('fp_holder').seek(cropped_clip.min/10);

		//$f('fp_holder').seek(20);
		//cropped_clip.start=30;
		//cropped_clip.duration=25;

		//player.playClip(cropped_clip);
		//player.Pause();
		//player.Seek(5);
		//player.DoPlay();
		//set_fp_crop(player, 10, 20);
	}
	$('crop_restore').onclick = function() {
		new Request({
			url: '/crop-file?id=' + escape(cropped_clip.id),
			method: 'post',
			encoding: 'utf-8',
			onSuccess: function(rh) {
				if(rh != 'ok')
					alert(rh.length < 1024 ? rh : 'Error');
				else
					window.location = '/user';
			},
			oFailure: function() {
				alert('Error');
			}
		}).post({'action':'update_crop', 'xsrf':Cookie.read('an_sid'), 'crop_s':0, 'crop_e':0});
	};
	//mySlideA.setMax(3);
	$('crop_update').onclick = function() {
		new Request({
			url: '/crop-file?id=' + escape(cropped_clip.id),
			method: 'post',
			encoding: 'utf-8',
			onSuccess: function(rh) {
				if(rh != 'ok')
					alert(rh.length < 1024 ? rh : 'Error');
				else
					window.location = '/user';
			},
			oFailure: function() {
				alert('Error');
			}
		}).post({'action':'update_crop', 'xsrf':Cookie.read('an_sid'), 'crop_s':cropped_clip.min*5, 'crop_e':(cropped_clip.limit-cropped_clip.max)*5});
	}
}


window.addEvent('domready', function() {
	try {
		document.video_pw = {dirs:'abc', oInterv:null, i:0, id:null, sw:function() {
			document.video_pw.id.src = document.video_pw.id.src.replace(/\/shot\/[a-c]+\//, '/shot/' + document.video_pw.dirs.charAt(document.video_pw.i) + '/');
			document.video_pw.i++; document.video_pw.i %= document.video_pw.dirs.length;
		}};
		if(document.fp_is_half_loaded) {
			document.fp_is_loaded = true;
			fp_onload();
		} else
			document.fp_is_half_loaded = true;
	} catch(e) {debug_log(e)}

	try {init_lib();} catch(e) {debug_log(e)}
	try {init_flash_check();} catch(e) {debug_log(e)}
	try {init_xloader();} catch(e) {debug_log(e)}
	//try {check_upload();} catch(e) {debug_log(e)}  // OBSOLETE
	try {init_tab_buttons();} catch(e) {debug_log(e)}
	try {init_preview();} catch(e) {debug_log(e)}
	try {init_preview2();} catch(e) {debug_log(e)}
	try {init_preview3();} catch(e) {debug_log(e)}
	try {init_menutoggle();} catch(e) {debug_log(e)}
	try {init_rmenu();} catch(e) {debug_log(e)}
	try {init_search();} catch(e) {debug_log('init_search: '+e)}
	//try {init_sort();} catch(e) {debug_log(e)} // OBSOLETE
	// try {init_login();} catch(e) {debug_log(e)} // OBSOLETE
	try {init_login2();} catch(e) {debug_log(e)}
	try {init_rating();} catch(e) {debug_log('init_rating: '+e)}
	try {init_embed();} catch(e) {debug_log(e)}
	try {init_fxscroll();} catch(e) {debug_log(e)}
	//try {init_upload();} catch(e) {debug_log(e)} // OBSOLETE
	try {init_upload_file();} catch(e) {debug_log(e)}
	try {init_speedlist();} catch(e) {debug_log(e)}
	try {init_playlist();} catch(e) {debug_log(e)}
	try {init_ajaxnav();} catch(e) {debug_log(e)}
	try {init_preload_images();} catch(e) {debug_log(e)}
	try {init_suggested_covers();} catch(e) {debug_log(e)}
	try {init_audio_list();} catch(e) {debug_log(e)}
	try {init_videolist_rating();} catch(e) {debug_log(e)}
	try {init_comment();} catch(e) {debug_log(e)}
	try {init_crop();} catch(e) {debug_log(e)} // called from fp_onload()
});


function reply_comment(id) {
	try {
		/*oForm = document.getElementById('comments_form');
		if(id == 0)
			oForm.style.display = (oForm.style.display == 'block') ? 'none' : 'block';
		else
			oForm.style.display = 'block';*/
		try{document.getElementById('reply_id').value = id;} catch(e) {}
	} catch(e) {debug_log(e);}
}
