/// <reference path="jquery.intellisense.js" />
/**
 * Cobalt Elements for jQuery
 * cobalt - the main cobalt initializer.
 *
 * 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.
 *
 */
$(document).ready(InitCobalt);

function InitCobalt()
{
	if (window._cobaltInitialized)
		return;
	else
		window._cobaltInitialized = true;

	if ($.fn.Flyout)
	{
		// Set up the hover images.
		$('img.ihover').hoverImage();
		$('[icobalt=CobaltControls.Controls.Flyout]').Flyout();
		$('[icobalt=CobaltControls.Controls.SideMenu][_flyout=true]').each(function(i){
			var menu = $(this);
			var maxlevels = $.toInt(menu.attr('_maxlevels'));
			menu.find('[_pageid]').Flyout({corner:$._DIR._UPPER_RIGHT,maxlevels:maxlevels});
		});
	}

	if ($.fn.calendar)
	{
		// Set up the calendar.
		$('input.calendar').calendar({onfocus:true});
		$('input.calendar2').calendar();
		$('input.calendarclock').calendar({clock:true,onfocus:true});
		$('input.clock').calendar({clock:true,onfocus:true,nodate:true});
	}

	if ($.fn.popup)
		// Set up any popup links.
		$('a[icobalt=CobaltControls.Controls.Popup]').popup();

	// Set up site search.
	$('[icobalt=CobaltControls.Controls.SiteSearch]').cobaltSiteSearch();

	// Reflect any images marked as such.
	if ($.fn.reflect)
		$('img.ireflect').reflect();

	// Set up any lightbox images.
	if ($.fn.lightbox)
		$('.ilightbox').lightbox();

	// And the data calendar.
	if ($.fn.datacalendar)
		$('[icobalt=CobaltControls.Controls.DataCalendar]').datacalendar();

	// Set up any cascading dropdowns.
	if ( !window._noflash ) {
		$("select[_cascade]").cascade();
	}

	// And the quicklinks.
	$('[icobalt=CobaltControls.Controls.QuickLinks]').each(function(i){
		var el = $(this);
		if (!el.is('select')) el = el.find('select');
		el.change(function(e){
			var href = $(this).val();
			if (href)
			{
				if (href.startsWith('http') || href.startsWith('/'))
					window.location.href = href;
				else
				{
					var root = $(document.body).attr('_root');
					window.location.href = root+href;
				}
			}
		});
	});

	// Flash movies get rendered after the images are downloaded.
	$.onImagesLoaded(SetupFlashMovies,10);
	$(window).unload(cleanupFlash);
}

// Setup all flash movies on the page.
function SetupFlashMovies()
{
	if (window._noflash)
		return;
	else
	{
		// Show the spotlight videos.
		$("div[icobalt='CobaltControls.Controls.Spotlight']").each(function(i){
			var div = $(this);
			var noplay = $.toBool(div.attr('_noplay'));
			if (!noplay)
				div.appendTo(document.body).css('display','block').cobaltFlash();
		});
	
		// We'll only automatically set up flash movies inside the form.  Wizard flash movies are handled individually.
		$('form div.buildflash').cobaltFlash();
		if ($.fn.scroller)
			// Activate any scrolling elements.
			$('div[icobalt=CobaltControls.Controls.ScrollingList]').scroller();
	}
}

// Clean up the crappy remove callback script when the page unloads.
function cleanupFlash()
{
	__flash__removeCallback = function(instance, name){
		if (instance != null && name != null)
			instance[name] = null;
	};
}

$.cobalt = $.cobalt || {};

