// VML detection function
function supportsVML() {
	if (typeof supportsVML.supported === "undefined") {
		var a = document.body.appendChild(document.createElement('div'));
		a.innerHTML = '<v:shape id="vml_flag1" adj="1" />';
		var b = a.firstChild;
		b.style.behavior = "url(#default#VML)";
		supportsVML.supported = b ? typeof b.adj === "object": true;
		a.parentNode.removeChild(a);
	}
		return supportsVML.supported;
}

// SVG detection function
function supportsSVG() {
	return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
}

// Get flash version
function getFlashVersion(){
  // ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');

			try { axo.AllowScriptAccess = 'always'; }
			catch(e) { return '6,0,0'; }
		} catch(e) {}

		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g , ',').match(/^,?(.+),?$/)[1];

		// other browsers
	} catch(e) {
		try {
			if ( navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin ) {
			return ( navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"] ).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}
	}
	return '0,0,0';
}


/*
 * jQuery UI 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
jQuery.ui || (function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {
	version: "1.7.2",
	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function(module, option, set) {
			var i = 0;
			var proto = $.ui[module].prototype;
			for(i = 0; i < set.length; i++) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			var i = 0;
			if(!set || !instance.element[0].parentNode) { return; }

			for (i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		return document.compareDocumentPosition
			? a.compareDocumentPosition(b) & 16
			: a !== b && a.contains(b);
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') === 'hidden') { return false; }

		var scroll = (a && a === 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({
	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {
		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	}
});


//Additional selectors
$.extend($.expr[':'], {
	data: function(elem, i, match) {
		return !!$.data(elem, match[3]);
	},

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
			// the element and all of its ancestors must be visible
			// the browser may report that the area is hidden
			&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options))._init());

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.namespace = namespace;
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				if (event.target == element) {
					return self._setData(key, value);
				}
			})
			.bind('getData.' + name, function(event, key) {
				if (event.target == element) {
					return self._getData(key);
				}
			})
			.bind('remove', function() {
				return self.destroy();
			});
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element
				[value ? 'addClass' : 'removeClass'](
					this.widgetBaseClass + '-disabled' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var callback = this.options[type],
			eventName = (type == this.widgetEventPrefix
				? type : this.widgetEventPrefix + type);

		event = $.Event(event);
		event.type = eventName;

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if (event.originalEvent) {
			for (var i = $.event.props.length, prop; i;) {
				prop = $.event.props[--i];
				event[prop] = event.originalEvent[prop];
			}
		}

		this.element.trigger(event, data);

		return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
			|| event.isDefaultPrevented());
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);

/*
 * jQuery UI Tabs 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.tabs", {

	_init: function() {
		if (this.options.deselectable !== undefined) {
			this.options.collapsible = this.options.deselectable;
		}
		this._tabify(true);
	},

	_setData: function(key, value) {
		if (key == 'selected') {
			if (this.options.collapsible && value == this.options.selected) {
				return;
			}
			this.select(value);
		}
		else {
			this.options[key] = value;
			if (key == 'deselectable') {
				this.options.collapsible = value;
			}
			this._tabify();
		}
	},

	_tabId: function(a) {
		return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '') ||
			this.options.idPrefix + $.data(a);
	},

	_sanitizeSelector: function(hash) {
		return hash.replace(/:/g, '\\:'); // we need this because an id may contain a ":"
	},

	_cookie: function() {
		var cookie = this.cookie || (this.cookie = this.options.cookie.name || 'ui-tabs-' + $.data(this.list[0]));
		return $.cookie.apply(null, [cookie].concat($.makeArray(arguments)));
	},

	_ui: function(tab, panel) {
		return {
			tab: tab,
			panel: panel,
			index: this.anchors.index(tab)
		};
	},

	_cleanup: function() {
		// restore all former loading tabs labels
		this.lis.filter('.ui-state-processing').removeClass('ui-state-processing')
				.find('span:data(label.tabs)')
				.each(function() {
					var el = $(this);
					el.html(el.data('label.tabs')).removeData('label.tabs');
				});
	},

	_tabify: function(init) {

		this.list = this.element.children('ul:first');
		this.lis = $('li:has(a[href])', this.list);
		this.anchors = this.lis.map(function() { return $('a', this)[0]; });
		this.panels = $([]);

		var self = this, o = this.options;

		var fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash
		this.anchors.each(function(i, a) {
			var href = $(a).attr('href');

			// For dynamically created HTML that contains a hash as href IE < 8 expands
			// such href to the full page url with hash and then misinterprets tab as ajax.
			// Same consideration applies for an added tab with a fragment identifier
			// since a[href=#fragment-identifier] does unexpectedly not match.
			// Thus normalize href attribute...
			var hrefBase = href.split('#')[0], baseEl;
			if (hrefBase && (hrefBase === location.toString().split('#')[0] ||
					(baseEl = $('base')[0]) && hrefBase === baseEl.href)) {
				href = a.hash;
				a.href = href;
			}

			// inline tab
			if (fragmentId.test(href)) {
				self.panels = self.panels.add(self._sanitizeSelector(href));
			}

			// remote tab
			else if (href != '#') { // prevent loading the page itself if href is just "#"
				$.data(a, 'href.tabs', href); // required for restore on destroy

				// TODO until #3808 is fixed strip fragment identifier from url
				// (IE fails to load from such url)
				$.data(a, 'load.tabs', href.replace(/#.*$/, '')); // mutable data

				var id = self._tabId(a);
				a.href = '#' + id;
				var $panel = $('#' + id);
				if (!$panel.length) {
					$panel = $(o.panelTemplate).attr('id', id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom')
						.insertAfter(self.panels[i - 1] || self.list);
					$panel.data('destroy.tabs', true);
				}
				self.panels = self.panels.add($panel);
			}

			// invalid tab href
			else {
				o.disabled.push(i);
			}
		});

		// initialization from scratch
		if (init) {

			// attach necessary classes for styling
			this.element.addClass('ui-tabs ui-widget ui-widget-content ui-corner-all');
			this.list.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
			this.lis.addClass('ui-state-default ui-corner-top');
			this.panels.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom');

			// Selected tab
			// use "selected" option or try to retrieve:
			// 1. from fragment identifier in url
			// 2. from cookie
			// 3. from selected class attribute on <li>
			if (o.selected === undefined) {
				if (location.hash) {
					this.anchors.each(function(i, a) {
						if (a.hash == location.hash) {
							o.selected = i;
							return false; // break
						}
					});
				}
				if (typeof o.selected != 'number' && o.cookie) {
					o.selected = parseInt(self._cookie(), 10);
				}
				if (typeof o.selected != 'number' && this.lis.filter('.ui-tabs-selected').length) {
					o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
				}
				o.selected = o.selected || 0;
			}
			else if (o.selected === null) { // usage of null is deprecated, TODO remove in next release
				o.selected = -1;
			}

			// sanity check - default to first tab...
			o.selected = ((o.selected >= 0 && this.anchors[o.selected]) || o.selected < 0) ? o.selected : 0;

			// Take disabling tabs via class attribute from HTML
			// into account and update option properly.
			// A selected tab cannot become disabled.
			o.disabled = $.unique(o.disabled.concat(
				$.map(this.lis.filter('.ui-state-disabled'),
					function(n, i) { return self.lis.index(n); } )
			)).sort();

			if ($.inArray(o.selected, o.disabled) != -1) {
				o.disabled.splice($.inArray(o.selected, o.disabled), 1);
			}

			// highlight selected tab
			this.panels.addClass('ui-tabs-hide');
			this.lis.removeClass('ui-tabs-selected ui-state-active');
			if (o.selected >= 0 && this.anchors.length) { // check for length avoids error when initializing empty list
				this.panels.eq(o.selected).removeClass('ui-tabs-hide');
				this.lis.eq(o.selected).addClass('ui-tabs-selected ui-state-active');

				// seems to be expected behavior that the show callback is fired
				self.element.queue("tabs", function() {
					self._trigger('show', null, self._ui(self.anchors[o.selected], self.panels[o.selected]));
				});

				this.load(o.selected);
			}

			// clean up to avoid memory leaks in certain versions of IE 6
			$(window).bind('unload', function() {
				self.lis.add(self.anchors).unbind('.tabs');
				self.lis = self.anchors = self.panels = null;
			});

		}
		// update selected after add/remove
		else {
			o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
		}

		// update collapsible
		this.element[o.collapsible ? 'addClass' : 'removeClass']('ui-tabs-collapsible');

		// set or update cookie after init and add/remove respectively
		if (o.cookie) {
			this._cookie(o.selected, o.cookie);
		}

		// disable tabs
		for (var i = 0, li; (li = this.lis[i]); i++) {
			$(li)[$.inArray(i, o.disabled) != -1 &&
				!$(li).hasClass('ui-tabs-selected') ? 'addClass' : 'removeClass']('ui-state-disabled');
		}

		// reset cache if switching from cached to not cached
		if (o.cache === false) {
			this.anchors.removeData('cache.tabs');
		}

		// remove all handlers before, tabify may run on existing tabs after add or option change
		this.lis.add(this.anchors).unbind('.tabs');

		if (o.event != 'mouseover') {
			var addState = function(state, el) {
				if (el.is(':not(.ui-state-disabled)')) {
					el.addClass('ui-state-' + state);
				}
			};
			var removeState = function(state, el) {
				el.removeClass('ui-state-' + state);
			};
			this.lis.bind('mouseover.tabs', function() {
				addState('hover', $(this));
			});
			this.lis.bind('mouseout.tabs', function() {
				removeState('hover', $(this));
			});
			this.anchors.bind('focus.tabs', function() {
				addState('focus', $(this).closest('li'));
			});
			this.anchors.bind('blur.tabs', function() {
				removeState('focus', $(this).closest('li'));
			});
		}

		// set up animations
		var hideFx, showFx;
		if (o.fx) {
			if ($.isArray(o.fx)) {
				hideFx = o.fx[0];
				showFx = o.fx[1];
			}
			else {
				hideFx = showFx = o.fx;
			}
		}

		// Reset certain styles left over from animation
		// and prevent IE's ClearType bug...
		function resetStyle($el, fx) {
			$el.css({ display: '' });
			if ($.browser.msie && fx.opacity) {
				$el[0].style.removeAttribute('filter');
			}
		}

		// Show a tab...
		var showTab = showFx ?
			function(clicked, $show) {
				$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
				$show.hide().removeClass('ui-tabs-hide') // avoid flicker that way
					.animate(showFx, showFx.duration || 'normal', function() {
						resetStyle($show, showFx);
						self._trigger('show', null, self._ui(clicked, $show[0]));
					});
			} :
			function(clicked, $show) {
				$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
				$show.removeClass('ui-tabs-hide');
				self._trigger('show', null, self._ui(clicked, $show[0]));
			};

		// Hide a tab, $show is optional...
		var hideTab = hideFx ?
			function(clicked, $hide) {
				$hide.animate(hideFx, hideFx.duration || 'normal', function() {
					self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
					$hide.addClass('ui-tabs-hide');
					resetStyle($hide, hideFx);
					self.element.dequeue("tabs");
				});
			} :
			function(clicked, $hide, $show) {
				self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
				$hide.addClass('ui-tabs-hide');
				self.element.dequeue("tabs");
			};

		// attach tab event handler, unbind to avoid duplicates from former tabifying...
		this.anchors.bind(o.event + '.tabs', function() {
			var el = this, $li = $(this).closest('li'), $hide = self.panels.filter(':not(.ui-tabs-hide)'),
					$show = $(self._sanitizeSelector(this.hash));

			// If tab is already selected and not collapsible or tab disabled or
			// or is already loading or click callback returns false stop here.
			// Check if click handler returns false last so that it is not executed
			// for a disabled or loading tab!
			if (($li.hasClass('ui-tabs-selected') && !o.collapsible) ||
				$li.hasClass('ui-state-disabled') ||
				$li.hasClass('ui-state-processing') ||
				self._trigger('select', null, self._ui(this, $show[0])) === false) {
				this.blur();
				return false;
			}

			o.selected = self.anchors.index(this);

			self.abort();

			// if tab may be closed
			if (o.collapsible) {
				if ($li.hasClass('ui-tabs-selected')) {
					o.selected = -1;

					if (o.cookie) {
						self._cookie(o.selected, o.cookie);
					}

					self.element.queue("tabs", function() {
						hideTab(el, $hide);
					}).dequeue("tabs");

					this.blur();
					return false;
				}
				else if (!$hide.length) {
					if (o.cookie) {
						self._cookie(o.selected, o.cookie);
					}

					self.element.queue("tabs", function() {
						showTab(el, $show);
					});

					self.load(self.anchors.index(this)); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171

					this.blur();
					return false;
				}
			}

			if (o.cookie) {
				self._cookie(o.selected, o.cookie);
			}

			// show new tab
			if ($show.length) {
				if ($hide.length) {
					self.element.queue("tabs", function() {
						hideTab(el, $hide);
					});
				}
				self.element.queue("tabs", function() {
					showTab(el, $show);
				});

				self.load(self.anchors.index(this));
			}
			else {
				throw 'jQuery UI Tabs: Mismatching fragment identifier.';
			}

			// Prevent IE from keeping other link focussed when using the back button
			// and remove dotted border from clicked link. This is controlled via CSS
			// in modern browsers; blur() removes focus from address bar in Firefox
			// which can become a usability and annoying problem with tabs('rotate').
			if ($.browser.msie) {
				this.blur();
			}

		});

		// disable click in any case
		this.anchors.bind('click.tabs', function(){return false;});

	},

	destroy: function() {
		var o = this.options;

		this.abort();

		this.element.unbind('.tabs')
			.removeClass('ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible')
			.removeData('tabs');

		this.list.removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');

		this.anchors.each(function() {
			var href = $.data(this, 'href.tabs');
			if (href) {
				this.href = href;
			}
			var $this = $(this).unbind('.tabs');
			$.each(['href', 'load', 'cache'], function(i, prefix) {
				$this.removeData(prefix + '.tabs');
			});
		});

		this.lis.unbind('.tabs').add(this.panels).each(function() {
			if ($.data(this, 'destroy.tabs')) {
				$(this).remove();
			}
			else {
				$(this).removeClass([
					'ui-state-default',
					'ui-corner-top',
					'ui-tabs-selected',
					'ui-state-active',
					'ui-state-hover',
					'ui-state-focus',
					'ui-state-disabled',
					'ui-tabs-panel',
					'ui-widget-content',
					'ui-corner-bottom',
					'ui-tabs-hide'
				].join(' '));
			}
		});

		if (o.cookie) {
			this._cookie(null, o.cookie);
		}
	},

	add: function(url, label, index) {
		if (index === undefined) {
			index = this.anchors.length; // append by default
		}

		var self = this, o = this.options,
			$li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label)),
			id = !url.indexOf('#') ? url.replace('#', '') : this._tabId($('a', $li)[0]);

		$li.addClass('ui-state-default ui-corner-top').data('destroy.tabs', true);

		// try to find an existing element before creating a new one
		var $panel = $('#' + id);
		if (!$panel.length) {
			$panel = $(o.panelTemplate).attr('id', id).data('destroy.tabs', true);
		}
		$panel.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide');

		if (index >= this.lis.length) {
			$li.appendTo(this.list);
			$panel.appendTo(this.list[0].parentNode);
		}
		else {
			$li.insertBefore(this.lis[index]);
			$panel.insertBefore(this.panels[index]);
		}

		o.disabled = $.map(o.disabled,
			function(n, i) { return n >= index ? ++n : n; });

		this._tabify();

		if (this.anchors.length == 1) { // after tabify
			$li.addClass('ui-tabs-selected ui-state-active');
			$panel.removeClass('ui-tabs-hide');
			this.element.queue("tabs", function() {
				self._trigger('show', null, self._ui(self.anchors[0], self.panels[0]));
			});

			this.load(0);
		}

		// callback
		this._trigger('add', null, this._ui(this.anchors[index], this.panels[index]));
	},

	remove: function(index) {
		var o = this.options, $li = this.lis.eq(index).remove(),
			$panel = this.panels.eq(index).remove();

		// If selected tab was removed focus tab to the right or
		// in case the last tab was removed the tab to the left.
		if ($li.hasClass('ui-tabs-selected') && this.anchors.length > 1) {
			this.select(index + (index + 1 < this.anchors.length ? 1 : -1));
		}

		o.disabled = $.map($.grep(o.disabled, function(n, i) { return n != index; }),
			function(n, i) { return n >= index ? --n : n; });

		this._tabify();

		// callback
		this._trigger('remove', null, this._ui($li.find('a')[0], $panel[0]));
	},

	enable: function(index) {
		var o = this.options;
		if ($.inArray(index, o.disabled) == -1) {
			return;
		}

		this.lis.eq(index).removeClass('ui-state-disabled');
		o.disabled = $.grep(o.disabled, function(n, i) { return n != index; });

		// callback
		this._trigger('enable', null, this._ui(this.anchors[index], this.panels[index]));
	},

	disable: function(index) {
		var self = this, o = this.options;
		if (index != o.selected) { // cannot disable already selected tab
			this.lis.eq(index).addClass('ui-state-disabled');

			o.disabled.push(index);
			o.disabled.sort();

			// callback
			this._trigger('disable', null, this._ui(this.anchors[index], this.panels[index]));
		}
	},

	select: function(index) {
		if (typeof index == 'string') {
			index = this.anchors.index(this.anchors.filter('[href$=' + index + ']'));
		}
		else if (index === null) { // usage of null is deprecated, TODO remove in next release
			index = -1;
		}
		if (index == -1 && this.options.collapsible) {
			index = this.options.selected;
		}

		this.anchors.eq(index).trigger(this.options.event + '.tabs');
	},

	load: function(index) {
		var self = this, o = this.options, a = this.anchors.eq(index)[0], url = $.data(a, 'load.tabs');

		this.abort();

		// not remote or from cache
		if (!url || this.element.queue("tabs").length !== 0 && $.data(a, 'cache.tabs')) {
			this.element.dequeue("tabs");
			return;
		}

		// load remote from here on
		this.lis.eq(index).addClass('ui-state-processing');

		if (o.spinner) {
			var span = $('span', a);
			span.data('label.tabs', span.html()).html(o.spinner);
		}

		this.xhr = $.ajax($.extend({}, o.ajaxOptions, {
			url: url,
			success: function(r, s) {
				$(self._sanitizeSelector(a.hash)).html(r);

				// take care of tab labels
				self._cleanup();

				if (o.cache) {
					$.data(a, 'cache.tabs', true); // if loaded once do not load them again
				}

				// callbacks
				self._trigger('load', null, self._ui(self.anchors[index], self.panels[index]));
				try {
					o.ajaxOptions.success(r, s);
				}
				catch (e) {}

				// last, so that load event is fired before show...
				self.element.dequeue("tabs");
			}
		}));
	},

	abort: function() {
		// stop possibly running animations
		this.element.queue([]);
		this.panels.stop(false, true);

		// terminate pending requests from other tabs
		if (this.xhr) {
			this.xhr.abort();
			delete this.xhr;
		}

		// take care of tab labels
		this._cleanup();

	},

	url: function(index, url) {
		this.anchors.eq(index).removeData('cache.tabs').data('load.tabs', url);
	},

	length: function() {
		return this.anchors.length;
	}

});

$.extend($.ui.tabs, {
	version: '1.7.2',
	getter: 'length',
	defaults: {
		ajaxOptions: null,
		cache: false,
		cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
		collapsible: false,
		disabled: [],
		event: 'click',
		fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }
		idPrefix: 'ui-tabs-',
		panelTemplate: '<div></div>',
		spinner: '<em>Loading&#8230;</em>',
		tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>'
	}
});

/*
 * Tabs Extensions
 */

/*
 * Rotate
 */
$.extend($.ui.tabs.prototype, {
	rotation: null,
	rotate: function(ms, continuing) {

		var self = this, o = this.options;

		var rotate = self._rotate || (self._rotate = function(e) {
			clearTimeout(self.rotation);
			self.rotation = setTimeout(function() {
				var t = o.selected;
				self.select( ++t < self.anchors.length ? t : 0 );
			}, ms);

			if (e) {
				e.stopPropagation();
			}
		});

		var stop = self._unrotate || (self._unrotate = !continuing ?
			function(e) {
				if (e.clientX) { // in case of a true click
					self.rotate(null);
				}
			} :
			function(e) {
				t = o.selected;
				rotate();
			});

		// start rotation
		if (ms) {
			this.element.bind('tabsshow', rotate);
			this.anchors.bind(o.event + '.tabs', stop);
			rotate();
		}
		// stop rotation
		else {
			clearTimeout(self.rotation);
			this.element.unbind('tabsshow', rotate);
			this.anchors.unbind(o.event + '.tabs', stop);
			delete this._rotate;
			delete this._unrotate;
		}
	}
});

})(jQuery);

