﻿var TEXTBOX_ID_KEY = "TextBoxID";
var WATERMARK_ID_KEY = "WaterMarkID";
var VALUEHIDDEN_ID_KEY = "ValueHiddenID";

Type.registerNamespace('ATI.Ajax.Scripts');

ATI.Ajax.Scripts.SearchFieldType = function() { }

ATI.Ajax.Scripts.SearchFieldType.prototype = {
  Normal: 0,
  Geo: 1,
  Date: 2
}
ATI.Ajax.Scripts.SearchFieldType.registerEnum("ATI.Ajax.Scripts.SearchFieldType", false);

ATI.Ajax.Scripts.PopupCloser = function() {
  ATI.Ajax.Scripts.PopupCloser.initializeBase(this);
}

ATI.Ajax.Scripts.PopupCloser.prototype = {
  OkButton: null,
  MessageHolder: null,
  Action: null,
  _cancelHandler: null,

  Prepare: function(p_sButtonID, p_sMessageHolderID, p_oActionDelegate, result) {
    this.OkButton = $get(p_sButtonID);
    this.MessageHolder = $get(p_sMessageHolderID);
    this.Action = p_oActionDelegate;
    this.MessageHolder.style.display = '';
    this._cancelHandler = Function.createDelegate(this, this.OnCancel);
    this._result = result;
    $addHandler(this.OkButton, "click", this._cancelHandler);
  },

  OnCancel: function(e) {
    var domEventVar = new Sys.UI.DomEvent(e);
    domEventVar.preventDefault();
    domEventVar.stopPropagation();
    $removeHandler(this.OkButton, "click", this._cancelHandler);
    if (this.MessageHolder)
      this.MessageHolder.style.display = 'none';
    if (this.Action) {
      this.Action(this._result);
    }
    this.OkButton = null;
    this.MessageHolder = null;
    this.Action = null;
    this._cancelHandler = null;
    return false;
  }
}

ATI.Ajax.Scripts.PopupCloser.registerClass('ATI.Ajax.Scripts.PopupCloser');



ATI.Ajax.Scripts.SearchDescriptor = function(p_sFieldName, p_EntityFieldType, p_SearchFieldType) {
  ATI.Ajax.Scripts.SearchDescriptor.initializeBase(this);
  this.FieldName = p_sFieldName;
  this.EntityFieldType = p_EntityFieldType;
  if (p_SearchFieldType != null)
    this.SearchFieldType = p_SearchFieldType;
}

ATI.Ajax.Scripts.SearchDescriptor.prototype = {
  FieldName: '',
  EntityFieldType: null,
  SearchFieldType: ATI.Ajax.Scripts.SearchFieldType.Normal,

  GetSerializedValue: function() {
    var fields = PageManager.FindField(this.EntityFieldType);
    var value = null;
    if (fields[0] != null &&
			fields[0].Value != null) {
      if (this.SearchFieldType == ATI.Ajax.Scripts.SearchFieldType.Date)
        value = fields[0].Value.substring(0, fields[0].Value.indexOf('T'));
      else if (this.SearchFieldType == ATI.Ajax.Scripts.SearchFieldType.Geo) {
        if (fields[0].Value != '' && fields[0].Value != '0')
          value = '2_' + fields[0].Value;
        else if (fields[1] != null && fields[1].Value != null && fields[1].Value != '' && fields[1].Value != '0')
          value = '1_' + fields[1].Value;
        else if (fields[2] != null && fields[2].Value != null && fields[2].Value != '' && fields[2].Value != '0')
          value = '0_' + fields[2].Value;
      }
      else
        value = fields[0].Value;
    }
    if (value == '' ||
			value == '0')
      return null;
    return value;
  }
}

ATI.Ajax.Scripts.SearchDescriptor.registerClass('ATI.Ajax.Scripts.SearchDescriptor');


ATI.Ajax.Scripts.PageManager = function() {
  ATI.Ajax.Scripts.PageManager.initializeBase(this);
}

