

var shortUrlPrefix = '[doorstepr.rezpondr.com]';

function playerReady(obj) { player.playerReady(); };
function playerStateListener(state) { playlist.stateListener(state); };

var playlist = {
	stateListener: function(state) {}
}

var player = {
	playerWrapperId: 	 'video',
	playerPlaceholderId: 'videoPlaceholder',
	playerId: 			 'rezpondaPlayer',
	height: 			  386,
	width: 				  630,
	instance:   		  new Object(),
	init: function() {
		if (livestream && livestream != 'default') {
			this.remove();
	        var attributes = {
	            id: 				this.playerId,
	            name: 				this.playerId
	        };
	        swfobject.embedSWF(livestream.url, this.playerPlaceholderId, this.width, this.height, '9.0.115', false, livestream.flashvars, livestream.params, attributes);
		} else {
			this.play('');
		}
	},
	playLivestream: function(index) {
		if (livestreamsList[index]) {
			this.remove();
			var attributes = {
	            id: 				this.playerId,
	            name: 				this.playerId
	        };
			swfobject.embedSWF(livestreamsList[index].url, this.playerPlaceholderId, this.width, this.height, '9.0.115', false, livestreamsList[index].flashvars, livestreamsList[index].params, attributes);
		}
	},
	playerReady: function() {
		this.instance = document.getElementById(player.playerId);
		this.instance.addModelListener('STATE', 'playerStateListener');
		
		if (directMedia.items) {
			directMedia.items[0].type = directMedia.type;
			playlist.playItem(directMedia.items[0]);
			directMedia.items = false;
		}
			
	},
	// Common format
	play: function(theFile, optParams) {
		this.remove();
		
		var flashvars = {
        	file: 				theFile,
            autostart: 			'true',
			backcolor:			'0xFCC442',
			frontcolor:			'0x222222',
			lightcolor:			'0x222222',
			screencolor:		'0xFCC442',
			stretching: 		'exactfit'
        };

		if (optParams) {
			if (optParams.image) flashvars.image = optParams.image;
			if (optParams.item) flashvars.item = optParams.item;
			if (optParams.playlist) flashvars.playlist = optParams.playlist;
            if (optParams.playlistsize) flashvars.playlistsize = optParams.playlistsize;
			if (optParams.skin) flashvars.skin = optParams.skin;
		}
		
        var params = {
            allowfullscreen: 	'true',
            allowscriptaccess: 	'always'
        };
        var attributes = {
            id: 				this.playerId,
            name: 				this.playerId
        };
        swfobject.embedSWF('/mediaplayer-4.1.60/player.swf', this.playerPlaceholderId, this.width, this.height, '9.0.115', false, flashvars, params, attributes);
	},
	// Bambuser
	playBambuser: function(id) {
		this.remove();

		var flashvars = {
			vid: 				id,
			autostart:  		'yes'
		};
        var params = {
            allowfullscreen: 	'true',
            allowscriptaccess: 	'always',
			movie: 				'http://bambuser.com/r/player.swf'
        };
        var attributes = {
            id: 				this.playerId,
            name: 				this.playerId
        };
		swfobject.embedSWF('http://bambuser.com/r/player.swf', this.playerPlaceholderId, this.width, this.height - 1, '9.0.115', false, flashvars, params, attributes);
	},
	remove: function() {
		swfobject.removeSWF(this.playerId);
        var tmp = document.getElementById(this.playerWrapperId);
        if (tmp) { tmp.innerHTML = '<div id=' + this.playerPlaceholderId + '></div>'; }
		scroll(0, 0);
	},
};

