/**
 * #######################
 * Functionality for plaza
 * #######################
 */


// Chopless namespace
var CL = CL || {};

CL.Content = CL.Content || {};








/**
 * Singelton
 * Contains a page's post-items
 * (= items on a page that represent a -unique- post)
 */
CL.Content.PostItems = {
	
	// Container
	storage : [],
	
	// Loads all postimems in storage-array
	init : function()
	{
		dojo.query('.postItem').forEach( function( elem )
		{
			if( dojo.attr(elem, 'rel') )
			{
				var postItem = eval( '(' + dojo.attr(elem, 'rel') + ')' );
				postItem.elem = elem;
				CL.Content.PostItems.storage.push(postItem);
			}
		});
	},
	
	// Finds matching elements by given query
	// query must contain 'postItem' as object, followed by a property
	// Ex: " postItem.parentId==30 && postItem.type=='picture' "
	find : function( query )
	{
		var result = [];
		for(i in CL.Content.PostItems.storage)
		{
			var postItem = CL.Content.PostItems.storage[i];
			if( eval(query) )
				result.push(postItem);
		}
		return result;
	}
}








 
 


/**
 * @constructor
 * 
 * dojo.require("dijit.Dialog");
 * dojo.require("dojo.fx");
 */
CL.Content.Frontend_Edit = function(elem,props)
{
	// PRIVATE ATTRIBUTES
	var elem = elem;
	var id = props.id || null;
	var type = props.type || null;
	var title = props.title || 'Untitled post';
	var children = [];
	
	// PRIVILIGED METHODS
	this.getElem = function() {
		return elem;
	};
	this.getId = function() {
		return id;
	};
	this.getType = function() {
		return type;
	};
	this.getType = function() {
		return type;
	};
	this.getTitle = function() {
		return title;
	};
	this.getChildren = function() {
		return children;
	};
	this.addChild = function(elem) {
		children.push(elem);
	};
	this.removeChild = function(elem) {
		delete children[elem];
	};
	
	// CONSTRUCTOR CODE
	this.init();
};


// STATIC ATTRIBUTES
CL.Content.Frontend_Edit.removeUri = null;
CL.Content.Frontend_Edit.censureUri = null;
CL.Content.Frontend_Edit.isAdminUser = false;


// STATIC METHODS
CL.Content.Frontend_Edit.init = function(removeUri,censureUri,isAdminUser,redirectPage)
{
	// Set static values
	CL.Content.Frontend_Edit.removeUri = removeUri;
	CL.Content.Frontend_Edit.censureUri = censureUri;
	CL.Content.Frontend_Edit.isAdminUser = (isAdminUser==1) || false;
	CL.Content.Frontend_Edit.redirectPage = redirectPage || null;
	
	// Find appropiate elements and instantiate them
	dojo.query('.editable').forEach( function( elem )
	{
		var props = eval( '(' + dojo.attr(elem, 'rel') + ')' );
		new CL.Content.Frontend_Edit(elem,props);
	});

};


