var stv = {}

stv.state = {}
stv.state.exit = false;
stv.state.lso = false;
stv.state.loading = false;
stv.state.db = false;
stv.state.postdata = false;

stv.dump = function(o) {
	var tx = '<table width="100">';
	var props = new Array();
	for (var i in o) { props.push(i); }
	props.sort();
	for (var i=0; i<props.length; i++) {
		tx += '<tr><td>' + props[i] + '</td><td>' + o[props[i]] + '</td></tr>';
	}
	tx += '</table>';
	document.write(tx);
}

stv.v = function() {
}

stv.f = function() {
	return false;
}

stv.see = function(s) {
	window.open(s);
}

stv.language = function() {                                                                                                                                                                                                                                                                                                 
	if (document.body && document.body.parentElement && document.body.parentElement.lang) ret = document.body.parentElement.lang;
	else if (location.pathname && location.pathname.length > 3) ret = location.pathname.substring(1, 3);
	else ret = 'en';                                                                                                                                                                                                                                                                                                    
	return ret;
}

stv.alert = function(h, m, t) {
	if (t) {
		jQuery.noticeAdd({
			title: h,
			text: m,
			stayTime: t * 1000
		});
	} else {
		jQuery.noticeAdd({
			title: h,
			text: m
		});
	}
}

stv.tip = function(o, t, w) {
	$(document).ready(function() {
		$(o).tooltip({
			track: true,
			delay: 0,
			showURL: false,
			fixPNG: true,
			showBody: " - ",
			extraClass: "stv-pop",
			fade: 150,
			bodyHandler: function() {
				if (w) t = '<div style="width:' + w + 'px">' + t + '</div>';
				return t;
			}
		});
	});
}

stv.vid = function(o, v) {
	$(document).ready(function() {
		if (v) {
			if (document.domain.match('heiss.tv')) {
				v.key = '#@89695c417d3ea2b0ab1';
			} else {
				v.key = '#@1af9ae84b511636220c';
			}
		}
		$f(o, {
			src: '/flowplayer/flowplayer-3.1.5.swf',
			width: 640,
			height: 506
		}, v);
	});
}

stv.hook = {}
stv.hook.exit = function() {
	$('a').each(function(i, e) {
		$(e).click(function() {
			stv.state.exit = true;
		});
	});

	$('form').each(function(i, e) {
		$(e).submit(function() {
			stv.state.exit = true;
		});
	});

	c = function() {
		if (!stv.state.exit) {
			stv.state.exit = true;
			window.location = "http://www.erotik.tv/entry/setup/1";
			return 'Klick auf Abbrechen um geile Videos von privaten Amateuren bei erotik.tv zu sehen!';
		}
	}

	window.onbeforeunload = c;
	window.onbeforeclose = c;
}

stv.lso = {}
stv.lso.init = function(l) {
	if (l) {
		stv.state.lso = l;
		$(document).ready(function() {
			$('<div/>').attr('id', 'stv-lso').prependTo('body');
			var lso = new SWFObject('/swf/stv.swf', 'stvlso', '5', '5', '7');
			lso.addParam('swLiveConnect', 'true');
			lso.addParam('allowScriptAccess', 'always');
			lso.write('stv-lso');
		});
	}
}

stv.lso.get = function() {
	return stv.state.lso;
}

stv.lso.set = function(lso) {
	if (lso) Cookie.set('lso', lso);
}

stv.formtip = function(o, h, t, c, w) {
	if (o && h) {
		$(document).ready(function() {
			if (!t) t = ['focus', 'blur'];
			if (!c) c = false;
			if (!w) w = 200;
			$(o).bt(h, {shadow: true, fill: '#e4e276', trigger: t, positions: ['right'], closeWhenOthersOpen: c, width: w});
		});
	}
}

stv.regtip = function(o, h, c) {
	if (o && h) {
		$(document).ready(function() {
			if (!c) c = '#e4e276';
			if (!$(o).attr('orig')) $(o).attr('orig', h);
			$(o).bt(h, {shadow: true, fill: c, trigger: ['focus', 'none'], positions: ['right'], closeWhenOthersOpen: true, width: 210});
		});
	}
}

stv.check = {}
stv.check.query = function(o, d) {
	if (o) {
		if (o.val().length > 0) {
			if (o.attr('last') != o.val()) {
				o.attr('last', o.val());
				$.post('/' + stv.language() + '/user/check/', d, function(data) {
					if (data) {
						if (data.ok) {
							stv.regtip('#' + $(o).attr('id'), data.ok, '#73D367');
						} else if (data.err) {
							stv.regtip('#' + $(o).attr('id'), data.err, 'red');
						} else {
							stv.regtip('#' + $(o).attr('id'), 'error!', 'red');
						}
					} else {
						stv.regtip('#' + $(o).attr('id'), 'error!', 'red');
					}
					o.btOn();
				},'json');
			}
		} else {
			stv.regtip('#' + $(o).attr('id'), o.attr('orig'));
			o.btOn();
		}
	}
}