/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Version: 03/01/2009 +r14
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};

$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:(3000+2*$('.jqmOverlay').length),o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){/*if(this.className=='jqmOverlay'){return;};*/for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);





/* SPEED TEST DROPDOWN MENUS **********/
$.fn.ZINGCHART_customSelect = function() {
    if ( jQuery(this).length ) {
        jQuery(this).find('select').attr('selectedIndex',-1).change(function() {
            var optionText = jQuery(this).find('option:selected').text();
            jQuery(this).siblings('label').text(optionText)
        });
    }
};


$(document).ready(function() {

	var flashVersion = getFlashVersion().split(',').shift();

	if ( flashVersion < 10 ) {
		$('#flash-warning').show();
		$('#test5 option[value="flash"]').remove();
	}

	// Change title of the browser tab (mainly for IE)
	document.title = "Zingchart + Build HTML5 and Flash Charts & Graphs for Web Applications";

	// Enable the download button
	$('#fsubmit').removeAttr('disabled');

/**************************/
/***** PAGE FUNCTIONS *****/
/**************************/
	// Every AJAX call will show a loading gif
	$.ajaxSetup ({
		beforeSend:function() {
			$('#ajax-load-1').show();
			$('#ajax-load-2').show();
		},
		complete:function() {
			$('#ajax-load-1').hide();
			$('#ajax-load-2').hide();
		},
		success:function() {
			$('#ajax-load-1').hide();
			$('#ajax-load-2').hide();
		}
	});

	// Mailing list
	$('#mail-list').submit(function(e) {
		var fail = false;
		var user = $('#email').val();
		if (!user.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)) {

			fail = true;
			alert("Enter valid email");
			return !fail;
		}
	});

	// Modal - Try it for FREE today button
	$('.btn-tryfree').click(function(e){

		// Default action not triggered
		e.preventDefault();

		$('#h-demo-detail').jqmHide();
		$('#menu-download').click();
	});


/***********************/
/***** WELCOME TAB *****/
/***********************/

	// Downloads form
	$('#downloadform-1').submit(function(e) {

		// Default action not triggered
		e.preventDefault();

		// Get name and email
		var email = $('#femail').val();
		var name = $('#fname').val();
		var fail = false;

		// Change name and email to an empty string if it is default
		if( email == 'Email' ) email = '';
		if( name == 'Name' ) name = '';

		// Check to see if name is valid
		if (!name.match(/[a-z]+/) ) {

			fail = true;
			$('#fname').focus();
			alert("Enter a valid name");
			return !fail;
		}

		// Check to see if email is valid
		if (!email.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)) {

			fail = true;
			$('#femail').focus();
			alert("Enter valid email");
			return !fail;
		}

		// Handle download
		$.ajax({
			url: 'download/download-feature.php',
			dataType: 'json',
			data:  { name: name, email: email },
			success: function(data) {

				// Check to see if name and email are both valid
				if( data.status == 1 ) {
					$('#menu-download').click();
					$('#menu-download-form').hide();
					$('#menu-download-submitted').show();

					// Start download
					$('#start-download').attr('href', '/download/getfile.php?id=' + data.downloadId);
					window.location.href = '/download/getfile.php?id=' + data.downloadId;
					
					setTimeout("window.location = 'http://www.zingchart.com/download-welcome.php'", 3000);	
					
					//setTimeout("window.location = 'http://www.zingchart.com/#download?submitted=true'", 3000);					

				// If it is not a valid name or email, send errors
				} else {
					var errors = [];

					if ( data.errors.name ) {
						errors.push('- ' + data.errors.name);
					}
					if ( data.errors.email ) {
						errors.push('- ' + data.errors.email);
					}
					alert(errors.join("\n"));
				}
			}
		});
	});

