// This is a client based class to communicate with the remote search.
// stream, dl zusammen

var Vodsearch = Class.create();
Vodsearch.prototype = {
    initialize: function(container, options) { // searchId, filter
		options = options || {};

		this.container = $(container);

		this.vod_table = this.container.select('.vod-table').first();

		this.pager_disable = options.pager_disable;
		this.search_icon = options.search_icon;
		this.filmId = options.id;
		this.country = options.country;
		this.items_per_page = this.pager_disable ? 200 : 5;
		this.init_type = options.init_type || 'hilight';
		this.init_data = options.init_data;
		this.searchId = options.searchId;
		this.filter = options.filter;
		this.akaId = options.aka_id;

		this.ajaxRequestCount = 0;
		this.ajaxRequestCountMax = 10; // absolute max

		// this.onComplete = this.update.bindAsEventListener(this);
        // this.onAlertMeComplete = this.updateAlertMe.bindAsEventListener(this);

		if(this.vod_table.select('tbody tr').length) {
			if(this.update(this.vod_table.innerHTML.strip()))
				this.show_part();
		} else {
			this.ajaxRequest();
			//ajaxMergedLoad['film.view.vodsales.list'] = function(txt) {
			//	if(this.update(txt))
			//		this.show_part(this.init_type);
			//}.bind(this);
		}

		this.container.select('ul.options li').each(function(li, i) {
			li.observe('click', function(event) {
				this.show_part(li.readAttribute('type'), 0);
			}.bind(this));
		}, this);
	},

	ajaxRequest: function() {
		if(this.ajaxRequestCountMax < this.ajaxRequestCount)
			return;

		var url = '/search/ajax/vod/?id=' + encodeURIComponent(this.filmId) + '&country=' + this.country;
		if(this.filter)
			url += '&filter='+this.filter;
		if(this.akaId)
			url += '&aka_id='+this.akaId;

		url += '&refresh_count='+this.ajaxRequestCount;

		new Ajax.Request(url, {
				method: 'get',
				onComplete: function(transport) {
					// console.log('onComplete: ', { hi: transport.responseText}); // debug
					if(this.update(transport.responseText, true))
						this.show_part();
				}.bind(this),
				onInteractive: function(transport) {
					//var now = (new Date()).getTime();
					//if(! this._last_update) this._last_update = 0;
					//if(now - this._last_update < 2*1000)
					//	return;
					//this._last_update = now;

					// console.log('onInteractive: ', { hi: transport.responseText}); // debug
					if(this.update(transport.responseText))
						this.show_part();
				}.bind(this)
			}
		);
		this.ajaxRequestCount ++;
	},

	show_part: function(type, page_num) {
		if(typeof page_num == 'undefined')
			page_num = this.current_page || 0;

		var html = '<tbody>';
		var items = [];

		type = type || this.current_type || this.init_type || 'all';

		if(this.items_by_type[type]) {
			items = this.items_by_type[type];
		} else {
			throw new Error("type not found: " + type);
		}

		var pager_len = Math.ceil(items.length / this.items_per_page);

		this.current_type = this.current_type || type;
		this.current_page = page_num;

		// check if page_num - out of boundery
		if(page_num * this.items_per_page >= items.length)
			page_num = 0;

		for(var i = page_num * this.items_per_page; i < items.length && i < (page_num+1) * this.items_per_page; i++)
			html += items[i].html; //this.get_item_html(items[i]);

		html += '</tbody>';

		if(this.current_type != type) {
			this.container.select('ul.options li').each(function(li, i) {
				li.className = type == li.readAttribute('type') ? 'current' : '';
			}, this);
			this.current_type = type;
		}

		html += '<tfoot><tr><td colspan="5"><ul class="pager">';
		if(pager_len > 1) {
			html += '<li class="prev">&nbsp;</li>';
			for(var i = 0; i < pager_len; i++)
				html += '<li class="'+(i == page_num ? 'current' : '')+'"><span>'+(i+1)+'</span></li>';
			html += '<li class="next">&nbsp;</li>';
		}
		html += '</ul></td></tr></tfoot>';

		this.vod_table.update(html);
		var tbody = this.vod_table.select('tbody').first();
		var tfoot = this.vod_table.select('tfoot td').first();

		if(! this.tbody_min_height || this.tbody_min_height < tbody.getHeight())
			this.tbody_min_height = tbody.getHeight();

		var margin = this.tbody_min_height - tbody.getHeight();
		if(margin > 0) margin += 2;

		tfoot.setStyle({paddingTop: margin + 'px', verticalAlign: 'bottom'});

		this.container.select('ul.pager li').each(function(li, i) {
			li.observe('click', function(event) {
				var page = parseInt(li.innerHTML.replace(/<\/?\w+[^>]*>/g,''));
				page = isNaN(page)
					? (li.className == 'next' ? this.current_page + 1 : this.current_page - 1)
					: page - 1;

				if(page < pager_len && page >= 0)
					this.show_part(null, page);
			}.bind(this));
		}, this);
	},

	update: function(data, onComplete) {
		// console.log({html: data}); // debug
		this.items = this.items || [];
		this.items_by_type = {}; // discard prev. content, this.items_by_type || {};
		this.items_by_type.all = this.items_by_type.all || []; // \w hilight; this.items;
		this.items_by_type.dvd = this.items_by_type.dvd || [];
		this.items_by_type.dto = this.items_by_type.dto || [];
		//this.items_by_type.dtr = this.items_by_type.dtr || []; // grouped with dto, see bellow
		this.items_by_type.book = this.items_by_type.book || [];
		this.items_by_type.music = this.items_by_type.music || [];
		this.items_by_type.poster = this.items_by_type.poster || [];
		//this.items_by_type.bluray = this.items_by_type.bluray || []; // grouped with dvd, see bellow
		this.items_by_type.hilight = this.items_by_type.hilight || [];

		if(! data) return false;

		data = data.replace(/[\r\n]+/g, ' ');
		var data_status = data.match(/<status>.*?<\/status>/g);
		if(data_status)
			data_status = data_status[data_status.length-1].match(/<status>(.*?)<\/status>/);

		if(! data_status)
			throw new Error("update: no status in input data");

		data_status = data_status[1].evalJSON(true);

		if(data_status.complete && this.search_icon)
			this.search_icon.style.display='none';

		data_status.refresh = parseInt(data_status.refresh); // important
		// console.log(data_status); // debug

		if(data_status.status != 'ok') {
			this.vod_table.update('<tfoot><tr><td>'+data_status.status+'</td></tr></tfoot>');
			return false;
		}

		data = data.match(/<tr[^>]*type=[^>]*>(.+?)<\/tr><!--\/type-->/ig); // <tr.*?<\/tr> // [^>]* type="[^>"]*"[^>]*>

		data.each(function(item, i) {
			item = {html: item};
			item.sort_order = parseInt(item.html.replace(/^.*?<tr[^>]*? sort_order="([^>"]*)"[^>]*?>.*$/ig, '$1'));
			var item_type = item.html.replace(/^.*?<tr[^>]*? type="([^>"]*)"[^>]*?>.*$/ig, '$1');
			var type_push = item_type;
			this.items.push(item); // this.get_item_html(i, item);

			if(type_push == 'dtr') type_push = 'dto';
			if(type_push == 'bluray') type_push = 'dvd';

			if(type_push && this.items_by_type[type_push]) // item.type: dvd, ...
				this.items_by_type[type_push].push(item);
			if(type_push && type_push != 'hilight')
				this.items_by_type.all.push(item);
		}, this);

		for(var i in this.items_by_type) {
			var elm = this.items_by_type[i];
			elm.sort(function(a, b) {
				if(isNaN(a.sort_order) || isNaN(b.sort_order)) return 0;
				return a.sort_order > b.sort_order ? 1 : (a.sort_order < b.sort_order ? -1 : 0);
			});
		}

		this.container.select('ul.options li').each(function(li, i) {
			var type = li.readAttribute('type');
			if(type && this.items_by_type[type]) {
				li.select('span.number').first().innerHTML = '('+this.items_by_type[type].length+')';
			}
		}, this);

		if(data_status.status == 'ok' && data_status.refresh > -1 && onComplete)
			window.setTimeout(this.ajaxRequest.bind(this), data_status.refresh * 1000);

		return data_status;
	},

	sendAlertMe: function(form) {
		var $form = $(form);
		var submit = $($form.select('input[type=submit]').first());
		var email = $form.email.value;
		var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;

		if(! submit.readAttribute('value_org'))
			submit.writeAttribute('value_org', submit.value);

		if(submit.disabled)
			return;

		if(email=='')
			alert('Email Feld darf nicht leer sein!');
		else if(! pattern.test(email))
			alert('Bitte gültige Email Adresse eingeben!');
		else {
			submit.writeAttribute('value', 'warten...');
			submit.disable();
			$form.request({
				onComplete: function(resp) {
					var response = resp.responseText;
					submit.enable();
					submit.writeAttribute('value', submit.readAttribute('value_org'));
					try {
						response = response.evalJSON();
					} catch(e) {
						alert("Fehler aufgetreten.");
						return;
					}
					if(response.success) {
						// $form.hide();
						// alert(response.success.stripTags());
						$('vod-alert-me-message').innerHTML = response.success;
						try { $form.select('.type').first().hide(); } catch(e) {}
					} else if(response.error) {
						alert(response.error);
					} else
						alert("Fehler aufgetreten.");
				}
			});
		}
	}
}

