/* BEGIN: вывод медиаобъектов */
function eau_object_window_is_accessible (hWnd) {
	var status = true;
	try {
		if (!hWnd || hWnd.closed || typeof hWnd.closed == 'undefined') {
			status = false;
		} else if (hWnd.outerHeight == 0) {
			status = false;
		}
	} catch (e) {
		status = false;
	}
	return status;
}
function eau_object_resize_window (hWnd, width, height) {
	try {
		if (_.isNumber(hWnd.outerWidth)) {
			hWnd.outerWidth = width;
			hWnd.outerHeight = height;
		} else if (window.resizeTo) {
			hWnd.resizeTo(width, height);
		} 
	} catch (error) {}
}
function eau_object_focus_window (hWnd) {
	try {
		if (window.focus) {
			hWnd.focus();
		}
	} catch (error) {}
}
function eau_object_update_window (hWnd, url, width, height) {
	eau_object_resize_window(hWnd, width, height);
	hWnd.document.location = url;
	hWnd.opener = window;
	eau_object_focus_window(hWnd);
}
function object_new_window(width, height, id) {
	var currentWindows
	    , windowToUpdate
	    , opts
	    , url = 'media-object.htm?id='+ encodeURIComponent(id);

	opts = [
		'width      = '+ width
		, 'height     = '+ height
		, 'top        = '+ (screen.availHeight - height) / 2
		, 'left       = '+ (screen.availWidth  - width) / 2
		, 'location   = 0'
		, 'menubar    = 0'
		, 'status     = 0'
		, 'resizable  = 1'
	].join(',');

	currentWindows = _.select(arguments.callee.cws || [], function (wnd) {
		return eau_object_window_is_accessible(wnd.wnd);
	});

	windowToUpdate = (eAu.UserOptions && eAu.UserOptions.useSinglePopup)
		? _.last(currentWindows)
		: _.detect(currentWindows, function (wnd) { return wnd.url == url; });

	if (windowToUpdate) {
		eau_object_update_window(windowToUpdate.wnd, url, width, height);
		windowToUpdate.url = url;
	} else {
		currentWindows.push({
			wnd: window.open(url, "_blank", opts),
			url: url
		});
	}

	arguments.callee.cws = currentWindows;

	return windowToUpdate ? windowToUpdate.wnd : _.last(currentWindows).wnd;
}

$window.bind('unload', function () {
	if (!object_new_window.cws) { return; }
	_.each(object_new_window.cws, function (wnd) {
		if (eau_object_window_is_accessible(wnd.wnd)) {
			try {
				wnd.wnd.close();
			} catch (error) {}
		}
	});
});

function object_write_to_hash(element, textContent, title, options) {
	options = _.extend({
		width: parseInt(_Xml.attr(element, 'width')),
		height: parseInt(_Xml.attr(element, 'height'))
	}, options || {});
	var alignCenter = (!options.width || !options.height) && options.align == 'center';
	options.width  = !options.width ? 800 : (options.width > screen.availWidth - 20 ? screen.availWidth - 20 : options.width);
	options.height = !options.height ? 600 : (options.height > screen.availHeight - 100 ? screen.availHeight - 100 : options.height);

	if (alignCenter) {
		textContent = '<table class="tbl-wrapper"><tr><td class="td-tbl-wrapper">'+ textContent +'</td></tr></table>';
	}

	var AC = object_write_to_window;
	if (!AC.objectsHash) {
		AC.objectsHash = {};
	}
	AC.objectsHash[_Xml.id(element)] = {
		title: title,
		text: textContent
	};
	
	return options;
}

function object_write_to_window(element, textContent, title, options) {
	options = object_write_to_hash(element, textContent, title, options);

	object_new_window(options.width, options.height, _Xml.id(element));
}

