/// <reference path="jquery.intellisense.js"/>  
/**
 * Cobalt Elements for jQuery
 * dialog - this manages the dialog box popup
 *
 * These methods are build on the jQuery and interface foundation to provider
 * client functionality to the Cobalt CMS system.
 *
 * Copyright (c) 2007 Scorpion Design, Inc.
 *
 */
(function($) {

	// Create the cobalt namespace if it has not already been done.
	$.cobalt = $.cobalt || {};
	$.cobalt.dialog = function(){};

	// Assign a global shortcut to this class.
	if (!window.$dl) { window.$dl = $.cobalt.dialog; }

	// Initialize these static properties/methods.
	$.extend($.cobalt.dialog, {

		html : '\
<div class="pdialog">\
	<h1 class="pheader">\
		<span></span>\
		<img class="pclose" src="Shared/images/spacer.gif" width="20" height="20" alt="Close" title="Close" />\
	</h1>\
	<div class="pmain"></div>\
	<h2 class="pfooter">\
		<div class="pfooter2">\
			<img class="pcancel" src="Shared/images/spacer.gif"/>\
			<img class="psave" src="Shared/images/spacer.gif" />\
		</div>\
	</h2>\
</div>',

		dialogStack : [],
		top : null,

		// Sort the stack of dialog boxes by zIndex.
		sortStack : function()
			{
				if ($dl.dialogStack.length)
					$dl.dialogStack.sort($dl.sortDelegate);
			},

		// Handle the sorting of the dialog boxes by zIndex.
		sortDelegate : function(a,b)
			{
				var z1 = a.getZIndex();
				var z2 = b.getZIndex();
				
				if (z1 > z2)
					return 1;
				else if (z1 < z2)
					return -1;
				else
					return 0;
			},

		// Sort the stack by zIndex and return the last one.
		getTop : function()
			{
				if (!$dl.top && $dl.dialogStack.length)
				{
					$dl.sortStack();
					$dl.top = $dl.dialogStack[$dl.dialogStack.length-1];
				}
				
				return $dl.top;
			},

		// Do we have enough room for the dialog box?
		enoughRoom : function(wn,bx)
			{
				// If we don't have enought height.
				if (wn.height <= bx.height)
					return false;
				// If we don't have enough width.
				else if (wn.width <= bx.width)
					return false;

				// Otherwise we're good.
				return true;
			},

		// Activate the specified dialog.
		activate : function(d)
			{
				// Get the toolbar and window dimenstions.
				var tb = document.body.toolbar && document.body.toolbar.toolbar.absPosition();
				var wn = $(window).absPosition();
				if (tb)
				{
					wn.top += tb.height;
					wn.height -= tb.height;
				}

				var offset = $.extend({top:0,left:0},d.offset||{});
				var top = $dl.getTop();

				if (top && top.box)
				{
					// If we already have a dialog box, adjust the zIndex to display this one above it.
					d.setZIndex(top.getZIndex()+1);

					// Offset, so that both close buttons are visible.
					var pos = top.box.absPosition();
					offset.top += 50;
					offset.left += 75;
					d.box.relativePos(window,{center:true},null,offset,wn);
				}
				else
				{
					// Otherwise set it for 100 (the baseline).
					d.setZIndex(100);

					// Display the dialog box in the center of the viewport.
					d.box.relativePos(window,{center:true},null,offset,wn);
				}

				// Add it to the stack.
				$dl.dialogStack.push(d);
				$dl.top = d;
			},

		// Bring the specified dialog box to the top, unless it's disabled.
		bringToTop : function(d)
			{
				var top;;
				if (d && !d.disabled && d!=(top=$dl.getTop()))
				{
					d.setZIndex(top.getZIndex()+1);
					$dl.resetStack();
				}
			},

		// Reset the stack positions
		resetStack : function()
			{
				$dl.top = null;

				if ($dl.dialogStack.length)
				{
					$dl.sortStack();
					for (var i=0;i<$dl.dialogStack.length;i++)
						var d = $dl.dialogStack[i].setZIndex(100+i);
				}
			},

		// Remove the specified dialog box from the stack.
		deactivate : function(d)
			{
				// Hide the box.
				d.box.hide();

				// Kill any loading indicators.
				d.box.doneLoading();
				d.box.find('[isloading]').doneLoading();
				
				// Reset the stack.
				$dl.dialogStack.removeItem(d);
				$dl.top = null;
			}
	});

	// Extend the dialogbox prototype.
	$.extend($.cobalt.dialog.prototype, {

		// Template browser components.
		title : 'DIALOG BOX',
		box : false,
		main : false,
		contenthtml : false,
		disabled : false,

		// Properties
		width : 500,
		zIndex : 0,
		padding : 0,
		offset : null,

		// Events.
		onselect : false,
		oncancel : false,
		onclose : false,

		// Open the dialog browser, attached to a specific element.
		open : function(o)
			{
				// Don't open the same dialog twice.
				if (this.isopen)
				{
					$dl.bringToTop(this);
					return;
				}

				// Note the state of the dialog.
				this.isopen = true;

				// Ensure we have initialized the dialog (and don't pass an event reference).
				if (o&&o.stopPropagation) o = null;
				this.init(o);

				// Clear any contents.
				this.clearContents.apply(this,arguments);

				// If we've specified hiding the footer buttons, do so now.
				if (o&&o.hideFooter)
					this.footer.hide();
				else
					this.footer.show();

				// Display the dialog box in the appropriate position.
				$dl.activate(this);

				// Start the dialog box, passing the same arguments along.
				this.startDialog.apply(this,arguments);

			},

		// Overload this function to clear any contents prior to activating the dialog.
		clearContents : function()
			{
			},

		// Overload this function to initialize other elements of the dialog box.
		startDialog : function()
			{
			},

		// Get the zIndex position of the current dialog box.
		getZIndex : function()
			{
				if (this.box)
				{
					if (this.zIndex)
						return this.zIndex;
					else
					{
						this.zIndex = $.toInt(this.box.css('zIndex'));
						return this.zIndex;
					}
				}
			},

		// Set the zIndex position of the current dialog box.
		setZIndex : function(z)
			{
				if (this.box)
				{
					this.zIndex = z;
					this.box.css({zIndex:z});
				}
			},

		// Bring this dialog box to the top.
		bringToTop : function(e)
			{
				$dl.bringToTop($(this).data('dialog'));
			},

		// Disable the dialog box (without closing).
		disable : function(message)
			{
				if (this.isopen && !this.disabled)
				{
					this.disabled = true;
					this.box.loading(0,{message:message||''});
				}
			},

		// Re-enable the dialog box.
		enable : function()
			{
				this.disabled = false;
				this.box.doneLoading();
			},

		// Overload this function to handle saving/selecting/processing the results of the dialog box session.
		select : function(e)
			{
				var d = $(this).data('dialog')||this;
				if (!$.isFunction(d.onselect) || d.onselect(d)!=false)
					d.close();
			},

		// Cancel the dialog box.
		cancel : function(e)
			{
				var d = $(this).data('dialog')||this;
				if ($.isFunction(d.oncancel)) { d.oncancel(d); }
				d.close();
			},

		// Close the dialog box.
		close : function()
			{
				var d = $(this).data('dialog')||this;
				if ($.isFunction(d.onclose)) { d.onclose(d); }
				$dl.deactivate(d);

				// Note the state of the dialog.
				d.isopen = false;
			},

		// Initialize the image browser for the first time.
		init : function(o)
			{
				// Assign the options.
				this.options = o = $.extend({},o||{});
				this.onselect = o.onselect||this.onselect;
				this.oncancel = o.oncancel||this.oncancel;
				this.onclose = o.onclose||this.onclose;

				// If the dialog box html has already been defined, stop here.
				if (this.box) return;

				// Create the box
				this.box = $($dl.html).appendTo(document.body).css({width:this.width});
				this.header = this.box.children('h1.pheader');
				this.title = this.header.children('span').html(this.title);
				this.main = this.box.children('div.pmain');
				this.footer = this.box.children('h2.pfooter');

				// Assign the events.
				this.closebtn = this.box.find('img.pclose').click(this.cancel).data('dialog',this);
				this.savebtn = this.box.find('img.psave').click(this.select).data('dialog',this);
				this.cancelbtn = this.box.find('img.pcancel').click(this.cancel).data('dialog',this);

				// Make the dialog box draggable.
				this.box.bind('mousedown',this.bringToTop).data('dialog',this);
				this.header.hoverClass('pheadero').data('dialog',this);
				this.box.draggable({handle:this.header});

				// Initialize the contents of the dialog box.
				if (this.contentHtml)
				{
					this.main.append($.cobalt.sprites.fixHtml(this.contentHtml));
					this.initContents();
				}
				
				// Use absolute positioning for IE6 and smaller screens.
				if ($.browser.msie6 || $(window).height()<750)
					this.box.css({position:'absolute'});
			},

		initContents : function()
			{
			}

	});

	// Define the sprites
	$.cobalt.sprites = {

		r_img : /(<img[^>]*?src\s*=\s*['"])([^'">]+)(['"][^>]*>)/gi,
		r_path : /Shared\/images\/(\w+)\/(\w+).gif/i,
		r_class : /\bclass\s*=\s*(?:(['"])([\s\S]*?)\1|([^\s"'>]+))/gi,
		
		// Look for a matching sprite class based on the path of the image.
		getClass : function(path) {
		
			var m = $.cobalt.sprites.r_path.exec(path);
			if (m)
			{
				var folder = m[1].toLowerCase();
				var file = m[2].toLowerCase()+'gif';
				var category = $.cobalt.sprites[folder];
				var cls = category && category[file];
				return cls;
			}
			return null;
		
		},

		// Replace images with a associated sprite images.
		fixHtml : function(html) {

			return html.replace($.cobalt.sprites.r_img,$.cobalt.sprites.replaceImg);

		},

		// Replace a specific image.
		replaceImg : function(m,m1,m2,m3) {

			// Search for a matching sprite class.
			var cls = $.cobalt.sprites.getClass(m2);
			if (cls)
			{
				if (m.indexOf('class')>0)
				{
					var img = m1+'Shared/images/spacer.gif'+m3;
					return img.replace($.cobalt.sprites.r_class,'class="$2$3 isprite'+($.browser.msie6?'6':'')+' '+cls+'"');
				}
				else
					return m1+'Shared/images/spacer.gif" class="isprite'+($.browser.msie6?'6':'')+' '+cls+m3;
			}
			else
				return m;

		},

		lookup : {},

		admin : {
		
			addgif:'sp0_0',
			addgroupgif:'sp1_0',
			addusergif:'sp2_0',
			advancedgif:'sp3_0',
			advancedsettingsgif:'sp4_0',
			appwindowgif:'sp5_0',
			attachfilegif:'sp6_0',
			calculatorgif:'sp7_0',
			calendar_schedulegif:'sp8_0',
			cancelgif:'sp9_0',
			cancelvideogif:'sp10_0',
			choosecolorgif:'sp11_0',
			closeagif:'sp12_0',
			codegif:'sp13_0',
			colormangif:'sp14_0',
			conflictgif:'sp15_0',
			contentgif:'sp0_1',
			copygif:'sp1_1',
			copyfoldergif:'sp2_1',
			cssgif:'sp3_1',
			deletegif:'sp4_1',
			delete2gif:'sp5_1',
			delete3gif:'sp6_1',
			deletefoldergif:'sp7_1',
			deletegroupgif:'sp8_1',
			deletetablegif:'sp9_1',
			deleteusergif:'sp10_1',
			documentgif:'sp11_1',
			doubleleftarrowgif:'sp12_1',
			doublerightarrowgif:'sp13_1',
			downloaddocumentgif:'sp14_1',
			edit_redogif:'sp15_1',
			edit_undogif:'sp0_2',
			editgif:'sp1_2',
			editcodegif:'sp2_2',
			editgroupsgif:'sp3_2',
			editlinkgif:'sp4_2',
			editpagegif:'sp5_2',
			editusergif:'sp6_2',
			editusersgif:'sp7_2',
			emailsgif:'sp8_2',
			envelopegif:'sp9_2',
			exitgif:'sp10_2',
			file_delgif:'sp11_2',
			file_uploadgif:'sp12_2',
			flashmanagergif:'sp13_2',
			fldr_delgif:'sp14_2',
			fldr_newgif:'sp15_2',
			fldrgif:'sp0_3',
			fldragif:'sp1_3',
			fldrhgif:'sp2_3',
			gotoparentfoldergif:'sp3_3',
			groupsgif:'sp4_3',
			groups2gif:'sp5_3',
			helpgif:'sp6_3',
			hiddengif:'sp7_3',
			historygif:'sp8_3',
			htmlgif:'sp9_3',
			html2gif:'sp10_3',
			hyperlinkgif:'sp11_3',
			imagesgif:'sp12_3',
			inserthyperlinkgif:'sp13_3',
			insertpicturegif:'sp14_3',
			javascriptgif:'sp15_3',
			layoutgif:'sp0_4',
			listgif:'sp1_4',
			livegif:'sp2_4',
			lockedgif:'sp3_4',
			mailsettingsgif:'sp4_4',
			managergif:'sp5_4',
			menugif:'sp6_4',
			newdocumentgif:'sp7_4',
			newfoldergif:'sp8_4',
			newmessagegif:'sp9_4',
			notegif:'sp10_4',
			novisiblegif:'sp11_4',
			opengif:'sp12_4',
			openfoldergif:'sp13_4',
			pagesgif:'sp14_4',
			pausegif:'sp15_4',
			pengif:'sp0_5',
			playgif:'sp1_5',
			previewgif:'sp2_5',
			removegif:'sp3_5',
			removepagegif:'sp4_5',
			savegif:'sp5_5',
			save2gif:'sp6_5',
			save3gif:'sp7_5',
			schedulergif:'sp8_5',
			searchgif:'sp9_5',
			sendgif:'sp10_5',
			sendbackwardgif:'sp11_5',
			sharemanagergif:'sp12_5',
			showallcommentsgif:'sp13_5',
			swfgif:'sp14_5',
			switchgif:'sp15_5',
			systemgif:'sp0_6',
			system2gif:'sp1_6',
			tablegif:'sp2_6',
			textboxgif:'sp3_6',
			textbox2gif:'sp4_6',
			thumbgif:'sp5_6',
			trashgif:'sp6_6',
			usergif:'sp7_6',
			user2gif:'sp8_6',
			usersgif:'sp9_6',
			viewlistgif:'sp10_6',
			warninggif:'sp11_6',
			webgif:'sp12_6',
			zoomgif:'sp13_6',
			podcastgif:'sp6_15',
			printgif:'sp14_15',
			stopgif:'sp2_16'

		},

		modules : {

			accountgif:'sp14_6',
			activategif:'sp15_6',
			adminlogingif:'sp0_7',
			appointmentgif:'sp1_7',
			billinggif:'sp2_7',
			billpaygif:'sp3_7',
			boardgif:'sp4_7',
			boardportalgif:'sp5_7',
			callgif:'sp6_7',
			coinsgif:'sp7_7',
			confemailgif:'sp8_7',
			contactgif:'sp9_7',
			creditcardgif:'sp10_7',
			directoriesgif:'sp11_7',
			disneygif:'sp12_7',
			donategif:'sp13_7',
			employmentgif:'sp14_7',
			eventsgif:'sp15_7',
			events2gif:'sp0_8',
			events3gif:'sp1_8',
			events4gif:'sp2_8',
			expertgif:'sp3_8',
			faqgif:'sp4_8',
			fashiongif:'sp5_8',
			flyoutgif:'sp6_8',
			formgif:'sp7_8',
			giftshopgif:'sp8_8',
			golfgif:'sp9_8',
			imagegif:'sp10_8',
			leadsgif:'sp11_8',
			managegif:'sp12_8',
			membershipsgif:'sp13_8',
			newslettergif:'sp14_8',
			newslettersgif:'sp15_8',
			nurserygif:'sp0_9',
			ordergif:'sp1_9',
			order2gif:'sp2_9',
			physiciangif:'sp3_9',
			practiceareasgif:'sp4_9',
			prereggif:'sp5_9',
			pressgif:'sp6_9',
			productsgif:'sp7_9',
			profilesgif:'sp8_9',
			scholargif:'sp9_9',
			servicesgif:'sp10_9',
			sitemapgif:'sp11_9',
			sitesearchgif:'sp12_9',
			spotlightgif:'sp13_9',
			statsgif:'sp14_9',
			transactionsgif:'sp15_9',
			trialsgif:'sp0_10',
			videogif:'sp1_10',
			wizardgif:'sp2_10',
			databasegif:'sp4_13',
			fieldgif:'sp5_13',
			bannergif:'sp7_15',
			ipodgif:'sp11_15',
			filmgif:'sp12_15',
			atomgif:'sp13_15',
			blogsgif:'sp15_15',
			call2gif:'sp0_16',
			showcasegif:'sp1_16'

		},

		page : {

			cancelbranchgif:'sp3_10',
			deletepagegif:'sp4_10',
			editlinkgif:'sp5_10',
			hidepagegif:'sp6_10',
			makebranchgif:'sp7_10',
			navigategif:'sp8_10',
			newchildgif:'sp9_10',
			newlinkgif:'sp10_10',
			newmodulegif:'sp11_10',
			newpagegif:'sp12_10',
			pagenotsslgif:'sp13_10',
			pagesecuritygif:'sp14_10',
			pagesslgif:'sp15_10',
			renamepagegif:'sp0_11',
			seogif:'sp1_11',
			showpagegif:'sp2_11'

		},
		
		tbox : {

			delrowgif:'sp3_11',
			exportgif:'sp4_11',
			importgif:'sp5_11',
			joincellgif:'sp6_11',
			moverowgif:'sp7_11',
			redogif:'sp8_11',
			resettblgif:'sp9_11',
			resizetblgif:'sp10_11',
			selectgif:'sp11_11',
			splitcellgif:'sp12_11',
			undogif:'sp13_11',
			gridgif:'sp14_11',
			aleftgif:'sp1_13',
			arightgif:'sp2_13',
			acentergif:'sp3_13',
			datalistgif:'sp7_13',
			dataitemgif:'sp8_13',
			searchgridgif:'sp9_13',
			dataformgif:'sp10_13',
			filtergif:'sp11_13',
			movecolgif:'sp12_13',
			delcolgif:'sp13_13',
			checkboxgif:'sp14_13',
			textboxgif:'sp15_13',
			buttongif:'sp0_14',
			passwordboxgif:'sp1_14',
			calendargif:'sp2_14',
			comboboxgif:'sp3_14',
			phonegif:'sp4_14',
			templatesgif:'sp5_14',
			headergif:'sp6_14',
			itemgif:'sp7_14',
			altitemgif:'sp8_14',
			footergif:'sp9_14',
			titlegif:'sp10_14',
			reqgif:'sp11_14',
			reqrangegif:'sp12_14',
			reqregexgif:'sp13_14',
			reqcomparegif:'sp14_14',
			reqcustomgif:'sp15_14',
			designgif:'sp0_15',
			codegif:'sp1_15',
			toolgif:'sp2_15',
			resizepicgif:'sp3_15',
			frame_imagegif:'sp4_15',
			menugif:'sp9_15',
			bargif:'sp10_15',
			mapgif:'sp3_16'

		},

		tree : {

			admingif:'sp15_11',
			branchgif:'sp0_12',
			filegif:'sp1_12',
			foldergif:'sp2_12',
			hpagegif:'sp3_12',
			linkgif:'sp4_12',
			modulegif:'sp5_12',
			pagegif:'sp6_12',
			poundgif:'sp7_12',
			rssgif:'sp6_13',
			audiogif:'sp5_15'

		},

		flags : {

			chinesegif:'sp8_12',
			englishgif:'sp9_12',
			frenchgif:'sp10_12',
			germangif:'sp11_12',
			hebrewgif:'sp12_12',
			italiangif:'sp13_12',
			japanesegif:'sp14_12',
			koreangif:'sp15_12',
			spanishgif:'sp0_13'

		}

	};

	// Generate a reverse lookup for the images.
	$.each(['admin','modules','page','tbox','tree','flags'],function(i){

		for (var p in $.cobalt.sprites[this])
		{
			var cls = $.cobalt.sprites[this][p];
			$.cobalt.sprites.lookup[cls] = 'shared/images/'+this+'/'+p.substr(0,p.length-3)+'.gif';
		}
		
	});

	// Preload these images.
	$.preload('Shared/images/titlebg2.gif');
	$.preload('Shared/images/Sprites.png');
	$.preload('Shared/images/tbox/cmsedit.png');
	
})(jQuery);
