jQuery(document).ready(function(){
	if(jQuery('#listview').length){
		listview.init();
		//listview._initInfoBox();
		if($.browser.msie && $.browser.version < 7){
			$('.infobox-content-small').addClass('infobox-content-small_ie6');	
		}
	}
});

var debug = true;
var listview = new ListView();
function ListView(){
	this.hash_call_counter = 0;
	this.searchParams = {start:'', end:'', ids:'', selected:'', max_items:0, start_item:0, specificRow:0};
	this.pageParams = {};
	
	this.do_scroll_checking = true;
	this.scroll_no_more_results = false;
	
	this.searchTimeOut_ID = 0;
	this.usePreOpen = true;
	this.click_events_enabled = true;
	
	this.init = function(){
		// Set height for panelWrapper so it dont "jump".
			jQuery('#panelWrapper').css('height', '45px');
		// ---
		try{
			var scope = this;
			this._initRows();
			jQuery.scrollTo(0, 0);
			jQuery.estilo.tools.watcher.watch(window.location, 'hash', function(old_value, new_value){
				if(new_value != null) {
					scope.hash_call_counter++;
					scope.scroll_no_more_results = false;
					scope._anchorCallback(new_value);
				}
			});		
			setTimeout(function(){
				scope._initScrollWatcher();
			}, 400);
		}catch(ex){ if(debug) alert(ex); }
	};
	this._initScrollWatcher = function(){	
		try{
			var scope = this;
			jQuery(document.body).append('<div id="logg" style="position:absolute; top:500px; left:0; z-index:100;"></div>');
			var intV = setInterval(function(){
				var left_to_scroll = (jQuery("#wrapper").height() + jQuery("#footer").height() + 50) - jQuery(window).height();
				if(jQuery.browser.safari){
					left_to_scroll -= document.body.scrollTop;
				}else{
					left_to_scroll -= document.documentElement.scrollTop;
				}
			
				if(left_to_scroll < 5 && (document.documentElement.scrollTop > 0 || document.body.scrollTop > 0) && ((jQuery("#wrapper").height() + jQuery("#footer").height() + 50) > jQuery(window).height())){
					if(scope.do_scroll_checking && !scope.scroll_no_more_results){
						scope.do_scroll_checking = false;
						scope._addMoreResults(function(successful, data, nr_of_items){
							scope.do_scroll_checking = true;						
						});	
					}
				}
			}, 150);	
		}catch(ex){ if(debug) alert(ex); }
	}
	this._initRows = function(){
		try{
			var scope = this;
			jQuery('#listview tr[class*=minimized], #listview tr[class*=maximized]').each(function(index, element){
				scope._initRow(this);
			});
		}catch(ex){ if(debug) alert(ex); }
	};
	this._initRow = function(row, display_delay){
		try{
			var scope = this;
			if(jQuery(row).attr('id') == 'row-template') return;
			if(display_delay == undefined) display_delay = 0;
			row = jQuery(row);
			var wrapper = jQuery(row).next();
			
			var previos = jQuery(row).prev().prev();
			var color = (previos.hasClass('white-minimized')) ? 'dark' : 'white';
			row[0].color = color;
			
			row.removeClass('white-minimized, dark-minimized').addClass(color+'-minimized');
			wrapper.removeClass('white-wrapper, dark-wrapper').addClass(color+'-wrapper');
			
			row[0].onclick = function(){
				// Check if click events are enabled
				if(scope.click_events_enabled){
					if(this.working == false || this.working == undefined){
						this.working = true;
						var me = this;
						setTimeout(function(){
							me.working = false;					
						}, 500);
						scope._onRowClick(this);
					}
				}
			};
			setTimeout(function(){
				if(jQuery.browser.msie)
					row.removeClass('hide');
				else{
					//row.fadeIn(); // Removed because fadeIn() causes the flashplayer to reload in FF.
					row.removeClass('hide');
				}
			}, display_delay);
		}catch(ex){ if(debug) alert(ex); }
	};
	this._updateNrOfStories = function(nrOf){
		try{
			setTimeout(function(){
				if(nrOf == undefined){
					nrOf = jQuery('.white-minimized, .dark-minimized').length;
					nrOf = (nrOf > 0) ? (nrOf-1) : nrOf;
				}
				panel().setNrOfStories(nrOf);
			}, 100);
		}catch(ex){ /* Error on init */ }
	};
	this._onRowClick = function(caller){
		try{
			var scope = this;	
			var id = parseInt(caller.id);
			var tr = jQuery('#' + id + '_content')[0];
			var content_tr = jQuery(tr).next(); 
			var content_div = jQuery('.content:first', content_tr); 
			if(content_div.css('display') != 'none'){
				this._openRow(id);
			}
			window.location.hash='start=' + scope.getUrlParam('start') + '&end=' + scope.getUrlParam('end') + '&ids=' + scope.getUrlParam('ids') + '&selected=' + scope.getUrlParam('selected') + '&currentId_dummy=' + (Math.ceil((Math.random()*100+10*1000)) + '&currentId=' + parseInt(caller.id)); 
		}catch(ex){ if(debug) alert(ex); }
	};
	this._getExistingRow = function(id){
		var scope = this;
		var tr = jQuery('#' + id + '_content');
		if(tr.length){
			return tr[0];
		}else
			return false;
	}
	this._openRow = function(id){
		try{
			var scope = this;
			var tr = this._getExistingRow(id);
			
			var content_tr = jQuery(tr).next(); 
			var content_div = jQuery('.content:first', content_tr); 
			if(content_div.length){
				if(content_div.css('display') == 'none'){
					if(tr.color == 'white'){
						jQuery(tr).addClass('white-maximized').removeClass('white-minimized');
					}else{
						jQuery(tr).addClass('dark-maximized').removeClass('dark-minimized');					
					}
					content_tr.css('visibility', 'visible');	
					content_div.slideDown(200, function(){
						scope._getContentForRow(content_tr, id)
					});
				}else{
					if(tr.color == 'white'){
						jQuery(tr).removeClass('white-maximized').addClass('white-minimized');
					}else{
						jQuery(tr).removeClass('dark-maximized').addClass('dark-minimized');					
					}
					content_div.slideUp(200, function(){
						content_tr.css('visibility', 'hidden');				
					});	
				}
				return true;
			}
		}catch(ex){ if(debug) alert(ex); }
	};
	this.getUrlParam = function(paramName) {
		var scope = this;
		if(paramName == null) {
			return scope.pageParams;
		}		
		// Get currentId from deeplink
		if(paramName == 'currentId' && scope.pageParams[paramName] == undefined && currentId_from_deep_link != undefined && currentId_from_deep_link > 0){
			return currentId_from_deep_link;
		}
		// ---
		return scope.pageParams[paramName];
	};
	this._getNrOfRows = function(){
		return jQuery('#listview tr[class*=minimized], #listview tr[class*=maximized]').not('#row-template').length;
	};
	this.addMoreResults = function(){
		this._addMoreResults();
	};
	this._addMoreResults = function(callback){
		try{
			var scope = this;
			this.searchParams.start_item = this._getNrOfRows();
			if(jQuery.browser.msie && jQuery.browser.version < 8)
				this.searchParams.max_items = 5;
			else
				this.searchParams.max_items = 10;
			
			function doGet(){
				scope._getMoreRows(function(successful, data, nr_of_items){
					if(nr_of_items == 0){
						jQuery('#no-more-results').fadeIn(function(){
							scope.scroll_no_more_results = true;
							callback(successful, data, nr_of_items);				
						});
					}else{
						callback(successful, data, nr_of_items);		
					}
				});
			}
			jQuery('#fetching-more-results').fadeIn(function(){
				doGet();
			});
		}catch(ex){ if(debug) alert(ex); }
	};
	this._getContentForRow = function(wrapper, id){
		try{
			var scope = this;
			wrapper = jQuery(wrapper);
			this.do_scroll_checking = false;	
			this.click_events_enabled = false;
			
			function addContent(data){
				var _item = data.rssc.item;
				var wp_id = _item.author['@attributes'].wp_id;
				var title = _item.title;
				var pubDate = _item.pubDate;
				var content = _item.content;
				var _link = _item.link;
				var color = (_item.color.indexOf('0x') > -1) ? _item.color : '0x9f9f9f';
				var hexa_color = color.replace('0x', '#');
				var stickers = _item.stickers.sticker;
				if(stickers.length == undefined) stickers = new Array(_item.stickers.sticker);
				
				var sticker_holder = jQuery('.stickers', wrapper);
				for(var i=0; i<stickers.length; i++){
					var sticker_attributes = stickers[i]['@attributes'];
					var sticker_id = sticker_attributes.id;
					var sticker_name = sticker_attributes.name;
					var sticker_color = sticker_attributes.color;
					var sticker_label = sticker_attributes.label;
					var sticker_isRemovable = sticker_attributes.isRemovable;
					
					if($.trim(sticker_name) != ''){
						var clone = jQuery('#sticker-template').clone().removeAttr('id').addClass('s_' + sticker_color);
						jQuery('.label', clone).empty().append(sticker_name);
						jQuery('input', clone)[0].value = sticker_id;
						jQuery(sticker_holder).append(clone);
						clone.show();
						stickerfields.initSticker(clone);
					}
				}
				
				// Set content
				// Get posted by uri
				jQuery('.top h3, .top h3 a', wrapper).css('color', hexa_color);
				var data = {wp_id:wp_id};
				jQuery.get(listviewplugin_url + '/profile-url.ajax.php?json_wrapper=?', data, function(data){
					if(data.uri != ''){
						jQuery('.top h3 a', wrapper).attr('href', data.uri);
					}else{
						jQuery('.top h3 a', wrapper).css("cursor", "default").bind('click', function(){ return false; }).addClass('no-underline');	
					}
				}, 'json');
				// ---
				
				jQuery('.top em', wrapper).empty().append(pubDate);
				jQuery('.top .headline a', wrapper).empty().append(title).attr('title', title).attr('href', _link);
				jQuery('.rss-content', wrapper).empty().append(content);
				jQuery('.rss-content a', wrapper).attr('target', '_blank');
				
				var height = jQuery('.content', wrapper).height();
				jQuery('.content', wrapper).css('height', 75 + 'px');
				
				if(!jQuery.browser.msie)
					jQuery('.content .top, .content .rss-content', wrapper).css('opacity', 0.1).animate({opacity:1});
				jQuery('.content', wrapper).animate({height:height}, function(){
					jQuery(this).css("height", "auto");
					// Auto open discuss or share if url contains "preOpen"
					if(window.location.href.indexOf('preOpen=dis') > -1 && scope.usePreOpen == true){
						scope.usePreOpen = false;
						var infoBoxHolder = jQuery('.content .infoBoxHolder', wrapper);
						jQuery.scrollTo(infoBoxHolder, 500, {easing:'easeOutQuint', offset: {top:-31}, onAfter:function(){
							jQuery('.ui-tabs-nav a.discuss', infoBoxHolder).click();
							scope.do_scroll_checking = true;
							scope.click_events_enabled = true;
						}});						
					}else if(window.location.href.indexOf('preOpen=sha') > -1 && scope.usePreOpen == true){
						scope.usePreOpen = false;
						var infoBoxHolder = jQuery('.content .infoBoxHolder', wrapper);
						jQuery.scrollTo(infoBoxHolder, 500, {easing:'easeOutQuint', offset: {top:-31}, onAfter:function(){
							jQuery('.ui-tabs-nav a.share', infoBoxHolder).click();
							scope.do_scroll_checking = true;
							scope.click_events_enabled = true;
						}});						
					}else{
						jQuery.scrollTo(jQuery('.content', wrapper), 1000, {easing:'easeOutQuint', offset: {top:-31}, onAfter:function(){
							scope.do_scroll_checking = true;	
							scope.click_events_enabled = true;		
						}});
					}
					//---	
				});	
				scope._initInfoBox(wrapper, id, color);	
			}
			if(jQuery('.content', wrapper).length > 1){
				// Get priority for color
				var priority = null;
				try{
					priority = (scope.getUrlParam('selected').indexOf('discussions') > -1) ? 'discussions' : ' ';
					priority += (scope.getUrlParam('selected').indexOf('appeals') > -1) ? 'appeals' : '';
				}catch(ex){}
				
				var url = jsBaseUrl + "/api/focus.php?type=item_details&priority="+priority+"&item_id="+id+"&output=json&json_wrapper=?";
				jQuery.get(url, null, function(data, txtStatus){					
					// Remove preloader
					if(jQuery('.content', wrapper).length > 1){
						jQuery('.content:first .loading-content', wrapper).fadeOut(200, function(){
							jQuery('.content:first', wrapper).remove();
							addContent(data);
						});
					}else{
						addContent(data);	
					}
				}, 'json');
			}else{
				scope.click_events_enabled = true;
				jQuery.scrollTo(jQuery('.content', wrapper), 1000, {easing:'easeOutQuint'});
			}
		}catch(ex){
			this.click_events_enabled = true;
			if(debug) alert(ex); 
		}
	};
	this._setUrlParams = function(hash){
		try{
			hash = hash.replace("#", "");
			var scope = this;
			this.pageParams = {};			
			var hasChanged = false;
			var arrParams = hash.split('&');
			for(var i = 0; i < arrParams.length; i++){
				if(arrParams[i] != "") {
					var oneParam = arrParams[i].split('=');
					var name = oneParam[0];
					var val = oneParam[1];
					this.pageParams[name] = val;
					if(this.searchParams[name] != undefined && this.searchParams[name] != val) {
						this.searchParams[name] = val;
						hasChanged = true;
					}
					if(name=='currentId') {
						this.selectedDataId = val;
					}
				}
			}
			return hasChanged;
		}catch(ex){ if(debug) alert(ex); }
	};
	this._anchorCallback = function(hash){
		try{
			var scope = this;
			hash = hash.replace("#", "");
			
			$('#main_menu a[title=Map view]').unbind("click").click(function () { 
				window.location.href = $('#main_menu a[title=Map view]').attr('href')+"#"+hash;
				return false;
			});
			$('#main_menu a[title=List view]').unbind("click").click(function () { 
				window.location.href = $('#main_menu a[title=List view]').attr('href')+"#"+hash;
				return false;
			});
			
			scope.pageParams = {};			
			var hasChanged = this._setUrlParams(hash);
			
			
			if(selected_stickers.length > 0 && this.hash_call_counter == 2){
				var selected_ids_str = this.getUrlParam('ids') + ',' + this.getUrlParam('selected');
				selected_ids_str = selected_ids_str.replace(',,', ',');
				var ids = new Array();
				var temp = selected_ids_str.split(',');
				for(var i=0; i<temp.length; i++){
					var exists = false;
					for(var a=0; a<selected_stickers.length; a++){
						if(selected_stickers[a] == temp[i]){
							exists = true;
							break;
						}
					}
					if(!exists)
						ids.push(temp[i]);
				}
				var selected = selected_stickers;
				selected_stickers = new Array();
				
				window.location.hash = 'ids=' + ids.join(',') + '&start=' + this.getUrlParam('start') + '&end=' + this.getUrlParam('end') + '&selected=' + selected.join(',');
				hasChanged = this._setUrlParams(window.location.hash);
				try {
					//panel().refreshFlashPanel(); // TODO: Fix bug in panel on refresh()
				}catch(ex){ if(debug) alert(ex); }
			}
			
			if(hasChanged) {
				this._getNewRows(function(){
					if(scope.getUrlParam('currentId') > 0){
						var currentId = scope.getUrlParam('currentId');
						var row_found = scope._openRow(currentId);
						if(!row_found){
							// TODO: If row not found, add own row at the top	
							scope.searchParams.specificRow = scope.getUrlParam('currentId');
							scope._getMoreRows(function(successful, data, nr_of_items){
								scope._openRow(currentId);
							});	
						}
					}				
				});
			}else if(this.getUrlParam('currentId') > 0){
				var currentId = this.getUrlParam('currentId');
				this._openRow(currentId);
			}
		}catch(ex){ if(debug) alert(ex); }
	};
	this._getURL = function(){
		try{
			var url = jsBaseUrl + "/api/search.php?type=vis&start="+this.searchParams.start+"&max_items="+this.searchParams.max_items+"&start_item="+this.searchParams.start_item+"&end="+this.searchParams.end+"&ids="+this.searchParams.ids+"&selected="+this.searchParams.selected+"&output=json&json_wrapper=?";
			if(this.searchParams.specificRow > 0){
				url += '&currentId=' + this.searchParams.specificRow;
				this.searchParams.specificRow = 0;
			}
			return url;
		}catch(ex){ if(debug) alert(ex); }
	};
	this._getNewRows = function(callback){
		try{
			this.searchParams.start_item = 0;
			var max_items = Math.ceil((jQuery(document.body).height()-300)/31);
			if(jQuery.browser.msie && jQuery.browser.version == 6)
				max_items = 25;
			
			this.searchParams.max_items = max_items;
			
			jQuery('tr', jQuery('#listview')).not('#row-template, #wrapper-template, #header, #status-messages').remove(); 
			jQuery('#no-more-results').fadeOut();
			jQuery('#searching').fadeIn(150);
			this._getMoreRows(function(successful, data, nr_of_items){
				jQuery('#searching').fadeOut(function(){
					if(nr_of_items == 0){
						if(jQuery.browser.msie && jQuery.browser.version > 7)
							jQuery('#no-results').show()
						else
							jQuery('#no-results').fadeIn();
					}else if(nr_of_items < max_items){
						jQuery('#no-more-results').fadeIn();
					}
					if(callback != undefined)
						callback(successful, data, nr_of_items);
				 });
			});			
		}catch(ex){ if(debug) alert(ex); }
	};
	this._getMoreRows = function(callback){
		try{
			var scope = this;
			var url = this._getURL();
			jQuery('#no-results, #search-error').hide();
			
			try{
				function addRows(data){
					if(data == null){
						// Something went deeply wrong
						jQuery('#search-error').fadeIn();
						return;
					}
					if(data.rssItems != undefined){				
						var rssItems = data.rssItems.rssItem;
						
						if((rssItems) && (rssItems.length == undefined)) {
							rssItems = new Array(data.rssItems.rssItem);
						}
						
						if(rssItems == undefined) rssItems = new Array();	
						
						for(var i=0; i < rssItems.length; i++){
							var rssItem = rssItems[i];
							var id = rssItem['@attributes'].id;
							var color = (rssItem.color.indexOf('0x') > -1) ? rssItem.color : '0x9f9f9f';
							
							var title = jQuery.trim(rssItem.title);
							var posted = rssItem.posted;
							var _link = rssItem.link;
							var author_name = rssItem.author['@attributes']['text'];
							var author_id = rssItem.author['@attributes'].id;
							var stickers = rssItem.stickers.sticker;
							
							if(!scope._getExistingRow(id)){
								var row_clone = jQuery('#row-template').clone();
								var wrapper_clone = jQuery('#wrapper-template').clone();
								
								row_clone.attr('id', id + '_content');
								var row_cells = jQuery('td', row_clone);
								var row_title = (title.length > 50) ? (title.substr(0, 50) + '...') : title;
								jQuery(row_cells[0]).empty().append(row_title);
								jQuery(row_cells[1]).empty().append(author_name);
								jQuery(row_cells[2]).empty().append(posted);
								
								wrapper_clone.attr('id', id + '_wrapper');
								jQuery('.top h3 a', wrapper_clone).empty().append('Posted by: ' + author_name);
								jQuery('#listview #status-messages').before(row_clone).before(wrapper_clone);
								
								wrapper_clone.removeClass('hide');
								scope._initRow(row_clone, 20*i);
							}
						}
						if(callback != undefined){
							setTimeout(function(){
								callback(true, data, rssItems.length);
							}, (20*rssItems.length) + 250);
						}
					}else{
						if(callback != undefined)
							callback(true, data, 0);
					}	
				}
				clearTimeout(scope.searchTimeOut_ID);
				scope.searchTimeOut_ID = setTimeout(function(){
					jQuery('#fetching-more-results, #searching').hide();
					addRows(null);	
					scope._updateNrOfStories();
				}, 5000);
				jQuery.get(url, null, function(data, txtStatus){
					clearTimeout(scope.searchTimeOut_ID);
					jQuery('#fetching-more-results').fadeOut(function(){
						addRows(data);	
						scope._updateNrOfStories();		
					});
				}, 'json');		
			}catch(ex){ 
				if(callback != undefined)
					callback(false, null, 0);
				if(debug) alert(ex);
			}
		}catch(ex){ 
			if(callback != undefined)
				callback(false, null, 0);
			if(debug) alert(ex);
		}
	};
	
	this.showNewPost = function(caller){
		try{
			var panel = $(caller).closest('.infobox-content-small');
			$('.ui-tabs-content:first', panel).hide();
			$('.new-post', panel).show();
			$('.new-post .ajaxOutput', panel).hide();
			$('.new-post form', panel)[0].reset();
		}catch(ex){ if(debug) alert(ex); }
	};
	this.submitNewPost = function(caller){
		try{
			var scope = this;
			var valid = true;
			var form = jQuery(caller).closest('form');
			var tr = jQuery(caller).closest('tr')[0];
			var message = $('.ajaxOutput', form);
			message.fadeOut(100);
			
			var validator = form.validate({
				rules: {
					content: {
						required: true
					}
				},
				showErrors: function(){}
			});
			function showMessage(text, is_error, fade_out_delay){
				if(fade_out_delay == undefined) fade_out_delay = -1;
				message.removeClass("error").empty().append(text).fadeIn(300);
				if(is_error) message.addClass('error');
				
				if(fade_out_delay > -1){
					setTimeout(function(){
						message.fadeOut(300);					
					}, fade_out_delay);
				}
			}
			// Validate
			if(!validator.element(form[0].content)){
				valid = false;
				showMessage('Please enter an comment.', true);
			}
			
			// Send if valid		
			if(form.length && valid){
				$.post(form.attr('action'), form.serialize(), function(data, txtStatus){
					if(data.indexOf('ok') > -1){
						showMessage('Your comment have been submited.', false, 1000);
						form[0].reset();
						setTimeout(function(){
							scope.showDiscussions(caller);
						}, 1000);
					}else{
						showMessage(data.replace('error:', ''), true);
					}
				}, 'html');
			}else if(!form.length){
				showMessage("Couldn't submit discuss form", true);
			}
		}catch(ex){ if(debug) alert(ex); }
	};
	this.showDiscussions = function(caller){
		try{
			var panel = $(caller).closest('.infobox-content-small');
			$('.ui-tabs-content:first', panel).show();
			$('.new-post', panel).hide();
			this._loadDiscuss(panel);
		}catch(ex){ if(debug) alert(ex); }
	};
	
	this._loadDiscuss = function(ui_panel){
		try{
			var scope = this;
			var bloggId = jQuery('[name=item_id]', ui_panel).attr('value');
			var ui_panel = $(ui_panel);
			var discussContent = $('.discuss-content', ui_panel);
			var discussUrl = jsBaseUrl + "/api/focus.php?type=item_discussion&item_id=" + bloggId + '&output=json&json_wrapper=?';
			
			discussContent.empty();
			$.get(discussUrl, null, function(json, txtStatus){
				if(json.rssc == undefined) {
					discussContent.empty().append('<p>No comments yet, be the first that comments.</p>');
				}
				else {
					var html = '';
					var discussions = json.rssc.item;
					if(discussions.length == undefined){
						discussions = [discussions];
					}
					for(var i = 0; i < discussions.length; i++) {
						var id = discussions[i].id;
						var pubDate = discussions[i].pubDate;
						var postedBy = discussions[i].postedBy;
						var content = discussions[i].content;
						
						html += '<div class="post"><p>' + content +'</p>' +
						'<div class="post-bottom"><span class="discussions-length">Post #' + (discussions.length-i) + '</span> <span class="postedby">('+ (discussions.length) + ') - ' + postedBy + '</span></div>' +
						'<img src="'+listviewplugin_url+'/images/alphaHR_medium.png" alt="hr" class="hr" /></div>';
					}
					discussContent.empty().append(html);
					scope._updateScrollPane(discussContent);
				}
			}, 'json');
		}catch(ex){ if(debug) alert(ex); }
	};
	this._updateScrollPane = function(target){
		try{
			$(target).jScrollPane({
				scrollbarWidth:23,	//the width of the generated scrollbar in pixels
				scrollbarMargin:3,	//the amount of space to leave on the side of the scrollbar in pixels
				//wheelSpeed:xxx,	//The speed the pane will scroll in response to the mouse wheel in pixels
				showArrows:false,	//Whether to display arrows for the user to scroll with
				//arrowSize:20,		//The height of the arrow buttons if showArrows=true
				//animateTo		-	//Whether to animate when calling scrollTo and scrollBy
				dragMinHeight:45,	//The minimum height to allow the drag bar to be
				dragMaxHeight:45,	//The maximum height to allow the drag bar to be
				animateInterval:100,//The interval in milliseconds to update an animating scrollPane (default 100)
				animateStep:5,		//The amount to divide the remaining scroll distance by when animating (default 3)
				maintainPosition:true, //Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
				scrollbarOnLeft:false, //Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
				reinitialiseOnImageLoad:false // - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded
			});
			//$('.jScrollPaneContainer').css("width",contentWidth+'px').css("height",contentHeight-footerHeight+'px') //stupid html, should net be needed
		}catch(ex){ if(debug) alert(ex); }
	};
	
	this._initInfoBox = function(wrapper, id, color){
		try{
			var scope = this;
			var hexa_color = color.replace('0x', '#');
			var infoBoxHolder_clone = jQuery('#infoBoxHolder-template').clone();
			jQuery('a.share', infoBoxHolder_clone).attr('class', 'share share_'+color);
			jQuery('a.discuss', infoBoxHolder_clone).attr('class', 'discuss discuss_'+color);
			jQuery('a.submit', infoBoxHolder_clone).css('color', hexa_color);
			
			jQuery('[name=item_id]', infoBoxHolder_clone).remove();
			jQuery('#discussPost', infoBoxHolder_clone).append('<input type="hidden" name="item_id" value="'+id+'" />');
			
			var new_id = 'infoBoxHolder_' + id;
			infoBoxHolder_clone.attr('id', new_id).show();
			jQuery('.rss-content', wrapper).after('<div class="infoBoxHolder">' + infoBoxHolder_clone.html() + '</div>');
			
			var infoBoxHolder = jQuery('.infoBoxHolder', wrapper);
			var tabs = jQuery('.tabs', infoBoxHolder);
			var tr = jQuery(tabs).closest('tr');
						
			// Get deeplink for post
			var data = {item_id:id};
			jQuery.get(listviewplugin_url + '/generate-deeplink.ajax.php?json_wrapper=?', data, function(data){
				jQuery('[name=bloggUrl]', infoBoxHolder).attr('value', data.uri);
				jQuery('[name=bloggUrl]', infoBoxHolder_clone).attr('value', data.uri);
			}, 'json');
			// ---
			
			jQuery('.ui-tabs-nav a', tabs).click(function(){
				var li = jQuery(this).closest('li');
				var tab_to_open = $('#' + $(this).attr('href').replace(/.*?#/i, ''), tabs);
				$('.infobox-content-small').not(tab_to_open).hide();
				$('.infoBoxHolder').removeClass("tab-opened");
				$('.ui-tabs-selected').not(li).removeClass('ui-tabs-selected');
				
				tab_to_open.parent().parent().parent().addClass("tab-opened");
				
				if(li.hasClass('ui-tabs-selected')){
					tab_to_open.hide();
					li.removeClass('ui-tabs-selected');
				}else{
					tab_to_open.show();
					li.addClass('ui-tabs-selected');
				}
				if($(this).hasClass('share')){
					
				}else if($(this).hasClass('discuss')){
					scope._loadDiscuss(tab_to_open);
				}
				return false;
			});
			// Init cufon for the new clone
			infoBoxCufon('#' + wrapper.attr('id'));
			
		}catch(ex){ if(debug) alert(ex); }	
	}
	// SHARE
	this.submitShare = function(caller){
		try{
			var valid = true;
			var form = jQuery(caller).closest('form');
			var message = $('.ajaxOutput', form);
			message.fadeOut(100);
			
			var validator = form.validate({
				rules: {
					receiverEmail: {
						required: true,
						email: true
					},
					comment: {
						required: true
					}
				},
				showErrors: function(){}
			});
			function showMessage(text, is_error, fade_out_delay){
				if(fade_out_delay == undefined) fade_out_delay = -1;
				message.removeClass("error").empty().append(text).fadeIn(300);
				if(is_error) message.addClass('error');
				
				if(fade_out_delay > -1){
					setTimeout(function(){
						message.fadeOut(300);					
					}, fade_out_delay);
				}
			}
			// Validate
			if(!validator.element(form[0].receiverEmail)){
				valid = false;
				showMessage('Please enter an valid emailaddress.', true);
			}else if(!validator.element(form[0].comment)){
				valid = false;
				showMessage('Please enter an comment.', true);
			}
			
			// Send if valid		
			if(form.length && valid){
				$.post(form.attr('action'), form.serialize(), function(data, txtStatus){
					if(data.indexOf('ok') > -1){
						showMessage('An e-mail have been sent', false, 1000);
						form[0].comment.value = '';
						form[0].receiverEmail.value = '';
					}else{
						showMessage(data, true);
					}
				});
			}else if(!form.length){
				showMessage("Couldn't submit share form", true);
			}
		}catch(ex){ if(debug) alert(ex); }
	};
}
