/**
 * ###########################################################
 * Common functionality shared between plaza, canvas and popup 
 * ###########################################################
 */


/*
 * Language managing
 */
var Lang = {
	
	// Properties
	xml : null,
	
	// Loads XML language file
	loadXml : function(xmlPath)
	{
		dojo.xhrGet({
			url: xmlPath,
			sync: true,
			handleAs: "xml",
			load: function(data,args){
				Lang.xml = data;
			},
			// if any error occurs, it goes here:
			error: function(error,args){
				console.warn("error!",error);
			}
		});
	},
	
	/**
	 * Translates given string
	 * Finds equivalent in XML, otherwise returns given string
	 * @param {string}	string
	 * @param {object}	opts	 		A contianer for optional arguments
	 * 			{boolean} upper 		True when string should be returned in uppercase
	 * 			{boolean} lower 		True when string should be returned in lowercase
	 * @return {string}
	 */
	transl : function( string , opts )
	{
		var returnVal = string;
		var opts = opts || {};
				
		// is XML loaded		
		if( this.xml )
		{

			var equivalentNode = this.xml.getElementsByTagName(string);
			if( equivalentNode.length > 0 )
				returnVal = equivalentNode[0].firstChild.nodeValue;
		}// Return given string when nothing else gave a result
		
		if( opts.upper ) returnVal = returnVal.toUpperCase();
		if( opts.lower ) returnVal = returnVal.toLowerCase();
		
		return returnVal;
	}
};
//dojo.onLoad(Lang.loadXml);



/*
 * Dialogs
 * dojo.require("dijit.Dialog");
 */
var Dialog = {
	
	// Static Properties
	text : {
		ok : Lang.transl('ok'),
		cancel : Lang.transl('cancel'),
		error : Lang.transl('error'),
		warning : Lang.transl('warning')
	},
	
	// Static Methods
	alert : function( message , title )
	{		
		var title = title || this.text.warning;
		var dialog = new dijit.Dialog({ title: title});
		dialog.startup();
				
		var contentNode = document.createElement('div');
		var paragraph = document.createElement('div');//appendChild( document.createTextNode(message) );
		
		var buttonContainer = document.createElement('div');
		buttonContainer.className = 'buttonset';
		buttonContainer.appendChild( this.getOkBtn(dialog.domNode.id) );
		
		contentNode.appendChild( paragraph );
		contentNode.appendChild( buttonContainer );
		
		paragraph.innerHTML = message;//appendChild( document.createTextNode(message) );
		
		dialog.containerNode.appendChild(contentNode);
		dialog.show();
		
		return dialog;
	},
	
	
	confirm : function( message , opts )
	{
		var title = opts.title || '';
		var onOk = opts.onOk || null;
		var onCancel = opts.onCancel || null;
			
		var dialog = new dijit.Dialog({ title: title});
		dialog.startup();
				
		var contentNode = document.createElement('div');
		var paragraph = document.createElement('div')//appendChild( document.createTextNode(message) );
		
		var buttonContainer = document.createElement('div');
		buttonContainer.className = 'buttonset';
		
		buttonContainer.appendChild( this.getOkBtn(dialog.domNode.id , onOk) );
		buttonContainer.appendChild( this.getCancelBtn(dialog.domNode.id , onCancel) );
		
		contentNode.appendChild( paragraph );
		contentNode.appendChild( buttonContainer );
		
		paragraph.innerHTML = message;//appendChild( document.createTextNode(message) );
		
		dialog.containerNode.appendChild(contentNode);
		dialog.show();
		
		return dialog;
	},
	
	
	getOkBtn : function( dialogId , callback )
	{
		var button = document.createElement('button');
		button.appendChild( document.createTextNode( this.text.ok ) );
		button.onclick = function()
		{				
			if( callback )
				callback.call();
			dijit.byId(dialogId).hide();
		};
		
		return button;
	},

	getCancelBtn : function( dialogId , callback )
	{
		var button = document.createElement('button');
		button.appendChild( document.createTextNode( this.text.cancel ) );
		button.onclick = function()
		{
			if( callback )
				callback.call();
			dijit.byId(dialogId).hide();
		};
		
		return button;
	}
};



var Text = function(type)
{
	this.type = type || 'html';//'html' or 'txt'
	this.handler = null;
	switch(type)
	{
		case 'html':
			this.handler = new TextHtml;
			break;
		case 'txt':
			this.handler = new TextTxt;
			break;
	}
};
Text.prototype.getLineBreak = function()
{
	return this.handler.getLineBreak();
};