// PUBLIC, NON-PRIVILIGED METHODS
CL.Content.Frontend_Edit.prototype = {
	
	// Creates a buttonpanel, upon this item
	init : function()
	{		
		var that = this;
		
		var buttonPanel = document.createElement('div');
		buttonPanel.className = 'frontendEdit';
		
		// remove button
		var removeBtn = document.createElement('div');
		removeBtn.className = 'deleteBtn';
		dojo.attr(removeBtn,'title',Lang.transl('deletePost'));
		dojo.connect(removeBtn,'onclick',function()
		{
			var confirmText = Lang.transl('areYouSureYouWant') + ' ' + Lang.transl('toDelete') + ' :<br />"' + that.getTitle() + '"';
			Dialog.confirm( confirmText , {onOk:function() {
				that.remove();										 
			} } );
		});
		buttonPanel.appendChild( removeBtn );
		
		// Censure button, only for admin
		if( CL.Content.Frontend_Edit.isAdminUser )
		{
			var censureBtn = document.createElement('div');
			censureBtn.className = 'censureBtn';
			dojo.attr(censureBtn,'title',Lang.transl('censurePost'));
			dojo.connect(censureBtn,'onclick',function()
			{
				var confirmText = Lang.transl('areYouSureYouWant') + ' ' + Lang.transl('toCensure') + ' :<br />"' + that.getTitle() + '"';
				Dialog.confirm( confirmText , {onOk:function() {
					that.censure();		 
				} } );
			});
			buttonPanel.appendChild( censureBtn );
		}
		
		dojo.style(this.getElem(), 'position', 'relative');
		this.getElem().appendChild( buttonPanel );
		
		// Show - Hide button panel
		dojo.style(buttonPanel, 'opacity', 0);
		dojo.connect(this.getElem(),'onmouseover',function(e) {
			e.stopPropagation();
			dojo.fadeIn({node:buttonPanel,duration:350}).play();
		});
		dojo.connect(this.getElem(),'onmouseout',function(e) {
			e.stopPropagation();
			dojo.fadeOut({node:buttonPanel,duration:350}).play();
		});
		
		this.loadChildren();
	},
	
	// Find children related to this item and store them
	// Two ways: smart and less elegant way (for eg Safari which don't support attribute value list item match)
	loadChildren : function()
	{
		var postItems = CL.Content.PostItems.find( 'postItem.parentId == ' +this.getId() );
		for( i in postItems )
			this.addChild(postItems[i].elem);
	},
	
	// Prepares URI by building a querystring to pass the data
	prepareUri : function(uri)
	{
		var uri = (uri.indexOf('?')==-1) ? uri+'?' : uri;// Add '?' if not there
		uri = (uri.charAt( uri.length - 1 )!='?') ? uri+'&' : uri;// Add '&' if not there, but contains queryvars
		uri += 'type='+this.getType()+'&';
		uri += 'id='+this.getId()+'&';
		return uri;
	},
	
	// Action to remove this item
	remove : function()
	{
		var that = this;
		
		dojo.xhrGet({
			url: this.prepareUri( CL.Content.Frontend_Edit.removeUri ),
			handleAs: "json",
			load: function(data,args){
				if(!data.success)// Action failed
					Dialog.alert( data.message );
				else{// Action succeeded
					// Remove from document
					that.erase( function() {
						if( CL.Content.Frontend_Edit.redirectPage )
							document.location = CL.Content.Frontend_Edit.redirectPage;
					} );
				}
			},
			// if any error occurs, it goes here:
			error: function(error,args){
				console.warn("error!",error);
				Dialog.alert( Lang.transl('deletePostFailed') );
			}
		});
	},
	
	// Action to censure this item
	censure : function()
	{
		var that = this;
		
		dojo.xhrGet({
			url: this.prepareUri( CL.Content.Frontend_Edit.censureUri ),
			handleAs: "json",
			load: function(data,args){
				if(!data.success)// Action failed
					Dialog.alert( data.message );
				else{// Action succeeded
					// Remove from document
					that.erase( function() {
						if( CL.Content.Frontend_Edit.redirectPage )
							document.location = CL.Content.Frontend_Edit.redirectPage;
					} );
				}
			},
			// if any error occurs, it goes here:
			error: function(error,args){
				console.warn("error!",error);
				Dialog.alert( Lang.transl('censurePostFailed') );
			}
		});
	},
	
	// Makes this item vanish from the page
	// and vanishes its possible children too
	// takes an optional callback-function as argument
	erase : function( callback )
	{
		var that = this;
		
		var anim_arr = [];
		
		// Main (parent) object
		var anim = dojo.fadeOut({node:this.getElem(),duration:700});
		dojo.connect(anim,"onEnd",function() {
			that.getElem().parentNode.removeChild( that.getElem() );
			if( callback )
				callback.call();
		});
		anim_arr.push( anim );
		
		// Child objects
		dojo.forEach(this.getChildren(),function(elem)
		{
			var animChild = dojo.fadeOut({node:elem,duration:700});
			dojo.connect(animChild,"onEnd",function() {
				elem.parentNode.removeChild( elem );
			});
			anim_arr.push( animChild );
		});
		
		// Play all animations
		dojo.fx.chain(anim_arr).play();
	}
};










/**
 * @constructor
 * 
 */
 
 