ATI.Ajax.Scripts.PageManager.prototype = {
	OnAfterUpdateDelegate: null,
	BusinessObject: null,
	EmptyObject: null,
	EntityType: 0,
	Action: ATI.Ajax.Scripts.FormActions.CloseAndRedirect,
	PopupCloser: null,
	ID: -1,
	OperationType: 0,

	CreateEntity: function(p_EntityType, p_OnAfterCreateDelegate)
	{
		this.EntityType = p_EntityType;
		this.OnAfterCreateDelegate = p_OnAfterCreateDelegate;
		localhost.EditPages.EditProcessor.CreateEntity(this.EntityType, Function.createDelegate(this, this.CreateEntity_Callback),
            Function.createDelegate(this, this.OnAjaxRequestFailed));
	},

	CreateEntity_Callback: function(result)
	{
		this.BusinessObject = result;
		this.EmptyObject = Object.clone(result);
		if (this.OnAfterCreateDelegate)
			this.OnAfterCreateDelegate.call(null, result);
	},

	DoUpdate: function(p_OnAfterUpdateDelegate)
	{
		this.OnAfterUpdateDelegate = p_OnAfterUpdateDelegate;
		localhost.EditPages.EditProcessor.UpdateEntity(this.EntityType, this.BusinessObject, this.OperationType,
            Function.createDelegate(this, this.UpdateEntity_Callback),
            Function.createDelegate(this, this.OnAjaxRequestFailed));
	},

	DoAction: function(result)
	{
		switch (parseInt(this.Action))
		{
			case ATI.Ajax.Scripts.FormActions.PickEntity:
				this.TryChangeActionName(this.ID == -1);
				var handler = null;
				if (this.EnsureOpenerLocation())
					handler = function(p_str) { window.opener.location.href = p_str; };
				else
					handler = function(p_str) { setTimeout(String.format('window.open("{0}");', p_str), 1); };
				/*DoSearch(this.EntityType == ATI.BO.EntityType.Truck ? "Load" : "Truck",
				'/Tables/Default.aspx', handler);*/
				handler(result.PickEntityQueryString);
				window.close();
				break;
			case ATI.Ajax.Scripts.FormActions.AddNewClearForm:
				this.ClearForm();
				break;
			case ATI.Ajax.Scripts.FormActions.AddNewLeaveData:
				this.TryChangeActionName(true);
				this.SetIdentityField(-1);
				break;
			case ATI.Ajax.Scripts.FormActions.CloseAndRedirect:
				var sQuery = this.GetQueryString(true);
				if (this.EnsureOpenerLocation())
				{
					if (window.opener.location.href.indexOf(sQuery) == -1)
						window.opener.location.href = sQuery;
				}
				else
					window.open(sQuery);
				window.close();
				break;
			case ATI.Ajax.Scripts.FormActions.CloseAndGoArchive:
				if (this.EnsureOpenerLocation())
					window.opener.location.href = "/EditPages/OwnItemsArc.aspx?EntityType=Unpublished" +
                    (this.EntityType == ATI.BO.EntityType.Truck ? "Truck" : "Load");
				window.close();
				break;

			default:
				this.TryChangeActionName(true);
				window.close();
				break;
		}
		return false;
	},

	TryChangeActionName: function(p_bNew)
	{
		try
		{
			if (ChangeActionName)
				ChangeActionName(p_bNew);
		}
		catch (e) { }
	},

	ClearForm: function()
	{
		this.TryChangeActionName(true);
		this.ProcessPage(this.EmptyObject);
		this.BusinessObject = Object.clone(this.EmptyObject);
		this.ID = -1;
	},

	ReloadOpener: function()
	{
		if (this.EnsureOpenerLocation() &&
            window.opener.location.href.indexOf("OwnItems") != -1)
			window.opener.location.href = window.opener.location.href;
	},

	GetQueryString: function(p_bAddOwnMode)
	{
		var sParameter = '';
		switch (this.EntityType)
		{
			case ATI.BO.EntityType.Truck:
				sParameter = "Truck";
				break;
			case ATI.BO.EntityType.Contact:
				return "/Office/Default.aspx";
			default:
				sParameter = "Load";
				break;
		}
		return String.format("/EditPages/OwnItems.aspx?EntityType={0}", sParameter);
	},

	EnsureOpenerLocation: function() { return window.opener && window.opener.location; },

	UpdateEntity_Callback: function(result)
	{
		if (result)
		{
			if (result.IsException)
				result.Messages = [GetErrorDescription(result)];
			result.Successful = !(result.Messages && result.Messages.length > 0);
			if (result.CallbackFieldsJSON != null &&
                typeof (result.CallbackFieldsJSON) == "string" &&
                result.CallbackFieldsJSON != '')
				eval('result.CallbackFields = ' + result.CallbackFieldsJSON);
			if (result.Successful)
			{
				this.SetIdentityField(result.CallbackFields.ID);
				this.ReloadOpener();
			}
			if (this.OnAfterUpdateDelegate)
				this.OnAfterUpdateDelegate.call(null, result);
		}
	},

	OnAjaxRequestFailed: function(error)
	{
		if (this.OnAfterUpdateDelegate)
		{
			var result = { Messages: [GetErrorDescription(error)], IsException: true, Successful: false };
			this.OnAfterUpdateDelegate.call(null, result);
		}
		else
		{
			//���������������, ����� �� ����������� ��������� �� ������
			//alert(GetErrorDescription(error, false));
			window.close();
		}
	},

	BuildPickEntityUrl: function(p_sStart, p_aSearchDescriptors)
	{
		var sb = new Sys.StringBuilder(p_sStart);
		for (var i = 0; i < p_aSearchDescriptors.length; ++i)
		{
			var value = p_aSearchDescriptors[i].GetSerializedValue();
			if (value != null)
				sb.append(String.format("&{0}={1}", p_aSearchDescriptors[i].FieldName, value));
		}
		return sb.toString();
	},

	FindField: function(p_EntityFieldType)
	{
		var arrFields = [];
		for (var i = 0; i < this.BusinessObject.Fields.length; ++i)
			if (this.BusinessObject.Fields[i].EntityFieldType == p_EntityFieldType)
			arrFields.push(this.BusinessObject.Fields[i]);
		return arrFields;
	},

	SetIdentityField: function(p_iID)
	{
		this.ID = p_iID;
		for (var i = 0; i < this.BusinessObject.Fields.length; ++i)
			if (this.BusinessObject.Fields[i].EntityFieldType == ATI.BO.EntityFieldType.ID)
		{
			this.BusinessObject.Fields[i].Value = p_iID;
			this.SetFormValue(this.BusinessObject.Fields[i]);
			break;
		}
	},

	ProcessPage: function(p_entity)
	{
		var entity = p_entity ? p_entity : this.BusinessObject;
		for (var i = 0; i < entity.Fields.length; ++i)
			if (entity.Fields[i].UIControlType != ATI.BO.UIControlType.None)
			p_entity ? this.SetFormValue(entity.Fields[i]) : this.ProcessField(entity.Fields[i]);
	},

	ProcessField: function(p_field)
	{
		var sControlID = p_field.UIControlTypePrefix + p_field.FieldName;
		if (p_field.UIControlType == ATI.BO.UIControlType.RadioButton)
		{
			var aButtons = document.getElementByPartOfID(sControlID, "INPUT");
			for (var i = 0; i < aButtons.length; ++i)
				if (aButtons[i].checked)
			{
				p_field.Value = aButtons[i].id.replace(sControlID, "");
				return;
			}
		}
		var oControl = $get(sControlID);
		if (oControl)
			switch (p_field.UIControlType)
		{
			case ATI.BO.UIControlType.TextBox:
				p_field.Value = this.GetValueFromTextBox(oControl, p_field.UIControlTypePrefix);
				break;
			case ATI.BO.UIControlType.CheckBox:
				p_field.Value = oControl.checked;
				break;
			case ATI.BO.UIControlType.DropDownList:
				p_field.Value = oControl.options[oControl.selectedIndex].value;
				break;
			case ATI.BO.UIControlType.Hidden:
				p_field.Value = oControl.value;
				break;
			case ATI.BO.UIControlType.AutoCompleteTextBox:
				p_field.Value = this.GetAutocompleteValue(oControl);
				break;
			case ATI.BO.UIControlType.CheckBoxList:
				p_field.Value = this.GetValueFromCheckBoxList(sControlID);
				break;
			case ATI.BO.UIControlType.ListBox:
				var iFieldValue = 0;
				for (var i = 0; i < oControl.options.length; ++i)
				{
					if (oControl.options[i].selected)
					{
						var iValue = parseInt(oControl.options[i].value);
						if (iFieldValue == 0)
							iFieldValue = iValue;
						else
							iFieldValue |= iValue;
					}
				}
				p_field.Value = iFieldValue;
				break;
			case ATI.BO.UIControlType.CheckedListBox:
				p_field.Value = this.GetValueFromCheckedListBox(sControlID);
				break;
			case ATI.BO.UIControlType.Phone:
				p_field.Value = $find(sControlID).get_value();
				break;
			case ATI.BO.UIControlType.ExtraPoints:
				var xml = $get('hdnExtraPointsXML').value;
				p_field.Value = xml;
				break;
			case ATI.BO.UIControlType.FileUpload:
				if (oControl.files == null) //IE
					p_field.Value = oControl.value;
				else //FF 3
					p_field.Value = oControl.files.item(0).getAsText();
				break;
		}
	}

    , GetValueFromCheckedListBox: function(controlId)
    {
    	var iFieldValue = 0;
    	var aControls = document.getElementByPartOfID(controlId, "input");
    	for (var i = 0; i < aControls.length; ++i)
    	{
    		if (aControls[i].checked)
    		{
    			var iValue = this.GetValueFromItemControl(aControls[i]);
    			if (iFieldValue == 0)
    			{
    				iFieldValue = iValue;
    			} else
    			{
    				iFieldValue |= iValue; //setBitByNumber(iFieldValue, iValue);
    			}
    		}
    	}
    	return iFieldValue;
    }

    , SetFormValue: function(p_field)
    {
    	this.DisableValidation();
    	var sControlID = p_field.UIControlTypePrefix + p_field.FieldName;
    	if (p_field.UIControlType == ATI.BO.UIControlType.RadioButton)
    	{
    		var aButtons = document.getElementByPartOfID(sControlID, "INPUT");
    		for (var i = 0; i < aButtons.length; ++i)
    			if (p_field.Value == aButtons[i].id.replace(sControlID, ""))
    		{
    			aButtons[i].checked = true;
    			if (aButtons[i].onclick != null &&
                        typeof (aButtons[i].onclick) == "function")
    				aButtons[i].onclick();
    			return;
    		}
    	}
    	var oControl = $get(sControlID);
    	if (oControl)
    		switch (p_field.UIControlType)
    	{
    		case ATI.BO.UIControlType.TextBox:
    		case ATI.BO.UIControlType.Hidden:
    			oControl.value = p_field.Value == null ? '' : p_field.Value;
    			this.SetWatermark(oControl, p_field.UIControlTypePrefix);
    			$common.tryFireEvent(oControl, "change");
    			break;
    		case ATI.BO.UIControlType.CheckBox:
    			oControl.checked = p_field.Value;
    			break;
    		case ATI.BO.UIControlType.DropDownList:
    			oControl.selectedIndex = 0;
    			if (oControl.options &&
                        oControl.options.length > 0)
    			{
    				for (var i = 0; i < oControl.options.length; ++i)
    					if (oControl.options[i].value == p_field.Value)
    					oControl.selectedIndex = i;
    			}
    			if (oControl.onchange != null &&
                        typeof (oControl.onchange) == "function")
    				oControl.onchange();
    			break;
    		case ATI.BO.UIControlType.AutoCompleteTextBox:
    			this.SetAutocompleteValue(oControl, p_field.Value);
    			break;
    		case ATI.BO.UIControlType.CheckBoxList:
    			this.SetCheckBoxListValues(sControlID, p_field.Value);
    			var oTxt = $get('txt' + p_field.FieldName);
    			if (oTxt)
    				oTxt.value = String.join(p_field.Value);
    			break;
    		case ATI.BO.UIControlType.ListBox:
    			var iFieldValue = parseInt(p_field.Value);
    			for (var i = 0; i < oControl.options.length; ++i)
    			{
    				var iValue = parseInt(oControl.options[i].value);
    				oControl.options[i].selected = ((iValue & iFieldValue) == iValue);
    			}
    			break;
    		case ATI.BO.UIControlType.CheckedListBox:
    			var iFieldValue = parseInt(p_field.Value);
    			var aControls = document.getElementByPartOfID(sControlID, "input");
    			for (var i = 0; i < aControls.length; ++i)
    			{
    				var iValue = this.GetValueFromItemControl(aControls[i]);
    				aControls[i].checked = ((iValue & iFieldValue) == iValue);
    			}
    			break;
    		case ATI.BO.UIControlType.Phone:
    			$find(sControlID).set_value(p_field.Value);
    			break;
    	}
    	this.EnableValidation();
    },

	GetValueFromItemControl: function(p_ctl)
	{
		var iValue = parseInt(p_ctl.value);
		if (isNaN(iValue) &&
            p_ctl.parentNode != null)
			iValue = parseInt(p_ctl.parentNode.getAttribute('value'));
		return isNaN(iValue) ? 0 : iValue;
	},

	GetValueFromCheckBoxList: function(p_sControlID)
	{
		var aReturn = [];
		var aLabels = document.getElementsByTagName("label");
		if (aLabels && aLabels.length > 0)
			for (var i = 0; i < aLabels.length; ++i)
		{
			var sFor = aLabels[i].htmlFor;
			if (sFor == null)
				continue;
			if (sFor.indexOf(p_sControlID) > -1)
			{
				var oChk = $get(sFor);
				if (oChk && oChk.checked)
					aReturn.push(aLabels[i].innerHTML);
			}
		}
		return aReturn;
	},

	SetCheckBoxListValues: function(p_sControlID, p_aValues)
	{
		var aLabels = document.getElementsByTagName("label");
		if (aLabels && aLabels.length > 0)
			for (var i = 0; i < aLabels.length; ++i)
		{
			var sFor = aLabels[i].htmlFor;
			if (sFor == null)
				continue;
			if (sFor.indexOf(p_sControlID) > -1)
			{
				var oChk = $get(sFor);
				oChk.checked = Array.indexOf(p_aValues, aLabels[i].innerHTML) != -1;
			}
		}
	},

	GetValueFromTextBox: function(p_element, p_sPrefix, p_sReplacement)
	{
		if (p_sReplacement == null)
			p_sReplacement = "wme";
		var sWatermarkID = p_element.id.replace(p_sPrefix, p_sReplacement);
		var oExtender = $find(sWatermarkID);
		if (oExtender &&
            p_element.value == oExtender.get_WatermarkText())
			return "";
		return p_element.value;
	},

	SetWatermark: function(p_element, p_sPrefix, p_sReplacement)
	{
		if (p_sReplacement == null)
			p_sReplacement = "wme";
		var sWatermarkID = p_element.id.replace(p_sPrefix, p_sReplacement);
		var oExtender = $find(sWatermarkID);
		if (oExtender)
			oExtender._onBlur();
	},

	GetAutocompleteStringValue: function(p_element)
	{
		var oTxt = $get(p_element.getAttribute(TEXTBOX_ID_KEY));
		var sWatermarkID = p_element.getAttribute(WATERMARK_ID_KEY);
		return this.GetValueFromTextBox(oTxt, oTxt.id, sWatermarkID);
	},

	GetAutocompleteValue: function(p_element)
	{
		var stringValue = this.GetAutocompleteStringValue(p_element);
		if (stringValue == "")
			return 0;
		var oValueHidden = $get(p_element.getAttribute(VALUEHIDDEN_ID_KEY));
		if (oValueHidden)
		{
			var intValue = (oValueHidden.value.indexOf('_') == -1) ? parseInt(oValueHidden.value) : parseInt(oValueHidden.value.split('_')[1]);
			if (!isNaN(intValue) &&
                intValue != 0)
				return intValue;
		}
		return stringValue;
	},

	GetAutocompleteStringHiddenValue: function(p_element)
	{
		var stringValue = this.GetAutocompleteStringValue(p_element)
		if (stringValue == "")
			return "0";
		var oValueHidden = $get(p_element.getAttribute(VALUEHIDDEN_ID_KEY));
		if (oValueHidden)
			return oValueHidden.value;
		return "0";
	},

	SetAutocompleteValue: function(p_element, p_value)
	{
		var oTxt = $get(p_element.getAttribute(TEXTBOX_ID_KEY));
		var sWatermarkID = p_element.getAttribute(WATERMARK_ID_KEY);
		oTxt.value = '';
		var oValueHidden = $get(p_element.getAttribute(VALUEHIDDEN_ID_KEY));
		if (oValueHidden)
			oValueHidden.value = p_value;
		this.SetWatermark(oTxt, oTxt.id, sWatermarkID);
	},

	WriteMessage: function(p_oElement, p_message, p_sCssClass)
	{
		p_sCssClass = p_sCssClass == null ? "FieldComment" : p_sCssClass;
		var sPattern = '<p class="' + p_sCssClass + '"><b>{0}</b></p>';
		p_oElement.innerHTML = String.format(sPattern, p_message);
	},

	WriteMessages: function(p_oElement, p_messages, p_sCssClass)
	{
		p_sCssClass = p_sCssClass == null ? "FieldComment" : p_sCssClass;
		p_oElement.innerHTML = '';
		var sPattern = '<p class="' + p_sCssClass + '" style="color: Red;"><b>{0}</b></p>';
		var sMessages = '';
		for (var i = 0; i < p_messages.length; ++i)
			sMessages += String.format(sPattern, p_messages[i]);
		p_oElement.innerHTML = sMessages;
	},

	DisableValidation: function()
	{
		if (ValidatorOnChange)
		{
			this._ValidatorOnChange = ValidatorOnChange;
			ValidatorOnChange = function(event) { };
		}
	},

	EnableValidation: function()
	{
		if (this._ValidatorOnChange)
			ValidatorOnChange = this._ValidatorOnChange;
		this._ValidatorOnChange = null;
	},

	RecheckCarTypeDependencies: function(carTypeControl, carTypesControlId)
	{
		if (carTypesControlId && carTypeControl)
		{
			var bitSum = PageManager.GetValueFromCheckedListBox(carTypesControlId);
			var itemValue = this.GetValueFromItemControl(carTypeControl);
			if (itemValue)
			{
				var aControls = document.getElementByPartOfID(carTypesControlId, "input");
				for (var i = 0; i < aControls.length; ++i)
				{
					var iValue = this.GetValueFromItemControl(aControls[i]);
					if (carTypeControl.checked)
					{
						if ((iValue & bitSum) == iValue)
						{
							aControls[i].checked = true;
						}
					} else
					{
						if ((iValue & itemValue) != 0)
						{
							aControls[i].checked = false;
						}
					}
				}
			}
			return PageManager.GetValueFromCheckedListBox(carTypesControlId);
		}
	}
}

ATI.Ajax.Scripts.PageManager.registerClass('ATI.Ajax.Scripts.PageManager');

//Global object Page Manager
var PageManager = new ATI.Ajax.Scripts.PageManager();

if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();