var TextHtml = function() {};
TextHtml.prototype.getLineBreak = function()
{
	return '<br />';
};


var TextTxt = function() {};
TextTxt.prototype.getLineBreak = function()
{
	return '\n';
};




/**
 * The safe way to fire an event
 */
function fireEvent(element,event)
{  
	if (document.createEventObject){  
		// dispatch for IE  
		var evt = document.createEventObject();  
		return element.fireEvent('on'+event,evt)  
	}else{  
		// dispatch for firefox + others  
		var evt = document.createEvent("HTMLEvents");  
		evt.initEvent(event, true, true ); // event type,bubbling,cancelable  
		return !element.dispatchEvent(evt);  
	}  
} 





/**
 * Sets cookies containing browserwindows width and height
  * @return void
 */
function setWindowDimensions()
{
	var winDim = getWindowDimensions();
	dojo.cookie("windowWidth", winDim[0], { expires: 1 });
	dojo.cookie("windowHeight", winDim[1], { expires: 1 });
}
/**
 * Gets browserwindows width and height
  * @return array
 */
function getWindowDimensions()
{
	var de = document.documentElement;
	var windowWidth = self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	var windowHeight = self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
	return [windowWidth,windowHeight];
}


/**
 * Moves element #toggleProperties so it fits the contentwidth
  * @return void
 */
function positionDetailProperties()
{
	dojo.query('#detail .content img').connect("onload",function(e)
	{// Wait for the image to be loaded, to know its width
		var contentEl = e.target;
		var de = document.documentElement;
		var windowWidth = self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;

		var contentWidth = dojo.marginBox(contentEl).w;
		
		var propOffset = Math.round(windowWidth/2) - Math.round(contentWidth/2);
		dojo.byId('properties').style.left = propOffset+'px';
		dojo.byId('topProperties').style.left = propOffset+'px';
	});
}



/**
 *
 */
function toggleDetails()
{
	ezToggle({
		node : 'properties',
		triggerNode : 'toggleProperties',
		start : 'hide'
	});
	dojo.style('properties',{
		visibility: 'visible',
		display: 'none'
	});
}




/**
 * Cecks whether a page is opened within a frame(set)
 * @return boolean
 */
function is_framed()
{
	
	var framed = false;
	
	// Will fail when parent.location.href is a different domain than window.location.href
	// and can therefore only be framed
	try {
		framed = (parent.location.href != window.location.href);
	}catch(err){
		framed = true;
	}
		
	return framed;
}//end function



/**
 * Sets target="_parent" on all un-targeted a-elements
 * @return void
 */
function setTargetParent()
{
	dojo.query('a').forEach(function(item) {
		if(!dojo.attr(item,'target'))
			dojo.attr(item,'target','_parent');
	});
}



/**
 * Returns a unique string
 * @param string
 * @return boolean
 */
function isset(varname){
	return(typeof(window[varname])!='undefined');
}



/**
 * Returns a unique string
 * In a loop it might give results like this:
16:24:12:222 1225380248547_15
16:24:12:231 1225380249618_16
16:24:12:240 1225380249818_17
 * @return string
 */
function unique()
{
	
	var iterator = 0;
	if( isset('unid') )
	{
		var uq_arr = unid.split('_');
		iterator = uq_arr[1];
	}
	
	iterator++;
	// In global scope
	unid = new Date().getTime() + '_' + iterator;
	return unid;
}



/**
 * Tells user his browser is not supprted for the current content
 */
function alertBrowserUnsupported()
{
	Dialog.alert( Lang.transl('browserUnsupported') );
}











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

/**
 *
 * dojo.require("dojo.io.iframe");
 *
 */