/* 
CL.Content.GeoListItem = function(defCenterLat,defCenterLon,defZoom)
{
	// PRIVATE ATTRIBUTES
	var LiMap;
	var mapContainer;
	var displayLocation;
	
	// PUBLIC ATTRIBUTES
	this.defCenterLat = defCenterLat || 9;
	this.defCenterLon = defCenterLon || 56;
	this.defZoom = defZoom || 6;
	
	// PRIVILIGED METHODS
	this.getLiMap = function() {
		return LiMap;
	};
	
	// CONSTRUCTOR CODE
	// Setup map
	mapContainer = document.createElement('div');
	mapContainer.id = 'listMap';
	dojo.addClass(mapContainer,'gmap_small');
	displayLocation = document.createElement('div');
	displayLocation.id = 'listMapContainer';
	displayLocation.appendChild(mapContainer);
	dojo.body().appendChild(displayLocation);
//	LiMap = new map('listMap',9.75585,56.438203,9);
	
	// Initiate list-items
	console.debug(this);
	this.initListItems();
};


// STATIC ATTRIBUTES
CL.Content.GeoListItem.defCenterLat = 9;
CL.Content.GeoListItem.defCenterLon = 56;
CL.Content.GeoListItem.defZoom = 6;



// STATIC METHODS
CL.Content.GeoListItem.init = function(defCenterLat,defCenterLon,defZoom)
{
	// Set static values
	if(defCenterLat) CL.Content.GeoListItem.defCenterLat = defCenterLat;
	if(defCenterLon) CL.Content.GeoListItem.defCenterLon = defCenterLon;
	if(defZoom) CL.Content.GeoListItem.defZoom = defZoom;

	// Setup map
	mapContainer = document.createElement('div');
	mapContainer.id = 'listMap';
	dojo.addClass(mapContainer,'gmap_small');
	displayLocation = document.createElement('div');
	displayLocation.id = 'listMapContainer';
	displayLocation.appendChild(mapContainer);
	dojo.body().appendChild(displayLocation);
//	LiMap = new map('listMap',9.75585,56.438203,9);
	
	// Find appropiate elements and instantiate them
	var postItems = CL.Content.PostItems.find( "postItem.locLat!='' && postItem.locLon!=''" );
	for( i in postItems )
	{
		var postItem = postItems[i];
		dojo.connect(postItem.elem,'onmouseover',function(e)
		{
			e.stopPropagation();
			var loc = {'lat':postItem.locLat,'lon':postItem.locLon};
			var cord = dojo.coords(this);
			console.debug(cord);
			displayLocation.style.top = cord.y + 'px';
			displayLocation.style.left = cord.x + 'px';
			displayLocation.style.display = 'block';
			
			displayLocation.style.border = '1px solid red';
		});
		
		dojo.connect(postItem.elem,'onmouseout',function(e)
		{
			e.stopPropagation();
			displayLocation.style.display = 'none';
		});
	}// end for
};


// PUBLIC, NON-PRIVILIGED METHODS
CL.Content.GeoListItem.prototype = {
	//
	initListItems : function()
	{
		// 
		console.log('initialting');
	}
};

		*/







 /**
  * Triggers a popup of a link inside a post item
  * @return void
  */
 function triggerPopup(type,id)
 {
	var postItems = CL.Content.PostItems.find( 'postItem.id == ' +id + ' && postItem.type == "' + type +'"' );
	for( i in postItems )
		fireEvent(dojo.query('a',dojo.byId(postItems[i].elem))[0],'click');
 }
 
 
 
 
 /**
  *
  *
  */
 function slideshow()
 {
	//Initialize the SlideShow with an ItemFileReadStore
	dijit.byId('slideshow').setDataStore(imageItemStore,
				{ query: {}, count:5 },
				{
					imageThumbAttr: "thumb",
					imageLargeAttr: "large"
				}
	);
	setTimeout("dijit.byId('slideshow').toggleSlideShow()",10000);
 }
 
 
 
 
 
/**
 * AJAX add comment
 */
function initAjaxComments()
//dojo.addOnLoad( function()
{
	var commentForm = dojo.byId('edit_comment');
	
	if(!commentForm) return;
	
	var commFormValid = new Form(commentForm,{doSubmit:false});
	dojo.connect(commFormValid.form , 'onsubmit' , function(e)
	{
		// Prevent the form from really submitting
		e.preventDefault();
		// Validate this form
		commFormValid.validate();
		// Send it when valid
		if( commFormValid.valid )
		{
			dojo.style("loadingComments", "display", "block");
			//var data = dojo.formToQuery(commentForm);
			// Post form ...
			dojo.xhrPost({
				url: '/ajax/edit-comment.php',
				form: commentForm,
				handleAs: "json",
				load: function(data,args){
					if(!data.success) {// Action failed
						dojo.style("loadingComments", "display", "none");
						Dialog.alert( data.message );
					}else{// Action succeeded
						// Reload comments
						clearInterval(reloadCommentsInterval);
						reloadComments();
						setInterval_reloadComments();
						// Clear text-fields
						dojo.byId('subject').value = '';
						dojo.byId('text').value = '';
					}
				},
				// if any error occurs, it goes here:
				error: function(error,args){
					dojo.style("loadingComments", "display", "none");
					console.warn("error!",error);
					Dialog.alert( Lang.transl('commentAddFailed') );
				}
			});//end dojo.xhrGet()
		}
	});//end dojo.connect()
}
//} );



/**
 * Sets up an interval for reloading comments
 * @return void
 */
function reloadComments()
{
	if( currId == '' || !dojo.byId('commentList') )
		clearInterval(reloadCommentsInterval);
	else{
		// Reload
		dojo.style("loadingComments", "display", "block");
		var data = 'type=article&id=' + currId + '&un=' + (new Date().getTime());
		dojo.xhrGet({
			url: '/ajax/getCommentList.php?' + data,
			handleAs: "text",
			load: function(data,args){
				dojo.byId('commentList').innerHTML = data;
				dojo.style("loadingComments", "display", "none");
			},
			// if any error occurs, it goes here:
			error: function(error,args){
				console.warn("error!",error);
			}
		});//end dojo.xhrGet()
	}
}

/**
 * Sets up an interval for reloading comments
 * @return void
 */
function setInterval_reloadComments()
{
	var interval = 1 * 60 * 1000;//every minute
	reloadCommentsInterval = setInterval('reloadComments()',interval);
}

