/*globals jQuery*/
/*jslint 
nomen: false
white: false*/
/*
depends on:
wijreportviewer.js
c1splitter.js
*/
(function ($) {
	"use strict";
	$.widget("c1.c1reportviewer", $.wijmo.wijreportviewer, {
		options: {

			/// <summary>
			/// Indicates whether the toolbar will be visible.
			/// Default: true
			/// Type: Boolean.
			/// Code example: $("#element").c1reportviewer({ toolBarVisible: false });
			/// </summary>
			toolBarVisible: true,
			/// <summary>
			/// Indicates whether the status bar will be visible.
			/// Default: true
			/// Type: Boolean.
			/// Code example: $("#element").c1reportviewer({ statusBarVisible: false });
			/// </summary>
			statusBarVisible: true,
			///	<summary>
			///	A value indicates the location of the splitter, in pixels, from the left edge of the splitter.
			/// Default: 250
			/// Type: Number.
			/// Code example: $("#element").c1reportviewer({ splitterDistance: 400 });
			///	</summary>
			splitterDistance: 250,
			///	<summary>
			///	Specifies whether the tools panel will be collapsed.
			/// Default: false
			/// Type: Boolean.
			/// Code example: $("#element").c1reportviewer({ collapseToolsPanel: true });
			///	</summary>
			collapseToolsPanel: false,
			///	<summary>
			/// Specifies the set of tools that will be available for the user.
			/// Possible values are: none, outline, search, thumbs, all.
			/// Default: "all"
			/// Type: String.
			/// Code example: $("#element").c1reportviewer({ availableTools: "outline, thumbs" });
			///	</summary>
			availableTools: "all",
			///	<summary>
			///		The default tool that will be expanded in the tools panel.
			///		Possible values are: "outline", "search", "thumbs".
			///	</summary>
			expandedTool: "outline",
			/// <summary>
			/// Set this option to true if you want to run report viewer in 
			///	full screen mode. 
			/// Note, when full screen mode is enabled document overflow style 
			///	will be changed to hidden and viewer will be fit in parent 
			///	container bounds.
			/// Default: false
			/// Type: Boolean.
			/// </summary>
			fullScreen: false
		},

		_setOption: function (key, value) {
			var o = this.options;
			switch (key) {
				case "toolBarVisible":
					o.toolBarVisible = value;
					this._initToolbar();
					this.invalidate();
					break;
				case "statusBarVisible":
					o.statusBarVisible = value;
					this._initStatusbar();
					this.invalidate();
					break;
				case "splitterDistance":
					this.element.find(".c1-c1reportviewer-splitter")
						.c1splitter("option", "splitterDistance", value);
					break;
				case "collapseToolsPanel":
					this.element.find(".c1-c1reportviewer-splitter")
						.c1splitter("option", "panel1", { collapsed: value });
					break;
				case "availableTools":
					this._ensureAvailableTools(value);
					break;
				case "expandedTool":
					this._ensureExpandedTool(value);
					break;
				case "fullScreen":
					this._onFullScreenModeChanged(value);
					break;
				default:
					break;
			}
			$.wijmo.wijreportviewer.prototype._setOption.apply(this, arguments);
		},
		widgetEventPrefix: "c1reportviewer",
		_create: function () {
			var tabs = this.element.find(".c1-c1reportviewer-tabs"),
				splitter = this.element.find(".c1-c1reportviewer-splitter");
			this.element.addClass("c1-c1reportviewer");
			if (splitter.length > 0 && splitter[0].className.indexOf("wijmo-wijsplitter") == -1) {
				this.element.find(".c1-c1reportviewer-splitter").c1splitter({
					splitterDistance: this.options.splitterDistance,
					panel1:
				{
					scrollBars: "none",
					collapsed: this.options.collapseToolsPanel
				}
				});
			}
			splitter.bind("c1splittersized c1splitterexpanded c1splittercollapsed", $.proxy(this._onSplitterResize, this));
			//sized 
			tabs.wijtabs({ alignment: "left",
				scrollable: false,
				tabTemplate: "<li><a href=\"#{href}\" title=\"#{label}\"><span class=\"ui-icon\"></span></a></li>",
				cache: true,
				load: $.proxy(this._onTabPanelLoaded, this)
			});
			this._ensureAvailableTools(this.options.availableTools);
			this._ensureExpandedTool(this.options.expandedTool);
			$.wijmo.wijreportviewer.prototype._create.apply(this, arguments);
		},


		_init: function () {
			var o = this.options;
			$.wijmo.wijreportviewer.prototype._init.apply(this, arguments);
			// remove ui-helper-hidden-accessible before invalidate:
			this.element.removeClass("ui-helper-hidden-accessible");
			this._initToolbar();
			this._initStatusbar();
			if (o.fullScreen) {
				this._onFullScreenModeChanged(o.fullScreen);
			}
			this.invalidate();
			$(window).resize($.proxy(this._onWindowResize, this));
		},
		_onWindowResize: function () {
			this.invalidate();
		},

		_onFullScreenModeChanged: function (isFullScreen) {
			var o = this.options, zInd;
			if (isFullScreen && !this._fullScreenRestoreHash) {
				this._fullScreenRestoreHash = {
					width: this.element[0].style.width,
					height: this.element[0].style.height,
					left: this.element.css("left"),
					top: this.element.css("top"),
					position: this.element.css("position"),
					docOverflow: document.body.style.overflow
				};
				this._prevWidth = this.element.css("width");
				$("<div style=\"display:none;\" id=\"c1rvpfullscreen" +
					this.element[0].id
					+ "\"></div>").insertAfter(this.element);
				this.element.prependTo("body");
				this.element.css("position", "fixed"); //"absolute");
				this.element.css("left", "0px");
				this.element.css("top", "0px"); //$(window).scrollTop()+"px");
				this.element.css("width", "100%");
				if ($.browser.msie && $.browser.version < 8) {
					//fix for 24728   
					document.body.style.overflow = "visible";
					this.element.css("height", $(document).height() + "px");
				} else {
					document.body.style.overflow = "hidden";
					this.element.css("height", "100%");
				}

				zInd = this.element.css("z-index");

				if (!zInd || zInd < 1 || zInd === "auto") {
					this.element.css("z-index", 1000);
				}

				this.invalidate();
			} else {
				if (this._fullScreenRestoreHash) {
					$("#c1rvpfullscreen" + this.element[0].id).replaceWith(this.element);
					this.element.css("position", this._fullScreenRestoreHash.position);
					this.element[0].style.width = this._fullScreenRestoreHash.width;
					this.element[0].style.height = this._fullScreenRestoreHash.height;
					this.element.css("left", this._fullScreenRestoreHash.left);
					this.element.css("top", this._fullScreenRestoreHash.top);
					document.body.style.overflow = this._fullScreenRestoreHash.docOverflow;
					this.invalidate();
				}
				this._fullScreenRestoreHash = null;
			}
		},

		_ensureAvailableTools: function (availableTools) {
			availableTools = availableTools.toLowerCase();
			var tabs = this.element.find(".c1-c1reportviewer-tabs"), tabCount = 0,
				eleId = this.element[0].id;
			tabs.wijtabs("remove", 0).wijtabs("remove", 0);
			if (availableTools === "none") {
				return;
			}
			if (availableTools.indexOf("outline") !== -1 || availableTools === "all") {
				tabs.wijtabs("add", this.options.reportServiceUrl +
				"?clientId=" + eleId +
				"&command=dialog&name=outline&tabId=Outline_" + eleId,
					this.localizeString("toolNameOutline", "Outline")
				)
				.find(".ui-tabs-nav li:eq(" + tabCount + ") .ui-icon")
					.addClass("ui-icon-bookmark");
				this._outlineTabIndex = tabCount;
				tabCount = tabCount + 1;
			}
			if (availableTools.indexOf("search") !== -1 || availableTools === "all") {
				tabs.wijtabs("add", this.options.reportServiceUrl +
				"?clientId=" + eleId +
				"&command=dialog&name=search&tabId=Search_" + eleId,
this.localizeString("toolNameSearch", "Search")
 )
				.find(".ui-tabs-nav li:eq(" + tabCount + ") .ui-icon")
					.addClass("ui-icon-search");
				this._searchTabIndex = tabCount;
				tabCount = tabCount + 1;
			}
			if (availableTools.indexOf("thumbs") !== -1 || availableTools === "all") {
				tabs.wijtabs("add", this.options.reportServiceUrl +
				"?clientId=" + eleId + "&command=dialog&name=thumbs&tabId=Thumbs_" + eleId,
this.localizeString("toolNameThumbs", "Thumbs")

)
				.find(".ui-tabs-nav li:eq(" + tabCount + ") .ui-icon")
					.addClass("ui-icon-image");
				this._thumbsTabIndex = tabCount;
				tabCount = tabCount + 1;
			}
		},
		_ensureExpandedTool: function (toolName) {
			toolName = toolName.toLowerCase();
			if (toolName === "search") {
				this.element.find(".c1-c1reportviewer-tabs").wijtabs("select", 1);
			}
			else if (toolName === "thumbs") {
				this.element.find(".c1-c1reportviewer-tabs").wijtabs("select", 2);
			}
		},

		_onTabPanelLoaded: function (e, ui) {
			if ($(ui.panel).siblings(".wijmo-wijtabs-content").length > 0) {
				this.log("fix wijtabs problem (tabpanel inserted outside of the wijtabs-content)", "warning");
				$(ui.panel).siblings(".wijmo-wijtabs-content").append(ui.panel);
			}
			if (ui.index === this._outlineTabIndex) {
				this._initOutlineTool($(ui.panel).find(".c1-c1reportviewer-outlinetool"));
			} else if (ui.index === this._searchTabIndex) {
				this._initSearchTool($(ui.panel).find(".c1-c1reportviewer-searchtool"));
			} else if (ui.index === this._thumbsTabIndex) {
				this._initThumbsTool($(ui.panel).find(".c1-c1reportviewer-thumbstool"));
			}
		},
		_initOutlineTool: function (container) {
			this._outlineContainer = container;
			if (this._outlineData) {
				// fix for 20913 qq: why wijtabs load event called twice?
				this._onOutlineReceived(this._outlineData);
			}
		},
		_initSearchTool: function (container) {
			this._searchContainer = container;
			container.find(".searchbutton").button({}).click($.proxy(this._onSearchButtonClick, this));
		},
		_initThumbsTool: function (container) {
			this._thumbsContainer = container;
			this._loadThumbs();
		},

		// thumbs tool
		_loadThumbs: function () {
			var o = this.options, docStatus = o.documentStatus, j, s, reqPrefix,
					id = this.element[0].id;
			if (!this._thumbsContainer) {
				return;
			}
			if (!docStatus || docStatus.state !== 0) {
				this._thumbsContainer.find(".thumbs").html("");
				return;
			}
			reqPrefix = o.reportServiceUrl + "?clientId=" + this.element[0].id +
			"&documentKey=" + docStatus.documentKey + "&dpi=40&zoom=30&pageIndex=";
			s = "";
			for (j = 0; j < docStatus.pageCount; j++) {
				s += "<div class=\"thumb\" pageIndex=\"" + j + "\" onclick=\"$('#" + id + "').c1reportviewer('scrollToPage', " + j + ")\">";
				s += "<img style=\"\" src=\"" + (reqPrefix + j) + "\" />";
				s += "<label>" + (j + 1) + "</label>";
				s += "</div>";
			}
			this._thumbsContainer.find(".thumbs").html(s);
		},
		_clearThumbs: function () {
			if (this._thumbsContainer) {
				this._thumbsContainer.find(".thumbs").html("");
			}
		},


		// outline>
		_onOutlineReceived: function (outline) {
			this._outlineData = outline; // fix for 20913 qq: why wijtabs load event called twice?
			this._handleCommonResponseFlags(outline);
			var outlineEntries = outline.oes;
			if (outlineEntries && outlineEntries.length > 0) {
				this.log("Outline received, outline entries count: " + outlineEntries.length);
				if (this._outlineContainer) {
					this._outlineContainer.find(".status").hide();
					this._outlineContainer.find(".outlinetree.wijmo-wijtree").wijtree("destroy");
					this._outlineContainer.find(".outlinetree").html("<ul>" + this._renderOutlineItems("", outlineEntries, 0) + "</ul");
					//this._outlineContainer.find(".outlinetree").html("			<ul><li><a><span>!Folder 1 hi!</span></a></li><li><a><span>Fold!er 2</span></a></li></ul>")
					this._outlineContainer.find(".outlinetree").wijtree().
					find(".wijmo-wijtree-node").bind("click", function () {
						var p = parseInt($(this).find("a > span").attr("p"));
						if (isFinite(p)) {
							$(this).parents(".c1-c1reportviewer").c1reportviewer("scrollToPage", p);
						}
					});
					//$("li.outlinenode").wijtreenode("option", "itemIconClass", "ui-icon-document");
					//this._outlineContainer.find(".outlinetree").wijtreenode(itemIconClass: "ui-icon-file");
					//alert("outline.oes.length=" + outline.oes.length);
				}
			}
			else {
				this._clearOutline(true);
				this.log("Outline received, outline is empty.");
			}
		},

		_clearOutline: function (resetStatus) {
			if (this._outlineContainer) {
				this._outlineContainer.find(".outlinetree.wijmo-wijtree").wijtree("destroy").html("");
				if (resetStatus) {
					this._outlineContainer.find(".status").show().html(
this.localizeString("outlineStatus", "[no outline]")
);
				}
			}
		},
		_renderOutlineItems: function (s, outlineEntries, level) {
			var entry;
			if (outlineEntries && outlineEntries.length > 0) {
				for (var ii = 0; ii < outlineEntries.length; ii++) {
					entry = outlineEntries[ii];
					s += "<li class=\"outlinenode\" itemiconclass=\"ui-icon ui-icon-tag\"><a><span p=\"" + entry.p.toString() + "\">" + entry.text + "</span></a></li>";
					//
					this._renderOutlineItems(s, entry.oes, ++level);
				}
			}
			return s;
		},
		//<

		// search>
		_onSearchButtonClick: function () {
			var query, caseSensitive, useRegExp;
			if (this._searchContainer) {
				query = this._searchContainer.find(".query").val();
				caseSensitive = this._searchContainer.find(".casesensitive")[0].checked;
				useRegExp = false;
				this.searchText(query, caseSensitive, useRegExp, $.proxy(this._onSearchResultsReceived, this));
			}
			return false;
		},
		_onSearchResultsReceived: function (data) {
			this.log("Search results received: " + data);
			if (typeof data === "string") {
				try {
					data = this._jsonParse(data);
				} catch (ex) {
					this.log("Unable to parse search results. " +
																	ex, "error");
					return;
				}
			}
			if (!this._handleCommonResponseFlags(data)) {
				this._searchContainer.find(".searchresults")
					.html("Server error.");
				return;
			}
			var isLocalSearch = false;
			this._searchResults = data;
			if (!data.count) {
				this._searchContainer.find(".searchresults")
					.html(
this._formatString(this.localizeString("searchNoMatchesFoundFormat", "No Matches Found for '{0}'"), data.query)
					);
			}
			else {
				var s = '';
				s += '<span class=\"C1Label\">' +
					this._formatString(this.localizeString("searchMatchesFoundFormat", "{0} Matches Found"), data.count) +
					((isLocalSearch) ? '(Local)' : '') + '</span><br/>';
				var arr = data.ses;
				s += '<ul>';
				var currentPage = -1;
				for (var i = 0; i < arr.length; i++) {
					var se = arr[i];
					if (currentPage !== se.p) {
						currentPage = se.p;
						s += '<li class=\"C1ListItem C1HeaderItem\">';
						s += this._formatString(this.localizeString("searchResultPageFormat", "Page {0}:"), (se.p + 1));
						s += '</li>';
					}
					s += '<li class=\"C1ListItem\">';
					s += '<a href=\"javascript:void(null)\" onclick=\"$(\'#' + this.element[0].id + '\').c1reportviewer(\'goToSearchEntry\', ' + i + ');\">' + se.text + '</a>';
					s += '</li>';
				}
				s += '</ul>';
				this._searchContainer.find(".searchresults").html(s);
			}
		},

		_resetTools: function () {
			this._clearOutline(false);
			this._clearThumbs();
			if (this._searchContainer) {
				this._searchContainer.find(".searchresults").html("");
			}
		},
		//< end of tools implementation


		// public methods>

		/// <summary>
		/// Preview and print active report.
		/// </summary>
		printWithPreview: function () {
			var buttonsHash = {}, self = this;
			this._onNotifyPrintPreviewHashCode = null;
			if (!this.printWithPreviewDialog) {
				this.printWithPreviewDialog = $('<div title="' +
					this.localizeString("labelPrint", "Print") + '"><div class="reportdialogcontent" style="width: 100%; height:100%;">' +
					this.localizeString("activityLoading", "Loading...") +
				'</div></div>');
				this.printWithPreviewDialog.appendTo(this.element);

				buttonsHash[this.localizeString("buttonPrint", "Print")] = function () {
					var dialog = $(this),
								contentWindow;

					dialog.find(".ui-dialog-buttonset .ui-button")
												.button("option", "disabled", true);
					contentWindow = dialog.find(".previewframe")[0]
																		.contentWindow;
					contentWindow.focus();
					contentWindow.print();
					dialog.wijdialog("close");
					//alert("Can't print, please wait until document preview will be ready.");							
					$(this).wijdialog("close");
				};
				buttonsHash[this.localizeString("buttonPrintTips", "Print Tips")] = function () {
					//
					var tips = self.localizeString("printTips", "1. Make sure that preview area contains the correct content,\n"
                     + "   if needed wait until preview area has updated successfully\n"
                     + "2. Be aware that content inside the preview area of C1ReportViewer will be printed 'as is'.\n"
                     + "\n"
                     + "Note on printing:\n"
                     + "  While the Print button provides a convenient and quick way to print"
                     + "  all or part of a document, it should be understood that it has"
                     + "  significant limitations."
                     + "  Anything printed from within a Web browser is subject to the browser’s"
                     + "  formatting, page headers and footers and so on. So normally, to print"
                     + "  the final copy of a document you would probably want to use the Save"
                     + "  button to save it as PDF and print that instead."
                     + "  PDF documents created by Report Viewer should be identical in appearance"
                     + "  to the documents in the viewer – but should print much better as they may"
                     + "  be printed avoiding limitations imposed by the Web browser.");
					alert(tips);
				};
				buttonsHash[this.localizeString("buttonCancel", "Cancel")] = function () {
					$(this).wijdialog("close");
				};
				this.printWithPreviewDialog.wijdialog({
					captionButtons: {
						pin: { visible: false },
						refresh: { visible: false },
						toggle: { visible: false },
						minimize: { visible: false }
					},
					buttons: buttonsHash,
					modal: true, width: 600, height: 480
				}).find(".reportdialogcontent")
				  .load(this.options.reportServiceUrl + "?clientId=" + this.element[0].id +
							"&command=dialog&name=print",
					$.proxy(this._onReportDialogContentLoaded, this));
			} else {
				this._onNotifyPrintPreview();
			}

			this.printWithPreviewDialog.wijdialog("open");

			return false;
		},

		/// <summary>
		/// Invalidates the entire surface of the control 
		/// and causes the control to be redrawn.
		/// </summary>
		refresh: function () {
			this.invalidate();
		},

		/// <summary>
		/// Invalidates the entire surface of the control 
		/// and causes the control to be redrawn.
		/// </summary>
		invalidate: function () {
			var innerW = this.element.innerWidth(),
				innerH = this.element.innerHeight(),
				statusbar = this.element.find(".c1-c1reportviewer-statusbar"),
				toolbar = this.element.find(".c1-c1reportviewer-toolbar"),
				statusbarH = statusbar.is(":visible") ?
								statusbar.outerHeight() : 0,
				toolbarH = toolbar.is(":visible") ?
							toolbar.outerHeight() : 0,
				resultSplitterH = innerH - statusbarH - toolbarH,
				resultSplitterW = innerW;
			/*
			this.log("invalidating UI, innerW=" + innerW + ", innerH=" +
			innerH + ",statusbarH=" + statusbarH + ",toolbarH=" + toolbarH +
			",resultSplitterH=" + resultSplitterH +
			",resultSplitterW=" + resultSplitterW);
			*/
			this.element.find(".c1-c1reportviewer-splitter")
						.width(resultSplitterW).height(resultSplitterH)
						.c1splitter("refresh");
			this._changeZoom(this.options.zoom);
			this._invalidateToolsPanel();
			//
		},
		_onSplitterResize: function (e) {
			if (e.type !== "c1splittercollapsed") {
				this._invalidateToolsPanel();
			}
			this._changeZoom(this.options.zoom);
		},
		_invalidateToolsPanel: function () {
			var splitter = this.element.find(".c1-c1reportviewer-splitter"),
				navWidth = splitter.find(".ui-tabs-nav").outerWidth(),
				panel1ClientW = splitter.find(".wijmo-wijsplitter-v-panel1-content").innerWidth(),
				resultToolCntW = panel1ClientW - navWidth; // -2; //-2px fix for FF?
			if (resultToolCntW < 0) {
				resultToolCntW = 0;
			}
			splitter.find(".wijmo-wijsplitter-v-panel1-content .wijmo-wijtabs-content").width(resultToolCntW);
			/*
			this.log("Invalidating tools panel. panel1ClientW=" + panel1ClientW +
			", navWidth=" + navWidth + ",resultToolCntW=" + resultToolCntW);
			*/
		},
		_initStatusbar: function () {
			var statusbar = this.element.find(".c1-c1reportviewer-statusbar");
			if (!this.options.statusBarVisible) {
				statusbar.hide();
				return;
			} else {
				statusbar.show();
			}
			if (this.statusbarEventsAdded) {
				return true;
			}
			statusbar.addClass("ui-widget-header ui-corner-all");
			this.statusbarEventsAdded = true;
		},
		_initToolbar: function () {
			var toolbar = this.element.find(".c1-c1reportviewer-toolbar"),
				o = this.options;
			if (!o.toolBarVisible) {
				toolbar.hide();
				return;
			} else {
				toolbar.show();
			}
			if (this.toolbarEventsAdded) {
				return true;
			}

			toolbar.addClass("ui-widget-header ui-corner-all");


			this.element.bind("c1reportviewerpageindexchanged",
									$.proxy(this._onPageIndexChanged, this))
						.bind("c1reportviewerdocumentstatuschanged",
									$.proxy(this._onDocumentStatusChanged, this))
						.bind("c1reportviewerzoomchanged",
									$.proxy(this._onZoomChanged, this));
			//
			toolbar.find(".print").button({
				disabled: true,
				text: false,
				icons: {
					primary: "ui-icon-print"
				}
			}).click($.proxy(this.printWithPreview, this));

			toolbar.find(".export")
				.button({
					disabled: true,
					text: false,
					icons: {
						primary: "ui-icon-disk"
					}
				})
				.click($.proxy(this._onExportClick, this));
			toolbar.find(".select_export_format").button({
				disabled: true,
				text: false,
				icons: {
					primary: "ui-icon-triangle-1-s"
				}
			}).click(function () {
				return false;
			});
			toolbar.find(".exportgroup").buttonset();

			toolbar.find(".firstpage").button({
				disabled: true,
				text: false,
				icons: {
					primary: "ui-icon-seek-start"
				}
			}).click($.proxy(this.firstPage, this));

			toolbar.find(".previouspage").button({
				disabled: true,
				text: false,
				icons: {
					primary: "ui-icon-triangle-1-w"
				}
			}).click($.proxy(this.previousPage, this));

			toolbar.find(".nextpage").button({
				disabled: true,
				text: false,
				icons: {
					primary: "ui-icon-triangle-1-e"
				}
			}).click($.proxy(this.nextPage, this));

			toolbar.find(".lastpage").button({
				disabled: true,
				text: false,
				icons: {
					primary: "ui-icon-seek-end"
				}
			}).click($.proxy(this.lastPage, this));

			toolbar.find(".continuousview").button({
				text: false,
				icons: {
					primary: "ui-icon-carat-2-n-s"
				}
			}).click(function () {
				$(this).parents(".c1-c1reportviewer").c1reportviewer("option", "pagedView", !this.checked);
			});

			toolbar.find(".fullscreenmode").button({
				text: false,
				icons: {
					primary: "ui-icon-newwin"
				}
			}).click(function () {
				$(this).parents(".c1-c1reportviewer").c1reportviewer("option", "fullScreen", this.checked);
			});

			//

			toolbar.find(".zoomin").button({
				disabled: true,
				text: false,
				icons: {
					primary: "ui-icon-zoomin"
				}
			}).click($.proxy(this.zoomIn, this));

			toolbar.find(".zoomout").button({
				disabled: true,
				text: false,
				icons: {
					primary: "ui-icon-zoomout"
				}
			}).click($.proxy(this.zoomOut, this));

			toolbar.find(".zoom").val(o.zoom).bind("change", function () {
				$(this).parents(".c1-c1reportviewer").c1reportviewer("option", "zoom", $(this).val());
			});

			toolbar.find(".pageindex").val(o.pageIndex + 1).bind("change blur", function () {
				var ind = parseInt($(this).val());
				if (isFinite(ind)) {
					$(this).parents(".c1-c1reportviewer").c1reportviewer("option", "pageIndex", ind - 1);
				}
			}).bind("keypress", function (e) {
				var ind; if (e.keyCode === 13) {
					e.preventDefault(); ind = parseInt($(this).val());
					if (isFinite(ind)) {
						$(this).parents(".c1-c1reportviewer").c1reportviewer("option", "pageIndex", ind - 1);
					}
				}
			});


			//this._initZoomCombo();
			this.toolbarEventsAdded = true;
		},

		_onExportClick: function () {
			var o = this.options,
				docStatus = o.documentStatus,
				formatIndex = this._exportFmtInd || 0,
				exportFormats;
			if (docStatus) {
				exportFormats = docStatus.exportFormats;
				if (exportFormats &&
						formatIndex < exportFormats.length - 1) {
					this._exportFmtInd = formatIndex;
					this.exportToFile(exportFormats[formatIndex],
								exportFormats[formatIndex + 1]);
				}
			}
			return false;
		},
		/*
		_initZoomCombo: function () {
		$(".xoom").wijcombobox({
		data: [{ label: "10%", value: "10%" }, { label: "25%", value: "25%" },
		{ label: "50%", value: "50%" }, { label: "75%", value: "75%" },
		{ label: "100%", value: "100%" }, { label: "125%", value: "125%" },
		{ label: "200%", value: "200%" }, { label: "400%", value: "400%" },
		{ label: "actual size", value: "actual size" },
		{ label: "fit page", value: "fit page" },
		{ label: "fit width", value: "fit width" },
		{ label: "fit height", value: "fit height"}],
		"select": function (e, item) {
		$(this).parents(".c1-c1reportviewer").c1reportviewer("option", "zoom", item.value);
		}
		}
		).bind("keypress blur", function (e) {
		if (e.keyCode === 13) {
		e.preventDefault();
		}
		$(this).parents(".c1-c1reportviewer").c1reportviewer("option", "zoom", this.value);
		});
		$(".xoom").val(this.options.zoom);
		//$(".xoom").wijcombobox("option", "labelText", this.options.zoom);
		},
		*/




		_onPageIndexChanged: function (e, index) {
			this.element.find(".c1-c1reportviewer-toolbar .pageindex").val(index + 1);
			this._ensureIndexToolbarButtonsState();
		},

		_onDocumentStatusChanged: function (e, docStatus) {
			var pageCountStr = docStatus.pageCount;
			switch (docStatus.state) {
				case 0: //generated:
					if (this._outlineContainer) {
						this._outlineContainer.find(".status").show().html(
				this.localizeString("activityLoadingOutline", "Loading outline...")
						);
					}
					this.loadOutline($.proxy(this._onOutlineReceived, this));
					this._loadThumbs();
					this._onExportFormatsChanged(docStatus.exportFormats);
					break;
				case 1: //GeneratingPages

					pageCountStr = this._getPageCountProgressString(docStatus.pageCount);
					if (this._outlineContainer) {
						this._outlineContainer.find(".status").show().html(
							this.localizeString("activityGenerating", "Generating...")
						);
					}
					break;
				case 2: //UpdatingPages
					if (this._outlineContainer) {
						this._outlineContainer.find(".status").show().html(
							this.localizeString("activityUpdatingPages", "Updating pages...")
						);
					}
					break;
				case 3: //ParametersRequested
					if (this._outlineContainer) {
						this._outlineContainer.find(".status").show().html(
							this.localizeString("activityWaitingForInput", "Waiting for input...")
						);
					}
					break;
				default:
					break;
			}
			this.element.find(".c1-c1reportviewer-toolbar .pagecount").html(pageCountStr);
			this._ensureDocStatusUIState();
		},
		_onExportFormatsChanged: function (exportFormats) {
			var formatDesc = "", formatExt = "", i = 0, s = "",
				menuTrigger = "#" + this.element[0].id +
					" .c1-c1reportviewer-toolbar .select_export_format";
			if ($(menuTrigger).length < 1) {
				return;
			}
			if (exportFormats) {
				while (i < exportFormats.length) {
					formatDesc = exportFormats[i];
					i++;
					formatExt = exportFormats[i];
					i++;
					s += "<li><a href=\"#\">" + formatDesc + "</a></li>";

					//C1ToolBarButton item = new C1ToolBarButton(null);                            
					//item.CommandName = "ExportToFile";
					//item.Text = formatDesc;
					//item.Value = formatExt;
					//exportDropDown.Items.Add(item);
				}
			}
			s = "<ul>" + s + "</ul>";
			if (this._exportMenu) {
				this._exportMenu.c1menu("destroy");
				this._exportMenu.remove();
			}
			this._exportMenu = $(s);
			this._exportMenu.appendTo(this.element)
			this._exportMenu.c1menu({
				orientation: "vertical",
				trigger: menuTrigger,
				position: { my: "left bottom",
					at: "left top"
				},
				select: $.proxy(this._onExportFormatSelected, this)
			});
		},
		_onExportFormatSelected: function (e, args) {
			var o = this.options,
				docStatus = o.documentStatus,
				formatIndex = args.item.index() * 2,
				exportFormats;
			if (docStatus) {
				exportFormats = docStatus.exportFormats;
				if (exportFormats &&
						formatIndex < exportFormats.length - 1) {
					this._exportFmtInd = formatIndex;
					this.exportToFile(exportFormats[formatIndex],
								exportFormats[formatIndex + 1]);
				}
			}
			return false;
		},
		_getPageCountProgressString: function (pageCount) {
			var i, s = "";
			if (!this._pageCountProgressCounter || this._pageCountProgressCounter > 3) {
				this._pageCountProgressCounter = 1;
			}
			for (i = 0; i < this._pageCountProgressCounter; i++) {
				s = s + ".";
			}
			this._pageCountProgressCounter++;
			return pageCount + s;
		},
		_ensureDocStatusUIState: function () {
			var docStatus = this.options.documentStatus,
				toolbar = this.element.find(".c1-c1reportviewer-toolbar");

			if (docStatus.state !== 0) {

				toolbar.find(".print.ui-button").button("option", "disabled", true)
														.removeClass("ui-state-hover")
														.removeClass("ui-state-focus");

				toolbar.find("button.ui-button").button("option", "disabled", true);

				this._resetTools();

			} else {
				toolbar.find("button.ui-button").button("option", "disabled", false);
			}
			this._ensureIndexToolbarButtonsState();
		},
		_ensureIndexToolbarButtonsState: function () {
			if (!this.toolbarEventsAdded) {
				return;
			}
			var o = this.options, pageIndex = o.pageIndex,
				docStatus = o.documentStatus,
				pageCount = docStatus.pageCount,
				toolbar = this.element.find(".c1-c1reportviewer-toolbar");
			if (pageIndex < 1 || pageCount === 0) {
				toolbar.find(".firstpage").button("option", "disabled", true)
														.removeClass("ui-state-hover")
														.removeClass("ui-state-focus");
				toolbar.find(".previouspage").button("option", "disabled", true)
														.removeClass("ui-state-hover")
														.removeClass("ui-state-focus");
			} else {
				toolbar.find(".firstpage").button("option", "disabled", false);
				toolbar.find(".previouspage").button("option", "disabled", false);
			}
			if (pageIndex === (pageCount - 1) || pageCount === 0) {
				toolbar.find(".nextpage").button("option", "disabled", true)
														.removeClass("ui-state-hover")
														.removeClass("ui-state-focus");
				toolbar.find(".lastpage").button("option", "disabled", true)
														.removeClass("ui-state-hover")
														.removeClass("ui-state-focus");
			} else {
				toolbar.find(".nextpage").button("option", "disabled", false);
				toolbar.find(".lastpage").button("option", "disabled", false);
			}
		},

		// print with preview internal implementation>
		_onReportDialogContentLoaded: function () {
			var cnt = this.printWithPreviewDialog.find(".reportdialogcontent"),
				h = $.proxy(this._onNotifyPrintPreview, this);
			this._onNotifyPrintPreviewHashCode = null;
			this._onNotifyPrintPreview();
			cnt.find(".notifypreview").bind("change",
                      h).keyup(
                      h).bind("click",
                      h);
		},

		_onNotifyPrintPreview: function (e) {
			var printOpts;
			if (this._onNotifyPrintPreviewLock)
				return;
			this._onNotifyPrintPreviewLock = true;
			printOpts = this._readPrintPreviewInput();
			if (this._onNotifyPrintPreviewHashCode &&
				this._onNotifyPrintPreviewHashCode === printOpts._hashCode) {
				this._onNotifyPrintPreviewLock = false;
				return;
			}
			this._onNotifyPrintPreviewHashCode = printOpts._hashCode;
			if (e && e.type == "keypress") {
				if (e.keyCode == 13) {
					this._refreshPrintPreviewFrame(printOpts);
				}
			}
			else {
				this._refreshPrintPreviewFrame(printOpts);
			}
			this._onNotifyPrintPreviewLock = false;

		},
		_readPrintPreviewInput: function () {
			var isRangeAll, isRangeVisible, isRangePages,
				rangeSubsetValue, isReversePages,
				printOptions = {},
				cnt = this.printWithPreviewDialog.find(".reportdialogcontent"),
				k, kk, hc = "", rangePagesValueStr, pageSets, visiblePages;
			/*
			pageRanges: [0, pageCount - 1], // array of page ranges to print
			*reversePages: false, // reverse pages during print
			*rangeSubset: 0, // // print range subset: 0 - all, 1 - odd, 2 - even
			*dpi: 150, // page images rendering DPI
			*zoom: 100 // pages zoom
			*/
			isRangeAll = cnt.find(".printrange-all")[0].checked;
			isRangeVisible = cnt.find(".printrange-visible")[0].checked;
			isRangePages = cnt.find(".printrange-pages")[0].checked;

			printOptions.reversePages = cnt.find(".reversepages")[0].checked;
			printOptions.rangeSubset = parseInt(cnt.find(".printrange-subset").val());

			rangePagesValueStr = cnt.find(".pagerange").val();

			if (isRangeAll) {
				printOptions.pageRanges = [0, this.options.documentStatus.pageCount];
			} else if (isRangeVisible) {
				visiblePages = this.getVisiblePageIndices();
				if (visiblePages.length < 1) {
					printOptions.pageRanges = [];
					alert("Visible pages not found, nothing to print.");
				} else {
					pageSets = [];
					for (k = 0; k < visiblePages.length; k++) {
						pageSets.push(visiblePages[k]); //set start
						pageSets.push(visiblePages[k]); //set end
					}
					pageSets = [visiblePages[0], visiblePages[visiblePages.length - 1]];
					printOptions.pageRanges = pageSets;
				}
			} else if (isRangePages) {
				try {
					pageSets = [];
					var aArr = rangePagesValueStr.split(',');
					for (k = 0; k < aArr.length; k++) {
						var aPageRange = aArr[k];
						if (!aPageRange || aPageRange == "")
							break;
						if (aPageRange.indexOf('-') == -1) {
							pageSets.push(parseInt(aPageRange) - 1); //set start
							pageSets.push(parseInt(aPageRange) - 1); //set end
						} else {
							var aArr2 = aPageRange.split('-');
							if (!aArr2[0])
								break;
							pageSets.push(parseInt(aArr2[0]) - 1); //set start
							if (aArr2[1]) {
								pageSets.push(parseInt(aArr2[1]) - 1); //set end    
							} else {
								pageSets.push(parseInt(aArr2[0]) - 1); //set end    
							}
						}
					}
					for (k = 0; k < pageSets.length; k++) {
						if (isNaN(pageSets[k])) {
							throw "Incorrect input: " + rangePagesValueStr;
						}
					}
					printOptions.pageRanges = pageSets;
				} catch (ex) {
					printOptions.pageRanges = [];
					alert("Error: " + ex);
				}
			}
			for (k in printOptions) {
				hc += "-" + printOptions[k];
			}
			printOptions._hashCode = rangePagesValueStr + hc;
			//alert("printOptions._hashCode?" + printOptions._hashCode + "; printOptions.rangeSubset?" + printOptions.rangeSubset);
			return printOptions;
		},
		_refreshPrintPreviewFrame: function (printOpts) {
			var previewerFrame = this.printWithPreviewDialog.find(".previewframe")[0],
				previewerFrameDocument;
			if (previewerFrame.contentDocument) {
				previewerFrameDocument = previewerFrame.contentDocument;
			} else {
				previewerFrameDocument = previewerFrame.contentWindow.document;
			}

			this.loadPreviewHtml(printOpts, function (data) {
				previewerFrameDocument.open('text/html', 'replace');
				previewerFrameDocument.write(data);
				previewerFrameDocument.close();
				window.setTimeout(function () {
					var body = previewerFrameDocument.body;
					if (body) {
						body.parentNode.style.margin = "0";
						body.style.margin = "0";
						body.style.padding = "0";
						body.style.backgroundColor = "#FFFFFF";
					}
				}, 1000);
			});
		},
		//< print with preview implementation

		//zoom combo behavior:
		_onZoomChanged: function (e, zoom, resolvedZoom) {
			var zoomSel = this.element.find(".c1-c1reportviewer-toolbar").find(".zoom"),
				isPercentage = false, newOption;
			zoom = zoom.replace("%", "").toLowerCase();
			if (zoom === "actual size" || zoom === "fit page" ||
				zoom === "fit width" || zoom === "fit height") {
			} else {
				zoom = resolvedZoom + "%";
				isPercentage = true;
			}
			if (zoomSel.find("option[value='" + zoom + "']").length > 0) {
				zoomSel.val(zoom);
			} else {
				if (isPercentage) {
					newOption = $("<option value=\"" + resolvedZoom +
						"%\" selected=\"selected\">" + resolvedZoom + "%</option>");
					zoomSel.find("option").each(function (ind, el) {
						if (parseInt(el.value.replace("%", ""), 10) > resolvedZoom) {
							newOption.insertBefore(el);
							newOption = null;
							return false;
						}
					});
					if (newOption) {
						if (zoomSel.find("option[value='actual size']").length > 0) {
							newOption.insertBefore(zoomSel.find("option[value='actual size']"));
						} else {
							newOption.appendTo(zoomSel);
						}
					}
					zoomSel.val(zoom); /*fix for 20922 case 1*/
				} else {
					this.log("zoom value not found:" + zoom, "warning");
				}
			}
		}

	}
	);
} (jQuery));