﻿/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace( "WindowsSite.Ajax.Controls" );

WindowsSite.Ajax.Controls.ListPanelBehavior = function( element ) 
{
	this._onClickDelegate = Function.createDelegate( this, this._onClick );
	this._onApplicationLoadDelegate = Function.createDelegate( this, this._onApplicationLoad );
	this._onMethodCompleteDelegate = Function.createDelegate( this, this._onMethodComplete );
	this._onMethodErrorDelegate = Function.createDelegate( this, this._onMethodError );
	this._onParentSelectedItemChangedDelegate = Function.createDelegate( this, this._onParentSelectedItemChanged );

	this._callID = 0;
    this._currentCallID = -1;
    this._items = [];
    this._selectedItem = null;
    
    this._item$delegates = 
    {
		click		: Function.createDelegate( this, this._onItemClick ),
		mouseover	: Function.createDelegate( this, this._onItemMouseOver ),
		mouseout	: Function.createDelegate( this, this._onItemMouseOut )
    }
    
	WindowsSite.Ajax.Controls.ListPanelBehavior.initializeBase( this, [element] );
}

WindowsSite.Ajax.Controls.ListPanelBehavior.prototype =
{
	initialize: function() {
		var loading = this.get_LoadingPanel();
		if (loading) {
			this._popupBehavior = $create(AjaxControlToolkit.PopupBehavior, { parentElement: this.get_element() }, {}, {}, loading);
			this._popupBehavior.set_positioningMode(AjaxControlToolkit.PositioningMode.Center);
		}
		Sys.Application.add_load(this._onApplicationLoadDelegate);

		WindowsSite.Ajax.Controls.ListPanelBehavior.callBaseMethod(this, 'initialize');
	},

	_onApplicationLoad: function(sender, args) {
		if (this._servicePath && this._serviceMethod) {
			this._popupBehavior.show();
			this._currentCallID = ++this._callID;
			Sys.Net.WebServiceProxy.invoke(this._servicePath, this._serviceMethod, false,
				{},
				this._onMethodCompleteDelegate,
				this._onMethodErrorDelegate,
				this._currentCallID);
			$common.updateFormToRefreshATDeviceBuffer();
		}
		else {
			var parent = this.get_ParentPanel();
			if (parent) {
				parent.add_SelectedItemChanged(this._onParentSelectedItemChangedDelegate);
			}
		}
	},

	_onMethodComplete: function(result, userContext, methodName) {
		var selectFirstItem = true;
		if (userContext == this._currentCallID) {
			this._popupBehavior.hide();
			this._refreshItems(result);
			this.set_SelectedItem(this._items[0]);
		}
	},

	_refreshItems: function(source) {
		var element = this.get_element();
		element.innerHTML = "";
		Array.clear(this._items);
		this.set_SelectedItem(null);
		for (var i in source) {
			var itemHtml = source[i].Title;
			if (source[i].IsGenuine) itemHtml += "<img alt=\"Genuine\" src=\"" + this.get_GenuineIconUrl() + "\"/>";
			var item = $common.createElementFromTemplate(
				{
					nodeName: 'div',
					cssClasses: [this.get_ItemCssClass()],
					properties: { innerHTML: itemHtml },
					events: this._item$delegates
				}, element
			);
			item.dataItem = source[i];
			Array.add(this._items, item);
		}
		element.scrollTop = 0;
	},

	_onMethodError: function(webServiceError, userContext, methodName) {
		this._popupBehavior.hide();
		this.get_element().innerHTML = "<div class=\"serviceErrorMessage\">Error contacting web service</div>";
		// DEBUG: this.get_element().innerHTML = webServiceError.get_timedOut() ? AjaxControlToolkit.Resources.DynamicPopulate_WebServiceTimeout : String.format( AjaxControlToolkit.Resources.DynamicPopulate_WebServiceError, webServiceError.get_statusCode() );
	},

	_onParentSelectedItemChanged: function(sender, args) {
		var item = sender.get_SelectedDataItem(),
			items = item ? item.Items : null;
		if (items) {
			this._refreshItems(items);
		}
	},

	_onItemClick: function(args) {
		this.set_SelectedItem(args.target);
	},

	_onItemMouseOver: function(args) {
		Sys.UI.DomElement.addCssClass(args.target, this.get_ItemHighlightedCssClass());
	},

	_onItemMouseOut: function(args) {
		Sys.UI.DomElement.removeCssClass(args.target, this.get_ItemHighlightedCssClass());
	},

	get_SelectedItem: function() { return this._selectedItem; },
	set_SelectedItem: function(value) {
		if (this._selectedItem != value) {
			var selectedStyle = this.get_ItemSelectedCssClass();
			if (this._selectedItem) {
				Sys.UI.DomElement.removeCssClass(this._selectedItem, selectedStyle);
				this._selectedItem = null;
			}

			if (this._selectedItem = value) {
				Sys.UI.DomElement.addCssClass(value, selectedStyle);
			}

			this.raisePropertyChanged("SelectedItem");
		}
		this.onSelectedItemChanged(Sys.EventArgs.Empty);
	},

	get_ParentPanel: function() { return this._parentPanel; },
	set_ParentPanel: function(value) {
		if (this._parentPanel != value) {
			this._parentPanel = value;
			this.raisePropertyChanged("ParentPanel");
		}
	},

	get_SelectedDataItem: function() {
		return this._selectedItem ? this._selectedItem.dataItem : null;
	},

	get_ItemCssClass: function() { return this._itemCssClass; },
	set_ItemCssClass: function(value) {
		if (this._itemCssClass != value) {
			this._itemCssClass = value;
			this.raisePropertyChanged("ItemCssClass");
		}
	},

	get_ItemHighlightedCssClass: function() { return this._itemHighlightedCssClass; },
	set_ItemHighlightedCssClass: function(value) {
		if (this._itemHighlightedCssClass != value) {
			this._itemHighlightedCssClass = value;
			this.raisePropertyChanged("ItemHighlightedCssClass");
		}
	},

	get_ItemSelectedCssClass: function() { return this._itemSelectedCssClass; },
	set_ItemSelectedCssClass: function(value) {
		if (this._itemSelectedCssClass != value) {
			this._itemSelectedCssClass = value;
			this.raisePropertyChanged("ItemSelectedCssClass");
		}
	},

	_onClick: function(sender, args) {

	},

	get_ServicePath: function() {
		/// <value type="String" mayBeNull="true" optional="true">
		/// The URL of the web service to call.  If the ServicePath is not defined, then we will invoke a PageMethod instead of a web service.
		/// </value>
		return this._servicePath;
	},
	set_ServicePath: function(value) {
		if (this._servicePath != value) {
			this._servicePath = value;
			this.raisePropertyChanged('ServicePath');
		}
	},

	get_ServiceMethod: function() {
		/// <value type="String">
		/// The name of the method to call on the page or web service
		/// </value>
		return this._serviceMethod;
	},
	set_ServiceMethod: function(value) {
		if (this._serviceMethod != value) {
			this._serviceMethod = value;
			this.raisePropertyChanged('ServiceMethod');
		}
	},

	get_LoadingPanel: function() { return this._loadingPanel; },
	set_LoadingPanel: function(value) {
		if (this._loadingPanel != value) {
			this._loadingPanel = value;
			this.raisePropertyChanged("LoadingPanel");
		}
	},

	get_GenuineIconUrl: function() { return this._genuineIconUrl; },
	set_GenuineIconUrl: function(value) {
		if (this._genuineIconUrl != value) {
			this._genuineIconUrl = value;
			this.raisePropertyChanged("GenuineIconUrl");
		}
	},

	add_SelectedItemChanged: function(handler) {
		this.get_events().addHandler("SelectedItemChanged", handler);
	},

	remove_SelectedItemChanged: function(handler) {
		this.get_events().removeHandler("SelectedItemChanged", handler);
	},

	onSelectedItemChanged: function(e) {
		this._fireHandler("SelectedItemChanged", e);
	},

	_fireHandler: function(name, e) {
		var handlers = this.get_events().getHandler(name);
		if (handlers) {
			handlers(this, e ? e : Sys.EventArgs.Empty);
		}
	},

	dispose: function() {
		//Add custom dispose actions here
		WindowsSite.Ajax.Controls.ListPanelBehavior.callBaseMethod(this, 'dispose');
	}
}
WindowsSite.Ajax.Controls.ListPanelBehavior.registerClass( 'WindowsSite.Ajax.Controls.ListPanelBehavior', AjaxControlToolkit.BehaviorBase );