/********************************/
/***** MULTIPLE RENDERS TAB *****/
/********************************/

	// When "Multiple Renders" tab is clicked
	$('#menu-multi-renders').click(function(){

		// Show graph
		$('#multi-code').hide();
		$('#multi-render').show();

		// Check of it is not IE9
		if ($.browser.msie < 9) {
			$('#r-canvas, #r-svg, #r-flash').removeClass('on');
			$('#r-vml').addClass('on');

			// Set default render to VML
			multi_render_settings.render = 'vml';
			multi_render_settings.dataurl = '/packagewww/images/section1-line-1.php';

			renderMultiRender(multi_render_settings.render, multi_render_settings.dataurl);
		// If it is any other browser or IE9
		} else {
			$('#r-svg, #r-vml, #r-flash').removeClass('on');
			$('#r-canvas').addClass('on');

			// Set default render to canvas
			multi_render_settings.render = 'canvas';
			multi_render_settings.dataurl = '/packagewww/images/section1-line-1.php';

			renderMultiRender(multi_render_settings.render, multi_render_settings.dataurl);
		}
	});

	// Default Multiple Render settings
	var multi_render_settings = {
		render: 'canvas',
		dataurl: '/packagewww/images/section1-line-1.php'
	};

	// When Chart Style is clicked
	$('#multi-type li a').click(function(e) {

		// Default action is not triggered
		e.preventDefault();

		// Show appropriate box
		$('#multi-code').hide();
		$('#multi-render').show();

		// Display button on
		$(this).parent().siblings().children().removeClass('on');
		$(this).addClass('on');

		// Get appropriate render
		multi_render_settings.render = $(this).attr('id').replace('r-','');

		renderMultiRender(multi_render_settings.render, multi_render_settings.dataurl);
	});

	// Get dataurl test tab
	$('#dataurl-picker li a').click(function(e){

		// Show appropriate box
		$('#multi-code').hide();
		$('#multi-render').show();

		// Default action is not triggered
		e.preventDefault();

		// Get appropriate graph
		multi_render_settings.dataurl = $(this).attr('href');

		renderMultiRender(multi_render_settings.render, multi_render_settings.dataurl);
	});

	// JSON button - Multiple renders
	$('#btn-json').click(function(){

		// Clear box
		$('#multi-render').html('');

		// Display highlighted JSON
		var getData = $.get(multi_render_settings.dataurl, function(sResponse) {
			$('#multi-code').html('<pre class="brush:js; gutter: false;">' + sResponse +'</pre>');
			$('#multi-render').hide();
			$('#multi-code').show();
			SyntaxHighlighter.highlight();
		});
	});

	// Render graphs
	var renderMultiRender = function(_render, _dataurl) {

		// Set messages
		var hasRendered = false;
		var flashMessage = '<div class="noflash_message">Your Flash missing? <br />You either blocked it or Steve Jobs did!<br />That\'s why you need ZingChart!</div>'
		var svgMessage = '<div class="nosvg_message">Your browser does not support SVG!</div>';
		var vmlMessage = '<div class="novml_message">Your browser does not support VML!</div>';
		var html5Message = '<div class="nohtml5_message">Your browser does not support HTML5!</div>';
		var flashVersionMessage = '<div class="flashVersion_message">Your browser needs to update Flash!</div>';

		$('.noflash_message, .novml_message, .nosvg_message, .nohtml5_message, .flashVersionMessage').remove();

		// Check to see if graph exists
		if ( $('#multi-render').length && $('#multi-render').html().length ) {

			// Destroy graph
			zingchart.exec('multi-render', 'destroy');
		}

		// Clear the box
		$('#multi-render').html('');
		$('#multi-render').css('background', '');

		// Check render
		switch( _render ) {

			// Canvas
			case 'canvas':
				if (!$.browser.msie || ($.browser.msie && $.browser.version >= 9)) {
					zingchart.render({
						output: 'canvas',
						id: 'multi-render',
						width : 303,
						height : 246,
						dataurl: _dataurl,
						preservecontainer: true
					});
				} else {
					$('#multi-render').html(html5Message);
				}
				break;

			// Flash
			case 'flash':
				if (FlashDetect.installed) {
					if ( flashVersion >= 10 ) {
						zingchart.render({
							output: 'flash',
							id: 'multi-render',
							width: 303,
							height: 246,
							dataurl: _dataurl,
							liburl: '/package/zingchart.swf',
							preservecontainer: true
						});
					} else {
						$('#multi-render').css('background', 'transparent url(packagewww/images/lego.png) no-repeat center bottom').html(flashVersionMessage);
					}
				} else {
					$('#multi-render').css('background', 'transparent url(packagewww/images/lego.png) no-repeat center bottom').html(flashMessage);
				}
				break;

			// SVG
			case 'svg':
				if ( supportsSVG() ) {
					zingchart.render({
						output: 'svg',
						id: 'multi-render',
						width: 303,
						height: 246,
						dataurl: _dataurl,
						preservecontainer: true
					});
				} else {
					$('#multi-render').html(svgMessage);
				}
					break;

			// VML
			case 'vml':
				if ( (supportsVML() && $.browser.version < 9) ) {
					zingchart.render({
						output: 'vml',
						id: 'multi-render',
						width: 303,
						height: 246,
						dataurl: _dataurl,
						preservecontainer: true
					});
					break;
				} else {
					$('#multi-render').html(vmlMessage);
				}
		}
		hasRendered = true;
	}