var rez = {
	loggedIn: false,
	data: new Object(),
	resizing: false,
	init: function() {
		
		// We have another button for backend
		$('#adminnavigation').hide();
		
		var fm = new FeedMenu();
      	fm.write('#jquery_feed_menu');
		$('')
		
		$('#map').css('height', document.documentElement.clientHeight - 85);   
		$(window).resize(function() {
	        $('#map').css('height', document.documentElement.clientHeight - 85);
	    });
	
		this.setupRowsLimit();
		
		/*$(window).resize(function() {
			rez.setupRowsLimitLivetime();
		});*/
		
		rez.timer();
		
		$.each($('select[service]'), function(i, s) {
			$(this).change(function() {
				rez.loadService($(this).attr('service'), { type: 'customService', service: $(this).val() });
			});
		});
		
		
		$('#townSelector').change(function() {
			document.location = 'http://' + this.value + '.doorstepr.com/';
		});
		
		rez.loadService('flickr', {});
		$('#serviceType').change(function() {
			if (this.value  == 'item') { 
				return;
			}
			rez.changeServiceType(this.value);
		});
		
		setTimeout(function() {
			rez.changeServiceType('bambuser');
		}, 1500);
	},
	changeServiceType: function(type) {
		
		$('#customRes').empty();
		/*
		$('#navigation-left a').attr('onclick', 'rez.loadService(\'' + type + '\', { type: \'forward\' }); return false;');
		$('#navigation-right a').attr('onclick', 'rez.loadService(\'' + type + '\', { type: \'backward\' }); return false;');
		*/
		if (rez.services[type]) {
			rez.services[type].build(rez.data[type]);
		}
	},
	setupRowsLimitLivetime: function() {
		if (this.resizing == true) { return; }
		this.resizing == true;
		setTimeout(function() {
			rez.setupRowsLimit();
			rez.resizing = false;
		}, 500);
	},
	setupRowsLimit: function() {
		this.resizing = true;
		/*var rows = Math.floor((parseInt($(window).width()) - 200) / 70)
		for (var type in rez.services) {
			if (type != '
			') {
				rez.services[type].rows = rows;
			}
		}*/
		rez.checkState(true);
	},
	timer: function() {
		setTimeout(function() {
			rez.checkState(false);
			rez.timer();
		}, 30000);
	},
	initControlTabs: function() {},
	checkState: function(force) {
		var force = force == true ? 'force=true' : '';
		var params = '';
		for (var type in rez.services) {
			params += '&params[' + type + '][limit]=' + rez.services[type].rows;
			params += '&params[' + type + '][page]=' + rez.services[type].page;
			params += '&params[' + type + '][service]=' + rez.services[type].service;
		}
		
		$.ajax({
	        type:   	'get',
	        url:    	'/services/state?' + force,
			dataType: 	'json',
			data: 		params,
	        success: 	function(response) {
				if (!checkServerResponse(response)) { return; }
				for (var type in response.result.services) {
					if (response.result.services[type].items) {
						rez.customRowBuild(type, { type: 'init' }, response.result.services[type]);
						rez.data[type] = response.result.services[type].items;
					}
				}
				
				if (response.result.streamPlayer) {
					livestream = response.result.streamPlayer;
					player.init();
				}
			}
		});
	},
	loadService: function(type, argObj) {
		if (argObj.type == 'forward') {
			rez.services[type].page++;
		} else if (argObj.type == 'backward') {
			if (rez.services[type].page != 0) rez.services[type].page--;
			else return;
		} else if (argObj.rows == 'more') {
			rez.services[type].rows += 9;
		} else if (argObj.rows == 'less') {
			if (rez.services[type].rows != 9) rez.services[type].rows -= 9;
			else return;
		} else if (argObj.type == 'customService') {
			rez.services[type].page = 0;
			rez.services[type].service = argObj.service;
		} else return;

		var params = '&params[' + type + '][limit]=' + rez.services[type].rows;
		params += '&params[' + type + '][page]=' + rez.services[type].page;
		params += '&params[' + type + '][service]=' + rez.services[type].service;
		
		$.ajax({
	        type:   	'get',
	        url:    	'/services/load-items/type/' + type,
			dataType: 	'json',
			data:   	params,
	        success: 	function(response) {
				if (!checkServerResponse(response)) { return; }
				if (response.result[type] && response.result[type].items) {
					//rez.customRowBuild(type, argObj, response.result[type]);
					rez.data[type] = response.result[type].items;
					/////////////////
					
					$('#customRes').empty();
					rez.services[type].build(rez.data[type]);
				}
			}
		});
	},
	customRowBuild: function(type, argObj, data) {
		
		
		if (!rez.services[type]) return;
		
		if (argObj.type == 'init')
			params = { opacity: 0 };
		else if (argObj.type == 'forward')
			params = { opacity: 0, left: "+=900px" };
		else if (argObj.type == 'backward')
			params = { opacity: 0, left: "-=900px" };
			
		//////////////////////////////////////
		if (type != 'twitter') return;
		
		var cId = '#' + type + 'Res';
		$(cId).animate(params, 500, null, function() {
			$(cId).empty();


			// Building selector
			$('select[service="' + type + '"]').empty();

			if (data.options.length != 1) {
				$('select[service="' + type + '"]').show();
				$('<option />').val('').html('Feed options').appendTo('select[service="' + type + '"]');
				$.each(data.options, function(i, o) {
					var opt = $('<option />').val(o.id).html(o.alias).appendTo('select[service="' + type + '"]');
					if (o.id == rez.services[type].service) opt.attr('selected', 'selected');
				});
			} else {
				$('select[service="' + type + '"]').hide();
			}

			// Building servive row
			rez.services[type].build(data.items);

			params.opacity = 1;
			if (argObj.type == 'forward') {
				$(cId).css('left', '-900px');
			} else if (argObj.type == 'backward') {
				$(cId).css('left', '900px');
			}

			$(cId).animate(params, 500, null, function() {});
			lightbox.initTt();
			picturePreview.init();
		});
	
		
	},
	rowBuildVideo: function(type, data, playCallback) {
		
		var div = $('<div class="footer-div" />').appendTo('#customRes');
		if (data.isHidden == 1) div.addClass('hidden');
	
		var a = $('<a href="javascript:void(0);" />').appendTo(div);
		var img = $('<img alt="thumbnail" class="rowThumbnail"/>').appendTo(a).attr({
			src: data.pData,
			title: data.title
		}).click(playCallback);
	},
	rowBuildPhoto: function(type, data, playCallback) {
		var div = $('<div class="footer-div" />').appendTo('#customRes');
		if (data.isHidden == 1) div.addClass('hidden');
	
		var a = $('<a href="javascript:void(0);" />').appendTo(div);
		var img = $('<img alt="thumbnail" class="rowThumbnail"/>').appendTo(a).attr({
			src: data.pData,
			title: data.title
		}).click(playCallback);
		/*
		var div = $('<div class="footer-div" />').appendTo('#customRes');
		if (data.isHidden == 1) div.addClass('hidden');
		var a = $('<a class="picturePreview" target="blank" />').appendTo(div).attr({
			href: data.pData,
			rel: data.pData,
			title: data.title
		});
		var img = $('<img alt="thumbnail" class="rowThumbnail"/>').appendTo(a).attr({
			src: data.pData,
			title: data.title
		});
		picturePreview.init();
		*/
	}
};
rez.services = {};

