(function($){
	var vBulletin = vBulletin || {};
	vBulletin.V5 = vBulletin.V5 || {};
	vBulletin.V5.SiteBuilder = vBulletin.V5.SiteBuilder || {};

	$(document).ready(function(){

		vBulletin.V5.SiteBuilder.selectLayout = function(targetLayout){
			if (!vBulletin.V5.SiteBuilder.currentLayout) {
				vBulletin.V5.SiteBuilder.currentLayout = targetLayout;
				return;
			}
			else if (vBulletin.V5.SiteBuilder.currentLayout == targetLayout) {
				return;
			}
			else if (targetLayout.indexOf('100') != -1) {
				$('#' + vBulletin.V5.SiteBuilder.currentLayout + ' > div.left > div')
					.appendTo('#' + targetLayout + ' > div.canvas-content-list');
				$('#' + vBulletin.V5.SiteBuilder.currentLayout + ' > div.right > div')
					.appendTo('#' + targetLayout + ' > div.canvas-content-list');
			}
			else if (vBulletin.V5.SiteBuilder.currentLayout.indexOf('100') != -1) {
				$('#' + vBulletin.V5.SiteBuilder.currentLayout + ' > div > div')
					.appendTo('#' + targetLayout + ' > div.left');

				vBulletin.V5.SiteBuilder.adjustDivider();
			}
			else {
				$('#' + vBulletin.V5.SiteBuilder.currentLayout + ' > div.left > div')
					.appendTo('#' + targetLayout + ' > div.left');

				$('#' + vBulletin.V5.SiteBuilder.currentLayout + ' > div.right > div')
					.appendTo('#' + targetLayout + ' > div.right');

				vBulletin.V5.SiteBuilder.adjustDivider();
			}
			vBulletin.V5.SiteBuilder.currentLayout = targetLayout;

		};

		vBulletin.V5.SiteBuilder.initPageTemplate = function(){
			//page template default page
			if ($('#sitebuilderForm_step3').length===1) {
				$('#btnBack').click(function(){
					location.href = $('#hiddenData').attr('prev-step-url');
				});

				$('#btnNewTemplate').click(function(){
					location.href = $('#hiddenData').attr('new-template-url');
				});

				$('select[name=controls-list]').change(function(){
					$('#btnSave').removeAttr('disabled');
				});
				return;
			}

			//create new page template starts here

			$('#btnPreview').click(function(){
				//todo:implement Preview
			});

			$('#btnBack').click(function(){
				location.href = $('#hiddenData').attr('prev-step-url');
			});

			$('#btnCreate').click(function(){
				//populate the corresponding hidden textbox with the added widgets for processing

				//widgets on the left
				var arrLeft = [];
				$('.canvas-content-list .canvas-content').each(function(index){
					arrLeft.push($(this).attr('widget-id') + '=' + ($(this).attr('widget-instance-id')||'0'));
				});
				$('#txtAddedWidgetsLeft').val(arrLeft.join(','));

				//widgets on the right
				var arrRight = [];
				$('.canvas-widget-list .canvas-content').each(function(index){
					arrRight.push($(this).attr('widget-id') + '=' + ($(this).attr('widget-instance-id')||'0'));
				});
				$('#txtAddedWidgetsRight').val(arrRight.join(','));

				return true;
			});

			//screen layout
			$('#layout_list input[type=radio]').thumbnailRadioButton({
				radioGroupId: 'layout_list',
				thumbnailClass:'radio-button-thumbnail layout-border',
				select:function($thumbnail, $radio){
					$('.canvas-outer .canvas-inner .canvas-layout').removeClass('show').addClass('hide');
					$('#canvas-' + $radio.attr('id')).removeClass('hide').addClass('show');
					vBulletin.V5.SiteBuilder.selectLayout('canvas-' + $radio.attr('id'));

					$('#btnSave').removeAttr('disabled');
				}
			});

			//+Add button
			$('.content-widget-container .content-widget-list .item .button').click(function(e){
				var buttonType = $(this).hasClass('widget') ? 'widget' : 'content';
				vBulletin.V5.SiteBuilder.addContentOrWidget(
					$(this).parent().parent().attr('id'),
					$(this).parent().prev().text(),
					buttonType,
					$('img', $(this).parent().prev().prev()).attr('src'));
			});

			//content/widget x button
			$('.canvas-content .canvas-content-item .close-button').live('click', function(){
				$gparent = $(this).parent().parent();
				//$gparent.addClass('hide');
				var isWidget = $gparent.parent().hasClass('canvas-widget-list');
				if (isWidget) {
					var $widget = $('.canvas-layout.show .canvas-widget-list');
					var $content = $('.canvas-layout.show .canvas-content-list');
					if ($widget.height() > $content.height()) {
						$content.height($widget.height());
					}
					else $content.height('auto');

				}
				$gparent.remove();
				vBulletin.V5.SiteBuilder.adjustDivider(isWidget);

				$('#btnSave').removeAttr('disabled');
			});

			//make page canvas items draggable-n-droppable
			$('.canvas-content-list, .canvas-widget-list').sortable({
				connectWith: ".connectedSortable",
				placeholder: "canvas-widget-highlight",
				update: function(event, ui){
					$('#btnSave').removeAttr('disabled');
				},
				sort:function(event, ui){
					var isWidget = ui.placeholder.parent().hasClass('canvas-widget-list');
					vBulletin.V5.SiteBuilder.adjustDivider(isWidget);
				}
			}).disableSelection();

			$('#config-dialog').dialog({
				title:'Widget Configuration',
				autoOpen:false,
				modal:true,
				resizable:false,
				closeOnEscape:false,
				height:500,
				width:800,
				dialogClass:'sb-dialog-container config-dialog-container shadow-dark',
				create:function(){
					//submit form handler to save config
					$('#sitebuilderForm_step3b_config').submit(function() {

			  		  $('body').css('cursor', 'wait');
			  		  $('#config-dialog .action-buttons button').attr('disabled', 'disabled');

					  $.ajax({
				  			url:this.action,
				  			type:this.method,
				  			data:($(this).serializeArray()),
				  			dataType: 'json',
				  			success:function(result){
				  				$('body').css('cursor', 'auto');

				  				//@todo:check for validation errors returned by the server here

				  				$('#config-dialog').dialog('close');
				  			},
				  			error:function(xhr, statusText, error){
				  				$('body').css('cursor', 'auto');
				  				initErrorDialog(null, function(){
				  					$('#config-dialog .action-buttons button').removeAttr('disabled');
								});
								showErrorDialog('<span>Error saving the configuration for "' + $('#config-dialog .widget-name h1').text() + '" widget.<br /><br />Please try again later.</span>');
								$('#config-dialog .widget-loader').hide();
				  			}
				  		});

					  	return false;
					});
					$('#btnCloseConfig').click(function(){
						$('#config-dialog').dialog('close');
					});
				},
				close:function(){
					$('#config-dialog .action-buttons button').removeAttr('disabled');
				}
			});

			vBulletin.V5.SiteBuilder.selectLayout($('.canvas-layout.show').attr('id'));
		};

		vBulletin.V5.SiteBuilder.addContentOrWidget = function(widgetId, widgetName, buttonType, thumbnail){
			var isWidget = buttonType == 'widget';
			var isLayout100 = $('.canvas-layout.show').attr('id').indexOf('100') != -1;
			$('<div widget-id="' + widgetId.replace(/widget_/, '') + '" widget-instance-id="" class="canvas-content' + (isWidget ? ' widget':'') + ' shadow">' +
			  '	 <div class="canvas-content-item">' +
			  '	 	<div class="canvas-content-icon"><img src="' + thumbnail + '" width="20" height="20" alt="" /></div>' +
			  '		<div class="canvas-content-title"><a href="#">' + widgetName + '</a></div>' +
			  '		<div class="close-button">x</div>' +
			  '	 	<div class="clear"></div>' +
			  '	 </div>' +
			  '</div>')
			  	.appendTo($('.canvas-layout.show .canvas-' + (isLayout100 ? 'content':buttonType) + '-list').height('auto'))
			  	.find('.canvas-content-title a').click(function(){
			  		var $widgetContainer = $(this).closest('.canvas-content');
			  		var widgetId = $widgetContainer.attr('widget-id');
			  		var widgetName = $(this).text();

			  		$('body').css('cursor', 'wait');
			  		$('#config-dialog .widget-loader').show();
			  		$('#config-dialog .widget-name h1').text(widgetName);
			  		$('#config-dialog .dialog-content .widget-config-container').hide().empty();
			  		$('#config-dialog').dialog('open');

			  		//get config items of the selected widget
			  		$.ajax({
			  			url:$('#hiddenData').attr('base-url') + '/index.php/ajax/widget/fetchConfigSchema',
			  			data:({
			  				widgetid: widgetId,
			  				widgetinstanceid: $widgetContainer.attr('widget-instance-id')||'', //if this widget instance has been configured before, its widget instance id exists, so use it
			  				pagetemplateid: $('#config_pagetemplateid').val(),
			  				configtype: 'admin'
			  			}),
			  			dataType: 'json',
			  			success:function(result){
			  				$('body').css('cursor', 'auto');
			  				if (result) {
			  					//set hidden fields
			  					$('#config_widgetid').val(result.widgetid);
			  					$('#config_widgetinstanceid').val(result.widgetinstanceid);
			  					$('#config_pagetemplateid, #txtPageTemplateId').val(result.pagetemplateid);

			  					//remember id of this widget instance for subsequent requests
			  					$widgetContainer.attr('widget-instance-id', result.widgetinstanceid);

			  					//loop through all the config items
			  					var idx = 0; //result.configs is an object literal and not an indexed array so we cannot use $.each index for math operations.
			  					$.each(result.configs, function(index, config){
			  						var $configValue;
			  						//convert config item to corresponding UI control
			  						switch(config.type){
			  							case 'Text':
			  								$configValue = $('<input type="text" />')
			  												.attr({
			  													name: 'data[' + config.name + ']'
			  												})
			  												.css('width', '100%')
			  												.val(config['default']);
			  								break;
			  							case 'LongText':
			  								$configValue = $('<textarea />')
			  												.attr({
			  													rows:3,
			  													name: 'data[' + config.name + ']'
			  												})
			  												.css('width', '100%')
			  												.text(config['default']);
			  								break;
			  							case 'YesNo':
			  								var $options = {
			  									'option_1' : $('<input type="radio" value="1" />')
			  												.attr({
		  														name: 'data[' + config.name + ']',
		  														id: config.name + '_1'
		  													}),
		  										'label_1': $('<label />')
			  													.attr({'for': config.name + '_1'})
			  													.text('Yes'),
			  									'option_0' : $('<input type="radio" value="0" />')
			  												.attr({
		  														name: 'data[' + config.name + ']',
		  														id: config.name + '_0'
		  													}),
		  										'label_0': $('<label />')
			  													.attr({'for': config.name + '_0'})
			  													.text('No')
			  								}

			  								$options['option_'+config['default']].attr('checked', 'checked');
			  								$configValue = $('<div />')
			  									.append(
			  										$options['option_1'], $options['label_1'],
			  										$options['option_0'], $options['label_0']
			  									);
			  								break;
			  						}

			  						//put * if field is required
			  						$requiredMark = $('<div />')
			  										.addClass('config-required-mark left')
			  										.append(function(){
			  											return (config.isRequired==1) ? '*':'&nbsp;'
			  										});

			  						//disable field if config is not editable
			  						if (config.isEditable==0) {
			  							if (config.type=='YesNo') {
			  								$configValue.find('input').attr('disabled', 'disabled');
			  							}
			  							else {
			  								$configValue.attr('disabled', 'disabled');
			  							}
			  						}

									//append the config row
			  						$('#config-dialog .dialog-content .widget-config-container').append(
			  							$('<div></div>')
			  								.addClass(function(){
			  									return "config-row" + (((++idx) % 2 != 0) ? ' odd':'');
			  								})
			  								.append(
				  								$('<div></div>').addClass('config-label left').html(config.label),
				  								$requiredMark,
				  								$('<div></div>').addClass('config-value left').append($configValue),
				  								$('<div></div>').addClass('clear')
			  							)
			  						);
								});
			  				}
			  				$('#config-dialog .dialog-content .widget-config-container').show();
							$('#config-dialog .widget-loader').hide();
			  			},
			  			error:function(xhr, statusText, error){
			  				$('body').css('cursor', 'auto');
			  				initErrorDialog(null, function(){
			  					$('#config-dialog').dialog('close');
							});
							showErrorDialog('<span>Error retrieving the configuration for "' + widgetName + '" widget.<br /><br />Please try again later.</span>');
							$('#config-dialog .widget-loader').hide();
			  			}
					});
			  		return false;
			  	});

			vBulletin.V5.SiteBuilder.adjustDivider(isWidget);

			$('#btnSave').removeAttr('disabled');
		}

		vBulletin.V5.SiteBuilder.adjustDivider = function(isWidget){
			var isLayout100 = $('.canvas-layout.show').attr('id').indexOf('100') != -1;
			if (!isLayout100) {
				var $widget = $('.canvas-layout.show .canvas-widget-list');
				var $content = $('.canvas-layout.show .canvas-content-list');
				if ($widget.height() > $content.height()) {
					$content.height($widget.height());
				}
				else if ($widget.height() < $content.height()) {
					$content.height('auto');
				}
			}
		}

		vBulletin.V5.SiteBuilder.initPageTemplate();
	});
})(jQuery);