function object_image(element) {
	return [
		element,
		'<div><img src="'+ _Xml.attr(element, 'src') +'" galleryimg="no" /></div>',
		eAu.String.trim(_Xml.attr(element, 'title')||''),
		{ align: 'center' }
	];
}
function object_generate_id(element) {
	return _Xml.safeId(element);
}
function object_flash(element) {
	var id = _Xml.id(element);

	var textContent = [
		'<div id="'+ object_generate_id(element) +'"/>',
		'<img src="images/loaded.gif" onload="',
		"	this.parentNode.removeChild(this);",
		"	embedFlashMovie('"+ id +"');",
		'" />'
	].join('\n');

	return [
		element,
		textContent,
		eAu.String.trim(_Xml.attr(element, 'title')||'')
	];
}

// This will be triggered before eAu:content:afterchange:animation-complete handler
// in this file
$window.bind('eAu:content:link:processed eAu:content:beforechange', function (event, data) {
	$('#cont').removeClass('eAu-fs-content');
});
$window.bind('eAu:content:link:processed eAu:content:afterchange:animation-complete', function (event, data) {
	var nodes   = []
	  , nodeIds = [];

	if (event.type == 'eAu:content:link:processed') {
		nodes   = _Xml.select(data.xmlnode, 'ancestor-or-self::object');
		nodeIds = _.map(nodes, function (node) { return _Xml.id(node); });
	}

	$('div.flash-media-object-placeholder').each(function () {
		var $this = $(this)
		  , options
		  , element;
		
		if (!$this.data('flash-is-loading') && ( ~_.indexOf(nodeIds, $this.data('dbid')) || event.type == 'eAu:content:afterchange:animation-complete' )) {
			$this.data('flash-is-loading', 'yes');
			if (event.type == 'eAu:content:afterchange:animation-complete') {
				element = _Xml.$(head, $this.data('dbid'));
			} else {
				element = nodes[ _.indexOf(nodeIds, $this.data('dbid')) ];
			}
			options = {
				width: $this.data('width'),
				height: $this.data('height')
			};
			if ($this.data('type') == 'test') {
				options.params = {
					allowScriptAccess: 'always',
					scale: 'noScale'
				};
				options.flashvars = {
					fonload: "question_exercise_set_flash_loaded('"+ $this.data('dbid') +"')"
				};
			} else {
				if ($this.is('.eAu-object-full-screen')) {
					$('#cont').addClass('eAu-fs-content');
					$this.parentsUntil('#cont').addClass('eAu-fs-content')
					options = {
						width: '100%',
						height: '100%'
					};
				}
			}
			embedFlashMovie(element, options);
		}
	});
	$('div.media-object-placeholder').each(function () {
		var $this = $(this)
		  , options
		  , url
		  , element;

		if (!$this.data('mediaobject-is-loading') && ( ~_.indexOf(nodeIds, $this.data('dbid')) || event.type == 'eAu:content:afterchange:animation-complete' )) {
			$this.data('mediaobject-is-loading', 'yes');
			if (event.type == 'eAu:content:afterchange:animation-complete') {
				element = _Xml.$(head, $this.data('dbid'));
			} else {
				element = nodes[ _.indexOf(nodeIds, $this.data('dbid')) ];
			}
			if ($this.is('.eAu-object-full-screen')) {
				$('#cont').addClass('eAu-fs-content');
				$this.parentsUntil('#cont').addClass('eAu-fs-content')
			}
			object_object(element, $this, 'writeToHashOnly');
			if (_Xml.hasAttr(element, 'gdocs-src')) {
				$this.find('iframe').attr('src', _Xml.attr(element, 'gdocs-src'));
			} else {
				$this.find('iframe').attr('src', 'media-object.htm?embed=yes&id='+ encodeURIComponent($this.data('dbid')));
			}
		}
	});
});