rez.services.flickr = {
	page: 0,
	rows: 14,
	service: 0,
	build: function(data) {
		$.each(data, function(i, m) {
			if (!m.pData) return;
			m.pData = m.pData.substring(0, m.pData.length - 6) + m.pData.substring(m.pData.length - 4);
			rez.rowBuildPhoto('flickr', m, function() {
				rez.services.flickr.play(i);
			});
		});
	},
	play: function(index) {
		//http://amp08.rezpondr.local/rss/2.0/service/flickr
		/*
		
		var item = rez.data.flickr[index];
		var url = item.mData;

		var part2 = url.substring(url.length - 4);
		var part1 = url.substring(0, url.length - 6);

		var url = part1 + part2;
		
		return;
		$('#lightboxTrigger').attr({
			href: url,
			title: item.title
		});
		$('#lightboxTrigger').click();
		
		*/
		if (this.service == 0) {
			var playlistUri = 'http://' + subdomainName + '.' + domainName + '/rss/2.0/service/flickr?page=' + this.page + '&limit=' + this.rows;
		} else {
			var playlistUri = 'http://' + subdomainName + '.' + domainName + '/rss/2.0/service/' + this.service;
		}
		
		showPopup('flickr');
		player.play(playlistUri, {
        //    image: 			item.pData,
            item: 			index,
            playlist: 		'right',
            playlistsize:  100,
		});
	}
};
rez.services.twitter = {
	page: 0,
	rows: 10,
	service: 0,
	build: function(data) {
		$('#twitterRes').empty();
		$.each(data, function(i, t) {
			var div = $('<div class="tweet" />').appendTo('#twitterRes');
			var p = $('<p>').appendTo(div).html(' ' + t.title);
			var span = $('<span class="tweet-blue" />').prependTo(p).html(t.pubDate + ' ago');
			
			var pa = $('<p>').appendTo(div);
			var a = $('<a />').appendTo(pa).attr({
				href: 'http://twitter.com/' + t.author,
				title: 'Open twitter account page in new window'
			}).html('@' + t.author);
		});
	},
	isLivetweetAccount: function(t) {
		var trigger = false;
		$.each(livetweetAccounts, function(i, a) {
			if (a.username == t.author) {
				trigger = true;
			}
		});
		return trigger;
	}
};
rez.services.youtube = {
	page: 0,
	rows: 14,
	service: 0,
	build: function(data) {
		$.each(data, function(i, m) {
			rez.rowBuildVideo('youtube', m, function() {
				rez.services.youtube.play(i);
			});
		});
	},
	play: function(index) {
		showPopup('youtube');
		var item = rez.data.youtube[index];
        player.play(escape(item.link));
	}
};
rez.services.bambuser = {
	page: 0,
	rows: 14,
	service: 0,
	build: function(data) {
		$.each(data, function(i, m) {
			rez.rowBuildVideo('bambuser', m, function() {
				rez.services.bambuser.play(i);
			});
		});
	},
	play: function(index) {
		showPopup('bambuser');
		var item = rez.data.bambuser[index];
		player.playBambuser(item.guid);
	}
};