CL.Userdata.Avatar = {
	//
	init : function()
	{
		// Hide upload for to start with
		dojo.query('#avatarForm').style('display','none');
		
		// Show upload form when desired
		dojo.query('#resetAvatar').connect('onclick',function(e){
			dojo.stopEvent(e);
			dojo.byId('avatar').value = '';
			dojo.query('#avatarImg img').forEach(function(item){
				item.src = '/images/def-avatar.png';
			});
		});
		
		// Show upload form when desired
		dojo.query('#changeAvatar').connect('onclick',function(e){
			dojo.stopEvent(e);
			CL.Userdata.Avatar.showUploadForm();
		});
		
		// Upload image immediately when user chooses one
		dojo.query('input[type=file]').connect('onchange',function(e)
		{
			var myInput = e.target;
			var myContainer = myInput.parentNode;
			var myUploadStatus = dojo.query('.uploadStatus',myContainer)[0];
				
			// Uploading...
			myUploadStatus.innerHTML = '<img src="/images/loading.gif" title="'+ Lang.transl('uploading') +'" />';
			dojo.style(myUploadStatus, {
				"opacity": 1,
				"display": "block"
			});
			dojo.query('#avatarForm').style('display','none');
			
			// http://www.dojotoolkit.org/forum/dojo-core-dojo-0-9/dojo-core-support/file-upload-iframe-not-working-ie
			//  WORKS !!
			dojo.io.iframe.send({
				url: "/ajax/uploadAvatar.php",
				method: "post",
				handleAs: "json",// For all values EXCEPT html, The server response should be an HTML file with a textarea element.
				form: 'avatarForm',
				load: function(data,ioArgs){
					console.debug(data);
					if(!data.success) {
						console.error(data.message)
						this.error();
					}else {
						var filename = data.files[0].name;
						dojo.style(myUploadStatus,'display','none');
						dojo.query('#changeAvatar').style('display','block');
						dojo.byId('avatar').value = filename;
						dojo.query('#avatarImg img').forEach(function(item){
							item.src = '/avatars/' + filename;
						});
					}
					return data;
				},
				error: function(error){
					myUploadStatus.innerHTML = Lang.transl('fileUploadFailed') + ', ' + Lang.transl('tryAgain',{lower:true});
					dojo.style(myInput,'display','block');
					
					var animArgs = {
						'node': myUploadStatus,
						'duration': 1000, // ms to run animation
						'delay': 3000 // ms to stall before playing
					};
					
					// Fade out
					var anim = dojo.fadeOut(animArgs);
					
					// When faded out, hide node
					dojo.connect(anim,"onEnd",function(){
						dojo.style(myUploadStatus,'display','none');
					});
					
					// Play that joint!
					anim.play();
				}
			});// end dojo.io.iframe.send
		});// end dojo.query('input[type=file]')
	},
	
	//
	showUploadForm : function()
	{
		dojo.query('#changeAvatar').style('display','none');
		dojo.fx.wipeIn({ node: dojo.byId('avatarForm') , duration:500 }).play();
	}
};




/*
 * ### SOCIAL ###
 */

CL.Social = CL.Social || {};


/*
 * ### Twitter ###
 */
CL.Social.Twitter = CL.Social.Twitter || {};

/**
 * Displays a box with the Twitter users a given twitter user is following
 *
 * dojo.require("dojo.io.script");
 * dojo.require("dijit.Tooltip");
 * 
 * @param {object}	opts
 * 		screenName	{string}			Twitter-username
 * 		containerEl	{string}/{object}	Element(-id) of where to place the box
 * 		max			{integer}			Max. number of users to display
 * @return void
 */
CL.Social.Twitter.showFollowing = function(opts)
{
	var opts = opts || {};
	var ws = 'http://twitter.com/statuses/friends/'+opts.screenName+'.json';
	var containerEl = dojo.byId(opts.containerEl);
	
	if(!containerEl || !opts.screenName) return;
	
	dojo.io.script.get({
		callbackParamName : 'callback',
		url: ws,
		handleAs: "json",
		load: function(response, ioArgs)
		{
			var total = response.length;
			// Build markup
			containerEl.innerHTML = '';
			var us = document.createElement('a');
			us.className = 'us';
			us.href = 'http://twitter.com/'+opts.screenName;
			us.appendChild( document.createTextNode(Lang.transl('followUsOnTwitter')) );
			var following = document.createElement('h4');
			following.className = 'following';
			following.appendChild( document.createTextNode( Lang.transl('following')+' ('+ (total+1) +'):' ) );
			containerEl.appendChild(us);
			containerEl.appendChild(following);
			
			var twitterEl = document.createElement('div');
			twitterEl.className = 'twitterFollowers';
			
			var max = (opts.max && opts.max<total) ? opts.max : total;
			if( max < total )
			{
				var rand = Math.round(Math.random()*(total-max));
				var start = ((rand + max) > total) ? (rand*-1) : rand;
				arr = response.slice(start,rand + max);
			}
			
			for(var i=0; i<max; i++)
			{
				var user = response[i];
				if(!user) continue;		
				var userEl = document.createElement('a');
				userEl.className = 'user';
				userEl.href = 'http://twitter.com/'+user.screen_name;
				var userAvatar = document.createElement('img');
				userAvatar.src = user.profile_image_url;
				userAvatar.width = 48;
				userAvatar.height = 48;
				var status = (user.status != null) ? user.status.text : '';
				var hover = new dijit.Tooltip({
					connectId: [userAvatar],
					label: '<strong>'+user.name+'</strong><br /><p>'+status+'</p>',
					maxWidth : '250px'
				});

				userEl.appendChild(userAvatar);
				twitterEl.appendChild(userEl);
			}
			containerEl.appendChild(twitterEl);
		},
		error: function(response, ioArgs){
			console.error('Error occured');
			console.error(response);
		}
	});
}




