(function($){
	"use strict";

	var app = {
		/* Tab managment */
		'tab'	: {
			'init'	: function () {
				bilbord.connection.get.statuses.all()
				.done(function(response){
					var columnCount = response.length,
					wrapper = $('#hashtagTabContent');

					for (var c=0; c<columnCount; c++) {
						var column = response[c].tab,
						statuses = response[c].statuses.data,
						statusCount = statuses.length,
						statusesHTML = '',
						container = $('#tabContent'+column.id+' > .tabContent');

						if (container.length < 1) {
							$('#unapprovedStatusesTabs a[href="#tabContent' + column.id + '"]');
							column.settings = !column.settings ? {'pinned':false} : column.settings;

							var containerHTML	= bilbord.theme.statusContainer(column.id, c === 0, column.settings);

							container = wrapper.append(containerHTML).find('#tabContent' + column.id + '>.tabContent');
						}

						for (var s=0; s<statuses.length; s++) {
							statusesHTML += bilbord.theme.status(statuses[s],'col-sm-4 col-lg-3');
						}
						container.append( statusesHTML );
					}

					app.tab.current.tab = $('#unapprovedStatusesTabs li.active[role="presentation"]');
					$('#unapprovedStatusesTabs li[role="presentation"]').eq(0).trigger('click');

					setColumns();
				});
			},

			'pin'		: function (e) {
				var dropdown = $('#unapprovedStatusesTabs .dropdown'),
				restList = $('#unpinnedTabsList'),
				attrID = $(this).closest('.tabContentWrapp').attr('id'),
				link = $('a[href=#'+attrID+']').parent(),
				form = $(this).closest('.tabSettingsForm'),
				id = form.find('input[name="columnId"]').val(),
				pined = $(this).is(':checked');

				bilbord.connection.post.tab.settings(id, {'pinned' : pined})
					.done(function(response){
						console.log('pin tab response', response);
					});

				if( pined ) {
					dropdown.before(link);
				} else {
					restList.append(link);
				}

				if( restList.children().length > 0 ) {
					dropdown.show();
				} else {
					dropdown.hide();
				}
			},

			'remove'	: function (e) {
				var tabId = $(this).closest('.tabSettingsForm').find('input[name=columnId]').val();

				bilbord.connection.post.tab.remove(tabId, {'state'	: -1})
				.done(function(response) {
					if( response.success != undefined ) {
						$('#tabContent'+tabId).remove();
						$('#unapprovedStatusesTabs a[href=#tabContent'+tabId+']').parent('li').remove();
						$('#unapprovedStatusesTabs a:first').tab('show');
					}
				});
			},

			'create'	: function (data) {
				if( data.error != undefined ){
					alert(data.error);
					return false;
				}

				$('#createNewColumnDialog').modal('hide');

				var tab = bilbord.theme.statusTab ( data, true ),
				containerHTML = bilbord.theme.statusContainer(data.id, true, {'pinned':false});

				$('#unpinnedTabs').before(tab);
				$('#hashtagTabContent').append(containerHTML);
				var tabContent =  $('#tabContent'+data.id);

				tabContent.nanoScroller()

				tabContent.find('.grid').masonry({
					columnWidth: '.grid-sizer',
					itemSelector: '.grid-item',
				});

				$('#tab'+data.id).parent().removeClass('active');

				$('#unapprovedStatusesTabs a[data-toggle="tab"]')
					.off('show.bs.tab', app.tab.open)
					.on('show.bs.tab', app.tab.open)
					.off('shown.bs.tab', app.lists.layout)
					.on('shown.bs.tab', app.lists.layout);
			},

			'open'		: function (e) {
				// console.log(e);
				if (app.tab.current.tab) {
					app.tab.current.tab.removeClass('active');
				}

				app.tab.current.tab = $(this.hash)
					.addClass('active')
					.on('preloaded', function (e) {
						var tab = $(this);

						if (!tab.is('.masonry')) {
							tab.masonry({
								'columnWidth'	: '.grid-sizer',
								'itemSelector'	: '.grid-item',
							})
							.addClass('masonry');
						}
						else {
							tab.masonry('layout');
						}

						// tab.nanoScroller();
					});

				app.tab.current.loaded = 0;
				app.tab.current.notLoaded = app.tab.current.tab.find('img.media');

				app.tab.current.notLoaded.each(function () {
					if (this.complete) {
						app.tab.current.loaded +=1;
					}
					else {
						$(this).one('load', app.tab.current.preload);
					}
				});
				app.tab.current.notLoaded = app.tab.current.notLoaded.length;

				if (app.tab.current.notLoaded == app.tab.current.loaded) {
					app.tab.current.tab.trigger('preloaded');
				}

				$(this).attr('data-hasnew', '0');
				this.imagesLoaded = 0;
			},

			'current' : {
				'tab'		: null,
				'loaded'	: 0,
				'notLoaded'	: 0,
				'preload'	: function (e) {
					app.tab.current.loaded +=1;

					if (app.tab.current.loaded >= app.tab.current.notLoaded) {
						app.tab.current.tab.trigger('preloaded');
					}
				}
			}
		},

		/* statuses managment */
		'status'		: {
			'beforeApprove'	: function (e) {
				var approvedStatusNum = $('#approvedStatusesList .status').length;
				if (approvedStatusNum >= bilbord.settings.maxStatuses) {
					alert('Popuniliste sva slobodna polja za odobrene statuse!')
					return false;
				}

				var status = $(this).closest('.status'),
				statusData = {
					'avatar'	: status.find('.avatar > img').attr('src'),
					'username'	: status.find('.username').text(),
					'txt'		: status.find('.text').text(),
					'media'		: status.find('.media').length > 0 ? status.find('.media').attr('src') : false,
					'id'		: status.find('input[name="id"]').val()
				},
				modalElm = $('#approveStatusModal'),
				ModalHtml = window.sessionStorage.getItem('approveStatusModalHtml'),
				contentWrapp = status.closest('.tabContentWrapp').attr('id');
				statusData.network = $('#unapprovedStatusesTabs a[href="#' + contentWrapp + '"]').data('network');

				modalElm.modal('show');
				modalElm.attr('data-statusId', statusData.id);

				for( var type in app.canvas.all ) {
					app.canvas.all[type].obj = app.canvas.init(type, statusData);
				}

				$('#approveStatus').on('click', app.status.approve);
			},

			'approve'	: function (e) {
				var modalElm = $('#approveStatusModal'),
				statuses = Array(),
				statusId = modalElm.attr('data-statusId'),
				status = $('input[name="id"][value="'+statusId+'"]').closest('.status');

				var i=0
				for (var type in app.canvas.all) {
					var canvas = app.canvas.all[type].canvas;
					canvas.deactivateAll().renderAll();
					statuses[i] = canvas.toDataURL();
					i++;
				};

				bilbord.connection.post.statuses.approved({
					"statusId"	: statusId,
					"photos"	: statuses
				})
				.done(function(response, message) {
					console.log('postApprovedStatus', response, message);
					modalElm.modal('hide');
					if (response.status == 'error') {
						alert('Something went wrong');
						return false;
					}

					$('#hashtagTabContent .masonry.active .grid')
						.masonry( 'remove', status )
						.masonry('layout');

					status
						.removeClass('col-sm-4 col-lg-3')
						.addClass('col-sm-12')
						.attr('style', null)
						.find('.statusFiles > img')
						.attr('src', statuses[1]);

					$('#approvedStatusesList .nano-content')
						.prepend( status );

					window.setTimeout(function() {
						$('#approvedStatusesForm').trigger('submit');
					}, 500);
				})
				.fail(function(response, message) {
					alert(message);
					modalElm.modal('hide');
				});
			},

			'unapprove'	: function (e) {
				console.log('unapprove', e.target);
				var confirmRemove = window.confirm('Remove status?');
				if(!confirmRemove) {
					return false;
				}

				var status		= $(this).closest('.status'),
					sid			= status.find('> input[name=id]').val(),
					remove		= status.closest('#unapprovedStatuses').length,
					newState	= remove > 0 ? -1 : 3;

				bilbord.connection.post.statuses
					.unapprove(sid, newState)
					.done(function(response) {
						status.remove();

						if( remove > 0 ) {
							$('#hashtagTabContent .masonry.active .grid').masonry('layout');
						} else {
							$('#approvedStatusesForm').trigger('submit');
						}
					});
			},

			'order'		: function (e) {
				var status = $(this).closest('.status');
				if( e.data.direction > 0 ) {
					$(status).next().after( status );
				} else {
					$(status).prev().before( status );
				}

				$('#approvedStatusesForm').trigger('submit');
			},

			'resort'	: function (e) {
				e.preventDefault();

				var form = $(this),
				formContent = form.find('.nano-content'),
				statuses = form
					.serializeArray()
					.map(function(val, index){
						if (val.hasOwnProperty('value')) {
							return val.value;
						}
					});

				bilbord.connection.post.statuses
					.resort({
						'statuses'	: statuses,
						'max'		: bilbord.settings.maxStatuses
					})
					.done(function (response) {
						formContent.find('.status').remove();

						for (var i=0; i<response.length; i++) {
							var elm = bilbord.theme.status(response[i], null);
							formContent.append(elm);
						}

						formContent.find('.status').each(function(i, elm) {
							app.status.init(elm);
						});
					});
			},

			'clone'		: function (e) {
				e.preventDefault();

				var alfa	= $(this).closest('.status'),
					id		= alfa.find('input[name="id"]').val();

				bilbord.connection.post.statuses.clone(id)
					.done(function (response) {

						var status = alfa.clone();
						status.find('input[name="id"]').val(response.id);

						alfa.after(status);

						$('#approvedStatusesForm').trigger('submit');
					});
			},

			'init' : function (status) {
				$(status)
					.on('click', '.cloneStatus', app.status.clone)
					.on('click', '.approveStatus', app.status.beforeApprove)
					.on('click', '.unapproveStatus', app.status.unapprove)
					.on('click', '.moveUpStatus', {'direction':-1}, app.status.order)
					.on('click', '.moveDownStatus', {'direction':1}, app.status.order);
			},
		},

		'lists'	: {
			'initApproved' : function  () {
				// console.log('setApprovedStatuses');
				var approvedList = $('#approvedStatusesList .nano-content');

				if (approvedList.length < 1){
					$('#approvedStatusesList').append('<div class="nano-content"></div>');
					approvedList = approvedList.find('.nano-content');
				}

				bilbord.connection.get.statuses.approved()
				.done(function(response){
					$('#approvedStatusesList')
						.css('height',function(){
							return $('#approvedStatuses').offset().top + $('#approvedStatuses').height() - $(this).offset().top;
						});

					if( response.error != undefined ){
						return false;
					}

					var statusesNum = response.length,
					statusesHTML = '';

					for ( var s in response ) {
						statusesHTML += bilbord.theme.status(response[s]);
					}

					approvedList.append(statusesHTML);

					approvedList.find('.status').each(function() {
						app.status.init(this);
					})/*
						.find('.moveUpStatus').on('click', {'direction':-1}, app.status.order);
					approvedList
						.find('.moveDownStatus').on('click', {'direction':1}, app.status.order);
					approvedList
						.on('click', '.unapproveStatus', app.status.unapprove);*/
				});
			},

			'initUnapproved'	: function () {
				bilbord.connection.get.tabs.all()
				.done(function(tabs){
					for( var c = 0; c < tabs.length; c++ ) {
						var pinned = (tabs[c].settings != null ? (tabs[c].settings.pinned != undefined ? tabs[c].settings.pinned : false) : false),
						tab = bilbord.theme.statusTab( tabs[c], c==0 ),
						parrent = pinned ? '#unpinnedTabs' : '#unpinnedTabsList',
						fn = pinned ? 'before' : 'append';

						$(parrent)[fn](tab);
					}
					var tabs = $('#unapprovedStatusesTabs');

					tabs.find('a[data-toggle="tab"]')
						.on('show.bs.tab', app.tab.open)
						.on('shown.bs.tab', app.lists.layout);// <!-- check -->

					app.tab.init();
				});
			},

			'layout'		: function (e) {
				/*var link = this,
				tabContent = $(this.hash + ' .grid');
				tabContent.masonry('layout');*/
				/*tabContent.find('img').on('load', function(){
					console.log('loaded');
					link.imagesLoaded+=1;
					if (link.imagesLoaded == images.length) {
						$('#hashtagTabContent .tabContentWrapp.active .grid').masonry('layout');
					}
				});*/
			}

		},

		'autoPilot'		: function (evt) {
			if( $(this).prop('checked') ) {
				window.crawlMedia = window.setInterval(app.crawlMedia, 30000);
			}
			else {
				clearInterval(window.crawlMedia);
			}
		},

		'crawlMedia'	: function () {
			var btn = $(this).find('.loading').addClass('fa fa-spinner fa-pulse');

			bilbord.connection.get.statuses.crone()
				.done(function(response, status, jqXHR) {
					btn.removeClass('fa fa-spinner fa-pulse');
					for( var s=0; s < response.length; s++ ) {
						var statuses = [];

						$('#tab'+response[s].id).attr('data-hasnew', function(){
							return parseInt( $(this).attr('data-hasnew') ) + response[s].statuses.length;
						});

						if( response[s].num > 0 ) {
							response[s].statuses.reverse();

							for( var i=0; i<response[s].statuses.length; i++ ) {

								if( response[s].statuses[i].length > 0 ) {
									for( var j=0; j<response[s].statuses[i].length; j++ ) {
										var status = bilbord.theme.status(response[s].statuses[i][j], 'col-sm-4 col-lg-3');
										status = $(status)
											.addClass('new');
										statuses.push( status );
									}
								}
								else {
									var status = bilbord.theme.status(response[s].statuses[i], 'col-sm-4 col-lg-3');
									status = $(status)
										.addClass('new');
									statuses.push( status );
								}
							}
						}

						$('#tabContent'+response[s].id+' .grid > .grid-sizer').after(statuses);
						var newElms = $('#tabContent'+response[s].id+' .grid > .new'),
						tabContent = $('#tabContent'+response[s].id);

						tabContent.find('.grid')
							.masonry('prepended', newElms)
							.masonry('layout');

						newElms.find('.approveStatus').on('click', app.status.beforeApprove);
						newElms.find('.unapproveStatus').on('click', app.status.unapprove);
						newElms.removeClass('new');
					}
				});
		},

		'init'	: function () {
			app.lists.initApproved();/* display approved Statuses */
			app.lists.initUnapproved();/* Get columns */

			$('#crawler').on('click', app.crawlMedia);

			$( "#approvedStatusesForm" )
				.on( "submit", app.status.resort);

			$('#createNewColumnDialog')
				.on('shown.bs.modal', function () {
					$('#selectSocialNetwork').focus();
				});

			$('#createNewColumnBtn')
				.on('click', function(e){
					bilbord.connection.post.tab.create({
						social_network	: $('#selectSocialNetwork').val(),
						hashtag			: $('#inputHashtag').val()
					})
					.done(app.tab.create);
				});

			$('#unapprovedStatusesTabs .addColumn').on('click', function(e){
				$('#createNewColumnDialog').modal('show');
			});

			for (var c in app.canvas.all) {
				app.canvas.all[c].design.background = $('#'+app.canvas.all[c].id).closest('.canvasOuterWrapper').data('background');
			}

			$('.decreaseFont').on('click', app.canvas.font.decrease)
			$('.increaseFont').on('click', app.canvas.font.increse)
		},


/**
 * Cavnas settings and manipulation
 */
		'canvas' : {
			'all'	: {
				"4x3": {
					"canvas": null,
					"id": "status4x3Canvas",
					"dimensions": {
						"width": 392,
						"height": 280
					},
					"design": {
						"avatar": false/*{
							"x": 1,
							"y": 260,
							"width": 20,
							"height": 20
						}*/,
						"logo": false/*{
							"files": {
								"twitter": "/administrator/images/4x3-tw.png",
								"instagram": "/administrator/images/4x3-in.png"
							},
							"x": 325,
							"y": 100
						}*/,
						"name": {
							"x": 260,
							"y": 220,
							"max_width": 110,
							"max_height": 18,
							"style": {
								"fontFamily": "Roboto",
								"fontSize": 8,
								"fontWeight": "bold",
								"fontStyle": "",
								"fill": "#333",
								"padding": 5
							}
						},
						"message": {
							"x": 260,
							"y": 68,
							"max_width": 112,
							"max_height": 146,
							"style": {
								"fontFamily": "Roboto",
								"fontSize": 11,
								"fontWeight": 400,
								"fontStyle": "regular",
								"fill": "#333"
							}
						},
						"picture"	: {
							"x"				: 11,
							"y"				: 45,
							"max_width"		: 210,
							"max_height"	: 158,
							"angle"			: 0
						},
						"background": ""
					}
				},
				"16x9": {
					"canvas": null,
					"id": "status16x9Canvas",
					"dimensions": {
						"width": 588,
						"height": 280
					},
					"design": {
						"avatar": false/*{
							"x": 284,
							"y": 146,
							"width": 25,
							"height": 25
						}*/,
						"logo": false/*{
							"files": {
								"twitter": "/administrator/images/16x9-tw.png",
								"instagram": "/administrator/images/16x9-in.png"
							},
							"x": 573,
							"y": 148
						}*/,
						"name": {
							"x": 411,
							"y": 218,
							"max_width": 130,
							"max_height": 18,
							"style": {
								"fontFamily": "Roboto",
								"fontSize": 8,
								"fontWeight": "bold",
								"fontStyle": "",
								"fill": "#333",
								"padding": 5
							}
						},
						"message": {
							"x": 411,
							"y": 38,
							"max_width": 130,
							"max_height": 177,
							"style": {
								"fontFamily": "Roboto",
								"fontSize": 11,
								"fontWeight": 900,
								"fontStyle": "regular",
								"fill": "#333"
							}
						},
						"picture": {
							"x"				: 55,
							"y"				: 27,
							"max_width"		: 293,
							"max_height"	: 222,
							"angle"			: 0
						},
						"background": ""
					}
				}
			},

			'getStyle'			: function (canvasName, type, style) {
				var baseStyle = app.canvas.all[canvasName].design[type].style;
				for (var key in style) {
					baseStyle[key] = style[key];
				}
				return baseStyle;
			},

			'clipPhoto'	: function (ctx, design) {
				ctx.save();
				ctx.setTransform(1, 0, 0, 1, 0, 0);

				ctx.rect(
					design.x, design.y,
					design.max_width, design.max_height
				);
				ctx.restore();
			},

			'data'	: null,

			'font' : {
				'changeSize'	: function (canvas, type, elm, delta) {
					var size	= new Number(  elm.getFontSize() ),
						design	= $.extend({}, app.canvas.all[type].design[elm.id]);

					canvas.setActiveObject(elm);
					elm.set('fontSize', (size + delta));

					elm.set({
						'text'	: wrapCanvasText(elm, canvas, design.max_width, design.max_height)
					});

					canvas.renderAll();
					return false;
				},

				'decrease'	: function (e) {
					e.preventDefault();

					var type = $(this).closest('.canvasOuterWrapper').data('canvas'),
					canvas = app.canvas.all[type].canvas,
					elm = canvas.getActiveObject();

					app.canvas.font.changeSize(canvas, type, elm, -1);
					return false;
				},

				'increse'	: function (e) {
					e.preventDefault();

					var type = $(this).closest('.canvasOuterWrapper').data('canvas'),
					canvas = app.canvas.all[type].canvas,
					elm = canvas.getActiveObject();
					// console.log(elm);

					app.canvas.font.changeSize(canvas, type, elm, 1);
					return false;
				}
			},

			'init'		: function (c, data) {
				// app.canvas.data = $.extend({}, data);

				var settings = app.canvas.all[c],
					design = settings.design,
					canvas = !settings.canvas ? new fabric.Canvas(settings.id) : settings.canvas,
					dimensions = settings.dimensions,

					nameStyle = app.canvas.getStyle(c, 'name', {
						'id'			: 'name',
						'left'			: design.name.x,
						'top'			: design.name.y,
						'lineHeight'	: 1,
						'lockMovementY'	: true,
						'lockRotation'	: true,
						'hasControls'	: false,
						'type'			: 'Text'
					}),
					name = new fabric.Text(data.username, nameStyle),

					messageStyle = app.canvas.getStyle(c, 'message', {
						'id'			: 'message',
						'left'			: design.message.x,
						'top'			: design.message.y,
						'lineHeight'	: 1,
						'lockRotation'	: true,
						'type'			: 'Text'
					}),
					message = new fabric.Text(data.txt, messageStyle);

				canvas.clear();
				canvas.loadFromJSON('{"objects":[],"background":"","backgroundImage":{}}', canvas.renderAll.bind(canvas));

				canvas.setDimensions(dimensions.width, dimensions.height);

				canvas.setBackgroundImage(design.background, canvas.renderAll.bind(canvas), {
					backgroundImageOpacity: 0.5,
					backgroundImageStretch: false
				});

				var formatedText = wrapCanvasText(message, canvas, design.message.max_width, design.message.max_height);

				message.setText(formatedText);

				bilbord.connection.get.imageBase64(data.avatar)
					.done(function(response, status) {
						// app.canvas.data.avatar = response['image'];

						fabric.Image.fromURL(response['image'], function(img) {
							img.crossOrigin = "Anonymous";
							img.set({
								left			: design.avatar.x,
								top				: design.avatar.y,
								width			: design.avatar.width,
								height			: design.avatar.height,
								lockMovementX	: true,
								lockMovementY	: true,
								lockRotation	: true,
								hasControls		: false,
								selectable		: false
							});

							canvas.add(img);
							// canvas.sendToBack(img);
						});
					})
					.fail(function(response, status) {
						console.log('getImageBase64 fail', response, status);
					});

				if (data.media) {
					bilbord.connection.get.imageBase64(data.media)
					.done(function(response, status) {
						// app.canvas.data.media = response['image'];

						fabric.Image.fromURL(response['image'], function(img) {
							var ratio = img.width/img.height;

							img.crossOrigin = "Anonymous";
							if( ratio > 1 ) {
								var h = design.picture.max_height,
								w = h * ratio;
							}
							else {
								var w = design.picture.max_width,
								h = w/ratio;
							}

							img.set({
								'id'			: 'media',
								'left'			: design.picture.x,
								'top'			: design.picture.y,
								'width'			: w,
								'height'		: h,
								'clipTo'		: function (ctx) {
									app.canvas.clipPhoto(ctx, design.picture);
								}
							});
							canvas.add(img);
							canvas.sendToBack(img);

							app.canvas.all[c].canvas = canvas;
						});
					})
					.fail(function(response, status) {
						console.log('getImageBase64 fail', response, status);
					});
				}

				/**
				 * Network logo
				 */
				if (design.logo) {
					var logoUrl = bilbord.settings.baseUrl + design.logo.files[data.network];
					fabric.Image.fromURL(logoUrl, function(img) {
						img.set({
							'id'			: 'logo',
							'left'			: design.logo.x - (img.width * 0.5),
							'top'			: design.logo.y,
							'lockRotation'	: true,
							'lockMovementY'	: true,
							'lockMovementX'	: true
						});

						canvas.add(img);
						app.canvas.all[c].canvas = canvas;
					});
				}

				canvas.add(message);
				canvas.add(name);

				return canvas;
			},

		},
	};

	bilbord.app = app;





	function setColumns() {
		var wrapper = $('#hashtagTabContent'),
		tabs = $('#unapprovedStatusesTabs');
		if( wrapper.data('set') != undefined ) {
			return false;
		}

		wrapper.data('set', true);
		$(window).on('resize', onResize).trigger('resize');

		/*var grid = wrapper.find('.tabContentWrapp.active .grid'),
		activeLink = tabs.find('li.active a').trigger('show.bs.tab').get();
		activeLink.imagesLoaded = 0;
		var images =  grid.find('img')
			.one('load', function (e) {
				console.log('img loaded');
				activeLink.imagesLoaded+=1;
				if (activeLink.imagesLoaded == images.length) {
					// grid.masonry('layout');
				}
			});*/

		wrapper.on('change', '.pinTabInp', app.tab.pin)
			.on('click', '.removeTab', app.tab.remove)
			.find('.tabContentWrapp.active .grid')
			.each(function(){
				// this.data('images-loaded', 0);
				var masonryObj = $(this).masonry({
					'columnWidth'	: '.grid-sizer',
					'itemSelector'	: '.grid-item',
				}).addClass('masonry');
				this.masonryObj = masonryObj;
			});

		/*window.adminSetttings = {
			imgsNum		: wrapper.find('img.media').length,
			imgsLoaded	: 0
		};*/

		/*wrapper.find('img.media')
			.on('load', layoutMasonry)
			.on('error', layoutMasonry);*/

		wrapper
			.on('click', '.approveStatus', app.status.beforeApprove)
			.on('click', '.unapproveStatus', app.status.unapprove);;

		tabs.find('li.active a').trigger('show.bs.tab');
		/*$('#unapprovedStatuses .moveUpStatus').on('click', {'direction':-1}, app.status.order);
		$('#unapprovedStatuses .moveDownStatus').on('click', {'direction':1}, app.status.order);*/
	}


	function onResize() {
		/*$('#unapprovedStatuses .tabContentWrapp').css('height', function(e) {
			var statuses = $('#unapprovedStatuses');
			return statuses.offset().top + statuses.height() - $('#hashtagTabContent').offset().top;
		});*/
	}


	$(document).ready(app.init);
})(jQuery);