// Setup a specific flash movie.
$.fn.cobaltFlash = function(options,reload)
{
	return this.each(function(i)
		{
			// If we're doing a reload of the flash movie, clear out any existing remnants.
			var el = $(this);
			if (reload)
			{
				el.empty();
			}
			
			if (el.children('object').length==0)
			{
				var movie,width,height,version,flashvars,attributes;
				
				// Set the default parameters.
				var params = {
					allowfullscreen:true,
					allowscriptaccess:'sameDomain',
					wmode:'transparent',
					pluginspage:'http://www.macromedia.com/go/getflashplayer'
				};
				if (options)
				{
					// Conver the options to SWFObject parameters.
					movie = options.swf;
					width = options.width;
					height = options.height;
					flashvars = {};
					if (options.params)
					{
						for (var p in options.params)
						{
							if (p=='flashvars')
								flashvars = options.params[p];
							else
								params[p] = options.params[p];
						}
					}
					if (options.id)
					{
						attributes = {};
						attributes.id = id;
					}
				}
				else
				{
					// Get the standard options.
					var movie = el.attr('_movie');
					var width = el.attr('_width');
					var height = el.attr('_height');
					var loop = $.toBool(el.attr('_loop'));
					var vars = el.attr('_flashvars');
					var id = el.attr('_id');
					version = el.attr('_version');

					// Make sure we have an id.
					if (!id)
						id = ('Player'+Math.random()).replace('.','');

					// We need to assign both the id and name for cross-platform support.
					attributes = {};
					attributes.id = id;
					attributes.name = id;

					// Add the loop
					params.loop = loop.toString();

					// Only override the default wmode if it is specifically set for opaque.
					if (el.attr('_wmode')=='opaque')
						params.wmode = 'opaque';

					// If we have flash variables.
					var flashvars = {};
					if (vars)
					{
						try
						{
							// Split the parameters and iterate through each one.
							var v = vars.split('&');
							for (var i=0;i<v.length;i++)
							{
								// Split the name/value pair and add each one as a named property.
								var pair = v[i].split('=');
								flashvars[pair[0]] = pair[1];
							}
						}
						catch(ex){ flashvars = {}; }
					}
				}

				if (movie)
				{
					// Create a container for the SWF movie inside the current element.
					var control = ('FlashSWF'+Math.random()).replace('.','');
					el.html('<div id="'+control+'"></div>');

					// Embed the movie.
					swfobject.embedSWF(movie, control, width, height, version||'9.0.0', "Shared/js/expressInstall.swf", flashvars, params, attributes, null, el[0].childNodes[0]);
				}
			}
		});
};

// Setup swf uploader
$.cobalt.swfUploader = function(el,url,options)
{
	if (!el || !url) return;

	// Configure the button.
	var btn = el.find('span.swfu_button');
	if (!btn.length) return;
	var id = ('swfub_'+Math.random()).replace(/\./g,'');
	btn.attr('id',id);

	var o = options||{};
	var swfu = new SWFUpload({
		// Backend Settings
		upload_url: url,
		post_params : {
			"ASPSESSID" : $(document.body).attr('_session'),
			"AUTHID" : $(document.body).attr('_auth')
		},

		// File Upload Settings
		file_size_limit : o.size||"256 KB",
		file_types : o.types||"*.jpg;*.jpeg;*.jpe;*.gif;*.png",
		file_types_description : o.typeDescription||"Images",
		file_upload_limit : o.limit||"1",    // Zero means unlimited

		// Alert the user when there is an error.
		file_queue_error_handler : function(file, errorCode, message) {
			switch (errorCode)
			{
				case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
					alert('File too large, maximum size is '+(o.limit||"256 KB"));
					break;
				case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
					if ((o.limit||"1")=="1")
						alert('Please upload one file at a time.');
					else
						alert('Too many files.');
					break;
				case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
					alert('The selected file is empty.');
					break;
				case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
					alert('Invalid file type.');
					break;
				default:
					alert(message||'The file could not be uploaded.  Tech services has been notified.');
					break;
			}
		},
		// Start the upload if files were selected.
		file_dialog_complete_handler : function(numFilesSelected, numFilesQueued) {
			try {
				if (numFilesQueued > 0) {
					this.startUpload();
				}
			} catch (ex) {
				this.debug(ex);
			}
		},
		// Update the progress bar.
		upload_progress_handler : function(file, bytesLoaded) {
			if (!this.customSettings.progress_bar)
			{
				this.customSettings.progress_bar = this.customSettings.upload_target.children('div.progressBar');
				this.customSettings.progress_status = this.customSettings.upload_target.children('div.progressStatus');
			}
			var w = parseInt(bytesLoaded / file.size) * 250;
			this.customSettings.progress_bar.css({width:w});
			this.customSettings.progress_status.html('Uploading - '+$.kbFormat(bytesLoaded)+' out of '+$.kbFormat(file.size));
		},
		// Any server-side error.
		upload_error_handler : function(file, errorCode, message) {
			switch (errorCode) {
				case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
				case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
				case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				default:
					alert(message);
					break;
			}
		},
		// After the file has successfully uploaded.
		upload_success_handler : function(file, serverData) {
			if (!this.customSettings.progress_status)
				this.customSettings.progress_status = this.customSettings.upload_target.children('div.progressStatus');
			this.customSettings.progress_status.html('Success - '+$.kbFormat(file.size));
		},
		// Once the upload is complete.
		upload_complete_handler : function(file) {
			/*  I want the next upload to continue automatically so I'll call startUpload here */
			if (this.getStats().files_queued > 0) {
				this.startUpload();
			}
			else if ($.isFunction(o.oncomplete))
			{
				// The file uploader replaces spaces with dashes, so make sure that updated filename is passed to the complete function.
				file.name = file.name.replace(/%20/g,'-').replace(/ /g,'-');
				o.oncomplete(this,file);
			}
		},

		// Button settings
		button_image_url : o.uploadBtn||"Shared/js/swfupload/uploadbtn.gif",
		button_placeholder_id : id,
		button_width: 79,
		button_height: 18,
		button_text_top_padding: 0,
		button_text_left_padding: 0,

		// Flash Settings
		flash_url : "Shared/js/swfupload/swfupload.swf",	// Relative to this file

		// Custom settings.
		custom_settings : {
			container : el,
			upload_target : el.find('div.progressContainer')
		},

		// Debug Settings
		debug: false
	});

	// Safe the swf uploader object.
	el.data('swfu',swfu);
};

