/**********************************
 * WPPAS VBC EDITOR 4.7.6 
 * @author Tunafish
***********************************/
(function( $ ) {
	"use strict";
	
	var _W = $.fn.wppas,
		got_saved = 1,
		cur_view_size = 1200,
		_4chars = '    ',
		keep_aspect_ratio = 1,
		resizing = false,
		text_resize = 0,
		timeline_arr = {
			main: {},
			v: '519',
			1200: {}
		},
		alphaID = '',
		bannerID = '',
		// PHP localized HTML froms.
		editor_forms = {
			//itm_editor_form_style: itm_editor_form_style.form,
			//itm_editor_form: itm_editor_form.form,
			itm_editor_cont: itm_editor_cont.form
		},
		prefedined = {
			buttons: JSON.parse(predefined.buttons)
		},
		save_confirms = JSON.parse(itm_editor_save_confirms.array);
	
	//console.log(editor_forms.itm_editor_form_style);

	$.extend(true, _W, {
		
		
		/**
		 * EDITOR VARS - SETTINGS
		 *
		 *
		 */
		editor_vars: function(options) {
			
			var defaults = {
				alphaID: '',
				editor: ace.edit("wppas_banner_html_editor_"+alphaID),
			}
			
			// Merge of Defaults									
			return options = $.extend(true,{},defaults, options);
		},
		
		
		/**
		 * EDITOR - SETTINGS
		 *
		 *
		 */
		editor: function(options) {
			
			var defaults = {
				
			}
			
			// Merge of Defaults									
			options = $.extend(true,{},defaults, options);
			var ajaxurl = typeof ajaxurl != 'undefined' ? ajaxurl : options.ajaxurl;
			
			// Set timeline arr
			//console.log(options.timeline_arr);
			if(typeof options.timeline_arr !== 'undefined' && options.timeline_arr !== null){
				if(Object.keys(options.timeline_arr).length > 0){
					timeline_arr = options.timeline_arr;
				}
			}
			console.log(timeline_arr);
			
			alphaID = timeline_arr['main']['alphaID'];
			bannerID = $('.'+alphaID).find('#banner_ID').val();

			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID});
			
			// @since v5.2.0 Make sure changes got saved before leaving the page!
			$(window).bind('beforeunload', function(){
				if(!got_saved){
					return 'Are you sure you want to leave?';
				}
			});
			// do stuff before exiting.
			$(window).unload(function(){ });
				
			
			// Load banner html if ID is available.
			if( bannerID != '' && bannerID != 0 && typeof bannerID != 'undefined'){
				var ID = bannerID;
				//console.log(ID);
				_t.wppas.view_size_adjustments({'scale':0});
				_t.wppas.update_view_btns();
				
				$('#banner-preview').find('.b_container').html( _v.editor.getSession().getValue() );
				$('#banner-preview').find('.b_container').html(_t.wppas.wppas_decode_html_items());
				
				_t.wppas.wppas_activate_layers();
				_t.wppas.add_adjustment_functions(options);
				
				_t.wppas.wppas_make_sortable();	
				$('.draggable_container').draggable({ handle: ".drag_handle", containment: "window" });
				//$('.draggable_container').draggable();
				$('.vbc-color-field').wpColorPicker();
				
				
				//timeline_arr = typeof options.timeline_arr !== 'undefined' && Object.keys(options.timeline_arr).length > 0 ? options.timeline_arr : timeline_arr;
				// fix objects if empty.
				if( timeline_arr[1200] == ''){
					timeline_arr[1200] = {};
				}
				if( timeline_arr['main'] == ''){
					timeline_arr['main'] = {};
				}
				
				// set bg color
				if( typeof timeline_arr['main'] !== 'undefined' && timeline_arr['main']!== null){
					if( typeof timeline_arr['main'].bbg !== 'undefined'){ // && 
						$('#banner-preview').find('.b_container').css({'background-color': timeline_arr['main'].bbg});
					}
				}
				
				
								
				// select Google Fonts
				_t.wppas.load_google_fonts({'itm': $('.b_container')});
			}
			
			
			
			_t.wppas.select_banner_advertiser();
			
			$('.tools_itm_container').on('mouseover', function(){
				$(this).find('.tools_rollout_menu').show();
			});
			$('.tools_itm_container').on('mouseout', function(){
				$(this).find('.tools_rollout_menu').hide();
			});
			
			
			// -- ON WORK AREA RESIZE --
			$('#wppas_banner_work_area').on('resize', function(){
				
				if( !resizing ){
					_t.wppas.wppas_check_work_area_size( { size: $(this).outerWidth(), screen_sizes: options.screen_sizes, sizes_arr: options.sizes_arr  } );
				}
			});	
			
			
			// -- CHANGE WINDOW VIEW --
			$('.view_btn').on('click', function(){
				//console.log('View btn click');
				
				var view = $(this).data('view'),
					size = $(this).data('min'),
					sizes = options.screen_sizes[size];
				
				$('.view_btn').removeClass('selected');
				$(this).addClass('selected');
				
				$('#wppas_banner_work_area').css({'width': sizes.size+'px'});
				// scale banner
				_t.wppas.scale_banner();
				
				// ADJUST HEIGHT TO FIT RATIO
				_t.wppas.aspect_ratio_sizing({editor:1, keep_aspect_ratio: keep_aspect_ratio});
				
				$('#wppas_banner_work_area').find('.work_area_info .current_view_size').html($('#wppas_banner_work_area').width()+'px');
				$('#wppas_banner_work_area').find('.work_area_info .device_view').html(sizes.view+': '+sizes.size+'px <');
				
				// size adjustment functions
				_t.wppas.view_size_adjustments();
				
				//console.log('start');
				//$('.editor_loader').show();
				// BETA - update timeline buttons
				_t.wppas.update_timeline_btn();
				//console.log('end');
				//$('.editor_loader').hide();
			});
			
			
			
			
			
			
			
			
			// -- Code Editor --
			_v.editor.setTheme("ace/theme/github");
			_v.editor.session.setMode("ace/mode/html");
			_v.editor.setOptions({
				maxLines: 20,
				minLines: 10,
				showPrintMargin: false
			});
			_v.editor.$blockScrolling = 'Infinity';
			
			
			// -- ON CODE EDITOR CHANGE --
			_v.editor.getSession().on("change", function(){
				
				got_saved = 0;
				
				console.log('editor on change, view size: '+cur_view_size);
				
				var textarea = $("textarea[name=wppas_banner_html_"+cur_view_size+"]"),
					code = _v.editor.getSession().getValue(),
					closest_size = _t.wppas.closest(cur_view_size, sizes_arr);
				
				if( code != $("textarea[name=wppas_banner_html_"+closest_size+"]").val()){
					textarea.val(code);
				}
				
				var bsize = $('#wppas_banner_size').val().split('x');
				_t.wppas.wppas_b_container( {'width': bsize[0],'height': bsize[1]});
				//console.log(code);
				
				$('.'+alphaID).find('#banner-preview').find('.b_container').html( code ); // code
				//_t.wppas.wppas_encode_html_items();
				// @since v5.1.6 Decode itm HTML for preview
				$('.'+alphaID).find('#banner-preview').find('.b_container').html( _t.wppas.wppas_decode_html_items() );
				_t.wppas.wppas_activate_layers();
				
				_t.wppas.wppas_make_draggable();
				//_t.wppas.add_adjustment_functions(); // !! Don't use this other wise rotation function keeps getting triggered.
				_t.wppas.update_view_btns();
			});
			
			// Off click.
			$('.'+alphaID).off('click');
			
			// -- ADD SHAPE --
			$('.'+alphaID).on('click', '#add_shape', function(){
				
				//_t.wppas.add_shape({type: $(this).data('type'), options: options});
				_t.wppas.shape_creator({'container':$('.itm_add_cont')});
				$('.itm_add_shape').detach().appendTo("body").show();
				_t.wppas.open_popup_func({'container': $('.itm_add_shape'), 'scroll':0});
			});
			
			
			
			
			
			// -- ADD TEXT BUTTON --
			$('.'+alphaID).on('click', '#b_add_text', function(){
				_t.wppas.add_text({options: options});
			});
			
			// -- ADD ICON BUTTON
			$('.'+alphaID).on('click', '.fa_icon_holder', function(){
				
				_t.wppas.add_icon({icon: $(this).data('fa'), icon_code: $(this).data('facode'), options: options});
			});
			
			// -- ADD SVG POPUP
			$('.'+alphaID).on('click', '#add_svg', function(){
				//jQuery('.vbc-color-field').wpColorPicker();
				//$('.itm_add_svg').show();
				_t.wppas.svg_creator({'container':$('.itm_add_cont')});
				$('.itm_add_svg').detach().appendTo("body").show();
				_t.wppas.open_popup_func({'container': $('.itm_add_svg'), 'scroll':0});
			});
			
			
			// -- ADD HTML BUTTON
			$('.'+alphaID).on('click', '#b_add_html', function(){
				$('.itm_add_html').detach().appendTo("body").show();
				
				_t.wppas.open_popup_func({'container': $('.itm_add_html'), 'scroll':0});
			});
			
			// -- ADD BTN BUTTON
			$('.'+alphaID).on('click', '#b_add_btn', function(){
				$('.itm_add_cont').find('#btn_prev_style').text('');
				$('.itm_add_cont').find('#btn_creator_class').val('');
				_t.wppas.button_creator({'container':$('.itm_add_cont')});
				$('.itm_add_button').detach().appendTo("body").show();
				_t.wppas.open_popup_func({'container': $('.itm_add_button'), 'scroll':0});
			});
			
			// -- ADD ZIP BUTTON
			$('.'+alphaID).on('click', '#b_add_zip', function(){
				$('.itm_add_zip').detach().appendTo("body").show();
			});
			
			$('.'+alphaID).on('click', '#wppas_upload_zip', function(e){
				
				//_t.wppas.upload_zip_file(e);
				e.preventDefault();
				var form_data = new FormData(), //$('#zip_upload_form')[0]
					itm = $('#wppas_zip_file').get(0).files[0];
					//fileInput = document.getElementById("wppas_zip_file");//file = $('#wppas_zip_file').prop('files')[0];
					
				//console.log(itm);
				//form_data.append('fileInput', fileInput.files[0] );
				//form_data.append('file', itm, 'test.zip' );
				form_data.append('name', 'test'); 
				form_data.append('itm', itm );
				form_data.append('action', 'upload_zip_files'); 
				
				$.ajax({
				   type: "POST",
				   url: ajaxurl,
				   processData: false,
				   contentType: false,
				   cache: false,
				   data: form_data
				}).done(function( msg ) {
			
					console.log(msg);
					
				});
			});
			
			
			
			// -- UPLOAD IMAGE --
			
			$('.'+alphaID).on('click', '.upload_image_btn', function()
			{
				_t.wppas.wp_media_uploader({options: options});
			});
			
			
			
			// -- CHANGE BANNER OVERFLOW status --
			$('.'+alphaID).find('#boverflow').on('change', function(){
				
				if( $(this).is(':checked') ){
					//$('#wppas_banner_work_area').find('.b_container').css({'overflow': 'visible' });
					$('.'+alphaID).find('#wppas_banner_work_area').find('#bpreview').css({'overflow': 'visible' });
				}else{
					//$('#wppas_banner_work_area').find('.b_container').css({'overflow': 'hidden'});
					$('.'+alphaID).find('#wppas_banner_work_area').find('#bpreview').css({'overflow': 'hidden'});
				}
			});
			
			
			// -- CHANGE BANNER TEXT RESIZE status --
			$('.'+alphaID).find('#btxtresize').on('change', function(){
				
				if( $(this).is(':checked') ){
					text_resize = 1;
					//$('#wppas_banner_work_area').find('.b_container').css({'overflow': 'visible' });
					//$('.'+alphaID).find('#wppas_banner_work_area').find('#bpreview').css({'overflow': 'visible' });
				}else{
					text_resize = 0;
					//$('#wppas_banner_work_area').find('.b_container').css({'overflow': 'hidden'});
					//$('.'+alphaID).find('#wppas_banner_work_area').find('#bpreview').css({'overflow': 'hidden'});
				}
				console.log(text_resize);
			});
			
			
			
			
			// -- OPEN BANNER HTML EDITOR --
			$('.bhtml_header').on('click', function(){
				$('.banner_html').slideToggle();
			});
			
			
			// -- CHANGE BANNER SIZE --
			$('#wppas_banner_size').on('change', function(){
				
				var bsize = $(this).val().split('x');
				_t.wppas.update_banner_size( bsize );
			});
			
			
			// -- WORK AREA TEMPLATE TOOLS --
			$('.toggle_tools').find('.menu_itm').on('click', function(){
				$(this).parent().find('.tools_box').slideToggle();
			});
			
			
			// -- CHANGE BANNER ASPECT RATIO status --
			$('#baspectratio').on('change', function(){
				
				if( $(this).is(':checked') ){
					keep_aspect_ratio = 1;
				}else{
					keep_aspect_ratio = 0;
				}
			});
		
			
			// -- TIMELINE BUTTON CONTROL --
			$('body').on('click', '.timeline_itm', function(){
				var itm_id = $(this).data('itm');
				
				$('.timeline_itm').removeClass('selected');
				$('#bpreview .b_container').find('.itm').draggable('destroy');
				$('#bpreview .b_container').find('.itm').resizable("destroy");
				$('#bpreview .b_container').find('.itm').removeClass('itm');	
				$('.rotate_handle').remove();
				
				$('#bpreview .b_container').find('.'+itm_id).addClass('itm');
				
				$(this).addClass('selected');
				
				//_t.wppas.wppas_make_draggable();
				_t.wppas.add_adjustment_functions(options);
			});
			
			// -- SELECT PREVIEW ITEM ON CLICK (select item, select layer)--
			$('body').on('click', '#wppas_banner_work_area .layer', function(){
			//$('.layer').on('click', function(){
				var itm_id = $(this).data('itm');
				var type = $(this).data('type');
				
				_t.wppas.deselect_items();
				$('#bpreview .b_container').find('.'+itm_id).addClass('itm');
				//$('#bpreview .b_container').remove('.Layer_isSelected');
				$('#bpreview .b_container').find('.Layer_isSelected').remove();
				$('#bpreview .b_container').find('.'+itm_id).prepend('<div class="Layer_isSelected"></div>');
				$('#itm_'+itm_id).addClass('selected');
				
				_t.wppas.text_editable({'itm_id':itm_id, 'edit': 1});
				_t.wppas.add_adjustment_functions(options);
			});
			
			
			
			// -- DE-SELECT ITEMS (de-select item, de-select layer) --
			$('body').on('click', '#wppas_banner_work_area', function(e){
				vbc_deselect_itms({e:e, itm: this});
			});
			$('body').on('click', '#wppas_vsb_container', function(e){
				vbc_deselect_itms({e:e, itm: this});
			});
			$('body').on('click', '.b_container', function(e){
				vbc_deselect_itms({e:e, itm: this});
			});
			function vbc_deselect_itms(args){
				if (args.e.target !== args.itm){
    				return;
				}else{
					console.log('click outside of item');
					_t.wppas.deselect_items();
					_t.wppas.wppas_update_code_editor_from_preview();
				}
			}
			
			
			
			// -- TRASH ITEM --
			$('body').on('click', '.trash_itm', function(){
				click_trash_itm(this);
			});
			$('.trash_itm').on('click', function(){
				click_trash_itm(this);
			});
			function click_trash_itm(obj){
				var itm = $(obj).data('itm');
				
				$('.b_container').find('.'+itm).remove();
				$(obj).parent().parent().remove();
				
				delete timeline_arr[cur_view_size][itm];
				
				_t.wppas.wppas_update_code_editor_from_preview();	
			}
			
			
			
			
			
			
			
			
			// -- OPEN MAIN ITM EDIT FORM --
			$('#vbc_main_itm').on('click', function(){
				$('.itm_edit_cont').hide();
				$(this).find('.itm_edit_cont').show();
			});
			
			// -- SAVE MAIN ITM EDIT SETTINGS --
			$('body').on('click', '.wppas_main_b_settings_save', function(event){
				
				// UPDATE TIMELINE ARRAY
				if(typeof timeline_arr['main'] !== 'undefined') {
					timeline_arr['main']['btime'] = $('#main_itm_edit_form').find('#edit_itm_btime').val();
					timeline_arr['main']['bbg'] = $('#main_itm_edit_form').find('#edit_itm_bbg').val();
					/*timeline_arr['main'] = {
						'btime': $('#main_itm_edit_form').find('#edit_itm_btime').val(),
						'bbg': $('#main_itm_edit_form').find('#edit_itm_bbg').val()
					};*/
				}
				
				// Coloring
				$('.b_container').css({'background-color': timeline_arr['main'].bbg});
				
				$('.itm_edit_cont').hide();
			});
			
			
			
			
			// -- DUPLICATE ITEM //
			$('body').on('click', '.wppas_vbc_edit_itm_duplicate', function(event){
				
				var itm = $(this).parent().parent(),
					ID = itm.data('itm'),
					clone_itm = $('.'+ID),
					type = ID.split('_'),
					layer_css = timeline_arr[cur_view_size][ID]['css']['layer'],
					itm_css = timeline_arr[cur_view_size][ID]['css']['item'],
					itm_data = timeline_arr[cur_view_size][ID]['data'];
					
				
				if(type[1] == 'shape' || type[1] == 'circle' || type[1] == 'square'){
					var new_itm = _t.wppas.add_shape({type: type[1], layer_css: layer_css, itm_css: itm_css, itm_data:itm_data, options: options});
				}else if(type[1] == 'text'){
					var new_itm = _t.wppas.add_text({type: type[1], layer_css: layer_css, itm_css: itm_css, itm_data:itm_data, options: options});
				}else if(type[1] == 'image'){
					console.log(timeline_arr[cur_view_size][ID]['data']);
					var new_itm = _t.wppas.add_image({type: type[1], layer_css: layer_css, itm_css: itm_css, itm_data:itm_data, options: options, attachment: {url: timeline_arr[cur_view_size][ID]['data'].src} });
				}
				
				console.log('duplicate');
			});
			
			
			
			
			// -- HIDE PREVIEW ITEM --
			$('body').on('click', '.timeline_itm .hide', function(event){
				var itm = $(this).parent().data('itm');
				
				if( $(this).hasClass('visible')){
					$(this).removeClass('visible');
					$(this).addClass('hidden');
					$(this).html('<i class="fa fa-eye-slash" aria-hidden="true"></i>');
					$('.'+itm).hide();
				}else{
					$(this).removeClass('hidden');
					$(this).addClass('visible');
					$(this).html('<i class="fa fa-eye" aria-hidden="true"></i>');
					$('.'+itm).show();
				}
				
			});
			
			
			
			// -- EXPORT FILES to ZIP (under construction) --
			$('#export_files').on('click', function(event){
				
				var ID = $(this).data('id'),
					json = $('#wppas_export_code').val();
				
				$.ajax({
				   type: "POST",
				   url: ajaxurl,
				   data: "action=export_files&ID="+ID+"&json="+encodeURIComponent(json)
				}).done(function( msg ) {
			
					console.log(msg);
					
				});
			});
			
			
			
			
			// -- OPEN ITM EDITOR FORM --
			$('html').off('click').on('click', '.wppas_vbc_edit_itm_style', function(event){
				click_wppas_vbc_edit_itm(this);
			});
			$(".wppas_vbc_edit_itm_style").off('click').on("click", ".wppas_vbc_edit_itm_style", function(event){
				click_wppas_vbc_edit_itm(this);
			});
			
			function click_wppas_vbc_edit_itm(obj){
				
				var itm = $(obj).parent().parent(),
					ID = itm.data('itm'),
					preview_itm = $('.'+itm.data('itm')),
					object = itm.data('object'),
					obj_itm = itm.data('item'),
					type = preview_itm.data('type'),
					pos = _t.wppas.wppas_css_itm_position_percentage(preview_itm);
				
				//itm.find('#btn_prev_style').text('');
				$(this).wppas.open_popup_func({'container': $('.itm_edit_cont'), 'scroll':1});
				if(obj_itm == 'button'){
					$(this).wppas.button_creator({container: itm, ID:ID});
				}
				if(obj_itm == 'svg'){
					$(this).wppas.svg_creator({container: itm, ID:ID});
				}
				if(type == 'shape'){
					$(this).wppas.shape_creator({container: itm, ID:ID});
				}
				//console.log(obj_itm);
				
				// TIMELINE ARR ITMS
				$(this).wppas.create_timeline_itm({ID: ID});
	
				// CSS VARS
				var layer_bg_color = typeof timeline_arr[cur_view_size][ID]['css']['layer']['background-color'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['background-color'] : '',
						
					layer_height = typeof timeline_arr[cur_view_size][ID]['css']['layer']['height'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['height'] : preview_itm.height()+'px',
						
					layer_width = typeof timeline_arr[cur_view_size][ID]['css']['layer']['width'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['width'] : preview_itm.width()+'px',
					
					layer_align_h = typeof timeline_arr[cur_view_size][ID]['css']['layer']['pos_h'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['pos_h'] : 'left',
					
					layer_align_v = typeof timeline_arr[cur_view_size][ID]['css']['layer']['pos_v'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['pos_v'] : 'top',
						
					layer_bottom = timeline_arr[cur_view_size][ID]['css']['layer']['bottom'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['bottom'] : pos.pix.bottom,
						
					layer_top = timeline_arr[cur_view_size][ID]['css']['layer']['top'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['top'] : pos.pix.top,
						
					layer_right = typeof timeline_arr[cur_view_size][ID]['css']['layer']['right'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['right'] : pos.pix.right,
						
					layer_left = typeof timeline_arr[cur_view_size][ID]['css']['layer']['left'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['left'] : pos.pix.left,
				
						
					layer_padding_top = typeof timeline_arr[cur_view_size][ID]['css']['layer']['padding_top'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['padding_top'] : '',
					layer_padding_right = typeof timeline_arr[cur_view_size][ID]['css']['layer']['padding_right'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['padding_right'] : '',
					layer_padding_bottom = typeof timeline_arr[cur_view_size][ID]['css']['layer']['padding_bottom'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['padding_bottom'] : '',
					layer_padding_left = typeof timeline_arr[cur_view_size][ID]['css']['layer']['padding_left'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['layer']['padding_left'] : '',
					
					
					// Item BG Color
					itm_bg_color = typeof timeline_arr[cur_view_size][ID]['css']['item']['background-color'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['item']['background-color'] : '',
					
					// Item Color (font)
					itm_color = typeof timeline_arr[cur_view_size][ID]['css']['item']['color'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['item']['color'] : '',
					
					// border
					itm_border = typeof timeline_arr[cur_view_size][ID]['css']['item']['border'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['item']['border'] : '',
					itm_border_style = typeof timeline_arr[cur_view_size][ID]['css']['item']['border-style'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['item']['border-style'] : '',
					itm_border_color = typeof timeline_arr[cur_view_size][ID]['css']['item']['border-color'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['item']['border-color'] : '',
					itm_border_radius = typeof timeline_arr[cur_view_size][ID]['css']['item']['border-radius'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['item']['border-radius'] : {
							'top-left': '',
							'top-right': '',
							'bottom-right': '',
							'bottom-left': ''
						},
					
					// FONT VARS
					itm_font_fam = typeof timeline_arr[cur_view_size][ID]['css']['item']['font-family'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['item']['font-family'] : preview_itm.css('font-family'),
						
					itm_fontsize = typeof timeline_arr[cur_view_size][ID]['css']['item']['font-size'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['item']['font-size'] : preview_itm.css('font-size'),
						
					itm_text_align = typeof timeline_arr[cur_view_size][ID]['css']['item']['text-align'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['css']['item']['text-align'] : 'left',
						
					
					// ANIMATION VARS
					itm_start_ani_type = typeof timeline_arr[cur_view_size][ID]['animation']['start_animation_type'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['start_animation_type'] : '',
					
					itm_start_ani_effect = typeof timeline_arr[cur_view_size][ID]['animation']['start_animation_effect'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['start_animation_effect'] : 'linear',
					
					itm_start_ani_speed = typeof timeline_arr[cur_view_size][ID]['animation']['start_animation_speed'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['start_animation_speed'] : 100,
					
					itm_fade_in_speed = typeof timeline_arr[cur_view_size][ID]['animation']['fade_in_speed'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['fade_in_speed'] : 100,
						
					itm_start_pos_offset = typeof timeline_arr[cur_view_size][ID]['animation']['start_pos_offset'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['start_pos_offset'] : 0,
						
					itm_end_ani_type = typeof timeline_arr[cur_view_size][ID]['animation']['end_animation_type'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['end_animation_type'] : '',
					
					itm_end_ani_effect = typeof timeline_arr[cur_view_size][ID]['animation']['end_animation_effect'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['start_animation_effect'] : 'linear',
					
					itm_end_ani_speed = typeof timeline_arr[cur_view_size][ID]['animation']['end_animation_speed'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['end_animation_speed'] : 0,
					
					itm_end_ani_repeat = typeof timeline_arr[cur_view_size][ID]['animation']['end_animation_repeat'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['end_animation_repeat'] : 0,
					
					itm_fade_out_speed = typeof timeline_arr[cur_view_size][ID]['animation']['fade_out_speed'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['fade_out_speed'] : 0,
						
					itm_start_time = typeof timeline_arr[cur_view_size][ID]['animation']['start_time'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['start_time'] : 0,
					
					itm_end_time = typeof timeline_arr[cur_view_size][ID]['animation']['end_time'] != 'undefined' ? 
						timeline_arr[cur_view_size][ID]['animation']['end_time'] : 0;
						
				$('.itm_edit_cont').hide();
				$('#itm_menu').wppas.tabs({container: '#itm_'+ID, ul:'.itm_edit_menu_toggle', nfer: '.itm_nfer'});
				
				// Remove options we don't need
				$(itm).find('.itm_edt_opt').each(function(i, obj) {
					
					if( $(obj).data('obj') != object ){
						$(obj).remove();
					}
				});
				
				
				// Show/select Font tab
				if( object == 'text'){
					itm.find('.itm_edit_menu_toggle').find('.font_tab').show();
					itm.find('.itm_edit_menu_toggle li').removeClass('selected');
					itm.find('.itm_edit_menu_toggle li.font_tab').addClass('selected');
					itm.find('.itm_nfer').hide();
					itm.find('#itm-edit-font').show();
				}
				
				// Show/select SHAPE tab
				if( object == 'shape' || object == 'square' || object == 'circle'){
					itm.find('.itm_edit_menu_toggle').find('.shape_tab').show();
					itm.find('.itm_edit_menu_toggle li').removeClass('selected');
					itm.find('.itm_edit_menu_toggle li.shape_tab').addClass('selected');
					itm.find('.itm_nfer').hide();
					itm.find('#itm-edit-shape').show();
				}
				
				// Show/select ICON tab
				if( object == 'icon' ){
					itm.find('.itm_edit_menu_toggle').find('.icon_tab').show();
					itm.find('.itm_edit_menu_toggle li').removeClass('selected');
					itm.find('.itm_edit_menu_toggle li.icon_tab').addClass('selected');
					itm.find('.itm_nfer').hide();
					itm.find('#itm-edit-icon').show();
				}
				
				// Show/select SVG tab
				if( object == 'svg' ){
					itm.find('.itm_edit_menu_toggle').find('.svg_tab').show();
					itm.find('.itm_edit_menu_toggle li').removeClass('selected');
					itm.find('.itm_edit_menu_toggle li.svg_tab').addClass('selected');
					itm.find('.itm_nfer').hide();
					itm.find('#itm-edit-svg').show();
				}
				
				// Show/select HTML tab
				if( object == 'html'){
					itm.find('.itm_edit_menu_toggle').find('.'+obj_itm+'_tab').show();
					itm.find('.itm_edit_menu_toggle li').removeClass('selected');
					itm.find('.itm_edit_menu_toggle li.'+obj_itm+'_tab').addClass('selected');
					itm.find('.itm_nfer').hide();
					itm.find('#itm-edit-'+obj_itm).show();
					
					// Show button tab
					if( obj_itm == 'button'){
						var html_code = decodeURIComponent(timeline_arr[cur_view_size][ID]['data']['code']),
							btn_style = timeline_arr[cur_view_size][ID]['data']['values']['class'],
							custom = timeline_arr[cur_view_size][ID]['data']['values']['custom'],
							button = btn_style != '' ? prefedined.buttons[btn_style] : '',
							btn_css = typeof custom != 'undefined' ? {
								'default':{
									'background-color': custom['css']['default']['background-color'],
									'color': custom['css']['default']['color'],
									'border-color': custom['css']['default']['border-color'],
									'border-style': custom['css']['default']['border-style'],
									'border-width': custom['css']['default']['border-width'],
									'border-radius': custom['css']['default']['border-radius'],
								},
								'hover':{
									'background-color': custom['css']['hover']['background-color'],
									'color': custom['css']['hover']['color'],
								}
							} : {
								'default':{
									'background-color': '#000000',
									'color': '#FFFFFF',
									'border-color': 'transparent',
									'border-style': 'none',
									'border-width': '',
									'border-radius': '',
								},
								'hover':{
									'background-color': '#000000',
									'color': '#FFFFFF',
								}
							};
						
						itm.find('#itm-edit-button').find('.btn_creator_preview').html(html_code.replace(/[%]27/g, "'"));
						itm.find('#itm-edit-button').find('#btn_creator_class').val(btn_style);
						
						itm.find('#itm-edit-button').find('#btn_creator_txt').val(timeline_arr[cur_view_size][ID]['data']['values']['text']);
						itm.find('#itm-edit-button').find('#btn_creator_border').val(btn_css['default']['border-width']);
						itm.find('#itm-edit-button').find('#btn_creator_border_radius').val(btn_css['default']['border-radius']);
						itm.find('#itm-edit-button').find('#btn_creator_border_style option[value="'+btn_css['default']['border-style']+'"]').prop('selected', 'selected').change();
						itm.find('#itm-edit-button').find('#btn_creator_border_color').wpColorPicker('color', btn_css['default']['border-color']);
						itm.find('#itm-edit-button').find('#btn_creator_bg_color').wpColorPicker('color', btn_css['default']['background-color']);
					
						itm.find('#itm-edit-button').find('#btn_creator_font_color').wpColorPicker('color', btn_css['default']['color']);
				
						itm.find('#itm-edit-button').find('#btn_creator_hover_bg_color').wpColorPicker('color', btn_css['hover']['background-color']);
						
						itm.find('#itm-edit-button').find('#btn_creator_hover_font_color').wpColorPicker('color', btn_css['hover']['color']);
				
					}else{
						var html_code = decodeURIComponent(timeline_arr[cur_view_size][ID]['data']['code']);
						//console.log(html_code);
						itm.find('#itm-edit-html').find('#edit_itm_html_code').val(html_code.replace(/[%]27/g, "'"));
					}
				}
				
			
				
				// FONT -------------------------------------------------------------------------------
				if( object == 'text'){
					var itm_txt = decodeURIComponent(timeline_arr[cur_view_size][ID]['data']['code']);
					
					var gfont_drop_exists = itm.find('#fontSelect-gfont_select').length;
					if( !gfont_drop_exists){
						itm.find('.itm_edit_form').find('#gfont_select').fontselect();
					}
					
					itm.find('.itm_edit_form').find('#edit_itm_html').val( itm_txt ); // jQuery.trim(preview_itm.find('.itm_html').html())
					itm.find('.itm_edit_form').find('#edit_itm_fontsize').val( itm_fontsize );
					//itm.find('.itm_edit_form').find('#edit_itm_font_color').val( itm_color ); // itm_font_color
					itm.find('.itm_edit_form').find('#edit_itm_font_color').wpColorPicker('color', itm_color);
					itm.find('.itm_edit_form').find('#edit_itm_text_align option[value='+itm_text_align+']').prop('selected', 'selected').change();
					itm.find('.itm_edit_form').find('#edit_itm_fontfamily option[value=\''+itm_font_fam+'\']').prop('selected', 'selected').change();
					//itm.parent().find("#edit_itm_html").css({'font-family': font});
					itm.find('.itm_edit_form').find('#edit_itm_html').css({'font-family': itm_font_fam, 'font-size': itm_fontsize});
					
					itm.find('textarea').select();
					
					/**
					 * UPDATE TEXTAREA CSS ON CHANGE
					 */
					// Font
					itm.find('.itm_edit_form').find('#edit_itm_fontfamily').on('change', function(){
						//console.log('oi '+$(this).val());
						itm.find('.itm_edit_form').find('#edit_itm_html').css({'font-family': $(this).val()});
					});
					// Font size
					itm.find('.itm_edit_form').find('#edit_itm_fontsize').on('change', function(){
						itm.find('.itm_edit_form').find('#edit_itm_html').css({'font-size': $(this).val()});
					});
					
					
					itm.find('textarea').on('change', function(){
						var txt_str = itm.find('.itm_edit_form').find('#edit_itm_html').val();
						//preview_itm.find('.itm_html').html( '\n'+ _4chars +itm.find('.itm_edit_form').find('#edit_itm_html').val()+'\n' );
						preview_itm.find('.itm_html').html( '\n'+ _4chars +encodeURIComponent(txt_str.replace(/'/g, "%27"))+'\n' );
						//wppas_update_code_editor_from_preview(); // werkt niet... dan kun je slechts 1 keer de text aanpasses...
					});
				}
				
				
				// CSS -------------------------------------------------------------------------------
				itm.find('.itm_edit_form_style').find('#edit_itm_align_h').val( layer_align_h );
				itm.find('.itm_edit_form_style').find('#edit_itm_align_v').val( layer_align_v );
				itm.find('.itm_edit_form_style').find('.wppas_align_btn.alh').each(function() {
					if( $(this).data('align') == layer_align_h ){
						$('.wppas_align_btn.alh').removeClass('selected');
						$(this).addClass('selected');	
					}
				});
				itm.find('.itm_edit_form_style').find('.wppas_align_btn.alv').each(function() {
					if( $(this).data('align') == layer_align_v ){
						$('.wppas_align_btn.alv').removeClass('selected');
						$(this).addClass('selected');	
					}
				});
				
				itm.find('.itm_edit_form_style').find('#edit_itm_left').val( layer_left );
				itm.find('.itm_edit_form_style').find('#edit_itm_right').val( layer_right );
				itm.find('.itm_edit_form_style').find('#edit_itm_top').val( layer_top );
				itm.find('.itm_edit_form_style').find('#edit_itm_bottom').val( layer_bottom );
				
				// Positioning
				// Horizontal
				if( layer_align_h == 'left' ){
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_left').val( _t.wppas.split_string(layer_left,'px')[0] );
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_right').val('');
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_right').prop('readonly', true);
				}else if( layer_align_h == 'center' ){
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_left').val( _t.wppas.split_string(layer_left,'px')[0] );
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_right').val(_t.wppas.split_string(layer_right,'px')[0]);
				}else if( layer_align_h == 'right' ){
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_left').val('');
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_right').val(_t.wppas.split_string(layer_right,'px')[0]);
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_left').prop('readonly', true);
				}
				// Vertical
				if( layer_align_v == 'top' ){
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_top').val( _t.wppas.split_string(layer_top,'px')[0] );
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_bottom').val('');
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_bottom').prop('readonly', true);
				}else if( layer_align_v == 'middle' ){
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_top').val( _t.wppas.split_string(layer_top,'px')[0] );
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_bottom').val( _t.wppas.split_string(layer_bottom,'px')[0] );
				}else if( layer_align_v == 'bottom' ){
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_top').val('');
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_bottom').val( _t.wppas.split_string(layer_bottom,'px')[0] );
					itm.find('.itm_edit_form_style').find('#edit_itm_offset_top').prop('readonly', true);
				}
				
				
				// Padding
				itm.find('.itm_edit_form_style').find('#edit_itm_padding_top').val( layer_padding_top );
				itm.find('.itm_edit_form_style').find('#edit_itm_padding_right').val( layer_padding_right );
				itm.find('.itm_edit_form_style').find('#edit_itm_padding_bottom').val( layer_padding_bottom );
				itm.find('.itm_edit_form_style').find('#edit_itm_padding_left').val( layer_padding_left );
				
				itm.find('.itm_edit_form_style').find('#edit_itm_width').val( layer_width );
				itm.find('.itm_edit_form_style').find('#edit_itm_height').val( layer_height );
				//itm.find('.itm_edit_form_style').find('#edit_itm_bg_color').val( layer_bg_color );
				
				itm.find('.itm_edit_form_style').find('#edit_layer_bg_color').wpColorPicker('color', layer_bg_color);
				itm.find('.itm_edit_form_style').find('#edit_itm_color').wpColorPicker('color', itm_bg_color);
				
				// Border
				itm.find('.itm_edit_form_style').find('#edit_itm_border').val( itm_border );
				itm.find('.itm_edit_form').find('#edit_itm_border_style option[value="'+itm_border_style+'"]').prop('selected', 'selected').change();
				
				itm.find('.itm_edit_form_style').find('#edit_itm_border_color').wpColorPicker('color', itm_border_color);
				//itm.find('.itm_edit_form_style').find('.wp-color-border').find('.wp-color-picker').val(itm_border_color);
				// border Radius
				itm.find('.itm_edit_form_style').find('#edit_itm_border_radius_top_left').val(itm_border_radius['top-left']);
				itm.find('.itm_edit_form_style').find('#edit_itm_border_radius_top_right').val(itm_border_radius['top-right']);
				itm.find('.itm_edit_form_style').find('#edit_itm_border_radius_bottom_right').val(itm_border_radius['bottom-right']);
				itm.find('.itm_edit_form_style').find('#edit_itm_border_radius_bottom_left').val(itm_border_radius['bottom-left']);
				
				
				
				// ANIMATION ---------------------------------------------------------------------------
				itm.find('.itm_animation_edit_form').find('#edit_itm_start_animation_type').val(itm_start_ani_type);
				itm.find('.itm_animation_edit_form').find('#edit_itm_start_animation_effect').val(itm_start_ani_effect);
				itm.find('.itm_animation_edit_form').find('#edit_itm_start_animation_speed').val(itm_start_ani_speed);
				itm.find('.itm_animation_edit_form').find('#edit_itm_fade_in_speed').val(itm_fade_in_speed);
				itm.find('.itm_animation_edit_form').find('#edit_itm_start_pos_offset').val(itm_start_pos_offset);
				
				itm.find('.itm_animation_edit_form').find('#edit_itm_fade_out_speed').val(itm_fade_out_speed);
				itm.find('.itm_animation_edit_form').find('#edit_itm_end_animation_type').val(itm_end_ani_type);
				itm.find('.itm_animation_edit_form').find('#edit_itm_end_animation_effect').val(itm_end_ani_effect);
				itm.find('.itm_animation_edit_form').find('#edit_itm_end_animation_speed').val(itm_end_ani_speed);
				itm.find('.itm_animation_edit_form').find('#edit_itm_end_animation_repeat').val(itm_end_ani_repeat);
				itm.find('.itm_animation_edit_form').find('#edit_itm_start_time').val(itm_start_time);
				itm.find('.itm_animation_edit_form').find('#edit_itm_end_time').val(itm_end_time);
				
				itm.find('.itm_edit_cont').show();
			}
				
			
			
			
			
			// -- SAVE EDIT ITEM BTN --
			$('body').on('click', '.wppas_itm_save_btn', function(event){
				
				var itm = $(this).closest('.timeline_itm.selected'),
					ID = itm.data('itm'),
					preview_itm = $('.'+itm.data('itm')),
					type = preview_itm.data('type'),
					object = itm.data('object'),
					obj_itm = itm.data('item'),
					//itm_bg_color = itm.find('.itm_edit_cont').find('#edit_itm_color').val(),
					itm_bg_color = itm.find('.'+object+'_edit').find('#edit_itm_color').val(),
					bg_color = itm.find('.itm_edit_cont').find('#edit_layer_bg_color').val(),
					border = itm.find('.itm_edit_cont').find('#edit_itm_border').val(),
					border_style = itm.find('.itm_edit_cont').find('#edit_itm_border_style').val(),
					border_color = itm.find('.itm_edit_cont').find('#edit_itm_border_color').val(),
					border_radius = {
						'top-left': itm.find('.itm_edit_form_style').find('#edit_itm_border_radius_top_left').val(),
						'top-right': itm.find('.itm_edit_form_style').find('#edit_itm_border_radius_top_right').val(),
						'bottom-right': itm.find('.itm_edit_form_style').find('#edit_itm_border_radius_bottom_right').val(),
						'bottom-left': itm.find('.itm_edit_form_style').find('#edit_itm_border_radius_bottom_left').val(),
					},
					font_size = itm.find('.itm_edit_cont').find('#edit_itm_fontsize').val(),
					font_family = type != 'icon' ? itm.find('.itm_edit_cont').find('#edit_itm_fontfamily').val() : 'FontAwesome',
					font_color = itm.find('.itm_edit_form').find('#edit_itm_font_color').val(),
					text_align = itm.find('.itm_edit_cont').find('#edit_itm_text_align').val(),
					html = itm.find('.itm_edit_cont').find('#edit_itm_html').val(),
					html_code = itm.find('.itm_edit_cont').find('#edit_itm_html_code').val();
				
				// FONT -------------------------------------------------------------------------------
				if(object == 'text'){
					preview_itm.find('.itm_html').html( '\n'+ _4chars +encodeURIComponent(html.replace(/'/g, "%27"))+'\n' );
					_t.wppas.addGoogleFont( font_family );
					
					// preview text in timeline button.
					itm.find('.txt_prev').val(html);
					itm.find('.txt_prev').css({color: font_color});
					
					preview_itm.css({
						'font-size': font_size,
						'font-family': font_family,
						'text-align': text_align,
						'color': font_color
					});
					preview_itm.find('.itm_html').css({
						'font-size': font_size,
						'font-family': font_family,
						'color': font_color
					});
				}
				
				if( object == 'icon' ){
					preview_itm.css({
						'color': font_color
					});
				}
				
				
				
				// Border
				if( border != '' ){
					preview_itm.find('.shape').css({
						'border-width': _t.wppas.get_value(border),
						'border-style': border_style,
						'border-color': border_color
					});
				}
				// Border radius 
				preview_itm.find('.shape').css({'border-radius': _t.wppas.border_radius_css(border_radius)});
				
				
				// UPDATE TIMELINE ARRAY
				// first make sure the arrays we need exist.
				$(this).wppas.create_timeline_itm({ID: ID});
				
				// UPDATE FONT ARRAY
				if(typeof timeline_arr[cur_view_size][ID] !== 'undefined') {
					
					if( object == 'text'){
						
						timeline_arr[cur_view_size][ID]['data']['code'] = typeof html != 'undefined' ? encodeURIComponent(html.replace(/'/g, "%27")) : '';
						//timeline_arr[cur_view_size][ID]['data']['code'] = typeof html != 'undefined' ? html.replace(/'/g, "\\'") : '';
					}
					
					if(typeof timeline_arr[cur_view_size][ID]['css']['layer'] == 'undefined') {
						timeline_arr[cur_view_size][ID]['css']['layer'] = {};
					}
					
					if(typeof timeline_arr[cur_view_size][ID]['css']['item'] == 'undefined') {
						timeline_arr[cur_view_size][ID]['css']['item'] = {};
					}
				}
				
				//console.log(itm.find('.itm_edit_form_style').find('#edit_itm_align_h').val());
				// CSS -------------------------------------------------------------------------------
				_t.wppas.align_layers(
					preview_itm, 
					{
						'pos_h': itm.find('.itm_edit_form_style').find('#edit_itm_align_h').val(),
						'pos_v': itm.find('.itm_edit_form_style').find('#edit_itm_align_v').val(),
						'top': itm.find('.itm_edit_cont').find('#edit_itm_offset_top').val(),
						'bottom': itm.find('.itm_edit_cont').find('#edit_itm_offset_bottom').val(),
						'right': itm.find('.itm_edit_cont').find('#edit_itm_offset_right').val(),
						'left': itm.find('.itm_edit_cont').find('#edit_itm_offset_left').val()
					}
				);
				preview_itm.css({
					'width': itm.find('.itm_edit_cont').find('#edit_itm_width').val(),
					'height': itm.find('.itm_edit_cont').find('#edit_itm_height').val()
				});
				
				
				
				// Coloring
				if( type == 'shape' ){
					preview_itm.html(encodeURIComponent($('#itm_'+itm.data('itm')).find('.shape_creator_preview').html().replace(/'/g, "%27")));
					$('#itm_'+itm.data('itm')).find('.preview_cont').find('.shape_preview').html($('#itm_'+itm.data('itm')).find('.shape_creator_preview').html())
					timeline_arr[cur_view_size][ID]['data']['code'] = encodeURIComponent($('#itm_'+itm.data('itm')).find('.shape_creator_preview').html().replace(/'/g, "%27"));
			
				}else if(type == 'svg'){
					
					//timeline_arr[cur_view_size][ID]['data']['code'] = $('#itm_'+itm.data('itm')).find('.svg_preview').html();
					preview_itm.html(encodeURIComponent($('#itm_'+itm.data('itm')).find('.svg_creator_preview').html().replace(/'/g, "%27")));
					$('#itm_'+itm.data('itm')).find('.preview_cont').find('.svg_preview').html($('#itm_'+itm.data('itm')).find('.svg_creator_preview').html())
					timeline_arr[cur_view_size][ID]['data']['code'] = encodeURIComponent($('#itm_'+itm.data('itm')).find('.svg_creator_preview').html().replace(/'/g, "%27"));
					
				}else if(type == 'text'){
					$('#itm_'+itm.data('itm')).find('.txt_prev').css({'background-color': bg_color});
				}else if(type == 'icon'){
					$('#itm_'+itm.data('itm')).find('.desc').find('.fa').css({'color': itm_bg_color});
				}
				
				// Defaults
				preview_itm.css({
					'background-color': bg_color
				});
				$('#itm_'+itm.data('itm')).find('.preview_cont').css({'background-color': bg_color, 'color': itm_bg_color});
				
				
				// Custom Class
				var custom_class = itm.find('.itm_edit_cont').find('#edit_itm_class').val();
				if( custom_class != '' ){
					preview_itm.addClass(itm.find('.itm_edit_cont').find('#edit_itm_class').val());
				}
				
				// UPDATE TIMELINE ARRAY
				if(typeof timeline_arr[cur_view_size] !== 'undefined') {
					
					if( object == 'html'){
						if(obj_itm == 'button'){
							
							var button_code = itm.find('#itm-edit-button').find('.btn_creator_preview').html();
							timeline_arr[cur_view_size][ID]['data']['code'] = encodeURIComponent(button_code.replace(/'/g, "%27"));
							preview_itm.html('\n'+ _4chars +button_code+'\n');
							
							timeline_arr[cur_view_size][ID]['data']['values']['class'] = itm.find('#itm-edit-button').find('#btn_creator_class').val();
							timeline_arr[cur_view_size][ID]['data']['values']['text'] = itm.find('#itm-edit-button').find('#btn_creator_txt').val();
							// Custom
							if( typeof timeline_arr[cur_view_size][ID]['data']['values']['custom'] == 'undefined'){
								timeline_arr[cur_view_size][ID]['data']['values']['custom'] = {
									'css': {
										'default':{},
										'hover':{}	
									}
								}
							}
							timeline_arr[cur_view_size][ID]['data']['values']['custom']['css']['default']['background-color'] = itm.find('#itm-edit-button').find('#btn_creator_bg_color').val();
							timeline_arr[cur_view_size][ID]['data']['values']['custom']['css']['default']['color'] = itm.find('#itm-edit-button').find('#btn_creator_font_color').val();
							timeline_arr[cur_view_size][ID]['data']['values']['custom']['css']['default']['border-color'] = itm.find('#itm-edit-button').find('#btn_creator_border_color').val();
							timeline_arr[cur_view_size][ID]['data']['values']['custom']['css']['default']['border-width'] = _t.wppas.get_value(itm.find('#itm-edit-button').find('#btn_creator_border').val());
							timeline_arr[cur_view_size][ID]['data']['values']['custom']['css']['default']['border-style'] = itm.find('#itm-edit-button').find('#btn_creator_border_style').val();
							timeline_arr[cur_view_size][ID]['data']['values']['custom']['css']['default']['border-radius'] = itm.find('#itm-edit-button').find('#btn_creator_border_radius').val();
							timeline_arr[cur_view_size][ID]['data']['values']['custom']['css']['hover']['background-color'] = itm.find('#itm-edit-button').find('#btn_creator_hover_bg_color').val();
							timeline_arr[cur_view_size][ID]['data']['values']['custom']['css']['hover']['color'] = itm.find('#itm-edit-button').find('#btn_creator_hover_font_color').val();
							timeline_arr[cur_view_size][ID]['data']['values']['custom']['css']['hover']['border-color'] = itm.find('#itm-edit-button').find('#btn_creator_hover_border_color').val();
							
								
						}else{
							preview_itm.html( '\n'+ _4chars +html_code+'\n' );
							timeline_arr[cur_view_size][ID]['data']['code'] = encodeURIComponent(html_code.replace(/'/g, "%27"));
						}
					}
					
					timeline_arr[cur_view_size][ID]['css']['layer'] = {
						'pos_h': itm.find('.itm_edit_form_style').find('#edit_itm_align_h').val(),
						'pos_v': itm.find('.itm_edit_form_style').find('#edit_itm_align_v').val(),
						'font-size': font_size,
						'font-family': font_family,
						'text-align': text_align,
						'color': font_color,
						'top': _t.wppas.get_value(itm.find('.itm_edit_cont').find('#edit_itm_offset_top').val()),
						'bottom': _t.wppas.get_value(itm.find('.itm_edit_cont').find('#edit_itm_offset_bottom').val()),
						'right': _t.wppas.get_value(itm.find('.itm_edit_cont').find('#edit_itm_offset_right').val()),
						'left': _t.wppas.get_value(itm.find('.itm_edit_cont').find('#edit_itm_offset_left').val()),
						'width': _t.wppas.get_value(itm.find('.itm_edit_cont').find('#edit_itm_width').val()),
						'height': _t.wppas.get_value(itm.find('.itm_edit_cont').find('#edit_itm_height').val()),
						'background-color': bg_color
					}
					
					timeline_arr[cur_view_size][ID]['css']['item'] = {
						'font-size': font_size,
						'font-family': font_family,
						'text-align': text_align,
						'color': font_color,
						'background-color': itm_bg_color,
						'custom_class': itm.find('.itm_edit_cont').find('#edit_itm_class').val(),
						'border': _t.wppas.get_value(itm.find('.itm_edit_cont').find('#edit_itm_border').val()),
						'border-style': itm.find('.itm_edit_cont').find('#edit_itm_border_style').val(),
						'border-color': itm.find('.itm_edit_cont').find('#edit_itm_border_color').val(),
						'border-radius': border_radius
					};
					
				}
				
				// ANIMATION -----------------------------------------------------------------------------
				itm.find('.itm_animation_edit_form').find('#edit_itm_start_animation_type').val();
				
				// UPDATE TIMELINE ARRAY
				if(typeof timeline_arr[cur_view_size] !== 'undefined') {
					timeline_arr[cur_view_size][ID]['animation'] = {
						'start_animation_type': itm.find('.itm_animation_edit_form').find('#edit_itm_start_animation_type').val(),
						'start_animation_effect': itm.find('.itm_animation_edit_form').find('#edit_itm_start_animation_effect').val(),
						'start_animation_speed': itm.find('.itm_animation_edit_form').find('#edit_itm_start_animation_speed').val(),
						'fade_in_speed': itm.find('.itm_animation_edit_form').find('#edit_itm_fade_in_speed').val(),
						'start_pos_offset': itm.find('.itm_animation_edit_form').find('#edit_itm_start_pos_offset').val(),
						'fade_out_speed': itm.find('.itm_animation_edit_form').find('#edit_itm_fade_out_speed').val(),
						'end_animation_type': itm.find('.itm_animation_edit_form').find('#edit_itm_end_animation_type').val(),
						'end_animation_effect': itm.find('.itm_animation_edit_form').find('#edit_itm_end_animation_effect').val(),
						'end_animation_speed': itm.find('.itm_animation_edit_form').find('#edit_itm_end_animation_speed').val(),
						'end_animation_repeat': itm.find('.itm_animation_edit_form').find('#edit_itm_end_animation_repeat').val(),
						'start_time': itm.find('.itm_animation_edit_form').find('#edit_itm_start_time').val(),
						'end_time': itm.find('.itm_animation_edit_form').find('#edit_itm_end_time').val()
					};
				}
				
				// DEFAULT -------------------------------------------------------------------------------
				_t.wppas.wppas_update_code_editor_from_preview();
				$('.itm_edit_cont').hide();
				
			});
			
			
			
			
			// ADD ITEM POPUP SAVE
			$('body').on('click', '.wppas_add_itm_save_btn', function(event){
				var type = $(this).data('itm');
				
				if( type == 'html'){
					_t.wppas.add_html({type: 'html', itm:'html', values: {}, code: $('#add_itm_html').val(), options: options});
				}
				else if( type == 'button' ){
					var code = $('.itm_add_cont').find('.btn_creator_preview').html(),
						values = {
							'class': $('.itm_add_cont').find('#btn_creator_class').val(),
							'text': $('.itm_add_cont').find('#btn_creator_txt').val(),
							'custom': {
								'css': {
									'default': {
										'background-color': $('.itm_add_cont').find('#btn_creator_bg_color').val(),
										'color': $('.itm_add_cont').find('#btn_creator_font_color').val(),
										'border-width': $('.itm_add_cont').find('#btn_creator_border').val(),
										'border-style': $('.itm_add_cont').find('#btn_creator_border_style').val(),
										'border-color': $('.itm_add_cont').find('#btn_creator_border_color').val(),
										'border-radius': $('.itm_add_cont').find('#btn_creator_border_radius').val(),
									},
									'hover': {
										'background-color': $('.itm_add_cont').find('#btn_creator_hover_bg_color').val(),
										'color': $('.itm_add_cont').find('#btn_creator_hover_font_color').val()
									}
								}
							}
						};
					
					$('.itm_add_cont').find('#btn_prev_style').text('');
					_t.wppas.add_html({type: 'html', itm:'button', values: values, code: code, options: options});	
					
				}
				else if( type == 'svg'){
					var code = $('.itm_add_cont').find('.svg_creator_preview').html();
					console.log('add svg');
					_t.wppas.add_svg({type: 'svg', code: code, options: options});
				}
				else if( type == 'shape'){
					var code = $('.itm_add_cont').find('.shape_creator_preview').html();
					console.log('add shape');
					_t.wppas.add_shape({type: 'shape', code: code, options: options});
					//_t.wppas.add_svg({type: 'svg', code: code, options: options});
				}
				else if( type == 'zip' ){
					_t.wppas.add_zip({type: 'zip', url: $('#add_itm_zip_url').val(), options: options});
				}
					
				$('#add_itm_html').val('');
				$('.itm_edit_cont').hide();
				
				_t.wppas.close_popup_func();
			});
			
			
			
			
			
			
			// -- CANCEL - close edit popup --
			$('body').on('click', '.wppas_itm_close', function(event){
				click_wppas_itm_close(this);
			});
			$('.wppas_itm_close').on('click', function(event){
				click_wppas_itm_close(this);
			});
			function click_wppas_itm_close(obj){
				//$('.itm_edit_form').hide();
				//$('.itm_edit_form_style').hide();
				$('.itm_edit_cont').hide();
				$(this).wppas.close_popup_func();
			}
			
			
			// -- SAVE BANNER COVER --
			$('.banner_cover').on('click', function(){
				var type = $(this).data('type');
				_t.wppas.create_banner_cover({'download': 1, 'type': type});
			});
			
			// -- PREVIEW BANNER --
			$('.preview_banner').on('click', function(){
				
				_t.wppas.deselect_items();
				//$('.vbc_loader_bg').detach().appendTo("body").show();
				//$('.vbc_preview_container').show();
				
				var ifm = '',
					html = '',
					files = '',
					bsize = $('#wppas_banner_size').val().split('x'),
					w = bsize[0] != 'full' ? bsize[0]+'px' : '100%',
					h = bsize[1] != 'full' ? bsize[1]+'px' : '100%',
					ID = bannerID != 0 ? bannerID : Math.floor(Date.now() / 1000),
					banners_html = [],
					link = $('#wppas_banner_link').val() != '' ? 'href="'+$('#wppas_banner_link').val()+'" target="'+$('#wppas_banner_target').val()+'"' : '';
				
				ifm+= '<div class="vbc_preview_frame_cont" style="max-width:'+w+'; width:100%; height:'+h+';margin:auto;border:solid 1px #f5f5f5;">';
					ifm+= '<iframe id="vbc_preview_frame" border="0" scrolling="no" allowtransparency="true" width="100%" height="100%" style="border:0;"></iframe>';
					/*ifm+= '<a class="wppas_preview_close wppas_preview_close_css">';
						ifm+= '<i class="fa fa-close" aria-hidden="true"></i>';
					ifm+= '</a>';*/
				ifm+= '</div>';
				
				//$('.vbc_preview_container').find('.preview_cont').html(ifm);
				$('#vbc_preview_container').show();
				$('#vbc_preview_container').find('.wppas-modal-content').html(ifm);
				
				// HTML
				html+= '<body>';
				html+= '<a class="b_container b_cont_'+ID+'"'+link+' style="max-width:'+w+'; max-height:'+h+';"></a>';
				html+= '<script type="text/javascript">';
					html+= 'var bhtml_'+ID+' = { ';
						$.each(options.screen_sizes, function( index, value ) {
							var b_html = $("#wppas_banner_html_"+value.size).val();
							
							if(b_html != "" && typeof b_html != 'undefined'){
								b_html = b_html.replace(/(\r\n|\n|\r)/gm,""); // remove line breaks.
								b_html = b_html.replace(/'/g, "\\'"); // Replace ' with \' to solve font-family issue with preview. 
								//html+= index+':"'+encodeURIComponent(b_html)+'",'; // @since v5.1.6 encodeURIComponent()
								html+= index+':\''+b_html+'\',';
							} 
						});
					html+= '};';
					
					html+= 'jQuery(document).ready(function($){';
						html+= '$(".b_cont_'+ID+'").wppas_show({';
							html+= 'bid:'+ID+',';
							html+= 'bw: $(".b_cont_'+ID+'").width(),';
							html+= 'html: bhtml_'+ID+',';
							html+= 'ID: '+ID+',';
							html+= 'size: "'+$("#wppas_banner_size").val()+'",';
							html+= 'w: "'+bsize[0]+'",';
							html+= 'h: "'+bsize[1]+'",';
							html+= 'force_size: "'+cur_view_size+'",';
							html+= 'keep_aspect_ratio: '+keep_aspect_ratio+',';
							html+= 'timeline_arr: { ';
								html+= $(this).wppas.check_array_and_output(timeline_arr);
							html+= '}';
						html+= '});';
					html+= '});';
				html+= '</script>';
				html+= '<div class="banner_cover cover" data-option="vbc-cover" style="cursor:pointer;"><i class="fa fa-camera" style="margin-right:5px;"></i></div>';
				html+= '</body>';
				html+= '</html>';
				
				files+= '<!DOCTYPE>';
				files+= '<html>';
					files+= '<head>';
						files+= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
						files+= '<style type="text/css">body{margin:0; padding:0;}</style>';
						files+= '<script type="text/javascript" src="'+URL.url+'/wp-includes/js/jquery/jquery.js"></script>';
						files+= '<link rel="stylesheet" href="'+WP_ADS_URL.url+'public/assets/css/vbc/wppas_vbc_bnr.css" type="text/css" media="all" />';
						files+= '<link rel="stylesheet" href="'+WP_ADS_URL.url+'includes/font-awesome/css/font-awesome.min.css" type="text/css" media="all" />';
						files+= '<script type="text/javascript" src="'+WP_ADS_URL.url+'public/assets/js/vbc/postscribe.min.js"></script>';
						files+= '<script type="text/javascript" src="'+WP_ADS_URL.url+'public/assets/js/dom-to-image.js"></script>';
						files+= '<script type="text/javascript" src="'+WP_ADS_URL.url+'public/assets/js/vbc/jquery.wppas.vbc.min.js"></script>';
						
						files+= '<script type="text/javascript" src="'+WP_ADS_URL.url+'public/assets/js/vbc/jquery-ui-effects.min.js"></script>';
					files+= '</head>';
				
				
				// Fill Iframe
				var iframe = document.getElementById('vbc_preview_frame');
				iframe = iframe.contentWindow || ( iframe.contentDocument.document || iframe.contentDocument);
				
				iframe.document.open();
				iframe.document.write( files+html );
				iframe.document.close();
				
			});
			
			
			// -- CLOSE PREVIEW --
			/*$('body').on('click', '.wppas_preview_close', function(){
				//$('.vbc_loader_bg').hide();
				$('#vbc_preview_container').find('.wppas-modal-content').html('');
				$('#vbc_preview_container').hide();
			});*/
			
			
			
			// -- SAVE BANNER --
			$('.save_banner').on('click', function(){
				
				_t.wppas.deselect_items();
				$('.vbc_loader_bg').show();
				$('.vbc_loader_duration').show();
				var url = window.location.href,
					hasID = url.indexOf("&bid") !== -1 ? 1 : 0;
				
				console.log(timeline_arr);
				//console.log($('body').find('#bnofollow').val());
				/*if(got_saved === 0){
					_t.wppas.create_banner_cover();
				}*/
				//console.log( $('.b_container').html() );
	
				
				var bsize = $('#wppas_banner_size').val().split('x'),
					alphaID = $('#wppas_banner_alpha_id').val(),
					auto_show = typeof $('#wppas_all_post_ad_sc').val() != 'undefined' ? {
						'post_types': typeof $('#wppas_all_post_ad_sc').val() != 'undefined' ? $('#wppas_all_post_ad').val() : null,
						'position': typeof $('#wppas_all_post_ad_sc').val() != 'undefined' ? $('#wppas_all_post_ad_position').val() : null,
						'paragraph': typeof $('#wppas_all_post_ad_sc').val() != 'undefined' ? $('#wppas_all_post_ad_parag').val() : null,
						'shortcode': typeof $('#wppas_all_post_ad_sc').val() != 'undefined' ? $('#wppas_all_post_ad_sc').val().replace(/"/g, "'") : null
					} : null,
					
					//no_follow = $('#bnofollow').val(),
					hide_pages = $('#wppas_banner_hide_pages').val() == null ? [] : $('#wppas_banner_hide_pages').val(),
					hide_posts = $('#wppas_banner_hide_posts').val() == null ? [] : $('#wppas_banner_hide_posts').val(),
					hide_tags = $('#wppas_banner_hide_tags').val() == null ? [] : $('#wppas_banner_hide_tags').val(),
					hide_cats = $('#wppas_banner_hide_categories').val() == null ? [] : $('#wppas_banner_hide_categories').val(),
					banners_html = [],
					banner_data = {
						ID: bannerID,
						alphaID: alphaID,
						//memorySize: _t.wppas.memorySizeOf( $('.b_container')),
						size: typeof $('#wppas_banner_size').val() != 'undefined' ? $('#wppas_banner_size').val() : null,
						w: bsize[0],
						h: bsize[1],
						status: typeof $('#wppas_banner_status').val() != 'undefined' ? $('#wppas_banner_status').val() : null,
						name: typeof $('#wppas_banner_name').val() != 'undefined' ? $('#wppas_banner_name').val() : null,
						link: typeof $('#wppas_banner_link').val() != 'undefined' ? $('#wppas_banner_link').val() : null,
						target: typeof $('#wppas_banner_target').val() != 'undefined' ? $('#wppas_banner_target').val() : null,
						advertiser: typeof $('#wppas_banner_advertiser').val() != 'undefined' ? $('#wppas_banner_advertiser').val() : null,
						campaign: typeof $('#wppas_banner_campaign').val() != 'undefined' ? $('#wppas_banner_campaign').val() : null,
						contract: typeof $('#wppas_bs_contract').val() != 'undefined' ? $('#wppas_bs_contract').val() : null,
						duration: typeof $('#wppas_bs_duration').val() != 'undefined' ? $('#wppas_bs_duration').val() : null,
						showhide: $('#bshowhide').val(),
						hide_for_categories: typeof $('#wppas_banner_hide_categories').val() != 'undefined' ? hide_cats : null,
						hide_for_tags: typeof $('#wppas_banner_hide_tags').val() != 'undefined' ? hide_tags : null,
						hide_for_posts: typeof $('#wppas_banner_hide_posts').val() != 'undefined' ? hide_posts : null,
						hide_for_pages: typeof $('#wppas_banner_hide_pages').val() != 'undefined' ? hide_pages : null,
						auto_show: auto_show,
						scale_banner: $('#bscale').val(),
						keep_aspect_ratio: typeof keep_aspect_ratio != 'undefined' ? keep_aspect_ratio : null,
						no_follow: typeof $('#bnofollow').val() != 'undefined' ? $('#bnofollow').val() : 0,
						//no_follow: no_follow,
						center: typeof $('#bcenter').val() != 'undefined' ? $('#bcenter').val() : null,
						timeline_arr: typeof timeline_arr != 'undefined' ? timeline_arr : null
					};
				var tst = typeof $('#wppas_banner_hide_pages').val() != 'undefined' ? 'NIET UNDEF' : 'UNDEF';
				
				_t.wppas.delete_null_properties(banner_data, true);
				//console.log(banner_data['timeline_arr']);
				console.log(alphaID);
				console.log(banner_data);
				//console.log(banner_data['memorySize']);
				
				$.each(options.screen_sizes, function( index, value ) {
					
					var b_html = $("#wppas_banner_html_"+value.size).val();
					
					if(b_html != ""){
						banners_html.push({
							"screen_size": value.size,
							"html": b_html.replace(/&quot;/g, "'") // Replace &quot with ' to solve issue with ajax not saving the HTML anymore.
						});
					}
				});
				
				var json_banners_html = encodeURIComponent(JSON.stringify( banners_html ));
				var json_banner_data = encodeURIComponent(JSON.stringify( banner_data ));
				
				$.ajax({
				   type: "POST",
				   url: ajaxurl,
				   data: "action=save_vbc_banner&banners="+json_banners_html+"&data="+json_banner_data+"&bid="+banner_data.ID+"&return="
				}).done(function( msg ) {
			
					console.log(msg);
					
					got_saved = 1;
					$('.'+alphaID).find('#banner_ID').val(msg);
					_t.wppas.wppas_export_banner(options);
					
					if(!isNaN(msg) && !hasID)
					{
						window.history.pushState("", "", url+'&bid='+msg);
						//window.location.href = window.location.href+'&bid='+msg;
					}
					
					// Save confirm message
					var conf_msg = save_confirms[Math.floor(Math.random()*save_confirms.length)];
					$('.vbc_conf_txt').html(conf_msg);
					$('.vbc_loader_duration').hide();
					$('.vbc_saved_confirm').show();
					
					setTimeout(function(){
						$('.vbc_saved_confirm').hide();
						$('.vbc_loader_bg').hide();
					}, 1000);
				});
			});
			
			
			
			
			// -- TRASH SCREEN SIZE VIEW --
			$('#wppas_trash_view').on('click', function(){
				var nr = $('.view_btn.selected').data('min');
				
				if( typeof timeline_arr[cur_view_size] !== 'undefined' ){
					delete timeline_arr[cur_view_size]; 
				}
		
				_v.editor.getSession().setValue('');
			});
			
			
			
			
			// -- TRASH BANNER --
			$('.trash_banner').on('click', function(){
				
				var ID = bannerID; //$('#banner_ID').val();
				
				if( ID ){
					$('.vbc_loader_bg').show();
					
					$.ajax({
					   type: "POST",
					   url: ajaxurl,
					   data: "action=trash_vbc_banner&ID="+ID
					}).done(function( msg ) {
						
						$('.vbc_loader_bg').css({opacity: .9});
						$('.vbc_loader_bg').html(msg);
					});
				}
			});
			
			
			// -- UNDO BANNER REMOVAL --
			$('body').on('click', '#wppas_undo_banner_removal', function(event){
				var ID = $(this).data('id');
				
				if( ID ){
					$('.wppas_remove_confirmation').remove();
					
					$.ajax({
					   type: "POST",
					   url: ajaxurl,
					   data: "action=undo_trash_vbc_banner&ID="+ID
					}).done(function( msg ) {
				
						//console.log(msg);
						$('.vbc_loader_bg').hide();
					});
				}
			});
			
			
			
			// -- EXPORT DISPLAY OPTINS --
			_t.wppas.display_options_func();
		},
		
		
		
		/**
		 * POPUP FUNCTIONS
		 */
		open_popup_func: function(args){
			if( args['scroll'] == 0 ){
				$("html").css({"overflow":"hidden"});
				$("body").css({"overflow":"hidden"});
			}
			args.container.css({'max-height': ($(window).height()-200)+'px'});
			/*args.container.find('#itm_edit_content_container').css({
				'max-height': $(window).height()+'px'
			});*/
		},
		close_popup_func: function(args){
			$("html").css({"overflow":"auto"});
			$("body").css({"overflow":"auto"});
		},
		
		
		
		display_options_func: function(){
			
			var _t = $(this),
				ID = $('#dopt_ID').val();
			
			// -- EXPORT DISPLAY OPTINS --
			$('#display_options_menu').wppas.tabs({container: '#display_options_container', ul:'.itm_edit_menu_toggle', nfer: '.itm_nfer'});
			$('.export_display_options').on('click', function(){
				var type = $(this).data('type');
				
				$('.export_display_options').removeClass('selected');
				$(this).addClass('selected');
				$('.display_option_form').removeClass('selected');
				$('.display_options').find('.'+type).addClass('selected');
				
				// Reset trigger options
				$('.dopt_trigger_option').val('');
				$('.trigger_itm_btn').removeClass('selected');
				$('.trigger_option_form').hide();
				
				if(type != 'inline'){
					$('.export_sc_cont').find('input').val('[wpproads id="'+ID+'" display="'+type+'"]'); 	
				}else{
					$('.export_sc_cont').find('input').val('[wpproads id="'+ID+'"]'); 	
				}
			});
			
			// -- TRIGGER OPTION BUTTON --
			$('.trigger_itm_btn').on('click', function(){
				var type = $(this).data('type');
				
				$('.trigger_itm_btn').removeClass('selected');
				$(this).addClass('selected');
				
				$('.display_option_form.selected').find('.trigger_option_form').hide();
				$('.display_option_form.selected').find('#'+type).show();
				$('.display_option_form.selected').find('#dopt_trigger_option').val(type);
			});
			
			
			// -- UPDATE SHORTCODE --
			$('.wppas_update_sc').on('click', function(){
				
				var ID = $('#dopt_ID').val(),
					type = $('#dopt_type').val(),
					display = $('.display_option_form.selected').find('#dopt_display').val(),
					args = '',
					effect = $('.display_option_form.selected').find('#dopt_load_effect').val(),
					custom_class = $('.display_option_form.selected').find('#dopt_custom_class').val(),
					trigger_option = $('.display_option_form.selected').find('#dopt_trigger_option').val(),
					margin = _t.wppas.offset_css({
						'top': 	$('.display_option_form.selected').find('#dopt_margin_top').val(),
						'right': $('.display_option_form.selected').find('#dopt_margin_right').val(),
						'bottom': 	$('.display_option_form.selected').find('#dopt_margin_bottom').val(),
						'left': 	$('.display_option_form.selected').find('#dopt_margin_left').val()
					}),
					inft_padding = _t.wppas.offset_css({
						'top': 	$('.display_option_form.selected').find('#dopt_inft_padding_top').val(),
						'right': $('.display_option_form.selected').find('#dopt_inft_padding_right').val(),
						'bottom': 	$('.display_option_form.selected').find('#dopt_inft_padding_bottom').val(),
						'left': 	$('.display_option_form.selected').find('#dopt_inft_padding_left').val()
					}),
					devices = _t.wppas.hide_devices({
						'desktop': $('.display_option_form.selected').find('#dopt_show_desktop').val(),
						'tablet': $('.display_option_form.selected').find('#dopt_show_tablet').val(),
						'mobile': $('.display_option_form.selected').find('#dopt_show_mobile').val(),
						'ios': $('.display_option_form.selected').find('#dopt_show_ios').val(),
						'samsung': $('.display_option_form.selected').find('#dopt_show_samsung').val(),
						'android': $('.display_option_form.selected').find('#dopt_show_android').val(),
						'windows_mobile': $('.display_option_form.selected').find('#dopt_show_windows_mobile').val(),
						'blackberry': $('.display_option_form.selected').find('#dopt_show_blackberry').val(),
						'sony_ericsson': $('.display_option_form.selected').find('#dopt_show_sony_ericsson').val(),
						'motorola': $('.display_option_form.selected').find('#dopt_show_motorola').val(),
						'iphone': $('.display_option_form.selected').find('#dopt_show_iphone').val(),
						'ipad': $('.display_option_form.selected').find('#dopt_show_ipad').val(),
						'ipod': $('.display_option_form.selected').find('#dopt_show_ipod').val(),
					});
				
				// DEDFAULT ARGS
				args+= devices != '' ? ' hide="'+devices+'"' : '';
				args+= _t.wppas.trigger_option_args(trigger_option);
				args+= effect != '' ? ' effect="'+effect+'"' : '';
				args+= custom_class != '' ? ' class="'+custom_class+'"' : '';	
				
				if( display == 'inline' ){
					var center = $('.display_option_form.selected').find('#dopt_center').val(),
						info_text = $('.display_option_form.selected').find('#dopt_info_text').val(),
						dopt_inft_pos = $('.display_option_form.selected').find('#dopt_inft_pos').val(),
						dopt_inft_font_size = $('.display_option_form.selected').find('#dopt_inft_font_size').val(),
						dopt_inft_cont_bg = $('.display_option_form.selected').find('#dopt_inft_cont_bg').val(),
						dopt_text_wrap = $('.display_option_form.selected').find('#dopt_text_wrap').val();
					
					args+= info_text != '' ? ' info_text="'+info_text+'"' : '';	
					args+= margin != '' ? ' margin="'+margin+'"' : '';
					args+= dopt_text_wrap != '' ? ' text_wrap="'+dopt_text_wrap+'"' : '';
					args+= center != 0 ? ' center="'+center+'"' : '';
					args+= inft_padding != '' ? ' inft_padding="'+inft_padding+'"' : '';
					args+= info_text != '' && dopt_inft_pos != '' ? ' inft_pos="'+dopt_inft_pos+'"' : '';
					args+= dopt_inft_cont_bg != '' ? ' inft_cont_bg="'+dopt_inft_cont_bg+'"' : '';
					args+= dopt_inft_font_size != '' ? ' inft_font_size="'+dopt_inft_font_size+'"' : '';
					
				}else if( display == 'sticky' ){
					var position = $('.display_option_form.selected').find('#dopt_position').val(),
						close_btn = 1,
						close_btn_position = $('.display_option_form.selected').find('#dopt_close_position').val();
					
					args+= ' display="'+display+'" position="'+position+'"';
					args+= close_btn ? ' close_btn_position="'+close_btn_position+'"' : '';
					args+= margin != '' ? ' margin="'+margin+'"' : '';
					
				}else if( display == 'popup' ){
					
					var popup_bg = $('.display_option_form.selected').find('#dopt_popup_bg').val();
					
					args+= ' display="'+display+'"';
					args+= popup_bg != '' ? ' bg="'+popup_bg+'"' : '';
				}
				
				$('.export_sc_cont').find('input').val('[wpproads id="'+ID+'"'+args+']'); 
			});
		},
		
		
		
		
		offset_css: function(args){
			
			var html = '';
			
			html+= args['top'] != '' ? args['top']+'px ' : 0+' ';
			html+= args['right'] != '' ? args['right']+'px ' : 0+' ';
			html+= args['bottom'] != '' ? args['bottom']+'px ' : 0+' ';
			html+= args['left'] != '' ? args['left']+'px' : 0+'';
			html = html == '0 0 0 0' ? '' : html;
			
			return html;
		},
		
		
		
		hide_devices: function(args){
			var _t = $(this),
				html = '';
			
			html+= args['desktop'] != 1 ? _t.wppas.add_comma(html)+'desktop' : '';
			html+= args['tablet'] != 1 ? _t.wppas.add_comma(html)+'tablet' : '';
			html+= args['mobile'] != 1 ? _t.wppas.add_comma(html)+'mobile' : '';
			
			html+= args['ios'] != 1 ? _t.wppas.add_comma(html)+'ios' : '';
			html+= args['samsung'] != 1 ? _t.wppas.add_comma(html)+'samsung' : '';
			html+= args['android'] != 1 ? _t.wppas.add_comma(html)+'android' : '';
			html+= args['windows_mobile'] != 1 ? _t.wppas.add_comma(html)+'windows_mobile' : '';
			html+= args['blackberry'] != 1 ? _t.wppas.add_comma(html)+'blackberry' : '';
			html+= args['sony_ericsson'] != 1 ? _t.wppas.add_comma(html)+'sony_ericsson' : '';
			html+= args['motorola'] != 1 ? _t.wppas.add_comma(html)+'motorola' : '';
			html+= args['iphone'] != 1 ? _t.wppas.add_comma(html)+'iphone' : '';
			html+= args['ipad'] != 1 ? _t.wppas.add_comma(html)+'ipad' : '';
			html+= args['ipod'] != 1 ? _t.wppas.add_comma(html)+'ipod' : '';
			
			return html;
		},
		
		
		
		add_comma: function(html){
			return html != '' ? ',' : '';
		},
		
		
		
		
		trigger_option_args: function(trigger_option){
			
			var args = '';
			if(trigger_option != ''){
				
				args+= ' trigger="'+trigger_option+'"';
				
				if( trigger_option == 'delay'){
					var delay = $('.display_option_form.selected').find('#dopt_trigger_delay').val();
					args+= delay != '' ? ' delay="'+delay+'"' : '';
				}
				else if(trigger_option == 'inactive'){
					var inactive_sec = $('.display_option_form.selected').find('#dopt_trigger_inactive_sec').val();
					args+= ' inactive_sec="'+inactive_sec+'"';
				}
				else if(trigger_option == 'scroll_detect'){
					var scroll_pos = $('.display_option_form.selected').find('#dopt_trigger_scroll_position').val();
					args+= ' scroll_pos="'+scroll_pos+'"';
				}
							
			}
			
			return args;
		},
		
		
		/**
		 * CREATE TIMELINE ITEM if not exists.
		 *
		 *
		 */
		create_timeline_itm: function(args){
			
			// first make sure the arrays we need exist.
			if( typeof timeline_arr[cur_view_size] == 'undefined' ){
				var _t = $(this),
					closest_size = _t.wppas.closest(cur_view_size, sizes_arr);
				
				console.log('create timeline arr for this item');
				
				timeline_arr[cur_view_size] = $.extend(true, {}, timeline_arr[closest_size]);
				//timeline_arr[cur_view_size] = {};
			}
			if(typeof timeline_arr[cur_view_size][args.ID] == 'undefined') {
				timeline_arr[cur_view_size][args.ID] = {
					ID: args.ID,
					css: {},
					data: {},
					animation: {},
					font: {},
					zindex: 0	
				};
			}
		},
		
		
		
		/**
		 * ADD SHAPE
		 *
		 *
		 */
		add_shape: function(args){
			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID}),
				shape_type = args.type, //$(this).data('type'),
				zindex = _t.wppas.get_latest_zindex(),
				layer_css = typeof args.layer_css != 'undefined' ? args.layer_css : {
					'pos_h': 'left',
					'pos_v':'top',
					'width': '100px',
					'height': '100px',
					'z-index': zindex
				},
				itm_css = typeof args.itm_css != 'undefined' ? args.itm_css : {
					'background-color': 'rgb(0, 0, 0)'
				},
				itm_data = typeof args.itm_data != 'undefined' ? args.itm_data : {
					'object': 'shape',
					'type': 'shape',
					'itm': 'shape',
					//'type': shape_type, //'shape',
					//'itm': shape_type,
					'icon': '',
					'src': '',
					'code': encodeURIComponent(args.code.replace(/'/g, "%27")),
					//'code': '<div class="shape '+shape_type+'" style="background-color:'+itm_css['background-color']+';"></div>',
					'layer_css': layer_css,
					'itm_css': itm_css
				},
				itm_id = _t.wppas.add_timeline_btn(itm_data, {'data':itm_data, 'itm_css':itm_css, 'layer_css':layer_css}),
				html = '';
			
			html+= '<div class="layer '+layer_css['pos_h']+' '+layer_css['pos_v']+' shape enc itm '+itm_id+'" data-itm="'+itm_id+'" data-type="shape" style="z-index:'+zindex+'; width:'+layer_css['width']+'; height:'+layer_css['height']+';">\n';
				html+= _4chars+encodeURIComponent(args.code.replace(/'/g, "%27"))+'\n';
				//html+= _4chars+'<div class="shape '+shape_type+'" style="background-color:'+itm_css['background-color']+';"></div>\n';
			html+= '</div>\n';
			
			// add code to editor
			_v.editor.getSession().insert({
			   row: _v.editor.getSession().getLength(),
			   column: 0
			}, '\n'+ html +'\n');
			
			var textarea = jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]");
			textarea.val(_v.editor.getSession().getValue());
			
			_t.wppas.add_adjustment_functions(args.options);
			
			return {ID:itm_id};
		},
		
		
		/**
		 * ADD TEXT
		 *
		 *
		 */
		add_text: function(args){
			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID}),
				zindex = _t.wppas.get_latest_zindex(),
				layer_css = typeof args.layer_css != 'undefined' ? args.layer_css : {
					'pos_h': 'left',
					'pos_v':'top',
					'z-index': zindex,
					'color': '#000000'
				},
				itm_css = typeof args.itm_css != 'undefined' ? args.itm_css : {},
				itm_data = typeof args.itm_data != 'undefined' ? args.itm_data : {
					'object': 'text',
					'type': 'text',
					'itm': 'text',
					'icon': '',
					'code': encodeURIComponent('YOUR TEXT'.replace(/'/g, "%27")),
					'src': '',
					'layer_css': layer_css,
					'itm_css': itm_css
				},
				itm_id = _t.wppas.add_timeline_btn(itm_data, {'data':itm_data, 'itm_css':itm_css, 'layer_css':layer_css}),
				html = '';
			
			
			html+= '<div class="layer left top text itm '+itm_id+'" data-itm="'+itm_id+'" data-type="text" style="z-index:'+zindex+';">\n';
				html+= _4chars+'<span class="itm_html Text_element enc">'+encodeURIComponent('YOUR TEXT'.replace(/'/g, "%27"))+'</span>\n';
			html+= '</div>\n';
			
			_t.wppas.text_editable({'itm_id':itm_id, 'edit': 1});
			
			// add code to editor
			_v.editor.getSession().insert({
			   row: _v.editor.getSession().getLength(),
			   column: 0
			}, '\n'+ html +'\n');
			
			var textarea = jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]");
			textarea.val(_v.editor.getSession().getValue());
			
			_t.wppas.add_adjustment_functions(args.options);
		},
		
		
		
		/**
		 * ADD ICON
		 *
		 *
		 */
		add_icon: function(args){
			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID}),
				zindex = _t.wppas.get_latest_zindex(),
				layer_css = {
					'pos_h': 'left',
					'pos_v':'top',
					'font-family': 'FontAwesome',
					'font-size': '100px;',
					'color': '#000000',
					'z-index': zindex
				},
				itm_css = {
					'font-family': 'FontAwesome',
					'font-size': '100px;',
					'color': '#000000',	
				},
				itm_data = {
					'object': 'icon',
					'type': 'icon',
					'itm': 'icon',
					'icon': args.icon,
					'code': '<i class="fa '+args.icon+' lhfx" aria-hidden="true"></i>',
					'src': '',
					'layer_css': layer_css,
					'itm_css': itm_css
				},
				itm_id = _t.wppas.add_timeline_btn(itm_data),
				html = '';
				
			//html+= '<div class="layer left top icon itm '+itm_id+'" data-itm="'+itm_id+'" data-type="icon" style="z-index:'+zindex+'; font-family: \'FontAwesome\'; font-size:100px;">\n';
			html+= '<div class="layer left top icon itm '+itm_id+'" data-itm="'+itm_id+'" data-type="icon" style="z-index:'+zindex+'; font-family: \''+layer_css['font-family']+'\'; font-size:'+layer_css['font-size']+';">\n';
				html+= _4chars+'<i class="fa '+args.icon+' lhfx" aria-hidden="true"></i>\n';
			html+= '</div>\n';
			
			
			// add code to editor
			_v.editor.getSession().insert({
			   row: _v.editor.getSession().getLength(),
			   column: 0
			}, '\n'+ html +'\n');
			
			var textarea = jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]");
			textarea.val(_v.editor.getSession().getValue());
			
			_t.wppas.add_adjustment_functions(args.options);
		},
		
		
		
		
		/**
		 * ADD SVG
		 *
		 *
		 */
		add_svg: function(args){
			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID}),
				zindex = _t.wppas.get_latest_zindex(),
				layer_css = {
					'pos_h': 'left',
					'pos_v':'top',
					'width': '100px',
					'height': '100px',
					'z-index': zindex
				},
				itm_css = {},
				itm_data = {
					'object': 'svg',
					'type': 'svg',
					'itm': 'svg',
					'code': encodeURIComponent(args.code.replace(/'/g, "%27")),
					'layer_css': layer_css,
					'itm_css': itm_css
				},
				itm_id = _t.wppas.add_timeline_btn(itm_data),
				html = '';
			
			html+= '<div class="layer left top svg enc itm '+itm_id+'" data-itm="'+itm_id+'" data-type="svg" style="z-index:'+zindex+'; width:'+layer_css['width']+'; height:'+layer_css['height']+';">\n';
				html+= _4chars+encodeURIComponent(args.code.replace(/'/g, "%27"))+'\n';
			html+= '</div>\n';
			
			// add code to editor
			_v.editor.getSession().insert({
			   row: _v.editor.getSession().getLength(),
			   column: 0
			}, '\n'+ html +'\n');
			
			var textarea = jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]");
			textarea.val(_v.editor.getSession().getValue());
			
			_t.wppas.add_adjustment_functions(args.options);
		},
		
		
		
		
		
		
		
		
		/**
		 * ADD HTML
		 *
		 *
		 */
		add_html: function(args){
			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID}),
				zindex = _t.wppas.get_latest_zindex(),
				style = '',
				layer_css = {
					'pos_h': 'left',
					'pos_v':'top',
					'z-index': zindex
				},
				itm_css = {},
				itm_data = {
					'object': 'html',
					'type': 'html',
					'itm': args.itm,
					'values': args.values,
					'icon': '',
					'code': encodeURIComponent(args.code.replace(/'/g, "%27")),
					'layer_css': layer_css,
					'itm_css': itm_css
				},
				itm_id = _t.wppas.add_timeline_btn(itm_data),
				html = '';
				
				// Create style state for buttons
				style = _t.wppas.wppas_add_html_styles({ID: itm_id});
				
			html+= '<div class="layer left top html enc itm '+itm_id+'" data-itm="'+itm_id+'" data-type="html" data-item="'+itm_data['itm']+'" style="z-index:'+zindex+';">\n';
				html+= _4chars+encodeURIComponent(args.code+style)+'\n';
			html+= '</div>\n';
			
			
			// add code to editor
			_v.editor.getSession().insert({
			   row: _v.editor.getSession().getLength(),
			   column: 0
			}, '\n'+ html +'\n');
			
			var textarea = jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]");
			textarea.val(_v.editor.getSession().getValue());
			
			_t.wppas.add_adjustment_functions(args.options);
		},
		
		
		
		
		
		
		/**
		 * ADD ZIP
		 *
		 *
		 */
		add_zip: function(args){
			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID}),
				zindex = _t.wppas.get_latest_zindex(),
				itm_data = {
					'type': 'zip',
					'icon': '',
					'url': args.url
				},
				itm_id = _t.wppas.add_timeline_btn(itm_data),
				html = '';
				
			html+= '<div class="layer left top zip itm '+itm_id+'" data-itm="'+itm_id+'" data-type="zip" style="z-index:'+zindex+';">\n';
				html+= _4chars+'<iframe src="'+args.url+'"></iframe>\n';
			html+= '</div>\n';
			
			
			// add code to editor
			_v.editor.getSession().insert({
			   row: _v.editor.getSession().getLength(),
			   column: 0
			}, '\n'+ html +'\n');
			
			var textarea = jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]");
			textarea.val(_v.editor.getSession().getValue());
			
			_t.wppas.add_adjustment_functions(args.options);
		},
		
		
		
		
		
		/**
		 * ADD IMAGE
		 *
		 *
		 */
		add_image: function(args){
			//wp.media.editor.send.attachment = function(props, attachment){
				// Load banner container items.
				var _t = $(this),
					_v = _t.wppas.editor_vars({'alphaID':alphaID}),
					zindex = _t.wppas.get_latest_zindex(),
					layer_css = {
						'pos_h': 'left',
						'pos_v':'top',
						'z-index': zindex
					},
					itm_css = {},
					itm_data = {
						'object': 'image',
						'type': 'image',
						'itm': 'image',
						'icon': '<span class="icon" style="background-image:url('+args.attachment.url+');"></span>',
						'src': args.attachment.url,
						'attach_id': args.attachment.id,
						'layer_css': layer_css,
						'itm_css': itm_css
					},
					itm_id = _t.wppas.add_timeline_btn(itm_data),
					html = '';
				
				html+= '<div class="layer left top image itm '+itm_id+'" data-itm="'+itm_id+'" data-type="image" style="z-index:'+zindex+';">\n';
					html+= _4chars+'<img src="'+args.attachment.url+'" />\n';
				html+= '</div>\n';
				
				_v.editor.getSession().insert({
				   row: _v.editor.getSession().getLength(),
				   column: 0
				}, '\n'+ html +'\n');
				
				var textarea = jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]");
				textarea.val(_v.editor.getSession().getValue());
				
				$('#banner-preview').find('.b_container').html( _v.editor.getSession().getValue() );
				_t.wppas.add_adjustment_functions(args.options);
			//}
			//wp.media.editor.open(this);
			
			//return false;
		},
		
		
		
		
		/**
		 * ADD IMAGE
		 *
		 *
		 */
		wp_media_uploader: function(args){
			var _t = $(this);
			
			
				
			wp.media.editor.send.attachment = function(props, attachment){
				
				_t.wppas.add_image({attachment: attachment, options: args.options});
			}
			
			if ( typeof wp !== 'undefined' && wp.media && wp.media.editor )
				wp.media.editor.open(_t);
			
			return false;
		},
		
		
		
		
		/** 
		 * MAKE TEXT EDITABLE
		 */
		text_editable: function(args){
			
			if( args.edit == 1){
				$('.'+args['itm_id']).find('.Text_element').attr("contentEditable", "true");
				$('.'+args['itm_id']).find('.Text_element').addClass('Text_isFocused');
				
				//$("body").on('DOMSubtreeModified', '.Text_element', function() {
				$("body").on('click', '.Text_element', function() {
					//console.log('text element change');
					//console.log($(this).parent().data('itm'));
					var layer = $(this).closest('.layer');
					if( layer.hasClass('itm')){
						//console.log('txt encode');
						var TE_Layer_ID = layer.data('itm'),
							TE_text = encodeURIComponent($.trim($(this).text().replace(/'/g, "%27")));
							//TE_text = $.trim($(this).text().replace(/'/g, "\\'"));
						//timeline_arr[cur_view_size][TE_Layer_ID]['data']['code'] = TE_text;
						//if( TE_text != timeline_arr[cur_view_size][TE_Layer_ID]['data']['code']){
							timeline_arr[cur_view_size][TE_Layer_ID]['data']['code'] = TE_text;
							$('#itm_'+TE_Layer_ID).find('.txt_prev').val(TE_text);
						//}
					}
				});
			}else{
				$('.Text_element').attr("contentEditable", "false");
				$('.Text_element').removeClass('Text_isFocused');
			}
		},
		
		
		
		/**
		 * CHOSEN: SELECT BANNER ADVERTISER/CAMPAIGN
		 *
		 *
		 */
		select_banner_advertiser: function(){
			
			jQuery('.chosen-select').chosen();
			if( jQuery('.select_banner_advertiser').val() == ''){
				jQuery('.select_banner_campaign').prop('disabled', true).trigger("chosen:updated");
			}
			
			$(".select_banner_advertiser").change(function() {
				
				if( $(this).val() != ''){ //$(this).val() != null
					$.ajax({
					   type: "POST",
					   url: ajaxurl,
					   data: "action=load_advertiser_campaigns_2&uid="+ $(this).val()
					}).done(function( msg ) {
							
						$('.select_banner_campaign').prop('disabled', false).trigger("chosen:updated");
								
						$('#select_cont').html( msg );
						$('.chosen-select').chosen({ width: "60%", max_selected_options:1 }); 
						
						// Campaign form settings
						if($('.select_banner_campaign').val() == '' ){
							
						}
						
						$('.select_banner_campaign').on('change', function(){
							if($(this).val() != ''){
								
							}else{
								
							}
						});
					});
				}else{
					
					$('.select_banner_campaign').prop('disabled', true).trigger("chosen:updated");
				}
			});
			
			
			jQuery('.select_banner_campaign').on('change', function(){
				if(jQuery('.select_banner_campaign').val() == '' ){
					
				}else{
					
				}
			});
		},
		
		
		
		
		
		
		/**
		 * UPDATE CODE EDITOR from preview code.
		 *
		 *
		 */
		wppas_update_code_editor_from_preview: function() {
			
			var _t = $(this),
				//_wppas = _t.wppas(),
				_v = _t.wppas.editor_vars({'alphaID':alphaID});
				
			console.log('updating code editor from preview');
			
			// destroy resizale - this fixes the issue stopping resizable from working after 1 time.
			jQuery('.itm').resizable("destroy");
			
			// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			// TESTING
			/*var banner_html = '';
			$.each($('.b_container .layer'), function() {
				
				if( $(this).hasClass('html') ){
					//console.log(timeline_arr[cur_view_size][$(this).data('itm')]['data']['code']);
					var inner_html = timeline_arr[cur_view_size][$(this).data('itm')]['data']['code'];
					//inner_html.replace(/[%]27/g, "'");
					$(this).html(inner_html);
				}
				
				banner_html += $(this)[0].outerHTML;
			});*/
			
			var wppas_b_item = _t.wppas.wppas_encode_html_items();
			//console.log(wppas_b_item);
			//var wppas_b_item = banner_html;
			// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			// END TESTING
			
			//var wppas_b_item = jQuery("#banner-preview").find('.b_container').prop('innerHTML');
			wppas_b_item = wppas_b_item.replace(' ui-draggable', '');
			wppas_b_item = wppas_b_item.replace(' ui-draggable-handle', '');
			wppas_b_item = wppas_b_item.replace(' ui-draggable-dragging', '');
			
			_v.editor.session.setValue(wppas_b_item);
		},
		
		
		
		
		
		
		/**
		 * DECODE BANNER HTML ITEMS
		 *
		 *
		 */
		wppas_decode_html_items: function() {
			
			var _t = $(this);
			
			var code = '';
			$.each($('.'+alphaID+' .b_container').find('.enc'), function() {
				var layer = $(this).closest('.layer');
				var inner_html = decodeURIComponent(timeline_arr[cur_view_size][layer.data('itm')]['data']['code']);
				//console.log(inner_html);
				$(this).html(inner_html.replace(/[%]27/g, "'"));
				
			});
			
			$.each($('.'+alphaID+' .b_container .layer'), function() {
				code += $(this)[0].outerHTML;
			});
			
			return code;
		},
		
		// @since v5.2.1
		wppas_activate_layers: function(){
			var _t = $(this),
				closest_size = _t.wppas.closest(cur_view_size, sizes_arr),
				style = '';
			//console.log('activate');	
			//$.each($('.'+alphaID+' .b_container .layer'), function() {
			$.each($('.'+alphaID+' .b_container').find('.enc'), function() {
				
				var layer = $(this).closest('.layer');
				if(typeof timeline_arr[closest_size][layer.data('itm')] != 'undefined'){
					style = _t.wppas.wppas_add_html_styles({ID: layer.data('itm')});
					var inner_html = decodeURIComponent(timeline_arr[closest_size][layer.data('itm')]['data']['code'])+style;
					$(this).html('');
					// FIX for SVG postscribe bug
					// http://jsfiddle.net/Znpxv/75/
					// https://github.com/krux/postscribe/issues/348
					if( layer.data('type') == 'svg'){
						console.log('svg');
						$(this).html(inner_html.replace(/[%]27/g, "'"));
						//inner_html = inner_html.replace("xmlns:", "");
						//inner_html = inner_html.replace(/xmlns:/g, "");
						//inner_html = inner_html.replace(/xml:/g, "");
					}else{
						postscribe($(this), inner_html.replace(/[%]27/g, "'"));
					}
				}
				if( layer.hasClass('itm') && !layer.find('.rotate_handle').length){
					$(this).append('<div class="rotate_handle"></div>');
					//console.log($(this)[0].outerHTML);
				}
			});
			
			// Timeline buttons
			$.each($('.'+alphaID+' .timeline_container .timeline_itm').find('.enc'), function() {
				if( typeof timeline_arr[closest_size][$(this).closest( "li.timeline_itm" ).data('itm')] != 'undefined'){
					if( timeline_arr[closest_size][$(this).closest( "li.timeline_itm" ).data('itm')]['v'] >= 522){
						style = _t.wppas.wppas_add_html_styles({ID: $(this).closest( "li.timeline_itm" ).data('itm')});
						var inner_html = decodeURIComponent(timeline_arr[closest_size][$(this).closest( "li.timeline_itm" ).data('itm')]['data']['code'])+style;
						$(this).html('');
						postscribe($(this), inner_html.replace(/[%]27/g, "'"));
					}
				}
			});
		},
		
		
		
		wppas_encode_html_items: function(){
			var _t = $(this),
				closest_size = _t.wppas.closest(cur_view_size, sizes_arr),
				banner_html = '',
				style = '';
				
			//$.each($('.'+alphaID+' .b_container .layer'), function() { // "#banner-preview").find(
			$.each($('.'+alphaID+' .b_container').find('.enc'), function() {
				var layer = $(this).closest('.layer');
				
				if( typeof timeline_arr[closest_size][layer.data('itm')] != 'undefined'){
					console.log('encode');
					style = _t.wppas.wppas_add_html_styles({ID: layer.data('itm')});
					//console.log(timeline_arr[closest_size][layer.data('itm')]['data']['code']);
					var inner_html = timeline_arr[closest_size][layer.data('itm')]['data']['code']+style; // cur_view_size
					//inner_html.replace(/[%]27/g, "'");
					$(this).html(inner_html);
				}
			});
			
			$.each($('.'+alphaID+' .b_container .layer'), function() {
				
				banner_html += $(this)[0].outerHTML;
			});
			
			return banner_html;
		},
		
		
		
		wppas_add_html_styles: function(args){
			//console.log(args.ID);
			//console.log(timeline_arr);
			var closest_size = $(this).wppas.closest(cur_view_size, sizes_arr),
				css = '';
			
			if(typeof timeline_arr[closest_size][args.ID] != 'undefined'){
				//console.log(timeline_arr[closest_size][args.ID]);
				var data = timeline_arr[closest_size][args.ID]['data'];
				
			
				if(data['itm'] == 'button'){
					var btn_style = data.values['class'],
						button = btn_style != '' ? prefedined.buttons[btn_style] : '',
						custom = data.values['custom'];
						
					css+= '<style>';
						css+= '.'+args.ID+' .btn{';
							if(button != '' && typeof button != 'undefined'){
								$.each(button['css']['default'], function(key, val) {
									css+= key+':'+val+';';
								});
							}
							if(custom != '' && typeof custom != 'undefined'){
								$.each(custom['css']['default'], function(key, val) {
									css+= key+':'+val+';';
								});
							}
						css+= '}';
						css+= '.'+args.ID+' .btn:hover{';
							if(button != '' && typeof button != 'undefined'){
								$.each(button['css']['hover'], function(key, val) {
									css+= key+':'+val+';';
								});
							}
							if(custom != '' && typeof custom != 'undefined'){
								$.each(custom['css']['hover'], function(key, val) {
									css+= key+':'+val+';';
								});
							}
						css+= '}';
					css+= '</style>';
				}
			}
			
			return css;
		},
		
		
		
		
		/**
		 * ADD ADJUSTMENT FUNCTIONS
		 *
		 *
		 */
		add_adjustment_functions: function(options) {
			$(this).wppas.wppas_make_draggable();
			$(this).wppas.rotating_itm();	
			//$(this).wppas.wppas_export_banner(options);
			//rotating_itm();
		},
		
		
		
		
		/**
		 * DESELECT ITEMS
		 *
		 *
		 */
		deselect_items: function() {
			console.log('deselect items');
			$('.timeline_itm').removeClass('selected');
			if( $('#bpreview .b_container').find('.itm').length > 0){
				$('#bpreview .b_container').find('.itm').draggable('destroy');
				$('#bpreview .b_container').find('.itm').resizable("destroy");
				$('#bpreview .b_container').find('.itm').removeClass('itm');
			}
			$('#bpreview .b_container').find('.Layer_isSelected').remove();
			$('.rotate_handle').remove();
			$('.itm_edit_cont').hide();
			
			$(this).wppas.text_editable({'edit': 0});
			//$('.wppas_edit_form').hide();
		},
		
		
		
		
		
		
		
		
		/**
		 * MAKE ITEMS DRAGGABLE
		 *
		 *
		 */
		wppas_make_draggable: function() { 
		
			var _t = $(this);
				//_wppas = _t.wppas();
			
			_t.wppas.wppas_make_resizable();
			
			jQuery('.itm').draggable({
				scroll: true,
				//containment: jQuery('#wppas_vsb_container'),
				start: function(event, ui){
					jQuery('.itm_edit_cont').hide();
				},
				cancel : '.Text_element',
				stop: function(event, ui) {
					//console.log(event);
					// Show dropped position.
					var stoppos = jQuery(this).position();
					
					var $elm = jQuery(this);
					var pos = _t.wppas.wppas_css_itm_position_percentage($elm);
					
					// UPDATE TIMELINE_ARR
					_t.wppas.update_item_position($elm);
					
					/*// first make sure the arrays we need exist.
					_t.wppas.create_timeline_itm({ID: $elm.data('itm')});
					timeline_arr[cur_view_size][$elm.data('itm')]['css']['top'] = pos.pix.top;
					timeline_arr[cur_view_size][$elm.data('itm')]['css']['right'] = pos.pix.right;
					timeline_arr[cur_view_size][$elm.data('itm')]['css']['left'] = pos.pix.left;
			
					$elm.css({'top': pos.pix.top, 'right': pos.pix.right, 'left': 'auto'});*/
					
					_t.wppas.wppas_update_code_editor_from_preview();
					//console.log(stoppos.left+' - '+stoppos.top);
				}	
			});
		},
		
		
		
		
		
		/**
		 * UPDATE ITEM POSITION CSS
		 *
		 *
		 */
		update_item_position: function($elm){
			
			var _t = $(this);
			
			// first make sure the arrays we need exist.
			_t.wppas.create_timeline_itm({ID: $elm.data('itm')});
			
			var pos = _t.wppas.wppas_css_itm_position_percentage($elm),
				pos_h = _t.wppas.item_alignement($elm, 'h'),
				pos_v = _t.wppas.item_alignement($elm, 'v');
			
			
			// HORIZONTAL
			if(pos_h == 'left'){
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['right'] = '';
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['left'] = pos.pix.left;
				$elm.css({'left': pos.pix.left, 'right': 'auto'});
			}else if(pos_h == 'right'){
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['right'] = pos.pix.right;
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['left'] = '';
				$elm.css({'right': pos.pix.right, 'left': 'auto'});
			}else{
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['right'] = pos.pix.right;
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['left'] = pos.pix.left;
				$elm.css({'right': pos.pix.right, 'left': pos.pix.left});
			}
			
			// VERTICAL
			if(pos_v == 'top'){
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['top'] = pos.pix.top;
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['bottom'] = '';
				$elm.css({'top': pos.pix.top, 'bottom': 'auto'});
			}else if(pos_v == 'bottom'){
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['top'] = '';
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['bottom'] = pos.pix.bottom;
				$elm.css({'bottom': pos.pix.bottom, 'top': 'auto'});
			}else{
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['top'] = pos.pix.top;
				timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['bottom'] = pos.pix.bottom;
				$elm.css({'bottom': pos.pix.bottom, 'top': pos.pix.top});
			}
			
		},
		
		
		
		/**
		 * GET ELEMENT ALIGNMENT
		 * pos = h || v
		 *
		 */
		item_alignement: function($elm, pos){
			
			var _t = $(this),
				align = {'h': 'left', 'v': 'top'},
				elm_h = timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['pos_h'],
				elm_v = timeline_arr[cur_view_size][$elm.data('itm')]['css']['layer']['pos_v'];
			
			align['h'] = typeof elm_h != 'undefined' ? elm_h : 'left';
			align['v'] = typeof elm_v != 'undefined' ? elm_v : 'top';
				
			return pos != '' ? align[pos] : align;
		},
		
		
		
		
		
		
		/**
		 * SPLIT/EXPLODE STRING
		 *
		 */
		split_string: function(string, x){
			
			var res = '';
			
			if( typeof string != 'undefined'){
				res = string.split(x);
			}
			
			return res;
		},
		
		
		
		
		
		
		
		/**
		 * MAKE ITEMS RESIZABLE
		 *
		 *
		 */
		wppas_make_resizable: function() {
			
			var _t = $(this);
				//_wppas = _t.wppas();
			
			console.log('make .itm resizable');
			
			jQuery('body').find('.itm').resizable({
			   handles: 'n, e, s, w, ne, se, sw, nw',
			   //aspectRatio: true,
			   start: function(event, ui){
				   resizing = true;
				   console.log('resizing'+$(this).data('itm'));
			   },
			   // Make text (font-size) resizable.
			   resize: function (event, ui) {
				   if( text_resize || $(this).data('type') == 'icon' ){
						var wr = $(this).outerWidth();
						var hr = $(this).outerHeight();
						var fr = $(this).css("font-size");
						fr = fr.split('px');
						var f = ((Number(hr) > Number(wr)) ? Number(wr) : Number(hr));
						$(this).css({'font-size': f+'px'});
						// Timeline edit form update
						var tid = 'itm_'+$(this).data('itm');
						$('#'+tid).find('#edit_itm_fontsize').attr('value', f+'px');
						
						$(this).find("*").each(function (i, elm) {
							if($(elm).hasClass('itm_html')){
								$(elm).css({'font-size': f+'px'});
							}
						});
				   }
			   },
			   stop: function(event, ui){
					resizing = false;
				    console.log('Finish resizing ');
					
					var itm = $(this).data('itm'),
						font_size = $('#itm_'+itm).find('#edit_itm_fontsize').val();
					
					// TIMELINE ARR ITMS
					_t.wppas.create_timeline_itm({ID: itm});
			
					timeline_arr[cur_view_size][itm]['css']['layer']['height'] = $('.'+itm).height()+'px';
					timeline_arr[cur_view_size][itm]['css']['layer']['width'] = $('.'+itm).width()+'px';
					timeline_arr[cur_view_size][itm]['css']['item']['font-size'] = font_size;
					timeline_arr[cur_view_size][itm]['css']['layer']['font-size'] = font_size;
					timeline_arr[cur_view_size][itm]['font']['font-size'] = font_size;
						
					_t.wppas.wppas_update_code_editor_from_preview();
			   }
			}); 	
			
		},
		
		
		
		
		
		/**
		 * MAKE ITEMS SORTABLE
		 *
		 *
		 */
		wppas_make_sortable: function(){
			
			var _t = $(this);
				
			jQuery('#timeline_container').sortable({
				handle: ".handle",
				axis: "y",
				containment: "#banner_timeline",
				update: function( event, ui ) {
					//alert("New position: " + ui.item.index());
					var timeline_itm = jQuery(ui.item);
					//var new_index = ui.item.index() + 5;
					_t.wppas.update_sortable_list_item_positions();
				},
				stop: function( event, ui ) {
					
				},
				placeholder: "ui-state-highlight"
			});
			jQuery( '#timeline_container' ).disableSelection();	
		},
		
		
		
		
		
		
		/**
		 * RESIZABLE WORK AREA
		 *
		 *
		 */
		wppas_resizable_work_area: function(size){
		
			jQuery( '#wppas_banner_work_area' ).resizable({
				containment: "#wppas_vsb_container",
				maxHeight: size,
      			minHeight: size,
				minWidth: 31	
			});
		},
		
		
		
		
		/**
		 * UPDATE BANNER SIZE
		 *
		 *
		 */
		update_banner_size: function( bsize ){
			
			console.log('update banner size');
			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID}),
				w = bsize[0] != 'full' ? bsize[0]+'px' : '100%',
				h = bsize[1] != 'full' ? bsize[1]+'px' : '100%';
			//var editor = ace.edit("wppas_banner_html_editor");
			_t.wppas.wppas_b_container( {'width': bsize[0],'height': bsize[1]});
			
			jQuery('#banner-preview').find('.b_container').html( _v.editor.getSession().getValue() );
			jQuery('#banner-preview').css({'max-width':w, 'max-height':h});
			//jQuery('#banner-preview').css({'width':w, 'height':h});
			_t.wppas.adjust_min_height(bsize);
			jQuery('#wppas_banner_work_area').css({'height': h, 'max-height':h});
			
			_t.wppas.wppas_make_draggable();
			_t.wppas.wppas_resizable_work_area(bsize[1]);	
		},
		
		
		
		/**
		 * Adjust editor min height - for full screen heights.
		 *
		 */
		adjust_min_height: function(bsize){
			
			if( bsize[1] == 'full'){
				jQuery('#banner-preview').css({'min-height':'400px'});
			}else{
				jQuery('#banner-preview').css({'min-height':'initial'});	
			}
		},
		
		
		
		
		/**
		 * CREATE TIMELINE BTN
		 *
		 *
		 */
		add_timeline_btn: function(itm_data, args){
			
			var _t = $(this),
				closest_size = _t.wppas.closest(cur_view_size, sizes_arr);
				
			//console.log('Add timeline btn for: '+cur_view_size+' '+closest_size);
			// create random ID
			var itm_id = 'wp'+_t.wppas.wppas_random_id('_'+itm_data.type);
			//console.log('T2');
			_t.wppas.wppas_reset_selected_items();
			
			var timeline = '',
				zindex = _t.wppas.get_latest_zindex(),
				icon = itm_data.icon;
			
			// add timeline button
			timeline += '<li class="wppas timeline_itm selected" id="itm_'+itm_id+'" data-itm="'+itm_id+'" data-object="'+itm_data.object+'" data-item="'+itm_data.itm+'">';
				timeline += '<span class="handle"><span class="zindex">'+zindex+'</span> <i class="fa fa-arrows-v" aria-hidden="true"></i></span>';
				timeline += '<span class="hide visible"><i class="fa fa-eye" aria-hidden="true"></i></span>';
				
				if( itm_data.type == 'text' ){
					timeline += '<span class="desc"><span class="preview_cont">'+itm_types[itm_data.type].icon+'</span> <span class="cont_desc"><small><input class="txt_prev" readonly value="'+itm_id+'" /></small></span></span>';
				}else if( itm_data.type == 'image' ){
					timeline += '<span class="desc" style="background-image:url('+itm_data.src+');">'+itm_types[itm_data.type].icon+'</span>';
				}/*else if( itm_data.type == 'square' || itm_data.type == 'circle' ){
					timeline += '<span class="desc"><span class="preview_cont">'+itm_types[itm_data.type].icon+'</span> <span class="cont_desc"><small>('+itm_id+')</small></span></span>';
				}*/
				else if( itm_data.type == 'shape'){
					timeline += '<span class="desc"><span class="preview_cont"><div class="enc shape_preview">'+itm_data.code+'</div></span> <span class="cont_desc"><small>('+itm_id+')</small></span></span>';
				}else if( itm_data.type == 'border' ){
					timeline += '<span class="desc"><span class="preview_cont"><div class="border_itm"></div></span> <span class="cont_desc"><small>('+itm_id+')</small></span></span>';
				}else if( itm_data.type == 'icon' ){
					timeline += '<span class="desc"><span class="preview_cont"><i class="fa '+itm_data.icon+'" aria-hidden="true"></i></span> <span class="cont_desc"><small>('+itm_id+')</small></span></span>';
				}else if( itm_data.type == 'svg' ){
					timeline += '<span class="desc"><span class="preview_cont"><div class="enc svg_preview">'+itm_data.code+'</div></span> <span class="cont_desc"><small>('+itm_id+')</small></span></span>';
				}else if( itm_data.type == 'html' ){
					if( itm_data.itm == 'button'){
						timeline += '<span class="desc"><span class="preview_cont"><i class="fa fa-check-square" aria-hidden="true"></i></span> <span class="cont_desc"><small>('+itm_id+')</small></span></span>';
					}else{
						timeline += '<span class="desc"><span class="preview_cont"><i class="fa fa-code" aria-hidden="true"></i></span> <span class="cont_desc"><small>('+itm_id+')</small></span></span>';
					}
				}
				
				timeline += '<span><a class="edit wppas_vbc_edit_itm_style"><i class="fa fa-pencil" aria-hidden="true"></i></a></span>';
				timeline += '<span><a class="edit wppas_vbc_edit_itm_duplicate"><i class="fa fa-files-o" aria-hidden="true"></i></a></span>';
				if( itm_data.type == 'image' ){
					timeline += '<span><a class="edit trash_itm wppas_img_remove" data-upload_id="'+itm_data.attach_id+'" data-itm="'+itm_id+'"><i class="fa fa-trash" aria-hidden="true"></i></a></span>';
				}else{
					timeline += '<span><a class="edit trash_itm" data-itm="'+itm_id+'"><i class="fa fa-trash" aria-hidden="true"></i></a></span>';
				}
				timeline += editor_forms.itm_editor_cont;
			timeline += '</li>';
			
			jQuery('.'+alphaID).find('#banner_timeline').find('#timeline_container').append(timeline);
			
			if( typeof timeline_arr[cur_view_size] == 'undefined'){
				// First check if another HIGHER screensize already has items. If YES copy them to the new screen size timeline.
				if(typeof timeline_arr[closest_size] != 'undefined'){
					timeline_arr[cur_view_size] = {};
					timeline_arr[cur_view_size] = jQuery.extend(timeline_arr[cur_view_size], timeline_arr[closest_size]);
					//timeline_arr[cur_view_size] = timeline_arr[closest_size];
				}else{
					timeline_arr[cur_view_size] = {};
				}
			}
			
			timeline_arr[cur_view_size][itm_id] = {
				'ID': itm_id,
				'zindex': zindex,
				'data': typeof args != 'undefined' ? args.data : itm_data,
				'css': {
					'layer': typeof args != 'undefined' ? args.layer_css : itm_data.layer_css,
					'item': typeof args != 'undefined' ? args.itm_css : itm_data.itm_css,
				},
				'font': {},
				'animation': {},
				'v': '522'
			};
			
			
			
			if( itm_data.type == 'shape' || itm_data.type == 'square' || itm_data.type == 'circle' ){
				timeline_arr[cur_view_size][itm_id]['css']['item']['background-color'] = '#000000';
				
				if( itm_data.type == 'circle' ){
					timeline_arr[cur_view_size][itm_id]['css']['item']['border-radius'] = {
						'top-left': '50%',
						'top-right': '50%',
						'bottom-right': '50%',
						'bottom-left': '50%',
					}
				}
			}
			
			
			console.log(timeline_arr);
			
			_t.wppas.wppas_make_sortable();	
			jQuery('.draggable_container').draggable({ handle: ".drag_handle" });
			jQuery('.vbc-color-field').wpColorPicker();
			
			return itm_id;
		},
		
		
		
		
		/**
		 * UPDATE TIMELINE BTN
		 *
		 *
		 */
		update_timeline_btn: function(){
			var _t = $(this),
				closest_size = _t.wppas.closest(cur_view_size, sizes_arr),
				t_arr = typeof timeline_arr[cur_view_size] != 'undefined' ? timeline_arr[cur_view_size] : timeline_arr[closest_size];
			
			console.log('UPDATE TIMELINE BTN');
			// Empty timeline container. 
			$('#banner_timeline').find('#timeline_container').html('');
			
			$.each(t_arr, function(key, group) {
				
				var type = group.ID.split('_'),
					timeline = '';
					
				// add timeline button
				timeline += '<li class="timeline_itm" id="itm_'+group.ID+'" data-itm="'+group.ID+'" data-object="'+group.data.object+'" data-item="'+group.data.itm+'">';
					timeline += '<span class="handle"><span class="zindex">'+group.zindex+'</span> <i class="fa fa-arrows-v" aria-hidden="true"></i></span>';
					timeline += '<span class="hide visible"><i class="fa fa-eye" aria-hidden="true"></i></span>';
					
					if( type[1] == 'text' ){
						timeline += '<span class="desc"><span class="preview_cont">'+itm_types[type[1]].icon+'</span> <span class="cont_desc"><small><input class="txt_prev" readonly value="'+group.ID+'" /></small></span></span>';
					}else if( type[1] == 'image' ){
						timeline += '<span class="desc" style="background-image:url('+group.data.src+');">'+itm_types[type[1]].icon+'</span>';
					}else if( type[1] == 'shape' ){
						var code = group.v >= 522 ? decodeURIComponent(group.data.code) : group.data.code;
						timeline += '<span class="desc"><span class="preview_cont"><div class="enc shape_preview">'+code+'</div></span> <span class="cont_desc"><small>('+group.ID+')</small></span></span>';
					}else if( type[1] == 'square' || type[1] == 'circle' ){
						timeline += '<span class="desc"><span class="preview_cont">'+itm_types[type[1]].icon+'</span> <span class="cont_desc"><small>('+group.ID+')</small></span></span>';
					}else if( type[1] == 'border' ){
						timeline += '<span class="desc"><span class="preview_cont"><div class="border_itm"></div></span> <span class="cont_desc"><small>('+group.ID+')</small></span></span>';
					}else if( type[1] == 'icon' ){
						timeline += '<span class="desc"><span class="preview_cont"><i class="fa '+group.data.icon+'" aria-hidden="true"></i></span> <span class="cont_desc"><small>('+group.ID+')</small></span></span>';
					}else if( type[1] == 'svg' ){
						var code = group.v >= 522 ? decodeURIComponent(group.data.code) : group.data.code;
						timeline += '<span class="desc"><span class="preview_cont"><div class="svg_preview enc">'+code+'</div></span> <span class="cont_desc"><small>('+group.ID+')</small></span></span>';
					}else if( type[1] == 'html' ){
						if( group.data.itm == 'button'){
							timeline += '<span class="desc"><span class="preview_cont"><i class="fa fa-check-square" aria-hidden="true"></i></span> <span class="cont_desc"><small>('+group.ID+')</small></span></span>';
						}else{
							timeline += '<span class="desc"><span class="preview_cont"><i class="fa fa-code" aria-hidden="true"></i></span> <span class="cont_desc"><small>('+group.ID+')</small></span></span>';
						}
					}
					/*else if( type[1] == 'html' ){
					timeline += '<span class="desc"><span class="preview_cont"><i class="fa fa-code" aria-hidden="true"></i></span> <span class="cont_desc"><small>('+group.ID+')</small></span></span>';
					}*/
					
					timeline += '<span><a class="edit wppas_vbc_edit_itm_style"><i class="fa fa-pencil" aria-hidden="true"></i></a></span>';
					timeline += '<span><a class="edit wppas_vbc_edit_itm_duplicate"><i class="fa fa-files-o" aria-hidden="true"></i></a></span>';
					timeline += '<span><a class="edit trash_itm" data-itm="'+group.ID+'"><i class="fa fa-trash" aria-hidden="true"></i></a></span>';
					timeline += editor_forms.itm_editor_cont;
				timeline += '</li>';
				
				// add timeline html to container
				$('#banner_timeline').find('#timeline_container').append(timeline);
				$('.vbc-color-field').wpColorPicker();
				
				// CSS
				if( type[1] == 'square' || type[1] == 'circle' ){
					$('#itm_'+group.ID).find('.desc').find('.fa').css({'color': group.css['item-color']});
					// colorpicker fix
					$('#itm_'+group.ID).find('#itm-edit-css').find('.wp-color-bg').find('.wp-color-result').css({'background-color': group.css['background-color']});
					$('#itm_'+group.ID).find('#itm-edit-css').find('.wp-color-itm').find('.wp-color-result').css({'item-color': group.css['item-color']});
				}
				if( type[1] == 'border' ){
					$('#itm_'+group.ID).find('.desc').find('.border_itm').css({'border-color': group.css['item-color']});
				}
				// font
				if( type[1] == 'text' ){
					$('#itm_'+group.ID).find('.txt_prev').val(group.font.html);
					$('#itm_'+group.ID).find('.txt_prev').css({'color': group.css['item-color'], 'background-color': group.css['background-color']});
				}
				
				// Defaults
				if( type[1] != 'border' ){
					$('#itm_'+group.ID).find('.preview_cont').css({'background-color': group.css['background-color'], 'color': group.css['item-color']});
				}else{
					$('#itm_'+group.ID).find('.preview_cont').css({'border-color': group.css['item-color']});
				}
				
			});
			
		},
		
		
		
		
		
		/**
		 * UPDATE SORTABLE LIST POSITIONS.
		 *
		 *
		 */
		update_sortable_list_item_positions: function(){
			
			var _t = $(this);
				//_wppas = _t.wppas();
				
			var positions = jQuery('#timeline_container').sortable( "toArray" );
					
			// Update z-indexes.
			var zindex = 4;
			jQuery.each(positions, function( index, value ) {
				zindex++;
				console.log(value);
				jQuery('#'+value).find('.zindex').text(zindex);
				jQuery('.b_container').find('.'+jQuery('#'+value).data('itm')).css({'z-index': zindex});
				
				// Update timeline array
				timeline_arr[cur_view_size][jQuery('#'+value).data('itm')]['zindex'] = zindex;
				//console.log( jQuery('#'+value).data('itm') );
			});
			
			_t.wppas.wppas_update_code_editor_from_preview();
			
			return zindex;
		},
		
		
		
		
		
		/**
		 * UPDATE VIEW BUTTONS
		 *
		 *
		 */
		update_view_btns: function(){
			
			jQuery.each(sizes_arr, function( index, value ) {
				if( jQuery("textarea[name=wppas_banner_html_"+value+"]").val() != '' ){
					jQuery('.view_btn.'+value).addClass('has_content');
				}else{
					jQuery('.view_btn.'+value).removeClass('has_content');
				}
			});
			
		},
		
		
		
		
		
		/**
		 * FIRE WHEN SCREEN/VIEW SIZE ADJUSTS
		 *
		 *
		 */
		view_size_adjustments: function(args){
			
			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID}),
				bsize = $('#wppas_banner_size').val().split('x');
			
			var defaults = {
				'scale': 1
			};
			args = jQuery.extend( defaults, args );
			
			_t.wppas.adjust_min_height(bsize);
				
			console.log('view adjustment');
			cur_view_size = jQuery('.view_btn.selected').data('min');
			
			if(args.scale){
				_t.wppas.scale_banner();
			}
			
			//console.log(cur_view_size);
			var textarea = jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]"),
				code = _v.editor.session.getValue();
			
			if( textarea.val() != '' ){
				// if textarea exists for this size, use it.
				console.log('not empty');
				_v.editor.session.setValue(textarea.val());
			}else{
				// if not, find closest "higher" textarea
				
				var closest_size = _t.wppas.closest(cur_view_size, sizes_arr),
					textarea = jQuery("textarea[name=wppas_banner_html_"+closest_size+"]");
				
				if( code != textarea.val() ){ 
					console.log('adjust code in editor: copy code from textarea wppas_banner_html_'+closest_size);
					_v.editor.session.setValue(textarea.val());
				
					// empty this textarea cause we do not need any content in it. it was already empty before.
					jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]").val("");
				}
				_t.wppas.update_view_btns();
			}
		},
		
		
		
		
		
		
		
		
		
		
		
		/**
		 * CHANGE WORK AREA DEVICE VIEW
		 *
		 *
		 */
		wppas_check_work_area_size: function(options){ // size
			
			var _t = $(this);
				//_wppas = _t.wppas();
			//var perc = ( size*100) / jQuery('#wppas_vsb_container').width();
			/*var grid = [];
			jQuery.each(screen_sizes, function( index, value ) {
				grid.push(value.size);
			});*/
			var closest_size = _t.wppas.closest_nr(options.size, options.sizes_arr); // grid
			var sizes = options.screen_sizes[closest_size];
			
			jQuery('#wppas_banner_work_area').find('.work_area_info .current_view_size').html(options.size+'px');
			
			// ADJUST HEIGHT TO FIT RATIO
			_t.wppas.aspect_ratio_sizing({editor:1, keep_aspect_ratio:keep_aspect_ratio});
		
			console.log('wppas_check_work_area_size');
			if( sizes != null){
				jQuery('#wppas_banner_work_area').find('.work_area_info .device_view').html(sizes.view+': '+sizes.size+'px <');
				jQuery('.view_btn').removeClass('selected');
				jQuery('#sizes_container').find('.'+sizes.size).addClass('selected');
				_t.wppas.view_size_adjustments();
			}
		},
		
		
		
		
		
		
		
		/**
		 * RESET SELECTED ITEMS IN TIMELINE
		 *
		 *
		 */
		wppas_reset_selected_items: function(){
			
			var _t = $(this),
				_v = _t.wppas.editor_vars({'alphaID':alphaID});
			console.log('reset selected items');
			jQuery('.'+alphaID).find('.b_container').find('.itm').draggable('destroy');
			jQuery('.'+alphaID).find('.b_container').find('.itm').resizable("destroy");
			jQuery('.'+alphaID).find('.b_container').find('.itm').removeClass('itm');
			jQuery('.'+alphaID).find('#timeline_container').find('.timeline_itm').removeClass('selected');	
			
			/*var html = '';
			html = jQuery("#banner-preview").find('.b_container').prop('innerHTML');*/
			
			var html = _t.wppas.wppas_encode_html_items();
			// Update editor.
			var textarea = jQuery("textarea[name=wppas_banner_html_"+cur_view_size+"]");
			_v.editor.session.setValue(html);
			textarea.val(_v.editor.getSession().getValue());
		},
		
		
		
		
		
		
		
		/**
		 * EXPORT BANNER CODE
		 *
		 *
		 */
		wppas_export_banner: function(options){
			
			var _t = $(this),
				html = '',
				sc = '',
				tpt = '',
				ifm = '',
				rss = '',
				files = '',
				ID = bannerID != 0 ? bannerID : Math.floor(Date.now() / 1000),
				bsize = $('#wppas_banner_size').val().split('x'),
				banners_html = [],
				link = $('#wppas_banner_link').val() != '' ? 'href="'+$('#wppas_banner_link').val()+'" target="'+$('#wppas_banner_target').val()+'"' : '';
			
			var bdata = $(this).wppas.get_banner_data(options);
			//console.log(JSON.parse(bdata.banner_data));
			
			// EXPORT
			$('#wppas_export_code').val( JSON.stringify(bdata) );
			_t.wppas.focus_textarea($('#wppas_export_code'));
			// end EXPORT
			
			
			if( bannerID != 0 ){
				
				link = $('#wppas_banner_link').val() != '' ? ' href="'+URL.url+'?pasID='+ID+'" target="'+$('#wppas_banner_target').val()+'"' : '';
				// SHORTCODE
				sc+= "<input type='text' id='wppas_sc_code' value='[wpproads id=\""+ID+"\"]' />";
				sc+= '<span class="description bottom">A Wordpress shortcode to show the banner on this website.</span>';
				$('.export_sc_cont').html(sc);
				_t.wppas.focus_textarea($('#wppas_sc_code'));
				// end SHORTCODE
				
				/*// TEMPLATE TAG
				tpt+= '<input type="text" value="echo do_shortcode(\'[wpproads_banner id=\"'+ID+'\"]\');" />';
				tpt+= '<span class="description bottom">Template tag to show the banner anywhere on this website.</span>';
				$('.export_tpt_cont').html(tpt);*/
				
				// RSS
				rss+= URL.url+'?wppas-rss='+ID;
				$('#wppas_rss_feed').val(rss);
				_t.wppas.focus_textarea($('#wppas_rss_feed'));
				
				// IFRAME
				var banner_data = JSON.parse(bdata.banner_data);
				ifm+='<textarea id="wppas_iframe_code" style="width:100%; height:100px; font-size: 11px; font-weight: normal; margin-bottom: 10px;" readonly="readonly">';
					ifm+= '<div style="max-width:'+banner_data.w+'px; width:100%; height:'+banner_data.h+'px;">';
						ifm+= '<iframe src="'+URL.url+'?wppasbid='+bannerID+'" border="0" scrolling="no" allowtransparency="true" width="100%" height="100%" style="border:0;"></iframe>';
					ifm+= '</div>';
				ifm+='</textarea>';
				ifm+= '<span class="description bottom">Iframe code. This code can be used to place the banner anywhere you want even on other websites.</span>';
				$('.export_iframe_cont').html(ifm);
				// end IFRAME
			}
			_t.wppas.focus_textarea($('#wppas_iframe_code'));
			
			// HTML
			html+= '<a class="b_container b_cont_'+ID+'"'+link+' style="max-width:'+bsize[0]+'px; max-height:'+bsize[1]+'px;" data-bid="'+ID+'"></a>';
			html+= '<script type="text/javascript">';
				html+= 'var bhtml_'+ID+' = { ';
					$.each(options.screen_sizes, function( index, value ) {
						var b_html = $("#wppas_banner_html_"+value.size).val();
						if(b_html != ""){
							b_html = b_html.replace(/(\r\n|\n|\r)/gm,""); // remove line breaks.
							b_html = b_html.replace(/'/g, '"'); // Replace &quot with ' to solve issue with ajax not saving the HTML anymore.
							html+= index+':\''+b_html+'\','; //encodeURIComponent()
						}
					});
				html+= '};';
				
				html+= 'function wppasReloadBnr_'+ID+'(){ ';
					html+= 'jQuery(".b_cont_'+ID+'").wppas_show({';
						html+= 'bid:'+ID+',';
						html+= 'bw: jQuery(".b_cont_'+ID+'").width(),';
						html+= 'html: bhtml_'+ID+',';
						html+= 'ID: '+ID+',';
						html+= 'size: "'+$("#wppas_banner_size").val()+'",';
						html+= 'w: '+bsize[0]+',';
						html+= 'h: '+bsize[1]+',';
						//html+= 'link: "'+$('#wppas_banner_link').val()+'",';
						//html+= 'target: "'+$('#wppas_banner_target').val()+'",'
						html+= 'keep_aspect_ratio: '+keep_aspect_ratio+',';
						html+= 'timeline_arr: { ';
							html+= $(this).wppas.check_array_and_output(timeline_arr);
						html+= '}';
					html+= '});';
				html+= '}';
				
				html+= 'jQuery(document).ready(function($){';
					html+= 'wppasReloadBnr_'+ID+'();';
				html+= '});';
				
			html+= '</script>';
			
			files+= '<!-- THIS PART CAN BE REMOVED IF USED ON THIS WEBSITE -->\n';
			files+= '<script type="text/javascript" src="'+URL.url+'/wp-includes/js/jquery/jquery.js"></script>';
			files+= '<script type="text/javascript" src="'+WP_ADS_URL.url+'public/assets/js/vbc/jquery-ui-effects.min.js"></script>';
			files+= '<script type="text/javascript" src="'+WP_ADS_URL.url+'public/assets/js/vbc/postscribe.min.js"></script>';
			files+= '<script type="text/javascript" src="'+WP_ADS_URL.url+'public/assets/js/vbc/jquery.wppas.vbc.min.js"></script>';
			files+= '<link rel="stylesheet" href="'+WP_ADS_URL.url+'public/assets/css/vbc/wppas_vbc_bnr.css" type="text/css" media="all" />';
			files+= '<link rel="stylesheet" href="'+WP_ADS_URL.url+'includes/font-awesome/css/font-awesome.min.css" type="text/css" media="all" />';
			files+= '\n<!-- DONT REMOVE ANYTHING AFTER THIS LINE -->\n\n';
			
			$('#wppas_html_code').val(files+html);
			_t.wppas.focus_textarea($('#wppas_html_code'));
			// end HTML
		},
		
		
		
		/**
		 * FOCUS TEXT AREA
		 */
		focus_textarea: function(obj){
			
			obj.focus(function(e) {
				e.target.select();
				$(e.target).one('mouseup', function(e) {
					e.preventDefault();
				});
			});
		},
		
		
		
		check_array_and_output: function(arr){
			
			var _t = $(this),
				html = '';
			
			if(typeof arr === 'object'){
				$.each(arr, function( index, value ) {		
					if(typeof value === 'object'){
						html+= "'"+index+"':{";
						
							html+= _t.wppas.check_array_and_output(value);
						html+= '},';
					}else{
						if(index == 'html'){
							
							var _val = value.replace(/\\/g, ''),
								_val = _val.replace(/'/g, "\\'");
							html+= '\''+index+'\':\''+_val+'\','; // Replace ' with \' 
						}else{
							html+= '\''+index+'\':\''+value+'\',';
						}
					}
				});
			}
			
			return html;
		},
		
		
		
		
		
		get_banner_data: function(args){
			
			var _t = $(this),
				bsize = $('#wppas_banner_size').val().split('x');
				
			_t.wppas.deselect_items();
			
			var banners_html = [];
			var banner_data = {
				ID: bannerID,
				size: $('#wppas_banner_size').val(),
				w: bsize[0],
				h: bsize[1],
				name: $('#wppas_banner_name').val(),
				link: $('#wppas_banner_link').val(),
				target: $('#wppas_banner_target').val(),
				advertiser: $('#wppas_banner_advertiser').val(),
				campaign: $('#wppas_banner_campaign').val(),
				keep_aspect_ratio: keep_aspect_ratio,
				no_follow: $('#bnofollow').val(),
				center: $('#bcenter').val(),
				timeline_arr: timeline_arr
			};
			
			//console.log(banner_data.w);
			/*var banner_data = {
				ID: $('#banner_ID').val(),
				size: $('#wppas_banner_size').val(),
				w: bsize[0],
				h: bsize[1],
				name: $('#wppas_banner_name').val(),
				link: $('#wppas_banner_link').val(),
				target: $('#wppas_banner_target').val(),
				advertiser: $('#wppas_banner_advertiser').val(),
				campaign: $('#wppas_banner_campaign').val(),
				keep_aspect_ratio: keep_aspect_ratio,
				timeline_arr: timeline_arr
			};*/
			
			$.each(args.screen_sizes, function( index, value ) {
				
				var b_html = $("#wppas_banner_html_"+value.size).val();
				
				if(b_html != ""){
					banners_html.push({
						"screen_size": value.size,
						"html": b_html.replace(/&quot;/g, "'") // Replace &quot with ' to solve issue with ajax not saving the HTML anymore.
					});
				}
			});
			
			var json_banner = {
				banner_html: JSON.stringify( banners_html ),
				banner_data: JSON.stringify( banner_data )
			}
			
			return json_banner;
		},
		
		
		
		
		
		/**
		 * GET CSS POSITIONS IN PERCENTAGE for any item.
		 *
		 *
		 */
		wppas_css_itm_position_percentage: function($elm){
			
			var pos = $elm.position(),
				parentSizes = {
					height: $elm.parent().height(),
					width: $elm.parent().width()
				};
			
			
			// GET elm RIGHT POSITION
			var posr = pos.left + $elm.outerWidth();
			var r = posr - parentSizes.width;
			r = r - (r*2);
			
			var top_pos = (pos.top/parentSizes.height) * 100,
				bottom_pos = (pos.bottom/parentSizes.height) * 100,
				left_pos = (pos.left/parentSizes.width) * 100,
				right_pos = (r/parentSizes.width)*100;
			
			var positions = {
				'perc': {
					'top': Math.round(top_pos),
					'bottom': Math.round(bottom_pos),
					'left': Math.round(left_pos),
					'right': Math.round(right_pos)
				},
				'pix': {
					'top': $elm.css('top'),
					'bottom': $elm.css('bottom'),
					'left': $elm.css('left'),
					'right': $elm.css('right')
				}
			}
			
			return positions;
		},
		
		
		
		
		
		
		/**
		 * ROTATING ITEM
		 *
		 *
		 */
		rotating_itm: function() { 
			//console.log('rotating');
			
			var _t = $(this),
				//_wppas = _t.wppas(),
				selected_itm = jQuery('.timeline_itm.selected').data('itm'),
				dragging = false,
				target_wp,
				o_x, o_y, h_x, h_y, last_angle;
				
			jQuery('.rotate_handle').remove();
			jQuery('.'+selected_itm).append('<div class="rotate_handle"></div>'); //<i class="fa fa-repeat" aria-hidden="true"></i>
			
			jQuery('body').unbind('mousedown').on('mousedown', '.rotate_handle', function(e) {
				if (dragging !== true) {
					console.log('start rotating');
					h_x = e.pageX;
					h_y = e.pageY; // clicked point
					e.preventDefault();
					e.stopPropagation();
					dragging = true;
					target_wp = jQuery(e.target).closest('.layer');
					//target_wp = jQuery(this).parent().find('.layer');
					//console.log(target_wp);
					if (!target_wp.data("origin")) target_wp.data("origin", {
						left: target_wp.offset().left,
						top: target_wp.offset().top
					});
					// Stop default item dragging. now it only needs to rotate.
					if(dragging && jQuery('.b_container').find('.itm').data('ui-draggable')){
						jQuery('.b_container').find('.itm').draggable('destroy');	
					}
					o_x = target_wp.data("origin").left;
					o_y = target_wp.data("origin").top; // origin point
					
					//last_angle = target_wp.data("last_angle") || 0;
					var mts = (360 / (2 * Math.PI));
					last_angle = (_t.wppas.getRotationDegrees(target_wp) / mts);
				}
			});
		
			jQuery(document).mousemove(function (e) {
				//console.log('oi');
				if (dragging) {
					//console.log(_t.wppas.getRotationDegrees(target_wp));
					//console.log(o_x+' '+e.pageX+' - '+o_y+' '+e.pageY);
					
					var s_x = e.pageX,
						s_y = e.pageY; // start rotate point
					if (s_x !== o_x && s_y !== o_y) { //start rotate
						var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin
						s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin
						s_rad += last_angle; // relative to the last one
						
						var degree = (s_rad * (360 / (2 * Math.PI)));
						
						target_wp.css('-moz-transform', 'rotate(' + degree + 'deg)');
						target_wp.css('-moz-transform-origin', '50% 50%');
						target_wp.css('-webkit-transform', 'rotate(' + degree + 'deg)');
						target_wp.css('-webkit-transform-origin', '50% 50%');
						target_wp.css('-o-transform', 'rotate(' + degree + 'deg)');
						target_wp.css('-o-transform-origin', '50% 50%');
						target_wp.css('-ms-transform', 'rotate(' + degree + 'deg)');
						target_wp.css('-ms-transform-origin', '50% 50%');
					}
				}
			}); // end mousemove
			
			jQuery(document).mouseup(function (e) {
				
				if(dragging){
					console.log('end rotating');
					var s_x = e.pageX,
						s_y = e.pageY;
						
					// Saves the last angle for future iterations
					var s_rad = Math.atan2(s_y - o_y, s_x - o_x); // current to origin
					s_rad -= Math.atan2(h_y - o_y, h_x - o_x); // handle to origin
					s_rad += last_angle;
					//target_wp.data("last_angle", s_rad);
					
					var degree = (s_rad * (360 / (2 * Math.PI)));
					
					timeline_arr[cur_view_size][selected_itm]['css']['layer']['transform'] = 'rotate('+degree+'deg)';
					timeline_arr[cur_view_size][selected_itm]['css']['layer']['transform-origin'] = '50% 50%';
					
					dragging = false;
					
					_t.wppas.wppas_update_code_editor_from_preview();
				}
				
			});
		},
		
		
		getRotationDegrees: function(obj) {
			var matrix = obj.css("-webkit-transform") ||
			obj.css("-moz-transform")    ||
			obj.css("-ms-transform")     ||
			obj.css("-o-transform")      ||
			obj.css("transform");
			if(matrix !== 'none') {
				var values = matrix.split('(')[1].split(')')[0].split(',');
				var a = values[0];
				var b = values[1];
				var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
			} else { var angle = 0; }
			return angle;
		},
		
		
		/**
		 * RETURN TIMELINE_ARR
		 *
		 *
		 */
		load_timeline_arr: function() { 
			return timeline_arr;
		},
		
		
		/**
		 * UPDATE GOT_SAVED
		 *
		 *
		 */
		update_got_saved: function(val) { 
			got_saved = val;
			return got_saved;
		},
		
		
		
		
		
		
		
		
		/**
		 * SHAPE CREATOR
		 *
		 *
		 */
		shape_creator: function(args) {
			var _t = $(this),
				colors = {},
				itm_color = '';
			
			args.container.find('.b_add_shape').off('click').on('click', args.container.find('.b_add_shape'), function(e){
				colors = {};
				itm_color = '';
				
				args.container.find('.shape_creator_preview').html( $(this).html() );
				var node = $(this).children().get(0).nodeName.toLowerCase();
				args.container.find('.edit_options').hide();
				args.container.find('.'+node+'_edit').show();
				
				//var style = args.container.find('.shape_creator_preview').find('.c1').attr('style');
				//console.log(style);
				
				$("body, html, #itm_edit_content_container").animate({ scrollTop: 0 }, "fast");
			});
			
			if( typeof args.ID != 'undefined' ){
				$('.rotate_handle').remove();
				$('.ui-resizable-handle').remove();
				
				args.container.find('.shape_creator_preview').html($('.'+args.ID).html());
				//args.container.find('.shape_creator_preview').find('.shape').css({'width':'100px', 'height':'100px'});
				args.container.find('.shape_creator_preview').find('.Layer_isSelected').remove();
				
				var node = args.container.find('.shape_creator_preview').children().get(0).nodeName.toLowerCase(),
					c1 = args.container.find('.shape_creator_preview').find('.c1'),
					bg_key = node == 'svg' ? 'background-color' : 'fill',
					border_key = node == 'svg' ? 'border-color' : 'stroke';
				//console.log(node);
				args.container.find('.edit_options').hide();
				args.container.find('.'+node+'_edit').show();
				//console.log(args.container.find('.shape_creator_preview').html());
				var bg_color = _t.wppas.search_style({'style': _t.wppas.get_item_style({'item': c1}),'key': bg_key}),
					border_color = _t.wppas.search_style({'style': _t.wppas.get_item_style({'item': c1}),'key': border_key});
				//console.log(bg_color);
				args.container.find('.'+node+'_edit').find('#'+node+'_shape_color_picker').wpColorPicker('color', bg_color);
				args.container.find('.'+node+'_edit').find('#'+node+'_shape_border_picker').wpColorPicker('color', border_color);
				
				
			}
			
			
			/**
			 * LIVE PREVIEW UPDATES
			 */
			//var ID = typeof args.ID != 'undefined' ? '#itm_'+args.ID : '.shape_creator_preview';
			var border_radius = {
				'top-left': args.container.find('#edit_itm_border_radius_top_left').val(),
				'top-right': args.container.find('#edit_itm_border_radius_top_right').val(),
				'bottom-left': args.container.find('#edit_itm_border_radius_bottom_left').val(),
				'bottom-right': args.container.find('#edit_itm_border_radius_bottom_right').val()
			};
			// text
			args.container.find('#edit_itm_border').on('change', function(){
				args.container.find('.shape_creator_preview').find('.shape').css({'border-width': $(this).val()});
			});
			args.container.find('#edit_itm_border_style').on('change', function(){
				args.container.find('.shape_creator_preview').find('.shape').css({'border-style': $(this).val()});
			});
			
			// Border Radius
			args.container.find('#edit_itm_border_radius_top_left').on('change', function(){
				border_radius['top-left'] = $(this).val();
				args.container.find('.shape_creator_preview').find('.shape').css({'border-radius': _t.wppas.border_radius_css(border_radius)});
			});
			args.container.find('#edit_itm_border_radius_top_right').on('change', function(){
				border_radius['top-right'] = $(this).val();
				args.container.find('.shape_creator_preview').find('.shape').css({'border-radius': _t.wppas.border_radius_css(border_radius)});
			});
			args.container.find('#edit_itm_border_radius_bottom_left').on('change', function(){
				border_radius['bottom-left'] = $(this).val();
				args.container.find('.shape_creator_preview').find('.shape').css({'border-radius': _t.wppas.border_radius_css(border_radius)});
			});
			args.container.find('#edit_itm_border_radius_bottom_right').on('change', function(){
				border_radius['bottom-right'] = $(this).val();
				args.container.find('.shape_creator_preview').find('.shape').css({'border-radius': _t.wppas.border_radius_css(border_radius)});
			});
		},
		
		/**
		 * GET THE INLINE STYLE FOR AN ITEM
		 *
		 *
		 */
		get_item_style: function(args){
			var style = args['item'].attr('style');
			var st = {};
			if( style != ""){
				style = style.split(';');
				$.each(style, function(key, val) {
					//console.log(val);
					var v = val.split(':');
					if( v[0] != ""){
						st[$.trim(v[0])] = $.trim(v[1]);
					}
				});
			}
			//console.log(st);
			return st;
		},
		
		
		search_style: function(args){
			var res = '';
			
			$.each(args['style'], function(key, val) {
				//console.log(key+' checking');
				//if($.inArray(key, values[args['type']]) != -1){
				if( key == args.key){
					//console.log(key+': '+val);
					res = val;
					return null;
				}
			});
			return res;
			/*var values = {
				'bg': ['background-color', 'fill'],
				'border': ['border-color', 'stroke']
			},
			res = '';
			
			$.each(args['style'], function(key, val) {
				//console.log(key+' checking');
				if($.inArray(key, values[args['type']]) != -1){
					//console.log(key+': '+val);
					res = val;
					return null;
				}
			});
			//console.log(res);
			return res;
			//console.log(values[args['type']]);
			*/
		},
		
		
		
		
		/**
		 * SVG CREATOR
		 *
		 *
		 */
		svg_creator: function(args) {
			var _t = $(this),
				colors = {},
				itm_color = '';
				
			args.container.find('.b_add_svg').off('click').on('click', args.container.find('.b_add_svg'), function(e){
				//console.log('add svg');
				colors = {};
				
				
				args.container.find('.svg_creator_preview').html( $(this).html() );
				args.container.find('.svg_edit_options_cont').find('.svg_color_picker').hide();
				$("body, html, #itm_edit_content_container").animate({ scrollTop: 0 }, "fast");
				
				/*var colors = $('.svg_creator_preview').find('svg').data('colors'),
					color = typeof colors != 'undefined' ? colors.split(",") : '';*/
				
				$.each(args.container.find('.svg_creator_preview').find('svg').find('.colorful'), function(key, val) {
					// 20 can be any number. It's just the max number of colors that are supported.
					for (var i = 0; i < 20; i++) { 
						if($(this).hasClass('c'+(i+1)) && typeof colors[i] == 'undefined'){
							itm_color = '';
							//colors[i] = $(this).attr('fill');
							itm_color = $(this).attr('fill') != null ? $(this).attr('fill') : '';
							itm_color = itm_color == '' ? $(this).prop("style")["stop-color"] != '' ? $(this).css('stop-color') : '' : itm_color;
							itm_color = itm_color == '' ? $(this).prop("style")["fill"] != '' ? $(this).css('fill') : '' : itm_color;
							//itm_color = itm_color == '' ? $(this).css('stop-color') != null ? $(this).css('stop-color') : '' : itm_color;
							//itm_color = itm_color == '' ? $(this).css('fill') ? $(this).css('fill') : '' : itm_color;
							
							colors[i] = itm_color;
							//colors[i] = $(this).attr('fill') ? $(this).attr('fill') : $(this).css('fill');
							//console.log($(this).css('stop-color')+' '+itm_color+' '+$(this).css('fill'));
							//console.log('c'+(i+1)+' '+colors[i]);
							args.container.find('.svg_edit_options_cont').find('.cont_svg_c'+(i+1)).show();
							args.container.find('.svg_edit_options_cont').find('#svg_c'+(i+1)).wpColorPicker('color', colors[i]);
							break;
						}
					}
				});
			});
			
			// Load preview button CSS
			if( typeof args.ID != 'undefined' ){
				
				$('.rotate_handle').remove();
				$('.ui-resizable-handle').remove();
				args.container.find('.svg_creator_preview').html($('.'+args.ID).html());
				
				$.each(args.container.find('.svg_creator_preview').find('svg').find('.colorful'), function(key, val) {
					// 20 can be any number. It's just the max number of colors that are supported.
					for(var i = 0; i < 20; i++) { 
						if($(this).hasClass('c'+(i+1)) && typeof colors[i] == 'undefined'){
							
							colors[i] = $(this).attr('fill') ? $(this).attr('fill') : $(this).css('fill');
							//console.log('c'+(i+1)+' '+colors[i]);
							args.container.find('.svg_edit_options_cont').find('.cont_svg_c'+(i+1)).show();
							args.container.find('.svg_edit_options_cont').find('#svg_c'+(i+1)).wpColorPicker('color', colors[i]);
							break;
						}
					}
				});
			}
		},
		
		
		change_svg_color: function(args){
			
			if( args['item'].attr('fill')){
				args['item'].attr("fill", args['color']);
				return;
			}
			if(args['item'].css('fill')){
				args['item'].css({"fill": args['color']});
				return;
			}if(args['item'].css('stop-color')){
				args['item'].css({"stop-color": args['color']});
				return;
			}if(args['item'].css('stroke')){
				args['item'].css({"stroke": args['color']});
				return;
			}
			
			/*if(args['item'].css('background-color')){
				args['item'].css({"background-color": args['color']});
			}if(args['item'].css('color')){
				args['item'].css({"color": args['color']});
			}*/
		},
		
		
		change_shape_color: function(args){
			//console.log(args['item']);
			if(args['type'] == 'attr'){
				if( args['item'].attr(args['key'])){
					args['item'].attr(args['key'], args['color']);
				}
			}else{
				if(args['item'].css(args['key'])){
					args['item'].css(args['key'], args['color']);
				}
			}
			
		},
		
		
		
		
		/**
		 * BUTTON CREATOR
		 *
		 *
		 */
		button_creator: function(args) { 
			var _t = $(this);
			
			// CLICK ON Predefined btn
			args.container.find('.predefined_buttons_cont').find('.prbtn').off('click').on('click', args.container.find('.predefined_buttons_cont').find('.prbtn'), function(e) {
				var css = '',
					btn_style = $(this).data('class'),
					button = btn_style != '' ? prefedined.buttons[btn_style] : '',
					text = '',
					style = {
						'border-width': button['css']['default']['border-width'] != '' ? button['css']['default']['border-width'] : 0,
						'border-color': button['css']['default']['border-color'] != '' ? button['css']['default']['border-color'] : 'transparent'
					};
				
				args.container.find('.btn_creator_preview').find('.btn').attr('data-class', btn_style);
				args.container.find('#btn_creator_class').val(btn_style);
				args.container.find('#btn_creator_border').val(style['border-width']);
				args.container.find('#btn_creator_border_style').val(button['css']['default']['border-style']);
				args.container.find('#btn_creator_border_radius').val(button['css']['default']['border-radius']);
				args.container.find('#btn_creator_border_color').wpColorPicker('color', style['border-color']);
				
				args.container.find('#btn_creator_bg_color').wpColorPicker('color', button['css']['default']['background-color']);
				args.container.find('#btn_creator_font_color').wpColorPicker('color', button['css']['default']['color']);
				args.container.find('#btn_creator_hover_bg_color').wpColorPicker('color', button['css']['hover']['background-color']);
				args.container.find('#btn_creator_hover_font_color').wpColorPicker('color', button['css']['hover']['color']);
				args.container.find('#btn_creator_hover_border_color').wpColorPicker('color', button['css']['hover']['border-color']);
				
				//console.log(args.container.find('.btn_creator_preview').find('.btn_content').length);
				if( !args.container.find('.btn_creator_preview').find('.btn_content').length ){
					//console.log('class not found');
					args.container.find('.btn_creator_preview').find('.txt').wrap('<div class="btn_content"></div>');
				}
				
				if( button['content']['icon'] != '' ){
					var style = button['content']['icon']['style'] != '' ? ' style="'+button['content']['icon']['style']+'"' : '';
					var icon = '<i class="fa '+button['content']['icon']['class']+'"'+style+'></i>';
					args.container.find('.btn_creator_preview').find('.btn_content').html('<span class="txt"></span>');
					
					//console.log(button['content']['icon']['position']);
					if( button['content']['icon']['position'] == 'before'){
						args.container.find('.btn_creator_preview').find('.btn_content').prepend(icon);
					}else{
						args.container.find('.btn_creator_preview').find('.btn_content').append(icon);
					}
					//text+= button['content']['icon']['position'] == 'before' ? icon : '';
				}else{
					args.container.find('.btn_creator_preview').find('.btn_content').html('<span class="txt"></span>');	
				}
				
				/*if( button['content']['icon'] != '' ){
					text+= button['content']['icon']['position'] == 'after' ? icon : '';
				}*/
				text+= button['content']['text'] != '' ? button['content']['text'] : '';
				args.container.find('.btn_creator_preview').find('.txt').html( text );
				args.container.find('#btn_creator_txt').val(button['content']['text']);
				//args.container.find('.btn_creator_preview').find('.btn').addClass(btn_style);
				
				css+= '#'+args.container.attr('id')+' .prevbtn .btn_creator_preview .btn{';
					$.each(button['css']['default'], function(key, val) {
						css+= key+':'+val+';';
					});
				css+= '}';
				css+= '#'+args.container.attr('id')+' .prevbtn .btn_creator_preview .btn:hover{';
					$.each(button['css']['hover'], function(key, val) {
						css+= key+':'+val+';';
					});
				css+= '}';
				
				args.container.find('#btn_prev_style').text('');
				args.container.find('#btn_prev_style').append(css);
			});
			
			
			// Load preview button CSS
			if( typeof args.ID != 'undefined' ){
				var btn_style = timeline_arr[cur_view_size][args.ID]['data']['values']['class'],
					button = btn_style != '' ? prefedined.buttons[btn_style] : '',
					custom = timeline_arr[cur_view_size][args.ID]['data']['values']['custom'],
					css = '';
				
				args.container.find('#btn_creator_bg_color').wpColorPicker('color', custom['css']['default']['background-color']);
				args.container.find('#btn_creator_font_color').wpColorPicker('color', custom['css']['default']['color']);
				args.container.find('#btn_creator_border_color').wpColorPicker('color', custom['css']['default']['border-color']);
				args.container.find('#btn_creator_hover_bg_color').wpColorPicker('color', custom['css']['hover']['background-color']);
				args.container.find('#btn_creator_hover_font_color').wpColorPicker('color', custom['css']['hover']['color']);
				args.container.find('#btn_creator_hover_border_color').wpColorPicker('color', custom['css']['hover']['border-color']);
					
				css+= '#itm_'+args.ID+' .btn{';
					if(button != '' && typeof button != 'undefined'){
						$.each(button['css']['default'], function(key, val) {
							css+= key+':'+val+';';
						});
					}
					if(custom != '' && typeof custom != 'undefined'){
						$.each(custom['css']['default'], function(key, val) {
							css+= key+':'+val+';';
						});
					}
				css+= '}';
				css+= '#itm_'+args.ID+' .btn:hover{';
					if(button != '' && typeof button != 'undefined'){
						$.each(button['css']['hover'], function(key, val) {
							css+= key+':'+val+';';
						});
					}
					if(custom != '' && typeof custom != 'undefined'){
						$.each(custom['css']['hover'], function(key, val) {
							css+= key+':'+val+';';
						});
					}
				css+= '}';
				
				
				args.container.find('#btn_prev_style').text('');
				args.container.find('#btn_prev_style').append(css);
			}
			
			
			/**
			 * LIVE PREVIEW UPDATES
			 */
			var ID = typeof args.ID != 'undefined' ? '#itm_'+args.ID : '.prevbtn .btn_creator_preview';
			// text
			args.container.find('#btn_creator_txt').on('change', function(){
				args.container.find('.btn_creator_preview').find('.txt').html( $(this).val() );
			});
			// Border width
			args.container.find('#btn_creator_border').on('change', function(){
				args.container.find('#btn_prev_style').append(ID+' .btn{border-width:'+_t.wppas.get_value($(this).val())+' !important;}');
			});
			// Border style
			args.container.find('#btn_creator_border_style').on('change', function(){
				args.container.find('#btn_prev_style').append(ID+' .btn{border-style:'+$(this).val()+' !important;}');
			});
			// Border radius
			args.container.find('#btn_creator_border_radius').on('change', function(){
				args.container.find('#btn_prev_style').append(ID+' .btn{border-radius:'+$(this).val()+' !important;}');
			});
		},
		
		
		
		change_button_color: function(args){
			//console.log(args['item']);
			var sel_col = args.color != "" ? args.color : "transparent",
				itm = $(args['item']);
			
			//if( $('.b_container').find('.'+$('#timeline_container').find(args['item']).data('itm')).length && $('.b_container').find('.'+$('#timeline_container').find(args['item']).data('itm')).hasClass('itm') ){
				//console.log($('#timeline_container').find(args['item']).data('itm'));
				//console.log(sel_col); 
				itm.find("#btn_prev_style").append(args['item']+" .prevbtn .btn_creator_preview .btn{"+args['key']+":"+sel_col+";}"); 
				//itm.find(".prevbtn #btn_creator_bg_color").val(sel_col);
			//}
			
		},
		
		
		
		
		
		/**
		 * Upload ZIP Files
		 *
		 *
		 */
		upload_zip_file: function(e) { 
			console.log('START UPLOAD ZIP '+$('#wppas_zip_file').val());
			e.preventDefault();
			var form_data = new FormData(),
				file = $('#wppas_zip_file').prop('files')[0];
				
			console.log(file);
			form_data.append('file', file);
			form_data.append('action', 'upload_zip_files'); 
			
			$.ajax({
			   type: "POST",
			   url: ajaxurl,
			   processData: false,
 			   contentType: false,
			   data: form_data
			}).done(function( msg ) {
		
				console.log(msg);
				
			});
		},
		
		
		/**
		 * Delete null properties
		 *
		 *
		 */
		delete_null_properties: function(test, recurse) {
			var _t = $(this);
			
			for (var i in test) {
				if (test[i] === null) { // || test[i] === ''
					delete test[i];
				} else if (recurse && typeof test[i] === 'object') {
					_t.wppas.delete_null_properties(test[i], recurse);
				}
			}
		},
		
		
		
		
		/**
		 * Create Banner Cover
		 */
		create_banner_cover: function(args){
			
			var defaults = {
				'download': 0,
				'type': 'toPng'
			};
			args = jQuery.extend( defaults, args );
			
			var node = document.getElementsByClassName('b_container')[0],
				alphaID = $('#wppas_banner_alpha_id').val(),
				file_type = args.type.toLowerCase(),
				ftype = file_type.split('to');
			
			file_type = ftype[1];
			file_type = file_type === 'jpeg' ? 'jpg' : file_type;
			//console.log(file_type);
			
			$('.vbc_loader_bg').show();
			$('.vbc_loader_duration').show();
			
			//var node = document.getElementById('bpreview');
			//var canvas = document.createElement('canvas');
			//canvas.setAttribute("id", "canvas_exp");
			
			//canvas.width = node.scrollWidth;
			//canvas.height = node.scrollHeight;
			//canvas.width = $('.b_container').width();
			//canvas.height = $('.b_container').height();
			
			
			/*domtoimage.toSvg(node, { width:$('.b_container').width(), height: $('.b_container').height() }).then(function (dataUrl) {
				var img = new Image();
				img.onload = function () {
					var context = canvas.getContext('2d');
			
					//context.translate(canvas.width, 0);
					//context.scale(-1, 1);
					context.drawImage(img, 0, 0);
			
					//parent.removeChild(node);
					document.body.appendChild(canvas);
				};
			
				img.src = dataUrl;
			});
			*/
			
			//var node = document.getElementById('canvas_exp');
			domtoimage[args.type](node, { width:$('.b_container').width(), height: $('.b_container').height() }).then(function (dataUrl) {
				var img = new Image();
				img.src = dataUrl;
				//document.body.appendChild(img);
				//console.log(img.src);
				if( args['download'] == 1 ){
					var link = document.createElement('a');
					link.download = 'banner-'+alphaID+'.'+file_type;
					link.href = dataUrl;
					link.click();
				}
				
				if( file_type != 'svg'){
					$.ajax({
					   type: "POST",
					   url: ajaxurl,
					   data: "action=save_banner_cover&data="+dataUrl+"&alphaID="+alphaID
					}).done(function( msg ) {
				
						//console.log(msg);
						$('.vbc_loader_bg').hide();
						$('.vbc_loader_duration').hide();
					});
				}
				
			}).catch(function (error) {
				console.error('oops, something went wrong!', error);
				$('.vbc_loader_bg').hide();
				$('.vbc_loader_duration').hide();
				alert('Woops, We couldn\'t download the banner.');
			});
			
		},
		
		
		
		
		
		
		
	});
	
}( jQuery ));