function wrapCanvasText(t, canvas, maxW, maxH, justify) {
	// console.log(t);
	if (typeof maxH === "undefined") {
		maxH = 0;
	}
	var text = t.originalText != undefined ? t.originalText : t.text;
	var words = text.replace(/(\r\n|\n|\r)/gm, ' ').replace("  ", ' ').split(" ");
	var formatted = '';

	// This works only with monospace fonts
	justify = justify || 'left';

	// clear newlines
	var sansBreaks = t.text.replace(/(\r\n|\n|\r)/gm, "");
	// calc line height
	var lineHeight = new fabric.Text(sansBreaks, {
		fontFamily: t.fontFamily,
		fontSize: t.fontSize
	}).height;

	// adjust for vertical offset
	var maxHAdjusted = maxH > 0 ? maxH - lineHeight : 0;
	var context = canvas.getContext("2d");


	context.font = t.fontSize + "px " + t.fontFamily;
	var currentLine = '';
	var breakLineCount = 0;

	n = 0;
	while (n < words.length) {
		var isNewLine = currentLine == "";
		var testOverlap = currentLine + ' ' + words[n];

		// are we over width?
		var w = context.measureText(testOverlap).width;

		if (w < maxW) { // if not, keep adding words
			if (currentLine != '') currentLine += ' ';
			currentLine += words[n];
			// formatted += words[n] + ' ';
		} else {

			// if this hits, we got a word that need to be hypenated
			if (isNewLine) {
				var wordOverlap = "";

				// test word length until its over maxW
				for (var i = 0; i < words[n].length; ++i) {

					wordOverlap += words[n].charAt(i);
					var withHypeh = wordOverlap + "-";

					if (context.measureText(withHypeh).width >= maxW) {
						// add hyphen when splitting a word
						withHypeh = wordOverlap.substr(0, wordOverlap.length - 2) + "-";
						// update current word with remainder
						words[n] = words[n].substr(wordOverlap.length - 1, words[n].length);
						formatted += withHypeh; // add hypenated word
						break;
					}
				}
			}
			while (justify == 'right' && context.measureText(' ' + currentLine).width < maxW)
			currentLine = ' ' + currentLine;

			while (justify == 'center' && context.measureText(' ' + currentLine + ' ').width < maxW)
			currentLine = ' ' + currentLine + ' ';

			formatted += currentLine + '\n';
			breakLineCount++;
			currentLine = "";

			continue; // restart cycle
		}
		if (maxHAdjusted > 0 && (breakLineCount * lineHeight) > maxHAdjusted) {
			// add ... at the end indicating text was cutoff
			formatted = formatted.substr(0, formatted.length - 3) + "...\n";
			currentLine = "";
			break;
		}
		n++;
	}

	if (currentLine != '') {
		while (justify == 'right' && context.measureText(' ' + currentLine).width < maxW)
		currentLine = ' ' + currentLine;

		while (justify == 'center' && context.measureText(' ' + currentLine + ' ').width < maxW)
		currentLine = ' ' + currentLine + ' ';

		formatted += currentLine + '\n';
		breakLineCount++;
		currentLine = "";
	}

	// get rid of empy newline at the end
	formatted = formatted.substr(0, formatted.length - 1);

	if (t.originalText == undefined) {
		t.originalText = t.text;
	}

	return formatted;
/*
	var options = {},
	disabledOptions = ['width', 'height', 'oCoords', 'text'],
	disabledOptionTypes = ['function', 'object'];*/

	/*console.log('');
	for (var prop in t) {
		if (
			prop.charAt(0) != '_' &&
			disabledOptionTypes.indexOf(typeof(t[prop])) === -1 &&
			disabledOptions.indexOf(prop) === -1
		) {
			if (!options.hasOwnProperty(prop)) {
				options[prop] = t[prop];
				console.log(prop, t[prop])
			}
		}
	};

	return new fabric[t.type](formatted, options);*/
}