//Layout-Code views
var CSTemplate;
var CSActions;
var CSWidgetQueue = new WidgetQueue();
var CSLayoutPageWidgets = null;

jQuery(function(){
	//var jq = jQuery.noConflict();
	var jq = jQuery;
	var breakpoints, breakpointKey;
	var iframeNode = jq('.csd-middle .site-wrapper iframe');

	iframeNode.data('loaded', false);
	iframeNode.load(function(){

		jq.ajax({
			url: iframeNode.data('json'),
			success: function(data) {
				jq.ajax({
					url: iframeNode.data('get-widgets'),
					dataType: "json",
					success: function(widgetData) {
						data.layoutPageWidgets = widgetData.layoutPageWidgets;
						CSTemplate = new Template(
							data.template ? data.template : data,
							jq('.csd-top .buttons')
						);

						if (typeof data.layoutPageWidgets !== 'undefined') {
							CSLayoutPageWidgets = data.layoutPageWidgets;
						}

						CSTemplate.render(
							iframeNode.contents().find(Template.SELECTOR)
						);

						createDraggable(
							jq(".csd-middle .widgets-wrapper")
						);

						jq('div', breakpoints).hide();
						jq(
							'a[data-value="' + breakpoints.data('default') + '"]',
							breakpoints
						).click();

						jq('.row', iframeNode.contents()).CSDroppable({
							drop: Template.prototype.dropCallback,
							excludedSelectors: Template.DROPPABLE_EXCLUDED_SELECTORS
						});

						iframeNode.data('loaded', true);
						CSTemplate.enable();
						var Manager = new ContentManager(iframeNode);
						enableTabs(Manager);
						CSTemplate.setContentManager(Manager);
						jQuery('body', jQuery(iframeNode).contents())
							.addClass(ContentManager.STRUCTURE_MODE_CLASS);

						setTimeout(function () {
							jQuery('body').removeClass(Template.LOADING_CLASS);
						}, 500);
					}});
			}
		});

		jq('.csd-top .csd-options .csd-show-all').click(function(event) {
			event.preventDefault();
			jq('body', iframeNode.contents()).toggleClass('show_hidden');
			jq(this).toggleClass('active');
		});

		jq('.csd-bottom .icon-group.views').data('locked', false);
		jq('.csd-bottom .icon-group.views a').click(function (event) {
			event.preventDefault();

			if (!jq('.csd-bottom .icon-group.views').data('locked')) {
				if (jq('.csd-bottom .icon-group.views a.active').get(0) != this) {
					jq('.csd-bottom .icon-group.views a').removeClass('active');
					jq(this).addClass('active');
					if (jq(this).hasClass('code')) {
						CSTemplate.disable();
						jq('.csd-bottom .icon-group.widgets-views .hidden').click();
						jq('.csd-bottom').data('locked', true);
						jq('.csd-options').data('locked', true);
						jq('#template_code').val(
							CSTemplate.getHtml()
						);
					} else {
						jq('.csd-options').data('locked', false);
						jq('.csd-bottom').data('locked', false);
						jq('.csd-bottom .icon-group.widgets-views .right').click();
						CSTemplate.setHtml(
							jq('#template_code').val()
						);
					}
					jq('.csd-middle .view').hide();
					jq('.csd-middle .view.'+jq(this).data('wrapper')).show();
				}
			}
		});

		breakpoints = jq('.csd-bottom .responsive-views');
		if (breakpoints.length > 0) {
			jq('div span', breakpoints).click(function (event) {
				var node;

				event.preventDefault();
				
				if (!jq('.csd-bottom').data('locked')) {
					jq('div span.active', breakpoints).removeClass('active');
					jq(this).addClass('active');
					if (jq(this).data('width') > 0) {
						iframeNode.width(
							jq(this).data('width') + 20
						);
						refreshIframe();
					}
				}
			});
			jq('a', breakpoints).click(function (event) {
				var sizes;

				event.preventDefault();

				if (!jq('.csd-bottom').data('locked') && !jq(this).hasClass('active')) {
					jq('a.active', breakpoints).removeClass('active');
					jq('div', breakpoints).fadeOut('fast');
					jq(this).addClass('active');
					CSTemplate.changeBreakpoint(jq(this).data('value'));
					sizes = jq(this).next(
						'div[data-breakpoint="'+jq(this).data('value')+'"]'
					);
					if (sizes.length > 0) {
						sizes.children().first().click();
						if (sizes.children() > 1) {
							sizes.fadeIn('fast');
						}
					}
				}
			});

		}
		
		//Widgets bar views
		jq('.csd-bottom .icon-group.widgets-views a').click(function (event) {
			event.preventDefault();

			if (!jq('.csd-bottom').data('locked')) {
				jq('.csd-bottom .icon-group.widgets-views a').removeClass('active');
				jq(this).addClass('active');
				jq('.csd-middle').removeClass('bar-left no-bar bar-right');
				jq('.csd-middle').addClass(jq(this).data('option'));
			}
		});
		jq('.csd-middle .widgets-wrapper .search form').submit(function () {
			var $this = jq(this);
			if (
				!$this.data('submitted') &&
				$this.serialize() != $this.data('search')
			) {
				$this.data('submitted', true);
				$this.data('search', $this.serialize());
				jq.ajax({
					'type': $this.prop('method'),
					'data': $this.serialize(),
					'url': $this.prop('action'),
					'complete': function (response) {
						var data, node, element;

						node = jq(
							'.csd-middle .widgets-wrapper .search .results.'
							+$this.data('type')
						);
						node.slideUp('fast').empty();
						if (response.status == 200) {
							data = jq.parseJSON(response.responseText);

							if (data) {
								jq.each(data, function(index, item){

									//element.append(jq('<span/>', {
									//	'title': 'Eliminar'
									//}));

									if ($this.data('type') == 'widgets') {

										var _iClass = item.favorite ? 'fa-star' : 'fa-star-o';
										var _aText  = item.title||item.name;

										element = jq('<li/>', {
											'class': Template.DRAGGABLE_CLASS,
											'html': jq('<a/>', {
												'href': 'javascript: void(0);',
												'title': item.name  ? item.name : item.title,
												'text' : item.name  ? item.name : item.title,
												'data-info': JSON.stringify(item),
												'html': '<i data-type="favorite" class="fa '+ _iClass +'"></i> ' + _aText
											})
										});

										element.addClass(ContentManager.TOOLBAR_DRAGGABLE_WIDGETS);
										element.attr('data-widget-id', item.id);

									} else {

										element = jq('<li/>', {
											'class': Template.DRAGGABLE_CLASS,
											'html': jq('<a/>', {
												'href': 'javascript: void(0);',
												'title': item.name,
												'text' : item.name,
												'data-info': JSON.stringify(item)
											})
										});
									}

									node.append(element);

									if ($this.data('type') == 'widgets') {
										CommonDesigner.init(element.find('[data-type="favorite"]'), true);
									}
								});
								if ($this.data('type') == 'widgets') {
									CSTemplate.getContentManager()
										.enableDraggableToolBar();
								} else {
									createDraggable(
										node
									);
								}
								node.slideDown();
							}
						}
						$this.data('submitted', false);
					}
				});
			}

			return false;
		});
	});

	function createDraggable(node, start, stop)
	{
		try {
			jq("."+Template.DRAGGABLE_CLASS, node)
				.CSDroppable('destroy');
		} catch(error){}

		if (!start) {
			start = function(){
				CSTemplate.disable(true);
				CSTemplate.enableDroppable();
			};
		}
		if (!stop) {
			stop = function(){
				CSTemplate.enable(true);
			};
		}

		jq("."+Template.DRAGGABLE_CLASS, node).CSDraggable({
			helper: 'clone',
			dragstart: start,
			dragend: stop,
			render: function(event, target){
				var $target = CSTemplate;
				var data, layout, item, total, columns;
				
				item = $target.generateLayout();
				jq.CSDragAndDropStore.customData['non-droppable-layouts'] = [];
				if (jQuery('a', this).data('columns') > 1) {
					jq('.'+Layout.CONTENT_CLASS, item).append(jq('<div/>', {
						'class': Layout.ROW_CLASS
					}));

					total = jQuery('a', this).data('columns');
					columns = Math.floor($target.columns/total);
					for (var i = 0; i < total; i++) {
						jq('.'+Layout.ROW_CLASS, item).append(
							$target.generateLayout(columns)
						);
					}
				} else if (jQuery('a', this).data('info')) {
					data = jQuery('a', this).data('info');
					if (data.id) {
						$target.disable(true);
						item.attr(
							'data-info',
							JSON.stringify(
								CSTemplate.getLayoutInfo(data.id)
							)
						);
						layout = CSTemplate.getLayoutObject(data.id);
						if (layout) {
							item = layout.getTarget().clone();
						}
						$target.enable(true);
					}
					if (!layout) {
						item.attr('data-info', JSON.stringify(data));
						item.html(data.code);
					}

					jq.CSDragAndDropStore.customData['non-droppable-layouts'] = getAllChildrenIds(data);

				}
				item = jq('<div/>', {
					'class': Layout.ROW_CLASS,
					'html': item
				});
				
				return item.wrap('<div/>').parent().html();
			}
		});
	}

	function refreshIframe()
	{
		if (iframeNode.data('loaded')) {
			iframeNode.data('loaded', false);
			CSTemplate.disable();
			CSTemplate.enable();
			iframeNode.data('loaded', true);
		}
	}

	function getAllChildrenIds(json)
	{
		var ids = [];

		for(var i = 0; i < json.children.length; i++) {
			var result = getAllChildrenIds(json.children[i]);
			ids = ids.concat(result);
		}

		ids.push(json.id);

		return ids;
	}

	function enableTabs(contentManager)
	{
		jQuery('#designer-tabs li').on('click', function() {
			if (!jq('.csd-options').data('locked') && !jQuery(this).hasClass('active')) {
				jQuery('[data-tab-content]').hide();
				jQuery('[data-tab-content="'+jQuery(this).data('tab')+'"]').show();
				jQuery('[data-tab]').removeClass('active');
				jQuery(this).addClass('active');

                if(jQuery(this).data('mode') === 'vce') {
                	jQuery('.csd-bottom .icon-group.views').data('locked', true);
                    contentManager.enableContentMode();
                    CSTemplate.setMode(Template.CONTENT_MODE);
                } else if(jQuery(this).data('mode') === 'vle') {
                    CSTemplate.setMode(Template.STRUCTURE_MODE);
                    contentManager.disableContentMode();
                    jQuery('.csd-bottom .icon-group.views').data('locked', false);
                }
            }
        });
    }
});