// Cascade one dropdown to another.
$.fn.cascade = function() {
	return this.each(function(i){
		// Get the cascade property
		var input = $(this);
		var cascade = input.attr('_cascade');
		if ( cascade ) {
			// Find the cascading select.
			var child = $("form select[id$='_"+cascade+"']");

			// Build a list of child options.
			var items = [];
			child.children('option').each(function(i){
				var option = $(this);
				items.push({
					parent: option.attr('_parent'),
					value: option.attr('value'),
					label: option.html()
				});
			});
			child.data('items', items);

			// Bind the change event.
			input.data('cascade', child)
				.bind('change update', function(e){
					// Get the cascading child.
					var input = $(this);
					var child = input.data('cascade');
					var items = child.data('items');
					var parent = input.val();

					// Build out the matching items.
					var sb = [];
					for ( var i=0; i<items.length; i++ ){
						var item = items[i];
						if ( !item.parent || item.parent == parent ) {
							sb.push('<option value="');
							sb.push(item.value);
							sb.push('">');
							sb.push(item.label);
							sb.push('</option>');
						}
					}

					// Set them.
					var val = child.val();
					child.html(sb.join('')).val(val||'');
				})
				.trigger('update');
		}
	});
};


// Handle a site search control.
$.fn.cobaltSiteSearch = function()
{
	return this.each(function(i)
		{
			// Get the element and the main search properties.
			var el = $(this);
			var path = el.attr('_path');
			var limit = el.attr('_limit');
			var exclude = el.attr('_exclude');

			// Build a closure to redirect to the search page with the criteria.
			var input = el.is('input:text') ? el : el.find('input:text:first');
			var fn = function(input,path,limit,exclude){
				return function(e){
					var content = $.encode(input.val());
					var url = path + '?C='+content;
					if (limit) url += '&L='+limit;
					if (exclude) url += '&X='+exclude;
					input = null;
					path = null;
					limit = null;
					exclude = null;
					var root = $(document.body).attr('_root')||'/';
					window.location.href = root+url;
					return false;
				};
			}(input,path,limit,exclude);

			// Set the events.
			input.toggleValue();
			el.find('img,input:button,input:submit,input:image').click(fn);

			// If we have an autosuggest.
			if (el.attr('_autosuggest')=='true')
			{
				var success = function(input){
					return function(row){
						input.val(row[this.options.textField]);
						input.data('fire')();
						input = null;
						return false;
					};
				}(input);
				input.data('fire',fn).combobox({
					getResultsUrl:$.getAjaxUrl(window.location.href,{AutoSuggest:el.attr('id')}),
					textField:el.attr('_textfield'),
					onselect:success
				});
			}
			else
				input.onenter(fn);
		});
};


/**
 * Cobalt Elements for jQuery
 * simplelink - this is a simplified link creator.
 *
 * These methods are build on the jQuery and interface foundation to provider
 * client functionality to the Cobalt CMS system.
 *
 * Copyright (c) 2008 Scorpion Design, Inc.
 *
 */