/**************************/
/***** SPEED-TEST TAB *****/
/**************************/

	// When "Speed test" tab is clicked
	$('#menu-speed-test').click(function() {

		// Hide graph render boxes
		$('#render1, #render2').hide();

		// Enable Render With menu
		$('#test3, #test4').attr('disabled', '');

		// Show appropriate graph/render or image for render boxes
		if ( $('#selection-pic').is(":visible") && $('#selection-pic2').is(":visible") && $('#render1').is(":visible") && $('#render2').is(":visible") ) {
			$('#selection-pic, #selection-pic2').hide();
		} else {
			$('#selection-pic, #selection-pic2').show();
		}

		// Show appropriate speed test results or plot menu boxes
		if ( $('.speed-results').is(":visible") ) {
			$('.speed-results').hide();
			$('#speed-test-submitted').show();
		}

		// Set default plot to "100 DATA POINTS" and on a to "LINE CHART"
		var render_1, render_2;
		var plot = $('#test1').val($("#test1 option[value='1']").val()).change();
		var ona = $('#test2').val($("#test2 option[value='line']").val()).change();

		/***** Browser checks *****/
		// Will set appropriate values for render box depending on support

		// Firefox
		if ($.browser.mozilla) {
			render_1 = $('#test3').val($("#test3 option[value='canvas']").val()).change();

			// Check if Flash is installed
			if (FlashDetect.installed) {
				if ( flashVersion >= 10 ) {
					render_2 = $('#test4').val($("#test4 option[value='flash']").val()).change();
				} else {
					$('#test3, #test4').children('[value="flash"]').remove();
				}
			} else {
				$('#test3, #test4').children('[value="flash"]').remove();
			}

			// Check if VML support exists
			if ( supportsVML() ) {
				render_2 = $('#test4').val($("#test4 option[value='vml']").val()).change();
			} else {
				$('#test3, #test4').children('[value="vml"]').remove();
			}

			// Check if SVG support exists
			if ( supportsSVG() ) {
				render_2 = $('#test4').val($("#test4 option[value='svg']").val()).change();
			} else {
				$('#test3, #test4').children('[value="svg"]').remove();
			}

		// IE
		} else if ($.browser.msie) {

			// Check if IE9 or greater
			if ($.browser.version >= 9) {
				render_1 = $('#test3').val($("#test3 option[value='svg']").val()).change();
				render_2 = $('#test4').val($("#test4 option[value='canvas']").val()).change();
				$('#test3, #test4').children('[value="vml"]').remove();
			} else {
				render_1 = $('#test3').val($("#test3 option[value='vml']").val()).change();

				$('#test3, #test4').children('[value="canvas"]').remove();
				$('#test3, #test4').children('[value="svg"]').remove();
			}

			// Check if Flash is installed
			if (FlashDetect.installed) {
				if ( flashVersion >= 10 ) {
					render_2 = $('#test4').val($("#test4 option[value='flash']").val()).change();
				} else {
					$('#test3, #test4').children('[value="flash"]').remove();
				}
			} else {
				$('#test3, #test4').children('[value="flash"]').remove();
			}

		// Other browsers
		} else {
			render_1 = $('#test3').val($("#test3 option[value='canvas']").val()).change();

			// Check if Flash is installed
			if (FlashDetect.installed) {
				if ( flashVersion >= 10 ) {
					render_2 = $('#test4').val($("#test4 option[value='flash']").val()).change();
				} else {
					$('#test3, #test4').children('[value="flash"]').remove();
				}
			} else {
				$('#test3, #test4').children('[value="flash"]').remove();
			}

			// Check if SVG support exists
			if ( supportsSVG() ) {
				render_2 = $('#test4').val($("#test4 option[value='svg']").val()).change();
			} else {
				$('#test3, #test4').children('[value="svg"]').remove();
			}

			// Check if VML support exists
			if ( supportsVML() ) {
				render_2 = $('#test4').val($("#test4 option[value='vml']").val()).change();
			} else {
				$('#test3, #test4').children('[value="vml"]').remove();
			}
		}
	});

	function _i_(mValue) { return parseInt(mValue, 10); }
	function _r_(iMin,iMax) { return iMin+(iMax-iMin)*Math.random(); }

	// Get Speed Test data set
	var speedtestDataSet = function(iElements, iMin, iMax, fScale) {
	    fRange = Math.abs(iMax - iMin);
    	var sData = '[';
    	var fBase = fScale*_r_(iMin,iMax);
    	for (var i=0;i<iElements;i++) {
			var fValue = fBase + fScale*_r_(-fRange, fRange);
			if (fValue < iMin) {
				fValue = iMin + fScale*fRange;
			}
			if (fValue > iMax) {
				fValue = iMax - fScale*fRange;
			}
           	fBase = fValue;
           	sData += Number(fValue).toFixed(1) + ',';
       	}
	   	sData = sData.substring(0, sData.length-1) + ']';
	   	return sData;
	};

	// Render speed test results
	var speedTestRender = function(plot, ona, render_1, render_2) {

		// Set variables
		var flashMessage = '<div class="noflash_message">Your Flash missing? <br />You either blocked it or Steve Jobs did!<br />That\'s why you need ZingChart!</div>';
		var svgMessage = '<div class="nosvg_message">Your browser does not support SVG!</div>';
		var vmlMessage = '<div class="nosvg_message">Your browser does not support VML!</div>';
		var html5Message = '<div class="nohtml5_message">Your browser does not support VML!</div>';
		var flashVersionMessage = '<div class="flashVersion_message">Your browser needs to update Flash!</div>';
		var startTimes = {
			render_1: 0,
			render_2: 0
		}

		$('.noflash_message, .novml_message, .nosvg_message, .nohtml5_message, .flashVersionMessage').remove();

		$('#render1, #render2').html('');
		$('#render1, #render2').css('background', '');

		if (render_1 == 'svg' && render_2 == 'vml')
		{
			$('#svg-id, #vml-id').show();
			$('#flash-id, #canvas-id').hide();
		} else if (render_1 == 'svg' && render_2 == 'canvas')
		{
			$('#svg-id, #canvas-id').show();
			$('#flash-id, #vml-id').hide();
		} else if (render_1 == 'svg' && render_2 == 'flash')
		{
			$('#svg-id, #flash-id').show();
			$('#canvas-id, #vml-id').hide();
		} else if (render_1 == 'vml' && render_2 == 'flash')
		{
			$('#vml-id, #flash-id').show();
			$('#canvas-id, #svg-id').hide();
		} else if (render_1 == 'vml' && render_2 == 'canvas')
		{
			$('#vml-id, #canvas-id').show();
			$('#svg-id, #flash-id').hide();
		} else if (render_1 == 'flash' && render_2 == 'canvas')
		{
			$('#flash-id, #canvas-id').show();
			$('#svg-id, #vml-id').hide();
		}

		if (render_2 == 'svg' && render_1 == 'vml')
		{
			$('#vml-id, #svg-id').show();
			$('#flash-id, #canvas-id').hide();
		} else if (render_2 == 'svg' && render_1 == 'canvas')
		{
			$('#canvas-id, #svg-id').show();
			$('#flash-id, #vml-id').hide();
		} else if (render_2 == 'svg' && render_1 == 'flash')
		{
			$('#flash-id, #svg-id').show();
			$('#canvas-id, #vml-id').hide();
		} else if (render_2 == 'vml' && render_1 == 'flash')
		{
			$('#flash-id, #vml-id').show();
			$('#canvas-id, #svg-id').hide();
		} else if (render_2 == 'vml' && render_1 == 'canvas')
		{
			$('#canvas-id, #vml-id').show();
			$('#svg-id, #flash-id').hide();
		} else if (render_2 == 'flash' && render_1 == 'canvas')
		{
			$('#canvas-id, #flash-id').show();
			$('#svg-id, #vml-id').hide();
		}

		$('#speed-test-submitted').hide();
		$('#speed-test-start').show();
		$('#flash-time, #canvas-time, #svg-time, #vml-time').html('Calculating...');

		/*_gaq.push(['_trackEvent', 'SpeedTestScenario', $('#test1').val() + '/' + $('#test2').val()]);	*/

		// Setup JSON
		var sJson = '{"graphset":[{"type":"'+ona+'","chart":{"margin":"10 10 25 40"},"plotarea":{"margin":"10 10 25 40"},"scale-x":{"max-items":10,"max-labels":10,"item":{"font-size":9}';
		sJson += '},"scale-y":{"values":"-100:100:20","item":{"font-size":9},"ref-line":{"visible":true}},"plot":{"exact":true,"mode":"fast","line-width":1,"shadow":false},';
		sJson += '"series":[';
		var iPlots = 1, iNodes = 100;
		switch (_i_(plot)) {
			case 1: iPlots = 1;iNodes = 100;break;
			case 2: iPlots = 1;iNodes = 500;break;
			case 3: iPlots = 1;iNodes = 1000;break;
			case 4: iPlots = 3;iNodes = 100;break;
			case 5: iPlots = 3;iNodes = 500;break;
			case 6: iPlots = 3;iNodes = 1000;break;
		}
		for (var p=0;p<iPlots;p++) {
			sJson += '{"values":' + speedtestDataSet(iNodes, -100, 100, 0.1) + ',"marker":{"type":"none"}},';
		}
		sJson = sJson.substring(0, sJson.length-1);
		sJson += ']}]}';


		//var render_base = {

		//	width: 277,
		//	height: 224,
		//	data: sJson,
		//	preservecontainer: true

		//}




		// Check 1st Render With box
		switch( render_1 ) {

			// Flash
			case 'flash':
				if (FlashDetect.installed) {
					if ( flashVersion >= 10 ) {
						startTimes.render_1 = new Date().getTime();
						zingchart.render ({
							output	: 'flash',
							id		: 'render1',
							width	: 277,
							height	: 224,
							data	: sJson,
							liburl	: '/package/zingchart.swf',
							preservecontainer: true
						});
					} else {
						$('#multi-render').css('background', 'transparent url(packagewww/images/lego.png) no-repeat center bottom').html(flashVersionMessage);
					}
				} else {
					$('#render1').css('background', 'transparent url(packagewww/images/lego.png) no-repeat center bottom').html(flashMessage);
				}
				break;

			// Canvas
			case 'canvas':
				if (!$.browser.msie || ($.browser.msie && $.browser.version >= 9)) {
					startTimes.render_1 = new Date().getTime();
					zingchart.render ({
						output : 'canvas',
						id		: 'render1',
						width	: 277,
						height	: 224,
						data	: sJson,
						preservecontainer: true,
						events : {
							load : function() {
								var now_1 = new Date().getTime();
								var duration = now_1 - startTimes.render_1;
								$('#canvas-time').html(duration/1000);
								__render_2();
							}
						}
					});
				} else {
					$('#render1').html(html5Message);
				}
				break;

			// SVG
			case 'svg':
				if ( supportsSVG() ) {
					startTimes.render_1 = new Date().getTime();
					zingchart.render ({
						output : 'svg',
						id		: 'render1',
						width	: 277,
						height	: 224,
						data	: sJson,
						preservecontainer: true,
						events : {
							load : function() {
								var now_1 = new Date().getTime();
								var duration = now_1 - startTimes.render_1;
								$('#svg-time').html(duration/1000);
								__render_2();
							}
						}
					});
				} else {
					$('#render1').html(svgMessage);
				}
				break;

			// VML
			case 'vml':
				if ( (supportsVML() && $.browser.version < 9) ) {
					startTimes.render_1 = new Date().getTime();
					zingchart.render ({
						output : 'vml',
						id		: 'render1',
						width	: 277,
						height	: 224,
						data	: sJson,
						preservecontainer: true,
						events : {
							load : function() {
								var now_1 = new Date().getTime();
								var duration = now_1 - startTimes.render_1;
								$('#vml-time').html(duration/1000);
								__render_2();
							}
						}
					});
				} else {
					$('#render1').html(vmlMessage);
				}
				break;
		}

		function __render_2() {

		// Check 2nd Render With box
		switch( render_2 ) {

			// Flash
			case 'flash':
				if (FlashDetect.installed) {
					if ( flashVersion >= 10 ) {
						startTimes.render_2 = new Date().getTime();
						zingchart.render ({
							output	: 'flash',
							id		: 'render2',
							width	: 277,
							height	: 224,
							data	: sJson,
							liburl	: '/package/zingchart.swf',
							preservecontainer: true
						});
					} else {
						$('#multi-render').css('background', 'transparent url(packagewww/images/lego.png) no-repeat center bottom').html(flashVersionMessage);
					}
				} else
					$('#render2').css('background', 'transparent url(packagewww/images/lego.png) no-repeat center bottom').html(flashMessage);
				break;

			// Canvas
			case 'canvas':
				if (!$.browser.msie || ($.browser.msie && $.browser.version >= 9)) {
					startTimes.render_2 = new Date().getTime();
					zingchart.render ({
						output : 'canvas',
						id		: 'render2',
						width	: 277,
						height	: 224,
						data	: sJson,
						preservecontainer: true,
						events : {
							load : function() {
								var now_2 = new Date().getTime();
								var duration = now_2 - startTimes.render_2;
								$('#canvas-time').html(duration/1000);
							}
						}
					});
				} else {
					$('#render2').html(html5Message);
				}
				break;

			// SVG
			case 'svg':
				if ( supportsSVG() ) {
					startTimes.render_2 = new Date().getTime();
					zingchart.render ({
						output : 'svg',
						id		: 'render2',
						width	: 277,
						height	: 224,
						data	: sJson,
						preservecontainer: true,
						events : {
							load : function() {
								var now_2 = new Date().getTime();
								var duration = now_2 - startTimes.render_2;
								$('#svg-time').html(duration/1000);
							}
						}
					});
				} else {
					$('#render2').html(svgMessage);
				}
				break;

			// VML
			case 'vml':
				if ( (supportsVML() && $.browser.version < 9) ) {
					startTimes.render_2 = new Date().getTime();
					zingchart.render ({
						output : 'vml',
						id		: 'render2',
						width	: 277,
						height	: 224,
						data	: sJson,
						preservecontainer: true,
						events : {
							load : function() {
								var now_2 = new Date().getTime();
								var duration = now_2 - startTimes.render_2;
								$('#vml-time').html(duration/1000);
							}
						}
					});
				} else {
					$('#render2').html(vmlMessage);
				}
				break;
		}

		}

		// When render is complete, print time
		zingchart.complete = function(dataObj) {

			var now = new Date().getTime();

			if( dataObj.id == 'render1' ) {
				if (render_1 == 'flash') {
					var duration = now - startTimes.render_1;
					$('#flash-time').html(duration/1000);
					__render_2();
				}
			}
			else if( dataObj.id == 'render2' ) {
				var duration = now - startTimes.render_2;
				if (render_2 == 'flash') {
					var duration = now - startTimes.render_1;
					$('#flash-time').html(duration/1000);
				}
			}
		}
	};

	// Handle Speed Test renders
	var handleSpeedTestRender = function(){

		// Get appropriate values
		var plot = $('#test1').val();
		var ona = $('#test2').val();
		var render_1 = $('#test3').val();
		var render_2 = $('#test4').val();

		// Check to see if all fields are populated
		if ( !plot || !ona || !render_1 || !render_2 ) {
			$('#btn-render').attr("disabled", true);
		} else {
			// Show appropriate boxes
			$('#selection-pic, #selection-pic2').hide();
			$('.selection, .speed-results, #render1, #render2').show();

			// Disable Render With drop down menu
			$('#test3, #test4').attr('disabled', 'disabled');

			speedTestRender(plot, ona, render_1, render_2);
		}
	};

	// When change is detected in 1st "Render With" box
	$('#test3').change(function(){

		$('#test4').children().each(function(){

			if( ( $(this).is('optgroup') ? $(this).children(':first').val() : $(this).val() ) == $('#test3').val() ) {

				if( $.browser.msie && $.browser.version.substr(0,1)<=7 ) {
					$(this).wrap('<optgroup label="' + $(this).text() + '" />');
					$(this).parent().data('option', $(this).remove());
				} else {
					$(this).attr('disabled', 'disabled');
				}

			} else {

				if( $(this).is('optgroup') ) {
					$(this).replaceWith($(this).data('option'));
				} else {
					$(this).removeAttr('disabled');
				}
			}
		})

	});

	// When change is detected in 2nd "Render With" box
	$('#test4').change(function(){

		$('#test3').children().each(function(){

			if( ( $(this).is('optgroup') ? $(this).children(':first').val() : $(this).val() ) == $('#test4').val() ) {

				if( $.browser.msie && $.browser.version.substr(0,1)<=7 ) {
					$(this).wrap('<optgroup label="' + $(this).text() + '" />');
					$(this).parent().data('option', $(this).remove());
				} else {
					$(this).attr('disabled', 'disabled');
				}

			} else {

				if( $(this).is('optgroup') ) {
					$(this).replaceWith($(this).data('option'));
				} else {
					$(this).removeAttr('disabled');
				}
			}
		})

	});

	// Render button
	$('#btn-render').click(function() {

		// Get appropriate values
		var plot = $('#test1').val();
		var ona = $('#test2').val();
		var render_1 = $('#test3').val();
		var render_2 = $('#test4').val();

		// Check to see if fields are not empty
		if ( plot && ona && render_1 && render_2 ) {

			// Disable Render button
			$('#btn-render').attr("disabled", false);

			handleSpeedTestRender();
		}

	});

	// Start over button
	$('.restart-btn').click(function() {

		// Hide graph render boxes
		$('#render1, #render2').hide();

		// Show render instructions
		$('#selection-pic, #selection-pic2').show();

		// Enable Render With menu
		$('#test3, #test4').attr('disabled', '');

		// Show Plot and on a
		$('#speed-test-start').hide();
		$('#speed-test-submitted').show();

		// Delete charts
		zingchart.exec('render1', 'destroy');
		zingchart.exec('render2', 'destroy');
	});
