/*!
 * stitchBuilder Widget - Web Edition
 *   http://www.stitchbuilder.com
 *
 * Copyright (c) 2010 webmade inc.  www.webmade.ca
 * No distribution or use without written consent.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 */
$.sbw = function(){};
$.sbw.defaultOptions = {
        spinnerSrc: '/sbw/shared/images/loading.gif',
        spinnerAlt: 'Loading...'
};

$.sbw.idcounter = 0;
$.sbw.dialogZIndex = 1000;

/* Need to change the plugin to use cross domain get, instead of post 
 *  http://stackoverflow.com/questions/1576040/synchronous-cross-sub-domain-post-request-with-jquery
 **/


//$.sbw.homeURL = "http://local.yloft.ca:8080";

// constructor
$.fn.sbw = function(p_options) {
	var _options = $.extend({}, $.sbw.defaultOptions, p_options);
    
    return this.each(function(){
        var $this = $(this);
        
        var _div = $('<table width="100%" height="100%"><tr><td valign="middle" align="center"><img src="'+_options.spinnerSrc+'" /></td></tr></table>');
        //var _img = $('<img />');
        
        // div style
        //_div.css(_options.css);
        
        // Load image
        //_img.attr('src', _options.spinnerSrc);
        //_img.attr('alt', _options.spinnerTitle);
        
        //_div.append(_img);
        $this.html(_div);

        var widgetId = $this.attr('sbw-widget-id');
        if (widgetId==null) {
        	widgetId = $.sbw.idcounter++;
        	$this.attr('sbw-widget-id',widgetId);
        }
        $.sbw.loadWidget(widgetId);
    });
};

$.sbw.findNextAvailableDialog = function() {
	for (var i = 1; i<10; i++) {
		var d = $('#sbw-panel-dialog-'+i);
		if (d) {
			if (!d.dialog('isOpen')) {
				return d;
			}
		}
	}
	
	return -1;
};

$.sbw.getNumberOfOpenDialogs = function() {
	var count = 0;
	for (var i = 1; i<10; i++) {
		var d = $('#sbw-panel-dialog-'+i);
		if (d) {
			if (d.dialog('isOpen')) {
				count++;
			}
		}
	}
	
	return count;
};

$.sbw.getWidgetFromId = function(widgetId) {
	return $('.sbw-widget[sbw-widget-id="'+widgetId+'"]');
};

$.sbw.wrapWidgetInEditor = function(widgetId) {
	var widget = $.sbw.getWidgetFromId(widgetId);
	
	$.sbw.log(widgetId);
	$.sbw.log(widget);
	var fc = widget.parent('.sbw-widget-edit-control-div');
	if (fc.length==0) {
		widget.wrap('<div class="sbw-widget-edit-control-div" style="position: relative;"><div></div><img src="/sbw/app/styles/default/welcomeFish.png" width="18px" height="18px" style="position: absolute; right: -9px; top: -9px; z-index: 100; cursor: pointer;" onclick="$.sbw.editWidget(\''+widgetId+'\');" title="Edit Widget" /></div>');
	}
};

$.sbw.loadWidget = function(widgetId) {
	var widget = $.sbw.getWidgetFromId(widgetId);
	
	var widgetDataPath = widget.attr('sbw-widget-data-path');
    var widgetRenderingURL = widget.attr('sbw-widget-rendering-url');
    var widgetMode = widget.attr('sbw-widget-mode');
    
	// Query the server for the widget contents
    $.ajax({
		type: "POST",  
		url: widgetRenderingURL, 
		data: {
    		sbaction: 'sbw_widget_getcontents',
    		datapath: widgetDataPath
		},  
		success: function(data,status,request) {
			var sbwuser = request.getResponseHeader('sbwuser');
			if (sbwuser=='null') {
				//alert('not logged in');
			} else {
				$.sbw.wrapWidgetInEditor(widgetId);
			}
			
			widget.html(data);
		},
		
		error: function(response) {
		} 
	});
};

$.sbw.editWidget = function(widgetId) {
	var widget = $.sbw.getWidgetFromId(widgetId);
	
	var widgetDataPath = widget.attr('sbw-widget-data-path');
    var widgetEditorTitle = widget.attr('sbw-widget-editor-title');
    
	$.sbw.openDialog({
		url: '/sbw/app/editor/frame.jsp',
		params: {
			sbaction: 'sbw_widget_edit',
			datapath: widgetDataPath
		},
		title: widgetEditorTitle
	});
	
	$.sbw.log(widget);
};

$.sbw.editSite = function(siteURL) {
	$.sbw.openDialog({
		url: siteURL,
		params: {
			sbaction: 'sbw_widget_edit',
			page: '/sbw/app/editor/frame.jsp'
		},
		title: 'The editor frame'
	});
};

$.sbw.loadPanel = function(dialogId, panelId, url, datapath, data) {
	var dialogConfig = $.sbw.dialogConfigs[dialogId];
	var veto = dialogConfig.beforePanelUnload();
	if (veto) return;
	
	var panel = $('#'+panelId);
	
	panel.html('<table width="100%"  height="100%"><tr><td align="center" valign="middle" ><img src="'+$.sbw.defaultOptions.spinnerSrc+'" /></td></tr></table>');
	
	var d = {
		dialogid: dialogId,
		panelid: panelId,
		datapath: datapath
	};
	$.extend(d,data);
	
	$.ajax({
		type: "POST",  
		url: url, 
		data: d,
		success: function(data) { 
			panel.html(data);
		},
		error: function(response) {
			
		} 	
	});
};