stv.check.user = function(o) {
	stv.check.query(o, { user: o.val() })
}

stv.check.pass = function(o, u) {
	stv.check.query(o, { pass: o.val(), user: u.val() })
}

stv.check.pass2 = function(o, p) {
	stv.check.query(o, { pass: o.val(), pass2: p.val() })
}

stv.check.mail = function(o) {
	stv.check.query(o, { mail: o.val() })
}

stv.player = {}

stv.player.seek = function(o, time) {
//	if (streamInfo.stream_type == 'trailer' && time > 30) {
//		window.location.href = '/user/purchase/' + streamInfo.video_id
//		return false;
//	}
	if (document.getElementById('etv-i-video')) {
		$('#etv-i-video').attr('currentTime', time);
	} else {
//		state = flowplayer().getState();
		flowplayer().seek(time);
	}
}

stv.player.hideContent = function() {
	flowplayer().getPlugin("content").animate({width: 1, height: 1, opacity: 0}, 2000); 
}

stv.player.commentcalc = function(o) {
	var commentVal = $.trim($(o).val());
	commentVal = commentVal.replace(/\n+/g, ' ');
	commentVal = commentVal.replace(/(\.|,|\-)+/g, '');
	commentVal = commentVal.replace(/ +/g, ' ');
	if (commentVal.length == 0) {
		$('#stv-comment-count').html('');
		return { wc: 0, cc: 0 }
	} else {
		var commentWc = commentVal.split(' ').length;
		var commentCc = commentVal.replace(/ +/g, '').length;
		$('#stv-comment-count').html('<strong>' + commentWc + '</strong> ' + (commentWc == 1 ? 'Wort' : 'W&ouml;rter') + ', <strong>' + commentCc +'</strong> ' + (commentCc == 1 ? 'Zeichen' : 'Zeichen'));
		return { wc: commentWc, cc: commentCc }
	}
}

stv.player.setComment = function(vid, c, h) {
	if (c.val() == c.attr('stvcomment')) {
		$('#stv-comment-error').html('Bitte gebe zuerst Deinen Kommentar ein.');
	} else {
		var calc = stv.player.commentcalc(c);
		if (calc.wc > 50 && calc.cc > 250) {
			$('#stv-comment-error').html('<img src="/images/spinner.gif" height="25" width="25" />');
			$.post('/' + stv.language() + '/video/comment/', { id: vid, comment: c.val() }, function(data) {
				if (data && (data.ok || data.err)) {
					if (data.ok) {
						$('#stv-comment').animate({ height: 0 }, 750, 'swing', function() { $(this).removeClass('form').css('text-align','left').css('margin-top', '0').html('Vielen Dank f&uuml;r Deinen Kommentar.').animate({ height: '20px' }, 750) } ); 
					} else {
						$('#stv-comment-error').html(data.err);
					}
				} else {
					$('#stv-comment-error').html('Dein Kommentar konnte leider nicht gespeichert werden.');
				}
			},'json');
		} else {
			$('#stv-comment-error').html('Wir ben&ouml;tigen mindestens <strong>50 W&ouml;rter</strong> und <strong>250 Zeichen</strong>.');
		}
	}
}

stv.player.viewComment = function(c) {
	$('#comment-' + c).toggle('blind');
}

stv.player.setCategory = function(vid, c) {
	catText = $('#' + c + ' :selected').text();
	cat = $('#' + c);
	catVal = cat.val();
	p = cat.parent();

	stv.player.deleteCategory('#stv-category1', catVal);
	stv.player.deleteCategory('#stv-category2', catVal);
	stv.player.deleteCategory('#stv-category3', catVal);

	p.html('<img src="/images/spinner.gif" height="22" width="22" />').addClass('stv-category-save');
	$.post('/' + stv.language() + '/video/category/', { id: vid, cat: catVal }, function(data) {
		if (data && data.ok) {
			p.html(catText).addClass('stv-category-done');
			if ($('.stv-category').find('select').size() == 0 ) stv.player.hideContent();
			if (data.ok > 0) {
				$('.credits_display').effect('pulsate', { times: 3 }, 600);
				$('.credits_display').html('<span> ' + data.ok + ' <span class="units">Credits</span></span>');
			}
		} else {
			p.html('Fehler <strong>:-(</strong>');
		}
	},'json');
}

stv.player.deleteCategory = function(s, c) {
	$("#" + s + " option").each(function() {
		if ($(this).val() == c) $(this).remove();
	});
}

stv.player.scene = function(time) {
	if (stv.state.scroller) {
		time = time / 1000;
		$('.timecode').each(function(i,s) {
			if ($(s).hasClass('scene_' + time)) {
				$('#scroller').scrollable().click(i);
				return;
			}
		});
	}
}