/*************************/
/***** DOWNLOADS TAB *****/
/*************************/

	// Downloads form
	$('#downloadform-2').submit(function(e){

		// Get name and email
		var name = $('#fdl-name').val();
		var email = $('#fdl-email').val();
		var fail = false;

		// Change name and email to an empty string if it is default
		if( email == 'Email' ) {
			email = '';
		}
		if( name == 'Name' ) {
			name = '';
		}

		// Default action not triggered
		e.preventDefault();

		// Check to see if name is a valid name
		if (!name.match(/[a-z]+/) ) {
			fail = true;
			$('#fdl-name').focus();
			alert("Enter a valid name");
			return !fail;
		}

		// Check to see if email is a valid email
		if (!email.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)) {
			fail = true;
			alert("Enter valid email");
			$('#fdl-email').focus();
			return !fail;
		}

		// Handle download
		$.ajax({
			url: 'download/download-feature.php',
			dataType: 'json',
			data:  { name: name, email: email },
			success: function(data) {

				// Check to see if name and email are both valid
				if( data.status == 1 ) {
					$('#menu-download-form').hide();
					$('#menu-download-submitted').show();

					// Start download
					$('#start-download').attr('href', '/download/getfile.php?id=' + data.downloadId);
					window.location.href = '/download/getfile.php?id=' + data.downloadId;

					setTimeout("window.location = 'http://www.zingchart.com/download-download.php'", 3000);
					//setTimeout("window.location = 'http://www.zingchart.com/#download?submitted=true'", 3000);

				// If it is not a valid name or email, send errors
				} else {
					var errors = [];

					if ( data.errors.name ) {
						errors.push('- ' + data.errors.name);
					}
					if ( data.errors.email ) {
						errors.push('- ' + data.errors.email);
					}
					alert(errors.join("\n"));
				}
			}
		});
	});

	SyntaxHighlighter.defaults['tab-size'] = 2;