/*
 * ### Facebook ###
 */
CL.Social.Facebook = CL.Social.Facebook || {};

/**
 * Loads a Facebook Fanbox
 * placing an iFrame in a given element
 * @param {object}	opts
 * 		containerEl	{string}/{object}	Element(-id) of where to place the box
 * 		width		{integer}			Width of the box
 * 		height		{integer}			Height of the box
 * 		scrolling	{string}			Scrolling attribute options for iFrame (yes/no/auto)
 * 		max			{integer}			Max. number of users to display
 * @return void
 */
CL.Social.Facebook.showFanbox = function(opts)
{
	var opts		 = opts			 || {};
	var width		 = opts.width	 || 385;
	var height		 = opts.height	 || 300;
	var scrolling	 = opts.scrolling|| 'auto';
	var max			 = opts.max		 || 12;
	var containerEl	 = dojo.byId(opts.containerEl);
	var fanBoxUrl	 = '/ajax/iframeFbFanbox.php?width='+width+'&connections='+max;
	
	if(!containerEl) return;
	
	var iframe = document.createElement("iframe");
	iframe.setAttribute('id', 'facebookFanbox');
	iframe.setAttribute('border', '0');
	// Set Frameborder as propertie (NOT attribute) for IE's sake, but set other as attributes in stead
	iframe.frameSpacing = 0;
	iframe.frameBorder = 0;
	iframe.setAttribute('width', width);
	iframe.setAttribute('height', height);
	iframe.setAttribute('scrolling', scrolling);
	containerEl.appendChild(iframe);
	iframe.setAttribute('src', fanBoxUrl);
}






/**
 * Initiates event handlers for rating a post
 * @return void
 */
function initRating()
{
	var animSetting = {
		duration: 1500,
		delay:2000
	}
	dojo.query("ul.star-rating li").forEach( function(elem, index) {
		var containerEl = elem.parentNode;
		var type = dojo.attr(containerEl, 'rel');
		var postId = dojo.attr(containerEl, 'postid');
		
		// user wants to rate this post
		dojo.connect(elem, "onclick", function(e) {
			dojo.stopEvent(e);
			if( index>0 )
				dojo.xhrPost({
					url: '/ajax/set-rating.php',
					content: {type: type, post_id: postId, score: index},
					handleAs: "json",
					load: function(data,args){
						if( data.success == false ) {
							// remove focus, since it displays current users choice
							dojo.query('a:focus',containerEl).forEach( function(elem, index){
								elem.blur();
							} );
							Dialog.alert( data.message.replace('origPage=%s','origPage='+location.href) );
						}else{
							//display new value
							dojo.fadeOut({
								node: containerEl,
								duration: animSetting.duration,
								delay: animSetting.delay,
								onEnd: function() {
									// set new value
									dojo.query('li:first-child', containerEl).forEach( function(elem, index){
										dojo.style(elem, 'width', data.average.pct+'%');
									} );
									// remove focus, since it displays current users choice
									dojo.query('a:focus',containerEl).forEach( function(elem, index){
										elem.blur();
									} );
									// show new result
									dojo.fadeIn({
										node: containerEl,
										duration: animSetting.duration
									}).play();
								}
							}).play();
						}
					},
					// if any error occurs, it goes here:
					error: function(error,args){
						Dialog.alert( Lang.transl("requestError") );
					}
				});
		} );
	} );
}