stv.channel = function(c) {
	$('#chan_tab1').removeClass('selected');
	$('#chan_tab2').removeClass('selected');
	$('#chan_tab3').removeClass('selected');
	$('#chan_tab4').removeClass('selected');
	$('#chan_tab' + c).addClass('selected');
	$('#slider_container').scrollable().seekTo(c-1);
}

stv.focus = function(o) {
	$(document).ready(function() {
		if (o) $(o).focus();
	});
}

stv.popup = function(url) {
	var width = 800;
	var height = 600;
	var left = parseInt((screen.availWidth/2) - (width/2));
	var top = parseInt((screen.availHeight/2) - (height/2));
	window.open(url, 'pinwin', 'width=' + width + ',height=' + height + ',status,resizable,left=' + left + ',top=' + top + 'screenX=' + left + ',screenY=' + top);
}

stv.paymentpin = function() {
	$('#paymentpin_name').val($('#card_name').val());
	$('#paymentpin_account').val($('#card_account_number').val());
	$('#paymentpin_bank').val($('#card_bank_id').val());
	$('#paymentpin').submit();
}

stv.payment = function(f, p) {
	f = findForm(f);
	f.payment_type.value = p;
	$(f).submit();
}

stv.videorate = function() {
	$('#videorate').show();
}

stv.rate = function(vid, t, p) {

	r = 0;
	v = $('#stv-rating');
	if (p) v.show('pulsate', { times: 3 }, 600);
	else v.fadeIn();

	v.children('span').each(function(i, s) {
		$(s).attr('rateid', i);

		$(s).unbind('mouseover').mouseover(function () {
			v.children('span').each(function(ii, ss) {
				$(ss).removeClass();
				if (ii <= $(s).attr('rateid')) $(ss).addClass('stv-rating-over');
				else if ($(s).attr('ratedone') == 1) $(ss).addClass('stv-rating-done');
			});
		});

		$(s).unbind('mouseout').mouseout(function () {
			v.children('span').each(function(ii, ss) {
				if ($(s).attr('ratedone') == 1) $(ss).addClass('stv-rating-done');
				else $(ss).removeClass();
			});
		});

		$(s).unbind('click').click(function () {
			v.html('<img src="/images/spinner.gif" style="float:left" />');
			$.post('/' + stv.language() + '/video/rate/', { id: vid, rate: parseInt($(s).attr('rateid')) + 1 }, function(data) {
				if (data && data.ok) {
					v.html('<strong>' + t + '</strong>');
					if (data.ok > 0) {
						$('.credits_display').effect('pulsate', { times: 3 }, 600);
						$('.credits_display').html('<span> ' + data.ok + ' <span class="units">Credits</span></span>');
					}
				} else {
					v.html('Die Bewertung konnte leider nicht verarbeitet werden.<br />Bitte versuche es zu einem sp&auml;teren Zeitpunkt noch einmal.');
				}
			},'json');
		});
	});
}

