define(['app'], function (app) {
	app.controller('TshirtdesignCtrl', function ($scope, $rootScope, $window, $timeout, $illustration, $favorite) {
		$scope.Math = window.Math;
		$scope.savedFrameView = 'views/design_part/tshirt-saved.html?ver='+VERSION;
		var canvas = new fabric.Canvas('main-design-container');
		var diffX = 40, diffY = 40;
		var _coorTrash_x = 567;
		var _coorTrash_y = 545;
		var ObjectOrd=0;
		//Set width and height canvas
		function setSizeCanvas() {
			if(typeof $rootScope.placeTshirt.place == 'undefined')
				return;

			var _modalWidth = $('.modal-dialog').width();
			var _windowWidth = window.innerWidth;
			var place = $rootScope.placeTshirt.place;

			switch (place) {
				case 't_shirt_p_1' :
					$scope.designCanvasClass = 'design-content-t_shirt_p_1';
					if(_windowWidth > 762) {
						var _contentCanvasWidth = (_modalWidth*8/12)/1.2;
						var _contentCanvasHeight = _contentCanvasWidth;
					} else {
						var _contentCanvasWidth = _windowWidth-70;
						var _contentCanvasHeight = _contentCanvasWidth;
					}
					break;
				case 't_shirt_p_2' :
					$scope.designCanvasClass = 'design-content-t_shirt_p_2';
					if(_windowWidth > 762) {
						var _contentCanvasWidth = (_modalWidth*8/12)/1.2;
						var _contentCanvasHeight = (_modalWidth*8/12)/2.2;

					} else {
						var _contentCanvasWidth = _windowWidth-70;
						var _contentCanvasHeight = (_windowWidth)/2.5;
					}
					break;
				default:
					break;
			}
			
			canvas.setWidth(_contentCanvasWidth);
			canvas.setHeight(_contentCanvasHeight);
			
			var mainDsWidth = (_modalWidth*8/12)-30;
			var mainDsHeight = (place == 't_shirt_p_1' ? 80 : 400) + _contentCanvasHeight;
			// console.log(mainDsWidth, mainDsHeight);
			diffX = 40;
			diffY = (mainDsHeight - _contentCanvasHeight)/2;
			_coorTrash_x = _contentCanvasWidth + 20;
			_coorTrash_y = _contentCanvasHeight + diffY - 90;
			console.log(_coorTrash_x, _coorTrash_y);
		}
		setSizeCanvas();
		//Window resize event
		$(window).resize(function () {
			setSizeCanvas();
		});

		//Custom control
		fabric.Object.prototype.transparentCorners = true;
		fabric.Object.prototype.hasRotatingPoint = false;
		canvas.selection = false;

		var ctrVisible = {tl: false, ml:false, bl:false, mb: false, br: true, mr: false, tr: true, mt: true, mtr: false};
		for(key in ctrVisible) {
			fabric.Object.prototype.setControlVisible(key,ctrVisible[key]);
		}

		fabric.Object.prototype.customiseCornerIcons({
			settings: {
				borderColor: '#0000ff',
				cornerSize: 25,
				cornerShape: 'circle',
				cornerBackgroundColor: '#0171b4',
				cornerPadding: 6
			},
			mt: {
				icon: 'images/control-icon/ok.png'
			},
			br: {
				icon: 'images/control-icon/resize.png'
			},
			tr: {
				icon: 'images/control-icon/rotate.png'
			}
		});

		fabric.Canvas.prototype.customiseControls({
			mt: {
				cursor: 'pointer',
				action: function(e, target) {
					fabric.Object.prototype.selectable = false;
					canvas.deactivateAll().renderAll();
					delete currentObj;
					$scope.designTextValue = '';
					$timeout(function(){
						fabric.Object.prototype.selectable = true;
					},20);
				}
			},
			br: {

			},
			tr: {
				action: 'rotate',
				cursor: 'crosshair'
			}
		});

		canvas.on({
			'object:added'      : onIllustrationAdded,
			'object:moving'     : onIllustrationMoving,
			'object:scaling'    : onIllustrationChange,
			'object:rotating'   : onIllustrationChange,
			'object:selected'   : onObjectSelected,
			'object:modified'   : onIllustrationModifield,
			'selection:cleared' : onObjectOut,
		});
		
		var currentObj;
		var listObj = [];
		var stateObj = [];
		var indexCurr = 0;
		var indexCurr2 = 0;
		var actionObj = false;
		var refreshObj = true;
		var spacingNum = 0;
		$scope.itemFont = 0;

		$scope.showDesignTab = function(tab){
			canvas.deactivateAll().renderAll();
			$rootScope.isShowLeftPanel = tab;
			switch (tab) {
				case 'illustration': {
					$scope.IllustrationList = $illustration.getAll();
					$rootScope.outputImage = false;
					$scope.illustrationSelectConfig = {
						allowClear:true
					};
					$timeout(function(){
						$('.illstration-item').tooltip({
							animated: 'fade',
							placement: 'bottom',
							html: true
						});
					},1000);
					break;
				}
				case 'text': {
					break;
				}
			}
		};
		$scope.showDesignTab('default');

		
		function onIllustrationAdded(options){
			var object = options.target;
		
		    if (actionObj === true) {
		        stateObj = [stateObj[indexCurr2]];
		        listObj = [listObj[indexCurr2]];
		
		        actionObj = false;
		        console.log(stateObj);
		        indexCurr = 1;
		    }
		    object.saveState();
		
		    // console.log(object.originalState);
		    stateObj[indexCurr] = JSON.stringify(object.originalState);
		    listObj[indexCurr] = object;
		    indexCurr++;
		    indexCurr2 = indexCurr - 1;
		    refreshObj = true;
		}
		
		function onIllustrationModifield(options){
			$('.object-border').hide();
			//
		    var pointer = canvas.getPointer(options.e);
			if (pointer.x >= _coorTrash_x && pointer.y >= _coorTrash_y && pointer.x <= _coorTrash_x+50 && pointer.y <= _coorTrash_y+70){
				canvas.getActiveObject().remove();
				$('.design-content .trash-design img').attr({'src':'images/trash.png'});
				return;
			}
			
			//
			try{
				var objOffset = canvas.getActiveObject().getBoundingRect();
				var cH = canvas.height, cW = canvas.width, H0 = 20, W0 = 20;
				//console.log(objOffset,canvas.height,canvas.width);
				if (objOffset.left<W0-objOffset.width || objOffset.left>cW-W0 || objOffset.top<H0-objOffset.height || objOffset.top>cH-H0){
					if (confirm('削除してもよろしいですか')){
						canvas.getActiveObject().remove();
					}else{
						undoCanvas();
						return;
					}
				}
			}catch (e){
				//
			}
			
			var object = options.target;
		    if (actionObj === true) {
		        stateObj = [stateObj[indexCurr2]];
		        listObj = [listObj[indexCurr2]];
		
		        actionObj = false;
		        console.log(stateObj);
		        indexCurr = 1;
		    }
		
		    object.saveState();
		
		    stateObj[indexCurr] = JSON.stringify(object.originalState);
		    listObj[indexCurr] = object;
		    indexCurr++;
		    indexCurr2 = indexCurr - 1;
		    refreshObj = true;
		}
		
		function onIllustrationChange(options) {

		}
		
		function onIllustrationMoving(options) {
			var object = options.target;
			var pointer = canvas.getPointer(options.e);
			// console.log(pointer.x, pointer.y);
			if (pointer.x >= _coorTrash_x && pointer.y >= _coorTrash_y && pointer.x <= _coorTrash_x+50 && pointer.y <= _coorTrash_y+70){
				$('.design-content .trash-design img').attr({'src':'images/trash-hover.png'});
			}else{
				$('.design-content .trash-design img').attr({'src':'images/trash.png'});
			}
			
			// console.log(object.oCoords,object.originalState);
			object.setCoords();
			var Coords = object.oCoords;
			var xAngle = Math.cos(object.getAngle() * (Math.PI / 180))/2;
			var yAngle = Math.sin(object.getAngle() * (Math.PI / 180))/2;
			$('#object-border-left').css({'height':Math.ceil(object.originalState.height*object.scaleY), top: Coords.tl.y+diffY, left: Coords.tl.x+diffX});
			$('#object-border-right').css({'height':Math.ceil(object.originalState.height*object.scaleY), top: Coords.tr.y+diffY, left: Coords.tr.x+diffX});
			$('#object-border-top').css({'width':Math.ceil(object.originalState.width*object.scaleX), top: Coords.tl.y+diffY, left: Coords.tl.x+diffX});
			$('#object-border-bottom').css({'width':Math.ceil(object.originalState.width*object.scaleX), top: Coords.bl.y+diffY, left: Coords.bl.x+diffX});
			$('.object-border').css({
				'-ms-transform': 'rotate('+object.getAngle()+'deg)', /* IE 9 */
    			'-webkit-transform': 'rotate('+object.getAngle()+'deg)', /* Safari */
    			'transform': 'rotate('+object.getAngle()+'deg)' /* Standard syntax */
			});
			$('.object-border').show();
		}

		function onObjectOut() {
			console.log('onObjectOut');
			canvas.deactivateAll().renderAll();
			delete currentObj;
			$scope.designTextValue = '';
			$scope.safeApply();
		}

		function undoCanvas() {
		    if (indexCurr <= 0) {
		        indexCurr = 0;
		        return;
		    }
		
		    if (refreshObj === true) {
		        indexCurr--;
		        refreshObj = false;
		    }
		
		    console.log('undo');
		
		    indexCurr2 = indexCurr - 1;
		    currentObj = listObj[indexCurr2];
		    if (currentObj){
		    	currentObj.setOptions(JSON.parse(indexCurr[indexCurr2]));
		    }
		
		    indexCurr--;
		    currentObj.setCoords();
		    canvas.renderAll();
		    actionObj = true;
		}
		
		function redoCanvas() {
		    actionObj = true;
		    if (indexCurr >= stateObj.length - 1) {
		        return;
		    }
		
		    console.log('redo');
		
		    indexCurr2 = indexCurr + 1;
		    currentObj = listObj[indexCurr2];
		    currentObj.setOptions(JSON.parse(indexCurr[indexCurr2]));
		
		    indexCurr++;
		    currentObj.setCoords();
		    canvas.renderAll();
		}
		
		$scope.canvasClearAll = function(){
			if (confirm('配置されたすべての文字や画像を消去します')){
				canvas.clear();
				ObjectOrd = 0;
			}
		}

		function onObjectSelected(options) {
			var currentObj = options.target;
			if (typeof currentObj.toOrd != 'function'){
				var currentObjOrd = ++ObjectOrd;
				currentObj.toOrd = function(){
					return currentObjOrd;
				}
			}
			console.log(currentObj.toOrd());
			$scope.typeObject = currentObj.type;
			switch ($scope.typeObject) {
				case 'i-text' :
					$rootScope.isShowLeftPanel = 'text';
					var text = currentObj.text;
					if(text != '') {
						$scope.designText = text;
						$scope.designTextValue = text;
					}
					break;

				case 'path-group' :
					$rootScope.isShowLeftPanel = 'illustration';
					break;
					
				case 'image':
					$rootScope.isShowLeftPanel = 'image';
					break;

				default :
					$rootScope.isShowLeftPanel = 'default';
					break;
			}
			$rootScope.safeApply();
		}

		// Illustration process
		$scope.changeIllustrationCategory = function(currentIllustration){
			$scope.currentIllustrationCate = $illustration.getList(currentIllustration);
		};

		var arrSvgOriginal = [];
		$scope.insertSvg = function(item){
			fabric.loadSVGFromURL(item.path, function(objects, options) {
				var shape = fabric.util.groupSVGElements(objects, options);
				var currentObjOrd = ++ObjectOrd;
				arrSvgOriginal[currentObjOrd] = item.path;
				shape.toOrd = function(){
					return currentObjOrd;
				}
				canvas.add(shape.scale(0.6));
				shape.set({ left: 150, top: 100 }).setCoords();
				canvas.renderAll();
				canvas.setActiveObject(shape);
			});
		};

		// color pattern
		$scope.listColorPatterns = [
			'#000000','#ffff00','#ff6600','#ff0000','#ff6262','#ffa19c','#ff9933','#c45d01','#5d2b03','#ffffcc',
			'#ffff99','#ffd500','#c0db50','#21a52a','#00663f','#abfcab','#36ffaa','#89eaea','#00938c','#005450',
			'#0badff','#006cff','#839aff','#0410a0','#ffb2ff','#f93fff','#6600ca','#ff6699','#999999','#666666',
			'#333333'
		];
		
		$scope.changeColorPattern = function(color){
			var obj = canvas.getActiveObject();
			if (!color){
				color = 'none';
				// console.log(obj.toOrd(), arrSvgOriginal[obj.toOrd()]);
				if (typeof obj.toOrd == 'function' && typeof arrSvgOriginal[obj.toOrd()] != 'undefined'){
					var currentObjOrd = obj.toOrd();
					fabric.loadSVGFromURL(arrSvgOriginal[obj.toOrd()], function(objects, options) {
						var shape = fabric.util.groupSVGElements(objects, options);
						shape.toOrd = function(){
							return currentObjOrd;
						}
						obj.setCoords();
						shape.setScaleX(obj.getScaleX());
						shape.setScaleY(obj.getScaleY());
						shape.set('top',obj.getTop());
						shape.set('left',obj.getLeft());
						shape.set('angle',obj.getAngle());
						// shape.set('height',obj.getHeight());
						// shape.set('width',obj.getWidth());
						canvas.add(shape);
						shape.setCoords();
						// shape.set({ left: 150, top: 100 }).setCoords();
						canvas.renderAll();
						canvas.setActiveObject(shape);
						obj.remove();
					});
				}
			}else{
				if (obj instanceof fabric.PathGroup) {
					obj.getObjects().forEach(function(o) {
						o.fill = color;
					});
				}
				else {
					obj.fill = color;
				}
				canvas.renderAll();
			}
		};
		
		//Font
		$scope.listFontFamily = [
			// {
			// 	name : 'GN Aki iro Sesami Cookies',
			// 	slug : 'gn_aki_iro_sesami_cookies',
			// },
			// {
			// 	name : 'GN-Fuyu-iro_Script_Bold',
			// 	slug : 'gn_fuyu_iro_script_bold'
			// },
			// {
			// 	name : 'GN Killgothic U Kanana',
			// 	slug : 'gn_killgothic_u_kanana'
			// },
			// {
			// 	name : 'GN-Kin-iro_Alphabet_Cookies',
			// 	slug : 'gn_kin_iro_alphabet_cookies'
            //
			// },
			// {
			// 	name : 'GN-Kin-iro_SansSerif',
			// 	slug : 'gn_kin_iro_sansserif'
            //
			// },
			// {
			// 	name : 'GN-Koharuiro_Sunray',
			// 	slug : 'gn_koharuiro_sunray'
            //
			// },
			// {
			// 	name : 'GN-Kyu-pin',
			// 	slug : 'gn_kyu_pin'
			// },
			// {
			// 	name : 'gn_natsu_iro_schedule',
			// 	slug : 'gn_natsu_iro_schedule'
            //
			// },
			// {
			// 	name : 'gnkana_kiniro_sansserif_l',
			// 	slug : 'gnkana_kiniro_sansserif_l'
            //
			// },
			// {
			// 	name : 'gnkana_kiniro_sansserif_st',
			// 	slug : 'gnkana_kiniro_sansserif_st'
			// },
			// {
			// 	name : 'gnkana_kon_iro_nightfall',
			// 	slug : 'gnkana_kon_iro_nightfall'
            //
			// },
			// {
			// 	name : 'ms_gothic',
			// 	slug : 'ms_gothic'
            //
			// },
			// {
			// 	name : 'msmincho',
			// 	slug : 'msmincho'
			// },
			// {
			// 	name : 'ufonts_com_ms_pgothic',
			// 	slug : 'ufonts_com_ms_pgothic'
			// }
			{
				name: 'Roboto',
				slug: "'Roboto', sans-serif"
			},
			{
				name: 'Bungee',
				slug: "'Bungee', cursive"
			},
			{
				name: 'Aref Ruqaa',
				slug: "'Aref Ruqaa', serif"
			},
			{
				name: 'Open Sans',
				slug: "'Open Sans', sans-serif"
			},
			{
				name: 'Lato',
				slug: "'Lato', sans-serif"
			},
			{
				name: 'Slabo 27px',
				slug: "'Slabo 27px', serif"
			},
			{
				name: 'Oswald',
				slug: "'Oswald', sans-serif"
			},
			{
				name: 'Yrsa',
				slug: "'Yrsa', serif"
			},
			{
				name: 'Source Sans Pro',
				slug: "'Source Sans Pro', sans-serif"
			},
			{
				name: 'Montserrat',
				slug: "'Montserrat', sans-serif"
			},
			{
				name: 'Raleway',
				slug: "'Raleway', sans-serif"
			},
			{
				name: 'Merriweather',
				slug: "'Merriweather', serif"
			},
			{
				name: 'Open Sans Condensed',
				slug: "'Open Sans Condensed', sans-serif"
			},
			{
				name: 'Maitree',
				slug: "'Maitree', serif"
			},
			{
				name: 'Lora',
				slug: "'Lora', serif"
			},
			{
				name: 'Playfair Display',
				slug: "'Playfair Display', serif"
			},
			{
				name: 'Noto Sans',
				slug: "''Noto Sans', sans-serif', sans-serif"
			},
			{
				name: 'PT Sans Narrow',
				slug: "'PT Sans Narrow', sans-serif"
			},
			{
				name: 'Titillium Web',
				slug: "'Titillium Web', sans-serif"
			},
			{
				name: 'Muli',
				slug: "'Muli', sans-serif"
			},
			{
				name: 'Inconsolata',
				slug: "'Inconsolata', monospace"
			},
			{
				name: 'Indie Flower',
				slug: "'Indie Flower', cursive"
			},
			{
				name: 'Bitter',
				slug: "'Bitter', serif"
			},
			{
				name: 'Dosis',
				slug: "'Dosis', sans-serif"
			},
			{
				name: 'Oxygen',
				slug: "'Oxygen', sans-serif"
			},
			{
				name: 'Hind',
				slug: "'Hind', sans-serif"
			},
			{
				name: 'Tillana',
				slug: "'Tillana', cursive"
			},
			{
				name: 'Fjalla One',
				slug: "'Fjalla One', sans-serif"
			},
			{
				name: 'Cabin',
				slug: "'Cabin', sans-serif"
			},
			{
				name: 'Nunito',
				slug: "'Nunito', sans-serif"
			},
			{
				name: 'Anton',
				slug: "'Anton', sans-serif"
			},
			{
				name: 'Lobster',
				slug: "'Lobster', cursive"
			},
			{
				name: 'Yanone Kaffeesatz',
				slug: "'Yanone Kaffeesatz', sans-serif"
			},
			{
				name: 'Reem Kufi',
				slug: "'Reem Kufi', sans-serif"
			},
			{
				name: 'Merriweather Sans',
				slug: "'Merriweather Sans', sans-serif"
			},
			{
				name: 'Bree Serif',
				slug: "'Bree Serif', serif"
			},
			{
				name: 'Josefin Sans',
				slug: "'Josefin Sans', sans-serif"
			},
			{
				name: 'Abel',
				slug: "'Abel', sans-serif"
			},
			{
				name: 'Crimson Text',
				slug: "'Crimson Text', serif"
			},
			{
				name: 'Gloria Hallelujah',
				slug: "'Gloria Hallelujah', cursive"
			},
			{
				name: 'Bungee Inline',
				slug: "'Bungee Inline', cursive"
			},
			{
				name: 'Amatic SC',
				slug: "'Amatic SC', cursive"
			},
			{
				name: 'Shadows Into Light',
				slug: "'Shadows Into Light', cursive"
			},
			{
				name: 'Dancing Script',
				slug: "'Dancing Script', cursive"
			},
			{
				name: 'Orbitron',
				slug: "'Orbitron', sans-serif"
			},
			{
				name: 'Source Code Pro',
				slug: "'Source Code Pro', monospace"
			},
			{
				name: 'Permanent Marker',
				slug: "'Permanent Marker', cursive"
			}
		];
		
		// layer process
		$scope.layerProcess = function(mode) {
			// console.log('layerProcess');
			var activeObject = canvas.getActiveObject();

			if (activeObject){
				switch (mode) {
					case 1:
						activeObject.bringForward();
						break;
					case 2:
						activeObject.sendBackwards();
						break;
					case 3:
						activeObject.bringToFront();
						break;
					case 4:
						activeObject.sendToBack();
						break;
				}
				canvas.deactivateAll().renderAll();
			}
		};


		//Design text
		$scope.inputText = function(e) {
			currentObj = canvas.getActiveObject();
			var _iText = new fabric.IText('', {
				left: 150,
				top: 200,
				fontFamily: typeof $scope.itemFont != 'undefined' ? $scope.listFontFamily[$scope.itemFont].slug : $scope.listFontFamily[0].slug,
				fontWeight: 'normal',
				textAlign:  'center',
				fontSize: 28,
				fill: 'black',
				editable: false
			});
			if(typeof currentObj != 'undefined' && currentObj != null) {
				_iText.set({
					left: currentObj.left,
					top: currentObj.top,
					fontFamily: currentObj.fontFamily,
					fontSize: currentObj.fontSize,
					fill: currentObj.fill
				})
			}


			if(canvas.getActiveObject())
				canvas.getActiveObject().remove();

			_iText.set('text', e);
			canvas.add(_iText);
			canvas.setActiveObject(_iText);
			canvas.renderAll();

		};
		$scope.setFontFamily = function(font,index) {
			$scope.itemFont = index;
			if(canvas.getActiveObject()) {
				var currentObj = canvas.getActiveObject();
				if(currentObj.type == 'i-text') {
					currentObj.set('fontFamily', font);
					canvas.renderAll();
					canvas.setActiveObject(currentObj);
				}

			}
		};
		//Set letter spacing text
		$scope.setLetterSpacingText = function(e) {
			if(canvas.getActiveObject()) {
				var currentObj = canvas.getActiveObject();
				if(currentObj.type == 'i-text') {
					if(e == 'plus')
						spacingNum = spacingNum + 30;
					else if (spacingNum >= -30){
						spacingNum = spacingNum - 30;
					}
					if(e == 'default')
						spacingNum = 0;

					currentObj.set('charSpacing', spacingNum);
					canvas.renderAll();
					canvas.setActiveObject(currentObj);
				}
			}
		};
		
		
		/**** process insert image */
		if (typeof($window.localStorage.recentImages) != 'undefined'){
			$scope.recentImages = JSON.parse($window.localStorage.recentImages);
		}else{
			$scope.recentImages = {};
		}

		var addToRecentImage = function(name, data){
			if (typeof($window.localStorage.recentImages) != 'undefined'){
				$scope.recentImages = JSON.parse($window.localStorage.recentImages);
			}else{
				$scope.recentImages = {};
			}

			if (typeof($scope.recentImages[name]) == 'undefined'){
				var ii=0;
				var II = 0;
				for(var item in $scope.recentImages){
					if (II==0){
						II = item;
					}
					ii++;
				}
				if (ii>16 && II!=0){
					delete $scope.recentImages[II];
				}
				$scope.recentImages[name] = data;
				$window.localStorage.recentImages = JSON.stringify($scope.recentImages);
			}
		}
		$scope.chooseImage = function(e){//console.log(e);
			if (e.target.files[0] && e.target.files[0].size > 5*1024*1024){
				alert('アップロードできませんでした');
				return;
			}
			var reader = new FileReader();
		    reader.onload = function (event) {
		    	addToRecentImage ($('#imgLoader').val(), event.target.result);
		        var imgObj = new Image();//console.log($('#imgLoader').val());
		        imgObj.src = event.target.result;
		        imgObj.onload = function () {
		            // start fabricJS stuff
		            
		            var image = new fabric.Image(imgObj);
		            image.set({
		                left: 50,
		                top: 50
		            });
		            //image.scale(getRandomNum(0.1, 0.25)).setCoords();
		            image.scaleToWidth(200);
		            canvas.add(image);
		        }
		    }
    		reader.readAsDataURL(e.target.files[0]);
		}

		$scope.insertRecentImage = function(data){
	        var imgObj = new Image();
	        imgObj.src = data;
	        imgObj.onload = function () {
	            // start fabricJS stuff

	            var image = new fabric.Image(imgObj);
	            image.set({
	                left: 50,
	                top: 50
	            });
	            image.scaleToWidth(200);
	            canvas.add(image);
	        }
		}

		//Traslation text
		$scope.rotateText =  function(style) {
			if(canvas.getActiveObject()) {
				var currentObj = canvas.getActiveObject();
				if(currentObj.type == 'i-text') {
					currentObj.set('rotate', Math.PI / 4);
					canvas.renderAll();
					canvas.setActiveObject(currentObj);
				}
			}
		};
		
		
		/* Process output */
		$scope.outputDesign = function(){
			$rootScope.outputImage = canvas.toDataURL('png');
			// console.log();
			$('#tshirt-design').modal('hide');
		}
		
		$scope.showRecommend = function(){
			$scope.recommendList = $favorite.getAll();
			$scope.favoriteList = $favorite.getAll();
			$('#tshirt-design-saved').modal({
				backdrop: 'static',
				keyboard: false
			});
			$timeout(function(){
				$('.saved-item').tooltip({
					animated: 'fade',
					placement: 'bottom',
					html: true
				});
			},1000);
		}
		
		$scope.closeSavedModal = function(){
			$('#tshirt-design-saved').modal('hide');
		}
		
		$scope.openSavedTab = function(tab){
			$('#tshirt-design-saved .subframe-design .nav-tabs li').removeClass('active');
			$('#tab-saved-'+tab).addClass('active');
			$('#tshirt-design-saved .subframe-design .tab-content .tab-pane').removeClass('active');
			$('#content-saved-'+tab).addClass('active');
			
			$timeout(function(){
				$('.saved-item img').tooltip({
					animated: 'fade',
					placement: 'bottom',
					html: true
				});
			},500);
		}
		
		$favorite.loadFromRemote();
		$scope.saveFavorite = function(){
			if (!confirm('Do you want to put current design to your favorite?')){
				return;
			}
			var dataDump = {
				thumb: canvas.toDataURL('png'),
				data: JSON.stringify(canvas)
			}
			$favorite.addToFavorite({
				data: dataDump
			})
			// console.log(JSON.stringify(dataDump));
			alert('saved');
		}
		
		$scope.restoreSaved = function(item){
			if (!confirm('this may be clear all current design frame, are you sure ?')){
				return;
			}
			$('#tshirt-design-saved').modal('hide');
			canvas.loadFromJSON(item.data,canvas.renderAll.bind(canvas));
			ObjectOrd = 0;
			canvas.forEachObject(function(obj){
				var currentObjOrd = ++ObjectOrd;
			    obj.toOrd = function(){
			    	return currentObjOrd;
			    }
			});
		}
		
		$scope.deleteFavorite = function(idx){
			if (confirm('are you sure?')){
				$favorite.removeFromFavorite({
					idx: idx
				});
				$scope.recommendList = $favorite.getAll();
				$scope.favoriteList = $favorite.getAll();
			}
		}
	});
});