rez.services.audioboo = {
	page: 0,
	rows: 14,
	service: 0,
	build: function(data) {
		$.each(data, function(i, m) {
			rez.rowBuildVideo('audioboo', m, function() {
				rez.services.audioboo.play(i);
			});
		});	
	},
	play: function(index) {
		var item = rez.data.audioboo[index];
		
		if (this.service == 0) {
			var playlistUri = 'http://' + subdomainName + '.' + domainName + '/rss/2.0/service/audioboo?page=' + this.page + '&limit=' + this.rows;
		} else {
			var playlistUri = 'http://' + subdomainName + '.' + domainName + '/rss/2.0/service/' + this.service;
		}
		
		showPopup('audioboo');
		player.play(playlistUri, {
        //    image: 			item.pData,
            item: 			index,
            playlist: 		'right',
            playlistsize: 	(player.width - 320),
		});
	}
};

function showPopup(type) {
	if (type == 'bambuser') {
		player.height	= 430;
		player.width	= 480;
		$('#dspopupHandler').attr('alt', '#TB_inline?height=444&amp;width=450&amp;inlineId=dspopup');
	} else {
		player.height	= 386;
		player.width	= 630;
		$('#dspopupHandler').attr('alt', '#TB_inline?height=400&amp;width=600&amp;inlineId=dspopup');
	}
	$('#dspopupHandler').click();
}