stv.wrap = function(url) {
	if (navigator && navigator.userAgent && navigator.userAgent.match(/ipad/i)) {
		location.href = url;
	} else {
		if (navigator.onLine) {
			$('#content').empty().append($('<div />').css('margin-left', '50%').css('margin-top', '50px').append($('<img />').attr('src', '/images/spinner.gif').css('margin-left', '-15px')));
			if (stv.state.db && !url.match(/\/(user|payment|options)\//)) {
				function errorHandler(transaction, error) {
				}
				function nullDataHandler(transaction, results) {
				}
				stv.state.db.transaction(function(tx) {
					tx.executeSql('delete from history;', [], nullDataHandler, errorHandler);
					tx.executeSql('insert into history (url) values (?);', [url], nullDataHandler, errorHandler);
					window.status = "updated: " + url;
				});
			}
			if (document.getElementById('etv-hijack')) {
				$(window).unbind('scroll');
				$('#etv-hijack').load(url, stv.hijack);
			} else {
				location.href = '/i/app';
			}
		} else {
			alert("Leider konnte keine Internet Verbindung gefunden werden.");
			stv.wrap(url);
		}
	}
}

stv.pagebrowse = function(c, p) {
	url = '/' + stv.language() + '/video/browse_page/' + c + '?page=' + p;
	$('#etv-inject-spinner').addClass('etv-inject-spinning');
	p = $('<span />').load(url, stv.hijack);
	$('#etv-inject').before(p);
}

stv.hijack = function() {
	if (navigator && navigator.userAgent && navigator.userAgent.match(/ipad/i)) return true;
	$('form').unbind('submit').bind('submit', function(e) {
		e.preventDefault();
		stv.state.postdata = {}
		$(this).find('input').each(function(i, ii) {
			if ($(ii).attr('type') == 'text' || $(ii).attr('type') == 'password' || $(ii).attr('type') == 'hidden' || $(ii).attr('type') == 'email' || $(ii).attr('type') == 'tel') {
				stv.state.postdata[$(ii).attr('name')] = $(ii).val();
			} else if ($(ii).attr('type') == 'radio' || $(ii).attr('type') == 'checkbox') {
				if ($(ii).is(':checked')) stv.state.postdata[$(ii).attr('name')] = $(ii).val();
			}
		});
		$(this).find('select').each(function(i, ii) {
			stv.state.postdata[$(ii).attr('name')] = $(ii).val();
		});
		$('#content').empty().append($('<div />').css('margin-left', '50%').css('margin-top', '50px').append($('<img />').attr('src', '/images/spinner.gif').css('margin-left', '-15px')));
		$.post($(this).attr('action'), stv.state.postdata, function(data) {
			var i_store = $.cookie('i_store');
			if (i_store) {
				stv.saveauth(i_store);
			}
			data = $(data).filter(function() {
				return $(this).is('div')
			});
			$('#etv-hijack').html('<div id="wrapper">' + data.html() + '</div>');
			stv.hijack();
		});
	});
	$('a').unbind('click').bind('click', function(e) {
		if ($(this).attr('href').match(/^http/) || $(this).attr('href').match(/^\//)) {
			e.preventDefault();
			stv.wrap($(this).attr('href'));
			var i_store = $.cookie('i_store');
			if (i_store) {
				stv.saveauth(i_store);
			}
		}
	});

	stv.state.loading = false;
	$('#etv-inject-spinner').removeClass('etv-inject-spinning');
}

stv.saveauth = function(authdata) {
	if (stv.state.db && authdata) {
		function errorHandler(transaction, error) {
		}
		function nullDataHandler(transaction, results) {
		}
		stv.state.db.transaction(function(tx) {
			tx.executeSql('delete from auth;', [], nullDataHandler, errorHandler);
			tx.executeSql('insert into auth (data) values (?);', [authdata], nullDataHandler, errorHandler);
		});
	}
}

stv.initdb = function(wrapurl) {
	try {

		var etvloaded = false;
		function etv() {
			if (!etvloaded) {
				etvloaded = true;
				stv.wrap(wrapurl);
			}
		}

		if (window.openDatabase) {
			stv.state.db = openDatabase('Erotik.TV', '1.0', 'Erotik.TV', 65535);
			if (stv.state.db) {
				function errorHandler(transaction, error) {
				}

				function escapeHandler(transaction, error) {
					if (wrapurl) etv();
				}

				function nullDataHandler(transaction, results) {
				}

				function urlHandler(transaction, results) {
					if (results.rows.length == 1 && results.rows.item(0)['url']) wrapurl = results.rows.item(0)['url'];
				}

				function authHandler(transaction, results) {
					if (results.rows.length == 1) {
						if (results.rows.item(0)['data']) {
							if (results.rows.item(0)['data'].length == 32) {
								$.cookie('_session_id', results.rows.item(0)['data'], { path: '/' });
							} else {
								$.cookie('i_store', results.rows.item(0)['data'], { path: '/', expires: 3650 });
							}
							if (wrapurl) etv();
						}
					} else {
						if (wrapurl) etv();
					}
				}

				stv.state.db.transaction(function(tx) {
					tx.executeSql('CREATE TABLE auth(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, data CHAR(32) NOT NULL);', [], nullDataHandler, errorHandler);
					tx.executeSql('CREATE TABLE history(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, pos integer NOT NULL default 0);', [], nullDataHandler, errorHandler);
				});

				if (wrapurl) {
					stv.state.db.transaction(function(tx) {
						tx.executeSql('select url from history order by id desc limit 1;', [], urlHandler, errorHandler);
					});
					stv.state.db.transaction(function(tx) {
						tx.executeSql('select data from auth;', [], authHandler, escapeHandler);
					});
				} else {
					var i_store = $.cookie('i_store');
					if (i_store) {
						stv.saveauth(i_store);
					}
				}
			}
		} else {
			if (wrapurl) etv();
		}
	} catch(e) {
		return;
	}
}

stv.overlay = {}
stv.overlay.open = function(o) {
	if (o) {
		$(document).ready(function() {
			window.setTimeout(function() { $(o).show('blind') }, 1000);
		});
	}
}

stv.overlay.close = function(o) {
	if (o) {
		$(o).parent().hide('blind');
	}
}

$.easing.etv = function (x, t, b, c, d) { 
	var s = 1.70158;  
	if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; 
	return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; 
}

function findForm(e) {
	var test = e
	while (test && test.tagName.toUpperCase() != 'FORM') {
		test = test.parentNode;
	}
	return test;
}

function linkSubmit(link) {
	form = findForm(link);
	$(form).submit();
}