var Filmman = Class.create();
Filmman.prototype = {
    initialize: function(id, customerId) {
        this.filmId = id;
        this.customerId = customerId;
        this.onComplete = this.updateLink.bindAsEventListener(this);
		this.filmRememberItem = $('film-remember');
		this.filmKnownItem = $('film-known');
		Event.observe(window,'dom:loaded',this.updateLinks.bind(this));
		Event.observe(this.filmRememberItem,'click',this.remember.bind(this));
    },

	updateLinks: function() {
		if (filmRemember)
		{
			this.filmRememberItem.className = 'more-link-right more-link-ok';
		}
		if (filmKnown)
		{
			this.filmKnownItem.className = 'more-link-right more-link-ok';
		}
	},

	remember: function() {
		this.filmRememberItem.className = 'more-link-right more-link-busy';
		var ajaxUrl = '/search/ajax/remember/?id=' + encodeURIComponent(this.filmId) + '&cust=' +encodeURIComponent(this.customerId);
		if (filmRemember)
		{
			ajaxUrl += '&remove=1'; 
		}
		var request = new Ajax.Request(ajaxUrl, {
					method: 'get',
					onSuccess: this.onComplete
				}
			);
		return false;
	},

	updateLink: function(transport) {
		var alertmeresponse = eval('('+transport.responseText+')');
		if (alertmeresponse.success)
		{
			if (filmRemember)
			{
				this.filmRememberItem.className = 'more-link-right more-link-none';
				filmRemember = false;
			//	alert('Remove: '+alertmeresponse.success);
			}
			else {
				this.filmRememberItem.className = 'more-link-right more-link-ok';
				filmRemember = true;
			//	alert('Add: '+alertmeresponse.success);
			}
		//	$('film-remember').innerHTML = alertmeresponse.success;
		}
		if(alertmeresponse.error) 
		{
			alert(alertmeresponse.error);
		}
	}
}