/***********************/
/***** DEMO MODALS *****/
/***********************/

	// Set render drop down list
	if ( !FlashDetect.installed ) {
		$('#test5 option[value="flash"]').remove();
		$('#flash-warning').show();
	}

	if ( !supportsVML() )
		$('#test5 option[value="vml"]').remove();

	if ( !supportsSVG() )
		$('#test5 option[value="svg"]').remove();

	if ( $.browser.msie ) {
		if ( $.browser.version < 9 ) {
			$('#test5 option[value="canvas"]').remove();
		} else {
			$('#test5 option[value="vml"]').remove();
		}
	}

	// Show demos
	var demo = {
		theme : '',
		id : -1,
		next : 1,
		prev : -1,
		showDemo : function(iDemoId, iCatId, output) {

			demo.id = iDemoId;
			$.ajax({
				type : 'GET',
				url : '/demos/',
				data : 'id=' + iDemoId + '&catid=' + iCatId,
				success : function(sResponse) {
					var oResponse = eval('(' + sResponse + ')');
						if ( $('#h-demo-detail-zingchart').length && $('#h-demo-detail-zingchart').html().length)
							zingchart.exec('h-demo-detail-zingchart', 'destroy');

						if (true || $('#h-demo-detail-zingchart').attr('tagName').toUpperCase() == 'DIV' || demo.json) {
							$('#h-demo-detail-json').hide();
							$('#h-demo-detail-middle').show();

							var aParams = {
								width				: 'auto',
								height				: 'auto',
								data 				: oResponse['json'],
								container 			: 'h-demo-detail-zingchart',
								bgcolor				: '#B2E74E',
								output				: output,
								preservecontainer		: true,
								liburl 				: '/package/zingchart.swf'
							};

							//$('#h-demo-detail-middle').html('<div id="h-demo-detail-zingchart">&nbsp;</div>');
							zingchart.render(aParams);

						}

					/* resize containers*/
					$('#h-demo-detail-middle').width(parseInt(oResponse['width'], 10));
					$('#h-demo-detail-middle').height(parseInt(oResponse['height'], 10));
					$('#h-demo-detail-json').width(parseInt(oResponse['width'], 10));
					$('#h-demo-detail-json').height(parseInt(oResponse['height'], 10));
					$('#h-demo-detail-json pre').width(parseInt(oResponse['width'], 10) + 150);
					$('#h-demo-detail-json pre').height(parseInt(oResponse['height'], 10) - 10);
					$('#h-demo-detail').width(parseInt(oResponse['width'], 10) + 95);

					$('#h-demo-detail').height(parseInt(oResponse['height'], 10) + 272);
					$('#h-demo-detail').css('left', ($('body').width()-$('#h-demo-detail').width())/2);
					$('#h-demo-detail-container').width(parseInt(oResponse['width'], 10) + 95);
					$('#h-demo-detail-container').height(parseInt(oResponse['height'], 10) + 10);
					$('#h-demo-detail-container').css('left', ($('body').width()-$('#h-demo-detail').width())/2);
					$('#h-demo-detail-title').html(oResponse['title']);
					//$('#h-demo-detail-left img,#h-demo-detail-right img').show();
					demo.next = oResponse['next'];
					demo.prev = oResponse['prev'];

					$('#h-demo-detail').height($('#h-demo-detail-title').outerHeight() + $('#h-demo-detail-container').outerHeight() + 200);
					$('#h-demo-detail-left').css('padding-top', ($('#h-demo-detail').height()-100)/3);
					$('#h-demo-detail-left').css('padding-bottom', ($('#h-demo-detail').height()-100)/3);
					$('#h-demo-detail-right').css('padding-top', ($('#h-demo-detail').height()-100)/3);
					$('#h-demo-detail-right').css('padding-bottom', ($('#h-demo-detail').height()-100)/3);
					$('#h-demo-detail-left img,#h-demo-detail-right img').show();


					//$('#h-demo-detail-json').text(oResponse['json']);

					if ($.browser.msie) {
						document.getElementById('h-demo-detail-json').innerHTML = '<pre style="white-space:pre;" class="brush:js; gutter:false;">' + oResponse['json'] + '</pre>';
					} else {
						$('#h-demo-detail-json').html('<div><pre class="brush:js; gutter:false">&nbsp;</pre></div>');
						$('#h-demo-detail-json pre').html(oResponse['json']);
					}

					SyntaxHighlighter.highlight();

					$('#h-demo-show-chart').addClass(' tab-on');
					$('#h-demo-show-json').removeClass(' tab-on');

				}
			});
		}
	};


	/*$('#h-demo-copy').click(function(e) {
		e.preventDefault();
		var jsonString = zingchart.exec('h-demo-detail-zingchart', 'getdata');

		$.post('proxy.php', { data: jsonString }, function(response) {

		//{"result":1,"error":"","zingid":"4daf1566c1faa","lockcode":"a3121b5e49c429d95163cbbd708495a4"}
		//33, 46
			var imageURL = response;
			imageURL = imageURL.substring(33, 46);

			$('#h-demo-copy').attr('href', 'hosted.zingchart.com/render?key=3e4da39c3a1f48b608d6553b0c092111&zingid=' + imageURL);

			//alert("hosted.zingchart.com/render?key=3e4da39c3a1f48b608d6553b0c092111?zingid=" + imageURL.zingid);
		});
	});*/


	$('.h-demo-theme').click(function() {
		demo.theme = $(this).attr('id').replace('h-demo-', '');
	});

	$('#h-demo-detail-viewall').click(function() {
		$('#h-demo-detail-json').hide();
		$('#h-demo-detail-middle').show();
		$('#h-demo-detail').jqmHide();

		window.setTimeout(function() { $('#h-demo').jqmShow(); }, 500);
	});

	// "Code View" button
	$('#h-demo-show-json').click(function(e) {

		// Prevent default behavior
		e.preventDefault();

		$('#h-demo-detail-middle').hide();
		$('#h-demo-detail-json').show();

		$('#h-demo-show-chart').removeClass('overlay-tab tab-on').addClass('overlay-tab');
		$('#h-demo-show-json').removeClass('overlay-tab').addClass('overlay-tab tab-on');
	});

	// "Chart View" button
	$('#h-demo-show-chart').click(function(e) {

		// Prevent default behavior
		e.preventDefault();

		$('#h-demo-detail-json').hide();
		$('#h-demo-detail-middle').show();

		$('#h-demo-show-chart').removeClass('overlay-tab').addClass('overlay-tab tab-on');
		$('#h-demo-show-json').removeClass('overlay-tab tab-on').addClass('overlay-tab');
	});

	// Handle different renders
	$('#test5').change(function(){
		demo.showDemo(demo.id, 0, $(this).val());
	});

	// Slideshow
	$('#h-demo').css('z-index', 1000).jqm({
    	trigger : '#h-group-container,#h-view-gallery',
    	overlay : 50,
    	onShow : function(hash) {
    	    $('#h-demo-slideshow').trigger('goto', [0]);
    		hash.w.fadeIn();
    	},
		onHide : function(hash) {
		    hash.w.fadeOut();
		    hash.o.remove();
		}
	});

	// When a demo is clicked
	$('#h-demo-detail').css('z-index', 1010).jqm({
    	trigger : '.h-demo-example,.h-random-example',
    	overlay : 50,
    	onShow : function(hash) {

		// Update the label
		$('#test5').val($("#test5 option:first").val()).ZINGCHARTupdateSelectLabel();
		hash.w.fadeIn();
		$('#h-demo-detail').css('left', ($('body').width()-$('#h-demo-detail').width())/2 + 'px');

			// Get IDs of chart
			var iDemoId = hash.t.id.replace('h-demo-example-', '').replace('h-random-example-', '');
    		iCatId = 0;
    		if (hash.t.className.indexOf('h-random-example') != -1) {
    			iCatId = parseInt(hash.t.className.replace('h-random-category-', '').replace('h-random-example', ''), 10);
    		}

			// Show the demo
    		demo.showDemo(iDemoId, iCatId, $('#test5').val());
		},
		onHide : function(hash) {
			zingchart.exec('h-demo-detail-zingchart', 'destroy');
			hash.w.fadeOut();
			hash.o.remove();
			$('#h-demo-detail-middle').html('<div id="h-demo-detail-zingchart">&nbsp;</div>');
		}
	});

	// Previous graph
	$('#h-demo-detail-left').click(function(e) {
		//$('#test5').val($("#test5 option:first").val()).ZINGCHARTupdateSelectLabel();
		e.preventDefault();
		zingchart.exec('h-demo-detail-zingchart', 'destroy');
		demo.showDemo(demo.prev, 0, $('#test5').val());
	});

	// Next graph
	$('#h-demo-detail-right').click(function(e) {
		//$('#test5').val($("#test5 option:first").val()).ZINGCHARTupdateSelectLabel();
		e.preventDefault();
		zingchart.exec('h-demo-detail-zingchart', 'destroy');
		demo.showDemo(demo.next, 0, $('#test5').val());
	});

	jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	};

	$('#more-prev, #more-next-disabled').hide();
	$('#more-prev-disabled, #more-next').show();

	$('#more-prev').attr('src', '/images/btn-demo-left-disabled.png');
	if ($('.h-demo-example').length <= 12) {
		$('#more-next').attr('src', '/images/btn-demo-right-disabled.png');
	}

	$('#h-demo-slideshow').serialScroll({
		items : 'li',
		prev : '#h-demo-examples a.prev',
		next : '#h-demo-examples a.next',
		duration : 1200,
		force : true,
		stop : true,
		lock : false,
		cycle : false,
		easing : 'easeOutQuart',
		jump : true,
		onBefore : function(e, elem, pane, items, pos) {
		    if (pos + 6 == items.length + 1 || items.length <= 6) { return false; }
			if (pos == 0) {
				$('#more-prev').attr('src', '/images/btn-demo-left-disabled.png');
			} else {
				$('#more-prev').attr('src', '/images/btn-demo-left.png');
			}
			if (pos + 6 == items.length) {
				$('#more-next').attr('src', '/images/btn-demo-right-disabled.png');
			} else {
				$('#more-next').attr('src', '/images/btn-demo-right.png');
			}
		}
	});

	// 'View example' on page
	$('#viewexample').click(function(e) {

		// Prevent default behavior
		e.preventDefault();
	});

	// Tooltips
	var initTooltips = function() {
		xOffset = 10;
		yOffset = 20;

		$('.tooltip').hover(function(e){
			this.t = $(this).attr('alt') || this.title;
			this.alt = '';
			this.title = '';
			$("body").append("<p id='tooltip' style='position: absolute; background-color: #FFF591; color: #333; font-size: 120%; padding: 3px 4px; -webkit-border-radius: 5px; -khtml-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;'>"+ this.t +"</p>");
			$(".tooltip")
				.css("top",(e.pageY - xOffset) + "px")
				.css("left",(e.pageX + yOffset) + "px")
				.fadeIn("fast");
		},

		function(){
			this.title = this.t;
			$(".tooltip").remove();
		});

		$(".tooltip a").mousemove(function(e){
			$(".tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
		});
	};

	// Page redirect
	var thisHref = document.location.toString();
	if (thisHref.match('#')) {
		$('a[href="#' + thisHref.split('#')[1] + '"]').click();
	}
	var page = thisHref.substr(thisHref.lastIndexOf("/"));
	if( !thisHref.match('#') && ( !page.length || page == '/' || page == '/index.php' || page =='/index-feature.php' ) ) {
		window.location = '#welcome'
	}

	// Get browser information
	$('#content-browser').html($.browser.name.toUpperCase() + ' ' + $.browser.versionNumber + ' (' + $.os.name.toUpperCase() + ')');

});