(function($) {

	if (!$.cobalt.dialog) return;
	$.cobalt.simplelink = new $.cobalt.dialog();

	// Assign a global shortcut to this classalttagedit
	if (!window.$sl) { window.$sl = $.cobalt.simplelink; }

	// Initialize these static properties/methods.
	$.extend($.cobalt.simplelink, {
		title : 'ADD/EDIT LINK',
		contentHtml : '\
<table cellpadding="0" cellspacing="0" border="0" style="margin:4px;">\
	<tr class="nn_selectpage">\
		<td>&nbsp;Url:&nbsp;</td>\
		<td><input type="text" class="sl_href" style="width:315px;"/></td>\
	</tr>\
	<tr class="nn_selectpage">\
		<td>&nbsp;Name:&nbsp;</td>\
		<td><input type="text" class="sl_name" style="width:315px;"/></td>\
	</tr>\
	<tr class="nn_selectpage">\
		<td>&nbsp;</td>\
		<td><input type="checkbox" class="sl_popup" id="sl_popup_check"/>\
			<label for="sl_popup_check">Open in new window.</label>\
		</td>\
	</tr>\
</table>',
		width:380,

		// Element properties
		element : null,

		// Activate the template editor.
		activate : function(el,o)
			{
				if ($sl.isopen) return;

				// Assign the specific element to the link browser.
				$sl.element = (el ? (el.jquery ? el : $(el)) : null);
				if ($sl.element && !$sl.element.is('a'))
					$sl.element = null;
				$sl.open(o);
			},

		// Clear any contents prior to activating the dialog.
		clearContents : function()
			{
				var el = $sl.element;
				var o = this.options||{};
				var body = $(document.body);
				var base = body.attr('_base');

				// Get the href.
				var href = ((el&&el.attr('href'))||o.href)||'';
				var root = body.attr('_root');
				if (href.startsWith(base))
					href = href.substring(base.length);
				else if (href.startsWith(root))
					href = href.substring(root.length);

				// Get the link name.
				var name = (el&&el.html())||o.text;

				// Assign the values.
				$sl.href.val(href||'');
				$sl.name.val(name||'');
				$sl.popup[0].checked = (el&&el.attr('target')=='_blank')?true:false;
			},

		// Overload this function to initialize other elements of the dialog box.
		startDialog : function()
			{
				setTimeout(function(){
					$sl.href.focus();
				},0);
			},

		// Save the current link settings.
		select : function(e)
			{
				// Get the link properties.
				var link = {
					Path : $sl.href.val(),
					Text : $sl.name.val()
				};
				if ($sl.popup[0].checked)
					link.Target = '_blank';

				try
				{
					// If the onselect event is defined fire it.  If there is no event or the event returns anything except false, also handle the default.
					var result;
					if (!$.isFunction($sl.onselect) || (result=$sl.onselect($sl.element,link,null,$sl))!=false)
					{
						var el = result&&result.jquery?result:$sl.element;
						if (el)
						{
							// Assign the properties of the link directly.
							el.attr('href',link.Path||'');
							if (link.Target) el.attr('target',link.Target); else el.removeAttr('target');
							if (link.Text) el.html(link.Text);
						}
					}
				}
				catch(ex) {}

				// Close the browser.
				$sl.close();
				
				return false;
			},

		// Initialize the named anchor dialog for the first time.
		initContents : function(o)
			{
				if (!$sl.main) return;

				// Get the components.
				$sl.href = $sl.main.find('input.sl_href').onenter($sl.select);
				$sl.name = $sl.main.find('input.sl_name').onenter($sl.select);
				$sl.popup = $sl.main.find('input.sl_popup');
			}
	});
	
})(jQuery);

// When the Flash Text Editor is ready.
function fteReady(p)
{
	// Grab the swf.
	var swf = window.document[p.id];
	if (swf)
	{
		// Record a reference to the swf.
		var div = $(swf).parent('div');
		div.data('swf',swf);

		// If a swfready event is defined, fire it.
		div.trigger('swfready');
	}
}

// When the Flash Text Editor contents have been changed.
function fteChanged(p)
{
	// Grab the swf.
	var swf = window.document[p.id];
	if (swf)
	{
		// Fire the change event.
		var div = $(swf).parent('div');
		div.trigger('swfchange');
	}
}

// When the Flash Text Editor needs to be saved.
function fteSave(p)
{
	// Grab the swf.
	var swf = window.document[p.id];
	if (swf)
	{
		// Fire the change event.
		var div = $(swf).parent('div');
		div.trigger('swfsave');
	}
}