/**
 *	Vodlist: non paged Vodsearch
 */

var Vodlist = Class.create();
Vodlist.prototype = {
    initialize: function(container, options) {
		options = options || {};
		this.container = $(container);

		this.film_id = options.id;
		this.country = options.country;
		this.filter = options.filter;
		this.akaId = options.aka_id;
		this.url = options.url || '/search/ajax/product/';
		this.search_icon = options.search_icon;
		this.ajaxRequestCount = 0;
		this.ajaxRequestCountMax = 10; // absolute max

		this.update(this.container.innerHTML, true)
	},

	ajaxRequest: function() {
		if(this.ajaxRequestCountMax < this.ajaxRequestCount)
			return;

		var error = '<!--<status>{status: "Fehler, bitte später nochmal versuchen."}</status>-->';

		var url = this.url + '?id=' + encodeURIComponent(this.film_id) + '&country=' + this.country;
		if(this.filter)
			url += '&filter='+this.filter;
		if(this.akaId)
			url += '&aka_id='+this.akaId;

		url += '&refresh_count='+this.ajaxRequestCount;

		new Ajax.Request(url, {
				method: 'get',
				onComplete: function(transport) {
					this.update(transport.responseText, true);
				}.bind(this),
				onInteractive: function(transport) {
					this.update(transport.responseText);
				}.bind(this),
				onException: function(req, e) { this.update(error); throw e; }.bind(this),
				onFailure: function(transport) { this.update(error); throw new Error("ajax error, status: " + transport.status); }.bind(this)
			}
		);
		this.ajaxRequestCount ++;
	},

	update: function(html, onComplete) {
		data = html.replace(/[\r\n]+/g, ' ');
		var data_status = data.match(/<status>.*?<\/status>/g);
		if(data_status)
			data_status = data_status[data_status.length-1].match(/<status>(.*?)<\/status>/);

		if(! data_status)
			throw new Error("update: no status in input data");

		data_status = data_status[1].evalJSON(true);
		// console.log(data_status); // debug

		if(data_status && 'status' in data_status) {
			if(data_status.status && data_status.status != 'ok') {
				this.container.update(data_status.status);
			} else {
				data_status.refresh = parseInt(data_status.refresh);
				if(data_status.complete && this.search_icon)
					this.search_icon.style.display='none';
				var tpl = data.match(/<tpl>(.*?)<\/tpl>/);

				if(tpl) {
					var body = '';
					var lis = data.match(/<!--li-->.*?<!--\/li-->/g) || [];
					var lis_bytype = {};
					tpl = tpl[1].evalJSON(true);

					lis.each(function(li, i) {
						var type = li.replace(/^.*?<li[^>]*? type="([^>"]*)"[^>]*?>.*$/ig, '$1');
						if(type in  tpl.type) {
							if(! (type in lis_bytype))
								lis_bytype[type] = [];

							lis_bytype[type].push({html: li, sort_order: parseInt(li.replace(/^.*?<li[^>]*? sort_order="([^>"]*)"[^>]*?>.*$/ig, '$1'))});
						}
					});

					for(var i in tpl.type) {
						var content = '';

						if(i in lis_bytype) {
							lis_bytype[i].sort(function(a, b) {
								if(isNaN(a.sort_order) || isNaN(b.sort_order)) return 0;
								return a.sort_order > b.sort_order ? 1 : (a.sort_order < b.sort_order ? -1 : 0);
							});
							var lis_html = '';
							for(var l = 0; l < lis_bytype[i].length; ++ l) {
								var args = {'class': (l % 2 == 0 ? '' : 'alternate')};
								lis_html += (new Template(lis_bytype[i][l].html)).evaluate(args);
							}
							content = (new Template(tpl.type_content)).evaluate({type: i, lis: lis_html});
						} else
							content = (new Template(tpl.type_content_empty)).evaluate({type: i});

						body += (new Template(tpl.type[i])).evaluate({type: i, content: content});
					}
					// console.log(tpl, lis_bytype, body); // debug
					this.container.update(body);
				} else
					this.container.update(html);

				if(data_status.status == 'ok' && data_status.refresh > -1 && onComplete)
					window.setTimeout(this.ajaxRequest.bind(this), data_status.refresh * 1000);
			}
		} else if(html) {
			this.container.update(html);
		}
	}
}

function expandtext(id) {
	t=$('text'+id);
	k=$('textexpand'+id);
	if (t && k) {
		k.style.display=(k.style.display=='none')?'':'none';
		t.style.display=(t.style.display=='none')?'':'none';
		//alert('height: '+o.style.height);
	}
}

function follow_link(a) {
	$a = $(a);
	if($a) {
		var href = $a.readAttribute('href');
		var target = $a.readAttribute('target');

		if(href) {
			if(target) window.open(href, target);
			else window.location = href;
		}
	}
}

/**
 * set on onmousedown
 */
function vod_click_film(container, page_track) {
	if(container.observing_vod_click) return;
	container.observing_vod_click = true;

	Event.observe(container, 'click', function(event) {
		Event.stop(event);
		vod_click_film_(container, page_track);
	});
}

function vod_click_film_(container, page_track) {
	if(page_track) {
		try {
			// _gaq.push(["_trackPageview", page_track]); // todo: activate in Mage 1.4
			pageTracker._trackPageview(page_track);
		} catch(e) { }

	//	if(typeof THE_FILM != 'undefined')
	//		new Ajax.Request('/easyrec/ajax/nearbuy/id/' + THE_FILM.film_id, {
	//			method: 'get',
	//			onSuccess: function(transport) { },
	//			onException: function(req, e) { throw e; },
	//			onFailure: function(transport) { throw new Error("ajax error, status: " + transport.status); }
	//		});
	}

	var $container = $(container);
	if($container)
		if($container.readAttribute('href'))
			follow_link($container);
		else
			follow_link($container.select('a').first());
}