/*
 * jQuery.ScrollTo - Easy element scrolling using jQuery
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 06/05/2009
 * @author Ariel Flesler
 * @version 1.4.2
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(c){var a=c.scrollTo=function(f,e,d){c(window).scrollTo(f,e,d)};a.defaults={axis:"xy",duration:parseFloat(c.fn.jquery)>=1.3?0:1};a.window=function(d){return c(window)._scrollable()};c.fn._scrollable=function(){return this.map(function(){var e=this,d=!e.nodeName||c.inArray(e.nodeName.toLowerCase(),["iframe","#document","html","body"])!=-1;if(!d){return e}var f=(e.contentWindow||e).document||e.ownerDocument||e;return c.browser.safari||f.compatMode=="BackCompat"?f.body:f.documentElement})};c.fn.scrollTo=function(f,e,d){if(typeof e=="object"){d=e;e=0}if(typeof d=="function"){d={onAfter:d}}if(f=="max"){f=9000000000}d=c.extend({},a.defaults,d);e=e||d.speed||d.duration;d.queue=d.queue&&d.axis.length>1;if(d.queue){e/=2}d.offset=b(d.offset);d.over=b(d.over);return this._scrollable().each(function(){var l=this,j=c(l),k=f,i,g={},m=j.is("html,body");switch(typeof k){case"number":case"string":if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(k)){k=b(k);break}k=c(k,this);case"object":if(k.is||k.style){i=(k=c(k)).offset()}}c.each(d.axis.split(""),function(q,r){var s=r=="x"?"Left":"Top",u=s.toLowerCase(),p="scroll"+s,o=l[p],n=a.max(l,r);if(i){g[p]=i[u]+(m?0:o-j.offset()[u]);if(d.margin){g[p]-=parseInt(k.css("margin"+s))||0;g[p]-=parseInt(k.css("border"+s+"Width"))||0}g[p]+=d.offset[u]||0;if(d.over[u]){g[p]+=k[r=="x"?"width":"height"]()*d.over[u]}}else{var t=k[u];g[p]=t.slice&&t.slice(-1)=="%"?parseFloat(t)/100*n:t}if(/^\d+$/.test(g[p])){g[p]=g[p]<=0?0:Math.min(g[p],n)}if(!q&&d.queue){if(o!=g[p]){h(d.onAfterFirst)}delete g[p]}});h(d.onAfter);function h(n){j.animate(g,e,d.easing,n&&function(){n.call(this,f,d)})}}).end()};a.max=function(j,i){var h=i=="x"?"Width":"Height",e="scroll"+h;if(!c(j).is("html,body")){return j[e]-c(j)[h.toLowerCase()]()}var g="client"+h,f=j.ownerDocument.documentElement,d=j.ownerDocument.body;return Math.max(f[e],d[e])-Math.min(f[g],d[g])};function b(d){return typeof d=="object"?d:{top:d,left:d}}})(jQuery);
/*
 * jQuery.SerialScroll - Animated scrolling of series
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 06/14/2009
 * @author Ariel Flesler
 * @version 1.2.2
 * http://flesler.blogspot.com/2008/02/jqueryserialscroll.html
 */
;(function(a){var b=a.serialScroll=function(c){return a(window).serialScroll(c)};b.defaults={duration:1e3,axis:"x",event:"click",start:0,step:1,lock:!0,cycle:!0,constant:!0};a.fn.serialScroll=function(c){return this.each(function(){var t=a.extend({},b.defaults,c),s=t.event,i=t.step,r=t.lazy,e=t.target?this:document,u=a(t.target||this,e),p=u[0],m=t.items,h=t.start,g=t.interval,k=t.navigation,l;if(!r){m=d()}if(t.force){f({},h)}a(t.prev||[],e).bind(s,-i,q);a(t.next||[],e).bind(s,i,q);if(!p.ssbound){u.bind("prev.serialScroll",-i,q).bind("next.serialScroll",i,q).bind("goto.serialScroll",f)}if(g){u.bind("start.serialScroll",function(v){if(!g){o();g=!0;n()}}).bind("stop.serialScroll",function(){o();g=!1})}u.bind("notify.serialScroll",function(x,w){var v=j(w);if(v>-1){h=v}});p.ssbound=!0;if(t.jump){(r?u:d()).bind(s,function(v){f(v,j(v.target))})}if(k){k=a(k,e).bind(s,function(v){v.data=Math.round(d().length/k.length)*k.index(this);f(v,this)})}function q(v){v.data+=h;f(v,this)}function f(B,z){if(!isNaN(z)){B.data=z;z=p}var C=B.data,v,D=B.type,A=t.exclude?d().slice(0,-t.exclude):d(),y=A.length,w=A[C],x=t.duration;if(D){B.preventDefault()}if(g){o();l=setTimeout(n,t.interval)}if(!w){v=C<0?0:y-1;if(h!=v){C=v}else{if(!t.cycle){return}else{C=y-v-1}}w=A[C]}if(!w||t.lock&&u.is(":animated")||D&&t.onBefore&&t.onBefore(B,w,u,d(),C)===!1){return}if(t.stop){u.queue("fx",[]).stop()}if(t.constant){x=Math.abs(x/i*(h-C))}u.scrollTo(w,x,t).trigger("notify.serialScroll",[C])}function n(){u.trigger("next.serialScroll")}function o(){clearTimeout(l)}function d(){return a(m,p)}function j(w){if(!isNaN(w)){return w}var x=d(),v;while((v=x.index(w))==-1&&w!=p){w=w.parentNode}return v}})}})(jQuery);

var g_loaded = false;
var g_contents = "";
var g_currentTypeId;

var g_next = -1;
var g_prev = -1;
var g_nexttopic = -1;
var g_prevtopic = -1;

/* returns array of elements whose 'prop' property is 'value'*/
function filterByProperty(arr, prop, value) {
    return $.grep(arr, function (item) { return item[prop] == value });
}

/* populates select list from array of items given as objects: { name: 'text', value: 'value' }*/
function populateSelect(el, items, selectedName) {
    el.options.length = 0;

    $.each(items, function () {
        el.options[el.options.length] = new Option(this.name, this.value);
        if (selectedName == this.name || selectedName == this.value || (this.path && (this.path == selectedName))){
            el.options[el.options.length-1].selected = true;
        }
    });
}

zingchart.load = function(){
    g_loaded = true;
    if (g_contents){
        var contents = g_contents;
        g_contents = "";
        document.getElementById('zingchart').zcData(contents);
    }
}

function updateExample(json, options, justData){
    var name = json['name'];
    var desc = json['desc'];
    var highlight = json['highlight'];
    var filename = json['filename'];
    var contents = json['contents'];
    var topicdesc = json['topicdesc'];
    var topicname = $('#charttopic option:selected').text();
    var typename = $('#charttype option:selected').text();

    if (filename && !justData){
        submitForm(options, filename);
    }
    else{
        var typeId = $('#charttype').val();
        var type = filterByProperty(options, 'typeid', typeId);
        var typePath =  type[0]["typepath"];

        var fullName = typename + " Chart" + " : " + topicname + " - " + name;
        var icon ='<span class="link link-' + typePath + '">' + fullName + '</span>';
        $('#example-name').html(icon);
        $('#example-name2').html(name + " Example");
        $('#example-breadcrumb').html(fullName);
        $('#example-desc').html(desc);
        $('#topic-name').html(topicname);
        $('#topic-desc').html(topicdesc);
        $('#example-code').html('<pre class=\"brush: js; highlight: [' + highlight + '] \">' + contents + '</pre>');
        SyntaxHighlighter.highlight();
        initList();

        if(!justData){
            if (g_loaded && document.getElementById('zingchart').zcData){
                document.getElementById('zingchart').zcData(contents);
            }
            else{
                g_contents = contents;
            }
        }
    }

    document.body.style.cursor = 'default';

}

function updateInitExample(json){
    var name = json['name'];
    var desc = json['desc'];
    var topicdesc = json['topicdesc'];
    var topicname = $('#charttopic option:selected').text;

    $('#example-name').html(name);
    $('#example-name2').html(name + " Example");
    $('#example-desc').html(desc);
    $('#topic-name').html(topicname);
    $('#topic-desc').html(topicdesc);

}