$.sbw.openDialog = function(vars) {
	var dialog = $.sbw.findNextAvailableDialog();
	var openCount = $.sbw.getNumberOfOpenDialogs();
	
	if (dialog==-1) {
		// could not find dialog, alert ( out of dialogs ) and return
		alert('The maximum number of allowable dialogs have been reached.');
		return;
	}
	
	var dialogConfig = $.sbw.dialogConfigs[dialog.attr('id')];
	if (vars.onClose) {
		dialogConfig.onClose = vars.onClose;
	} else {
		dialogConfig.onClose = null;
	}
	
	dialog.html('<table width="100%"  height="100%"><tr><td align="center" valign="middle" ><img src="'+$.sbw.defaultOptions.spinnerSrc+'" /></td></tr></table>');
	dialog.dialog('option', 'width', 700);
	dialog.dialog('option', 'height', 530);
	
	var p = [(openCount*50+50),50];
	dialog.dialog('option', 'position', p);
	
	dialog.dialog('option', 'resizable', false);
	
	dialog.dialog('option', 'title', vars.title+'<img src="/sbw/shared/images/stitchName.png" style="position: absolute; z-index: 9999999; margin-left: auto; margin-right: auto;"/>');
	dialog.dialog('option', 'zIndex', $.sbw.dialogZIndex++);
	
	dialog.dialog('open');
	
	var d = {
		dialogid: dialog.attr('id')
	};
	$.extend(d,vars.params);
	
	$.ajax({
		type: "POST",  
		url: vars.url, 
		data: d,
		success: function(data) { 
		dialog.html(data);
		},
		error: function(response) {
			alert('Sorry!  There was an error while attempting to retrieve the entry details.');
			dialog.dialog('close');
		} 	
	});
	
};

$.sbw.openUploadDialog = function(options,targetFolderPath,params) {
	var dialog = $('#sbw-dialog-upload');
	
	dialog.html('<table width="100%"  height="100%"><tr><td align="center" valign="middle" ><img src="'+$.sbw.defaultOptions.spinnerSrc+'" /></td></tr></table>');
	
	dialog.dialog('option', 'width', 450);
	dialog.dialog('option', 'height', 450);
	
	dialog.dialog('option', 'resizable', false);
	
	dialog.dialog('option', 'title', 'Upload File');
	dialog.dialog('option', 'zIndex', $.sbw.dialogZIndex++);
	
	//dialog.dialog('option', 'position', [$(window).height(),]);

	dialog.dialog('open');
	
	var d = {
			parentnodepath: targetFolderPath
	};
	$.extend(d,params);
	
	$.ajax({
		type: "POST",  
		url: '/sbw/app/editor/upload.jsp', 
		data: d,
		success: function(data) { 
			dialog.html(data);
		},
		error: function(response) {
			alert('Sorry!  There was an error.');
			dialog.dialog('close');
		} 	
	});
	
};

$.sbw.log = function log(o) {
	if (typeof(console)!='undefined') console.log(o);
};

$.sbw.dialogConfigs = [];

$.sbw.dialogConfig = function($dialog) {
	this.$dialog = $dialog;
	
	this.changed = false;
	
	 /* The default close action which should be set as the close when the frame loads */
	this._close = function() {
		if (!this.beforePanelUnload()) {
			this.$dialog.dialog('close');
		}
	};
	/* Should be replaced by the panel when it loads if any custom close callbacks are required */
	this.close = this._close;
	
	/* Return true to veto the action */
	this._beforePanelUnload = function() {
		return false;
	};
	
	/* Should be replace by the panel when it needs to perform a check before itself is unloaded */
	this.beforePanelUnload = this._beforePanelUnload;
	
	this.setLoading = function(flag) {
		if (flag) {
			this.$dialog.append('<div class="loading-overlay"><div style="position: absolute; left: 0px; top: 0px; opacity: 0.5; background-color: #FCFCFC; width: 100%; height: 100%;" /><table width="100%" height="100%" style="position: absolute; left: 0px; top: 0px; "><tr><td align="center" valign="middle" ><img src="'+$.sbw.defaultOptions.spinnerSrc+'" /></td></tr></table></div>')
		} else {
			this.$dialog.find('.loading-overlay').remove();
		}
	};
};


$(document).ready(function() {
	$('.sbw-widget').sbw();
	
	//$('body').append('<div id="sbw-site-editor-flap" class="sbw-site-editor-flap" style="cursor: pointer;" onclick="$.sbw.editSite();" title="Edit Site"><img src="/sbw/app/styles/default/welcomeFish.png" /></div>');
	
	for(var i = 1; i<10; i++) {
		$('body').append('<div id="sbw-panel-dialog-'+i+'"><div class="header">something</div></div>');
		
		var $dialog = $('#sbw-panel-dialog-'+i);
		$($dialog).dialog({ 
			autoOpen: false,
			modal: true, 
			width: '700',
			height: '530',
			minHeight: '630',
			zIndex: 0,
			dialogClass: 'flora',
			title: '',
			buttons: {
				
			},
			beforeClose: function(event, ui) {
				var $d = $(this);
				var dialogConfig = $.sbw.dialogConfigs[$d.attr('id')];
				if (dialogConfig.beforePanelUnload()) {
					return false;
				}
			},
			close: function() {
				var $d = $(this);
				var dialogConfig = $.sbw.dialogConfigs[$d.attr('id')];
				if (dialogConfig.onClose) {
					dialogConfig.onClose();
				}
			}
		});	
		
		$.sbw.dialogConfigs['sbw-panel-dialog-'+i] = new $.sbw.dialogConfig($dialog);
	}
	
	$('body').append('<div id="sbw-dialog-upload"></div></div>');
	$('#sbw-dialog-upload').dialog({ 
		autoOpen: false,
		modal: true, 
		dialogClass: 'flora upload',
		title: '',
		buttons: {
			
		},
		close: function() {
			$('#sbw-dialog-upload').empty;
		},
		open: function() {
		}
	});	
});