function get_flash_options_for_element(element, options) {
	var objectType = _Xml.attr(element, 'type')
	  , path = window.location.pathname
	  , mediafilename
	  , base
	  , isLocal = /^file/i.test('' + window.location.protocol);
	
	options || (options = {});
	var opts = _.extend({
		width:      (parseInt(_Xml.attr(element, 'width'))  || 800).toString(),
		height:     (parseInt(_Xml.attr(element, 'height')) || 600).toString(),
		flashvars:  _.extend({}, options.flashvars || {}),
		params:     {},
		attributes: _.extend({}, options.attributes || {}),
		src:        _Xml.attr(element, 'src'),
		safeId:     object_generate_id(element),
		minVersion: '10.0.0',
		install:    './scripts/lib/external/expressInstall.swf'
	}, options || {});

	opts.params = _.extend({
		base: _Xml.attr(element, 'base-src'),
		wmode: _Xml.parentOrSelf(element, 'question-exercise') ? 'window' : 'opaque',
		menu: 'false'
	}, options.params || {});

	if (/^(video|sound)$/.test(objectType)) {
		mediafilename = opts.src;
		try { mediafilename = decodeURI(mediafilename); } catch (e) {}
		try { path = decodeURI(path); } catch (e) {}
		base = window.location.protocol + '//' + window.location.host + path.replace(/[^\/]*$/, '');
		if (isLocal && objectType == 'sound')
			base = '';
		opts.src = 'shared/strobe/strobe_personal_'+ (isLocal ? 'local' : 'net') +'.swf';
		opts.params.allowFullScreen = objectType == 'video' ? "true" : "false";
		if (objectType == 'sound') opts.height = 35 + 97;
		_.extend(opts.flashvars, {
			src: encodeURIComponent(encodeURI(base + mediafilename.replace(/^\.\//, ''))),
			autoPlay: _Xml.attr(element, 'autoplay') == 'true' ? 'true' : 'false',
			playButtonOverlay: objectType == 'video',
			backgroundColor: '0x000000',
			streamType: 'recorded',
			controlBarAutoHide: 'false',
			controlBarPosition: 'bottom',
			playerMode: objectType,
			playCount:  parseInt(_Xml.attr(element, 'repeat'), 10) || 0,
			playItemId: opts.safeId
		});
		opts.params.base = encodeURI(base);
	}

	return opts;
}
function question_exercise_set_flash_loaded(id) {
	var AC = arguments.callee;
	if (!AC.flashes) {
		AC.flashes = [];
	}
	AC.flashes.push(id);
}
function question_exercise_get_flash_loaded(id) {
	return _.indexOf(question_exercise_set_flash_loaded.flashes || [], id) != -1;
}
function embedFlashMovie(id, options) {
	var objectNode = typeof id == 'string' ? _Xml.$(head, id) : id
	  , path = window.location.pathname
	  , mediafilename
	  , objectType;
	
	if (!objectNode) return;

	options = get_flash_options_for_element(objectNode, options);
	$('#'+ options.safeId).closest('.eAu-object-alignment').height(options.height);

	swfobject.embedSWF(
		options.src,
		options.safeId,
		options.width,
		options.height,
		options.minVersion,
		options.install,
		options.flashvars,
		options.params,
		options.attributes
	);

	if (!unloadFlashObjects.fl) {
		unloadFlashObjects.fl = [];
	}
	unloadFlashObjects.fl.push(options.safeId);

	return options.safeId;
}
function unloadFlashObjects() {
	question_exercise_set_flash_loaded.flashes = null;
	var AC = arguments.callee;
	if (!AC.fl) {
		AC.fl = [];
	}
	for (var i = 0, length = AC.fl.length; i < length; ++i) {
		try { swfobject.removeSWF(AC.fl[i]); } catch (e) {}
	}
	AC.fl = [];
}

$window.bind('eAu:content:beforechange unload', function (event, data) {
	unloadFlashObjects();
});

jQuery(function ($) {
	$(document.body)
		.append('<div class="content" id="eAu-fitting-room" style="overflow: hidden; margin: 0; position: absolute; top: -10000px; left: 10000px; max-height: 100%; max-width: 100%; width: 50%; padding: 1px;"><div style="padding: 1px;"></div></div>')
});

function show_in_tooltip (element, text, context) {
	new eAu.Tooltip('<h2 class="eAu">'+ eAu.String.trim(_Xml.attr(element, 'title')||'') +'</h2>' + text, { target: context });
}

function object_text(element, context) {
	_Xml.fetch(element);

	var options = { width: 800, height: 600 };
	
	$('#eAu-fitting-room > div')
		.html('<div style="margin: 15px;">'+ text_transform(_Xml.text(element)) +'</div>');

	for (var i = 10; i <= 100; i += 10) {
		$('#eAu-fitting-room').css({
			width: String(i) + '%',
			height: String(i) + '%'
		});
		if ($('#eAu-fitting-room > div').outerWidth() <= $('#eAu-fitting-room').width() && $('#eAu-fitting-room > div').outerHeight() <= $('#eAu-fitting-room').height()) {
			options.width = $('#eAu-fitting-room > div').outerWidth();
			options.height = $('#eAu-fitting-room > div').outerHeight();
			break;
		}
	}
	//options.width = $('#eAu-fitting-room > div').outerWidth();
	//options.height = $('#eAu-fitting-room > div').outerHeight();

	return [
		element,
		'<div style="margin: 15px;">'+ text_transform(_Xml.text(element)) +'</div>',
		_Xml.title(element),
		options
	];
}
function object_sound(element) {
	_Xml.attr(element, 'height', 35 + 97);
	return object_video(element);
}
function object_video(element) {
	var options = get_flash_options_for_element(element);
	return [
		element,
		'<div style="background: white;"><div id="'+ options.safeId +'" data-dbid="'+ _Xml.id(element) +'" data-width="'+ options.width +'" data-height="'+ options.height +'" data-type="" class="flash-media-object-placeholder"></div>',
		eAu.String.trim(_Xml.attr(element, 'title')||'')
	];
}
function object_object (element, link, writeToHashOnly) {
	var functionName
	  , arguments;
	
	functionName = /^text$/.test(_Xml.name(element)) ? 'text' : _Xml.attr(element, 'type');
	if (_.isFunction(window['object_' + functionName])) {
		arguments = window['object_' + functionName](element, link);
	} else {
		arguments = object_other(element);
	}
	if (writeToHashOnly == 'writeToHashOnly') {
		object_write_to_hash.apply(null, arguments)
	} else {
		object_write_to_window.apply(null, arguments)
	}
}
function object_other (element) {
	var src = _Xml.attr(element, 'src');
	var id = object_generate_id(element);

	if (_Xml.attr(element, 'eAu-supported-extension') === 'false') {
		src = 'not-supported-extension.htm?'+ eAu.toQueryString({
			extension: _Xml.attr(element, 'eAu-filename-extension'),
			filename: src
		});
	}

	return [
		element,
		'<div class="media-object-placeholder" id="'+ id +'"><iframe src="'+ src +'" id="iframe-'+ id +'" /></div>',
		eAu.String.trim(_Xml.attr(element, 'title')||'')
	];
}

function glossary_text(id, context) {
	if (document.getElementById('eAu-glossary-item-'+id)) { return; }
	if (_.isUndefined(getGlossary.Entries)) { return; }

	var index = getGlossary.EntriesHash[id];
	if (_.isUndefined(getGlossary.Entries[index].text)) {
		var element = _Xml.$(head, id);
		_Xml.fetch(element);
		getGlossary.Entries[index].text = '<div class="eAu-glossary-item-fieldset-wrapper">' + text_transform(_Xml.text(element)) + '</div>';
	}
	var el = document.createElement('div');
	el.className = 'eAu-glossary-item-description';
	el.id = 'eAu-glossary-item-'+id;
	$(el).html(getGlossary.Entries[index].text);
	context.parentNode.appendChild(el);
	$(context).replaceWith('<h2 class="eAu">'+ $(context).html() +'</h2>');
}
/* END: вывод медиаобъектов */