function updateNextPrev(options, typeId, featureId){
    var topicId = $('#charttopic').val();

    var type = filterByProperty(options, 'typeid', typeId);
    if (type.length > 0) {
        var topic = filterByProperty(type[0].topic, 'topicid', topicId);
        var featureindex = -1;
        if (topic.length > 0){
            $.each(topic[0].feature, function (i) {
                if (featureId == this.featureid){
                    featureindex = i;
                }
            });
            if (featureindex != -1){
                if (featureindex-1 >= 0){
                    g_prev = topic[0].feature[featureindex-1].featureid;
                    g_prevtopic = -1;
                    $('#linkprev, #linkprev2').html("<< Previous: " + topic[0].feature[featureindex-1].featurename);
                    $('#linkprev, #linkprev2').show();
                }
                else{
                    /*find previous topic*/
                    var topicindex = -1;
                    $.each(type[0].topic, function (i) {
                        if (topicId == this.topicid){
                            topicindex = i;
                        }
                    });

                    if (topicindex != -1 && (topicindex-1 >= 0) ){
                        g_prev = type[0].topic[topicindex-1].feature[type[0].topic[topicindex-1].feature.length-1].featureid;
                        g_prevtopic = type[0].topic[topicindex-1].topicid;
                        $('#linkprev, #linkprev2').html("<< Previous: " + type[0].topic[topicindex-1].topicname + " - " + type[0].topic[topicindex-1].feature[type[0].topic[topicindex-1].feature.length-1].featurename);
                        $('#linkprev, #linkprev2').show();
                    }
                    else{
                        g_prev = -1;
                        g_prevtopic = -1;
                        $('#linkprev, #linkprev2').hide();
                    }

                }

                if (featureindex+1 < topic[0].feature.length){
                    g_next = topic[0].feature[featureindex+1].featureid;
                    g_nexttopic = -1;
                    $('#linknext, #linknext2').html("Next: " + topic[0].feature[featureindex+1].featurename + " >>");
                    $('#linknext, #linknext2').show();
                }
                else{
                    /*find next topic*/
                    var topicindex = -1;
                    $.each(type[0].topic, function (i) {
                        if (topicId == this.topicid){
                            topicindex = i;
                        }
                    });

                    if (topicindex != -1 && (topicindex+1 < type[0].topic.length) ){
                        g_next = type[0].topic[topicindex+1].feature[0].featureid;
                        g_nexttopic = type[0].topic[topicindex+1].topicid;
                        $('#linknext, #linknext2').html("Next: " + type[0].topic[topicindex+1].topicname + " - " + type[0].topic[topicindex+1].feature[0].featurename + " >>");
                        $('#linknext, #linknext2').show();
                    }
                    else{
                        g_next = -1;
                        g_nexttopic = -1;
                        $('#linknext, #linknext2').hide();
                    }
                }
            }
        }


    }
}

function clickNextPrev(next){
    var id;
    var topicid;
    if (next){
        id = g_next;
        topicid = g_nexttopic;
    }
    else{
        id = g_prev;
        topicid = g_prevtopic;
    }

    if (id == -1){
        return false;
    }

    if (topicid != -1){
        $('#charttopic').val(topicid);
        $('#charttopic, #charttopic2').trigger('change', [true]);
    }

    $('#chartfeature').val(id);
    $('#chartfeature, #chartfeature2').trigger('change', [true]);

    $('#viewexample').trigger('click');
    return false;
}
function linkExample(hash){

    var vals = hash.split("-");
    if (vals.length == 3){
        topicid = vals[1];
        featureid = vals[2];

        $('#charttopic').val(topicid);
        $('#charttopic, #charttopic2').trigger('change', [true]);

        $('#chartfeature').val(featureid);
        $('#chartfeature, #chartfeature2').trigger('change', [true]);

        $('#viewexample').trigger('click');
    }
    return false;


}

function loadExample(options, justData){

    var typeId = $('#charttype').val();
    var featureId = $('#chartfeature').val();
    var topicId = $('#charttopic').val();
    window.location.hash = typeId + "-" + topicId + "-" + featureId;

    g_currentTypeId = typeId;

    updateNextPrev(options, typeId, featureId);

    if (featureId == 141){
        $('#standard').hide();
        $('#init').show();
        $.getJSON('../includes/getexample.php?gt=' + typeId + '&gf=' + featureId, updateInitExample);
    }
    else{
        $('#init').hide();
        $('#standard').show();
        document.body.style.cursor = 'wait';
        $.getJSON('../includes/getexample.php?gt=' + typeId + '&gf=' + featureId, function(json){updateExample(json, options, justData);});
    }
 }

function populateSelectLists(options, graphType, graphTopic, graphFeature, justData, onlyDefaults){
    var firstload = true;

    if (onlyDefaults && window.location.hash){
        var vals = window.location.hash.split("-");
        if (vals.length == 3){
            graphType = vals[0].replace("#","");
            graphTopic = vals[1];
            graphFeature = vals[2];
        }
    }

    /* populating 1st select list*/
    populateSelect($('#charttype').get(0), $.map(options, function(option) { return { name: option.typename, value: option.typeid, path: option.typepath}; }), graphType);
    if($('#charttype2').size()){
        populateSelect($('#charttype2').get(0), $.map(options, function(option) { return { name: option.typename, value: option.typeid, path: option.typepath}; }), graphType);
    }

    /* populating 2nd select list*/
    var typechange = function() {

        var typeId = this.value;

        $('#charttype').val(typeId);
        if($('#charttype2').size()){
            $('#charttype2').val(typeId);
        }
        PINT.updateLabel(document.getElementById("charttype"));
        if($('#charttype2').size()){
            PINT.updateLabel(document.getElementById("charttype2"));
        }

        var type = filterByProperty(options, 'typeid', typeId);
        var topics = [];

        if (type.length > 0)
            topics = $.map(type[0].topic, function(topic) { return { name: topic.topicname, value: topic.topicid}; });

        populateSelect($('#charttopic').get(0), topics, graphTopic);
        if($('#charttype2').size()){
            populateSelect($('#charttopic2').get(0), topics, graphTopic);
        }
        $('#charttopic').trigger('change', [true]);
        if($('#charttype2').size()){
            $('#charttopic2').trigger('change', [true]);
        }

        graphType = typeId;
    };

    $('#charttype').bind('change', typechange);
    if($('#charttype2').size()){
        $('#charttype2').bind('change', typechange);
    }

    /* populating 3rd select list*/
    var topicchange = function (evt, auto) {
        var topicId = this.value;

        $('#charttopic').val(topicId);
        if($('#charttype2').size()){
            $('#charttopic2').val(topicId);
        }
        PINT.updateLabel(document.getElementById("charttopic"));
        if($('#charttype2').size()){
            PINT.updateLabel(document.getElementById("charttopic2"));
        }

        var typeId = $('#charttype').val();
        var features = [];
        var def = "";
        var featureset = true;

        if (!auto){
            featureset = false;
        }

        var type = filterByProperty(options, 'typeid', typeId);
        if (type.length > 0) {
            var topic = filterByProperty(type[0].topic, 'topicid', topicId);
            if (topic.length > 0){
                if (topic[0].defaultid){
                    def = topic[0].defaultid;
                }
                features = $.map(topic[0].feature, function(feature) { return { name: feature.featurename, value: feature.featureid}; });
            }
        }

        if (def && !firstload && !featureset )
            graphFeature = def;


        populateSelect($('#chartfeature').get(0), features, graphFeature);
        if($('#charttype2').size()){
            populateSelect($('#chartfeature2').get(0), features, graphFeature);
        }

        $('#chartfeature').trigger('change', [true]);
        if($('#charttype2').size()){
            $('#chartfeature2').trigger('change', [true]);
        }

        graphTopic = topicId;
    };
    $('#charttopic').bind('change', topicchange);
    if($('#charttype2').size()){
        $('#charttopic2').bind('change', topicchange);
    }

    var featurechange = function (evt, auto) {
        graphFeature = this.value;
        $('#chartfeature').val(graphFeature);
        if($('#charttype2').size()){
            $('#chartfeature2').val(graphFeature);
        }
        PINT.updateLabel(document.getElementById("chartfeature"));
        if($('#charttype2').size()){
            PINT.updateLabel(document.getElementById("chartfeature2"));
        }

        if (!auto)
            featureset = true;
    };

    $('#chartfeature').bind('change', featurechange);
    if($('#charttype2').size()){
        $('#chartfeature2').bind('change', featurechange);
    }

    $('#charttype').trigger('change');
    if($('#charttype2').size()){
        $('#charttype2').trigger('change');
        loadExample(options, justData);
    }

    firstload = false;
 }

 function viewExampleLink(options){
     $('#viewexample').bind('click', function(event){
        event.preventDefault();
	    submitForm(options,null,"/learn/");
     });
 }


    function submitForm(options, filename,prefix){
        var typeId = $('#charttype').val();
        var type = filterByProperty(options, 'typeid', typeId);
        if (!prefix){
            prefix = "../";
        }
        var url =  prefix + type[0]["typepath"] + "/";
        if (filename){
            document.getElementById("fn").value = filename;
        }
        else{
            document.getElementById("fn").value = "";
        }
        document.forms["docform"].action = url;
        document.forms["docform"].submit();
    };

 function initList(){
     $('#options li')
			.css('pointer','default')
			.css('list-style','none');
		$('#options li:has(ul) > span:first-child')
			.click(function(event){
			    event.preventDefault();
				if (this == event.target) {
					$(this).css('background-image',
						(!$(this).siblings('ul').is(':hidden')) ? 'url(/images/plusbox.gif)' : 'url(/images/minusbox.gif)');
					$(this).siblings('ul').slideToggle();
				}
				return false;
			})
			.css({cursor:'pointer', 'padding-left': '15px', 'background':'url(/images/plusbox.gif) no-repeat left center'});
		$('#options li ul').hide();
 }

 function listShowAll(){
     $('#options li:has(ul) > span:first-child')
        .css('background-image','url(/images/minusbox.gif)')
        .siblings('ul').show();
     return false;
 }

 function listHideAll(){
     $('#options li:has(ul) > span:first-child')
        .css('background-image','url(/images/plusbox.gif)')
        .siblings('ul').hide();

     return false;
 }



 function init(options, includeFilename){
    $('#init').hide();
    $('#standard').show();

    var zcObj = {
		liburl 			: '/package/zingchart.swf',
		width	 		: 660,
		height 			: 330,
		container 		: 'zingchart'
	};

    if (includeFilename){
        zcObj["dataurl"] = includeFilename;
    }


    zingchart.render(zcObj);

    initList();

    var viewclick = function (event) {
        event.preventDefault();
        var typeId = $('#charttype').val();
        if (g_currentTypeId != typeId && document.location.href.indexOf("index2") == -1){
            submitForm(options);
        }
        else{
	       loadExample(options);
        }
    };

	$('#viewexample').bind('click', viewclick);
	$('#viewexample2').bind('click', viewclick);

 }

