/* DIFFERENT STANDALONE AND CONVINIENCE FUNCTIONS FOR CALCULATORS. */
/* No Initialization information must be placed here */

CalcUtils = function() {
	this.setOwnerType();
	/*		this.setDriversToggle();*/
}



CalcUtils.prototype = {

	watchCalcChanges: function()
	{
		var handler = function(event) { CalcActionButtons.setCalculateQuotationState(event); };
		$("#operationalButtonsToggleHolder input[type='checkbox']").click(handler);
		$("#operationalButtonsToggleHolder input[type!='checkbox'],#operationalButtonsToggleHolder select").change(handler);
	},

	setDependency: function(subject, object, eventType, properties)
	{
		var subject = $(subject);
		if (typeof (subject[0].actions) == "undefined")
		{
			subject[0].actions = new Array();
			subject[0].actions.dependent = new Array();
			subject[0].actions.properties = new Array();
		}
		subject[0].actions.push(eventType);
		subject[0].actions.dependent.push(object);
		subject[0].actions.properties.push(properties);
		if (subject[0].nodeName == 'SELECT')
		{
			subject.change(
							function()
							{
								for (var i = 0; i < this.actions.length; i++)
								{
									this.actions[i](i, this);
								}
							}
						);
		} else if (subject[0].nodeName == 'DIV' && eventType == cUtils.dependencyTypes.radio)
		{
			$('input', subject).click(
							function()
							{
								for (var i = 0; i < subject[0].actions.length; i++)
								{
									subject[0].actions[i](i, subject[0]);
								}
							}
						);
		} else
		{
			subject.click(
							function()
							{
								for (var i = 0; i < this.actions.length; i++)
								{
									this.actions[i](i, this);
								}
							}
						);
		}
	},

	checkDependenciesAfterLoad: function(inputcols)
	{
		for (var i = 0; i < inputcols.length; i++)
		{
			try
			{
				var actions = inputcols[i].actions;
				for (var j = 0; j < actions.length; j++)
				{
					actions[j](j, inputcols[i]);
				}
			} catch (e) { }
		}
	},

	dependencyTypes: {

		radioSelect: function(order, thisEl)
		{
			var dependent = $(this.dependent[order]);
			if (this.properties[order]['isInversed'])
			{
				if (thisEl.checked)
				{
					$(dependent).removeAttr('checked');
				}
			}
			try { this.properties[order]['callback']() } catch (e) { };
		},

		checked: function(order, thisEl)
		{
			var dependent = $(this.dependent[order]).not(".autosuggest");
			var isIgnored = false;
			if (thisEl.disabled && this.properties[order]['isInactive'])
			{
				isIgnored = true;
			}
			if (!isIgnored)
			{
				if (this.properties[order]['isInversed'])
				{
					if (thisEl.checked)
					{
						dependent.hide().css("visibility", "hidden"); ;
						$('input, select:not(.autosuggest), textarea', dependent).not(".autosuggest").attr('disabled', 'disabled');
					} else
					{
						dependent.show().css("visibility", "visible");
						$('input, select:not(.autosuggest), textarea', dependent).not(".autosuggest").removeAttr('disabled');
					}
				} else
				{
					if (thisEl.checked)
					{
						dependent.show().css("visibility", "visible");
						$('input, select:not(.autosuggest), textarea', dependent).not(".autosuggest").removeAttr('disabled');
					} else
					{
						dependent.hide().css("visibility", "hidden");
						$('input, select:not(.autosuggest), textarea', dependent).not(".autosuggest").attr('disabled', 'disabled')
					}

				}
				try { this.properties[order]['callback']() } catch (e) { };
			}
		},

		selected: function(order, thisEl)
		{
			var dependent = $(this.dependent[order]).not(".autosuggest");
			if (!this.properties[order]['isInversed'])
			{
				for (var i = 0; i < this.properties[order]['values'].length; i++)
				{
					if (this.properties[order]['values'][i] == thisEl.value)
					{
						dependent.show().css("visibility", "visible");
						$('input, select:not(.autosuggest), textarea', dependent).removeAttr('disabled');
						return null;
					}
				}
				dependent.hide().css("visibility", "hidden");
				$('input, select:not(.autosuggest), textarea', dependent).attr('disabled', 'disabled')
			} else
			{
				for (var i = 0; i < this.properties[order]['values'].length; i++)
				{
					if (this.properties[order]['values'][i] == thisEl.value)
					{
						dependent.hide().css("visibility", "hidden");
						$('input, textarea', dependent).attr('disabled', 'disabled');
						var sb = $("select:not(.autosuggest)", dependent);
						sb.each(function(){
							var sbi = $(this);
							if (sbi.children().filter("option").length != 0) {
								sbi.removeAttr('disabled');
							}
						});
						return null;
					}
				}
				dependent.show().css("visibility", "visible");
				$('input, textarea', dependent).removeAttr('disabled');
				var sb = $("select:not(.autosuggest)", dependent);
				sb.each(function(){
					var sbi = $(this);
					if (sbi.children().filter("option").length != 0) {
						sbi.removeAttr('disabled');
					}
				});
			}
			try { this.properties[order]['callback']() } catch (e) { };
		},

		radio: function(order, thisEl)
		{
			var dependent = $(this.dependent[order]);

			//var radioNode = $('input:radio', $(this.dependent[order]));
			//var value = $('input:checked', $(this.dependent[order])).val();
			var value = $('input:checked', $(thisEl)).val();
			if (!this.properties[order]['isInversed'])
			{
				for (var i = 0; i < this.properties[order]['values'].length; i++)
				{
					if (this.properties[order]['values'][i] == value)
					{
						dependent.show().css("visibility", "visible");
						$('input, select:not(.autosuggest), textarea', dependent).removeAttr('disabled');
						return null;
					}
				}
				dependent.hide().css("visibility", "hidden");
				$('input, select:not(.autosuggest), textarea', dependent).attr('disabled', 'disabled')
			} else
			{
				for (var i = 0; i < this.properties[order]['values'].length; i++)
				{
					if (this.properties[order]['values'][i] == value)
					{
						dependent.hide().css("visibility", "hidden");
						$('input, select:not(.autosuggest), textarea', dependent).attr('disabled', 'disabled');
						return null;
					}
				}
				dependent.show().css("visibility", "visible");
				$('input, select:not(.autosuggest), textarea', dependent).removeAttr('disabled')
			}
			try { this.properties[order]['callback']() } catch (e) { };
		}
	},

	initDependencyGroup: function(dependencyGroup)
	{
		for (var i = 0; i < dependencyGroup.length; i++)
		{
			this.setDependency(dependencyGroup[i]['main'], dependencyGroup[i]['dependant'], dependencyGroup[i]['type'], dependencyGroup[i]['params']);
		}
	},

	powerUnits: {
		convertHPtoKwt: function(inpValue)
		{
			var val = !this.value ? inpValue : this.value;
			if (!isNaN(val))
				$('#Kilowatt').attr('value', Math.round(val / 1.35962162));
			else
				$('#Kilowatt').attr('value', '');
		},

		convertKwttoHP: function(inpValue)
		{
			var val = !this.value ? inpValue : this.value;
			if (!isNaN(val))
				$('#Horsepower').attr('value', Math.round(val * 1.35962162));
			else
				$('#Horsepower').attr('value', '');
		},

		setPowerUnits: function(e)
		{
			var e = !e ? window.event : e;
			$('#powerUnitsType').attr('value', e.target.id);
			$('.powerunits').attr('name', '');
			$('#' + e.target.id).attr('name', 'QuotationCriteria_VehicleInfo_EnginePower');
			/*Utils.debug(e.target.id+' '+$('#'+e.target.id).attr('name'));*/
		},

		convertUnitsOnload: function(utilsObj)
		{
			var type = $('#powerUnitsType').attr('value');
			var hpInput = $('#Horsepower');
			var kwInput = $('#Kilowatt');
			//Kilowatt
			if (type == 'Horsepower')
			{
				kwInput.attr('value', utilsObj.powerUnits.convertHPtoKwt(hpInput[0].value));
			} else if (type == 'Kilowatt')
			{
				hpInput.attr('value', utilsObj.powerUnits.convertKwttoHP(kwInput[0].value));
			}
		}
	},

	setOwnerType: function()
	{
		$('#ownerType li').click(function()
		{
			$('#ownerType li').removeClass('active');
			$('#ownerTypeInput').attr('value', this.id)
			$('#' + this.id).addClass('active');
		});
	},

	retrieveCities: function(value)
	{
		var data = $.ajax({
			type: "GET",
			url: "/xml/regionCities.wbp?region=" + value,
			async: false
		});
		return eval("(" + data.responseText + ")")
	}
}
/* END DIFFERENT STANDALONE AND CONVINIENT FUNCTIONS FOR CALCULATORS */



/* POPUP NUMPAD FOR NUMBER FIELDS */
NumPad = function() {
	this.numpad = $('#numpad');
	this._initNumPad();
	var close = $('.closeMe', this.numpad);
	var self = this;
	close.click(function() { self.hide(self); });
	this.bind();
	$(".numpadDel").val(String.fromCharCode(8592));
}

NumPad.prototype = {
	numpad: null,

	target: null,

	bind: function()
	{
		var numpadCallers = $('.numpadButton');
		numpadCallers.click(this.show);
		for (var i = 0; i < numpadCallers.length; i++)
		{
			numpadCallers[i].thisObj = this;
		}

		var self = this;

		$(document).click(function(e)
		{
			if (self.numpad.css("display") != "block")
			{
				return;
			}

			var node = e.target;
			var isCalcClicked = false;
			while (node)
			{
				var found = false;

				if (node == self.numpad[0])
				{
					isCalcClicked = true;
					break;
				}

				for (var i = 0; i < numpadCallers.length; i++)
				{
					if (node == numpadCallers[i])
					{
						isCalcClicked = true;
						break;
					}
				}
				node = node.parentNode
			};

			if (!isCalcClicked)
			{
				self.hide(self);
			};
		});
	},

	show: function(e)
	{
		this.thisObj.hide(this.thisObj);
		this.thisObj._setTargetField(e);

		var delimiter = $(".delimiter", this.thisObj.numpad);
		if ($(this.thisObj.target).hasClass("decimalInput"))
		{
			delimiter.show();
		}
		else
		{
			delimiter.hide();
		}

		var position = $('.numpadButton', this.thisObj._getFieldContainer(e)).offset()
		this.thisObj.numpad.css('display', 'block')
			.css('left', (position['left'] - 193) + 'px')
			.css('top', (position['top'] + 35) + 'px');
		e.preventDefault();
		e.stopPropagation();
	},

	hide: function(self)
	{
		if (self.numpad.css('display') != 'none')
		{
			self.numpad.css('display', 'none');

			var target = $(self.target);
			if (target.val() != self.prevTargetValue)
			{
				target.change();
			}
		}
	},

	_setTargetField: function(e)
	{
		var e = !e ? window.event : e;
		var container = this._getFieldContainer(e);

		var input = $('input', container);
		this.target = input.get(0);

		this.prevTargetValue = input.val();
	},

	_initNumPad: function()
	{
		var numButtons = $('input', this.numpad);
		numButtons.click(this._sendValue);
		numButtons.mousedown(function()
		{
			$(this.thisObj.target).focus();
		})
		for (var i = 0; i < numButtons.length; i++)
		{
			numButtons[i].thisObj = this;
		}
	},

	_sendValue: function()
	{
		var thisObj = this.thisObj;

		var newVal = thisObj.target.value

		if (this.value == 'C')
		{
			newVal = "";
		} else if (this.value.charCodeAt(0) > 1000)
		{
			newVal = newVal.substring(0, newVal.length - 1)
		} else
		{
			newVal = newVal + this.value;
		}

+this.value;

		var doSendValue = true;
		var maxLength = thisObj.target.maxLength;
		if (maxLength && maxLength > 0)
		{
			doSendValue = maxLength >= newVal.length;
		}

		if (doSendValue)
		{
			thisObj.target.value = newVal;
			$(thisObj.target).keyup();
			$(thisObj.target).focus();
		}
	},

	_getFieldContainer: function(e)
	{
		return $(e.target).parents('div.numpadFld')
	},

	init: function()
	{
		this.bind();
	}
}
/* END POPUP NUMPAD FOR NUMBER FIELDS */

/* COLLAPSING NEXTSIBLING */
FormCollapser = function() {
	var formsParts = $('.formCollapser').click(this.toggleForm)
	for (var i = 0; i < formsParts.length; i++) {
		formsParts[i].thisObj = this;
	}
	//
}

FormCollapser.prototype = {
	toggleForm: function() {
		$('.collapsableForm').css('display', 'none');
		var next = $(this).next()
		var display = next.css('display');
		if (display == 'block' || display == '') {
			next.css('display', 'none');
		} else {
			next.css('display', 'block');
		}
	}
}
/* END COLLAPSING NEXTSIBLING */

/* COUNTING AGE FROM DATE */
DateProcessor = function(age, date) {
	this.ageFld = $(age);
	this.dateFld = $(date);
	this.dateFld[0].thisDateObj = this;
	this.dateFld.keyup(this.setAge);
	this.dateFld.focus(this.setAge);
}

DateProcessor.prototype = {
	setAge: function() {
		var thisObj = this.thisDateObj;
		var inputDate = thisObj._parseDate();
		var curDate = new Date();
		if (inputDate) {
			thisObj.ageFld[0].value = curDate.getFullYear() - inputDate;
		} else {
			thisObj.ageFld[0].value = ''
		}
	},

	_parseDate: function() {
		var d = this.dateFld[0].value
		var dArray = d.split('.');
		if (dArray.length == 3 && dArray[2].length == 4) {
			return dArray[2]
		} else {
			return false;
		}
	}
}
/* END COUNTING AGE FROM DATE */


FormSubmit = function()
{
	$('.formSubmitTypeButton').not(".skipFormValidation").bind(FormSubmit.OnSubmitEventName, FormSubmit.OnSubmit);
}

FormSubmit.OnSubmitEventName = "click.CalcActionButtonsBeforeSubmit";

FormSubmit.SetCustomSubmitHandler = function(buttons, handler)
{
	buttons.unbind(FormSubmit.OnSubmitEventName);
	buttons.bind(FormSubmit.OnSubmitEventName, handler);
}

FormSubmit.RemoveCustomSubmitHandler = function(buttons)
{
	buttons.unbind(FormSubmit.OnSubmitEventName);
	buttons.bind(FormSubmit.OnSubmitEventName, FormSubmit.OnSubmit);
}

FormSubmit.OnSubmit = function()
{
	try
	{
		var additionalParams = this.className.split(' ')[1];
		if (additionalParams == 'saveQuotationAsNew')
		{
			$('#caseID, #CaseID, input[name=CaseID]').attr('value', '');
			$(this).parents('form').attr('action', '?CaseID=');
		}
		if (additionalParams == 'goToPrivatePart') { $(this).parents('form').attr('action', '?gotoprivate=true') }
		if (additionalParams == 'openEnquiryWindow') { $(this).parents('form').attr('action', '?openEnquiryWindow=true') }
		if (additionalParams == 'makePolicyProject') { $(this).parents('form').attr('action', '?makePolicyProject=true') }

	} catch (e) { }

	// determine Action and PostAction
	var action;
	var postAction;

	switch (this.id)
	{
		case "OpenInsuranceApplicationForm":
			action = "CalculateQuotation";
			postAction = "OpenInsuranceApplicationForm";
			break;
		default:
			action = this.id;
			postAction = "";
			break;
	}
	$('#formSubmitType').val(action);
	$('#postAction').val(postAction);

	if (FormSubmit.validationHandler)
	{
		var message = FormSubmit.validationHandler();
		if (message)
		{
			if (!FormSubmit.isPopupMessageOpened)
			{
				FormSubmit.isPopupMessageOpened = true;

				var messagePopup = new PopUp('', 'alert', message != null ? message : "Расчёт не может быть выполнен.", 'Сообщение');
				messagePopup.modal = true;
				messagePopup.setButtonText({ 'ok': 'Да' });

				var callback =
				{
					popupNotify: function(b, o)
					{
						FormSubmit.isPopupMessageOpened = false;
					}
				};

				messagePopup.addResultListeners(callback);
				messagePopup.show(messagePopup);
			}

			return false;
		}
	}
}



FormSubmit.isPopupMessageOpened = false;



var Hint = function(){
	$('#main').click(function(event){
		$('.hintText').remove();
	})
	$('.hint').remove();
	this._setHintIcons();
	
}


Hint.prototype = {
	toggleHint: function(event) {
		$('.hintText').remove();
		var hintBlock = $('.hintText', this.input.parents('.inputWrapper'));
		if (hintBlock.length != 0) {
			hintBlock.remove();
		}
		else {
			var data = this.thisObj;
			var offset = $(this).offset();
			offset.top = offset.top + $(this).height();

			var maxWidth = 200;
			if (this.hintName == "QuotationCriteria_InsuranceTypeID") {
				maxWidth = 500; // Yes, this is hack.
			}

			var width = this.input.width() < maxWidth ? maxWidth : this.input.width();
			this.input.parents('.inputWrapper').append('<div class="hintText" style="display:table;width:' + width + 'px;top:' + offset.top + 'px;left:' + offset.left + 'px"><!--[if lte IE 6.5]><iframe class="hintSelectHider"></iframe><div class="hintSelectHider"></div><![endif]-->' + data.hints[this.hintName] + '</div>');
			$('div.hintText li').addClass('in-ul');
		}

		if (typeof ($.autosuggest) != "undefined")
		{
			$.autosuggest.CloseAllOpenedPopups();
		}

		return false;
	},

	_setHintIcons: function() {
		for (var name in this.hints) {
			if (name && name != "") {
				var label = $([]);

				if (name[0] == "#") {
					label = $(name);
				}
				else {
					var input = $("input[name='" + name + "'], select[name='" + name + "']");
					if (input.length == 0) {
						//search by id
						input = $("input[id='" + name + "'], select[id='" + name + "']");
					}

					if (input.length > 0) {

						var inputElt = input.get(0);
						if (inputElt.id && inputElt.id != "") {
							// try to find label by "for" attribute
							label = $("label[for='" + inputElt.id + "'],*.hasHint[for='" + inputElt.id + "']");
						}

						if (label.length == 0) {
							var inputWrapper = input.parents(".inputWrapper");
							if (inputWrapper.length > 0) {
								label = inputWrapper.children("label, *.hasHint");
							}
						}
					}
				}

				if (label.length > 0) {
					label.append('<img src="/media/system/imgs/qmark.gif" width="15" height="14" class="hint" />');
					if(label.prev('input').length !== 0){
						label.attr('class','long checkbox');
					}
					var hint = $('.hint', label);
					// hint.bind('click',this, this.toggleHint);
					if (hint.length > 0) {
						hint.click(this.toggleHint);
						var hintElt = hint.get(0);
						hintElt.thisObj = this;
						hintElt.hintName = name;
						hintElt.input = input;
					}
				}
			}
		}
	}
}

CalcActionButtons = function()
{
}

CalcActionButtons.calculateObjectPricesMode = false;

CalcActionButtons.setCalculateQuotationState = function(event)
{
	var controlsToHide = $('.HideOnChange');
	var controlsToShow = $('.ShowOnChange');

	if (CalcActionButtons.calculateObjectPricesMode)
	{
		controlsToShow = controlsToShow.not(".HideInCalculateObjectPricesMode");
	}

	var debugText = "Operation buttons fired";
	if (event)
	{
		debugText += ": " + event.type + ", " + event.target.id
	}

	Utils.debug(debugText);

	controlsToHide.hide();
	controlsToShow.show();

	// Приведенные ниже операции относятся к блоку результатов расчета.
	// TODO - вынести сам блок в отдельный шаблон, чтобы избежать копипаста в калькуляторах.
	CalcResultsBlock.clearCalculationResults(CalcActionButtons.resetCaseIDOnChange);
}

CalcActionButtons.isPopupMessageOpened = false;
CalcActionButtons.resetCaseIDOnChange = false;

CalcActionButtons.setCalculationImpossibleState = function(message)
{
	var buttons = $("#CalculateQuotation, #OpenInsuranceApplicationForm");
	buttons.unbind("click.CalculationImpossible");

	buttons.bind("click.CalculationImpossible", function()
	{
		if (!CalcActionButtons.isPopupMessageOpened)
		{
			CalcActionButtons.isPopupMessageOpened = true;

			var messagePopup = new PopUp('', 'alert', message != null ? message : "Расчёт не может быть выполнен.", 'Сообщение');
			messagePopup.modal = true;
			messagePopup.setButtonText({ 'ok': 'Да' });

			var callback =
			{
				popupNotify: function(b, o)
				{
					CalcActionButtons.isPopupMessageOpened = false;
				}
			};

			messagePopup.addResultListeners(callback);
			messagePopup.show(messagePopup);
		}

		return false;
	});
}

CalcActionButtons.clearCalculationImpossibleState = function()
{
	var buttons = $("#CalculateQuotation, #OpenInsuranceApplicationForm");
	buttons.unbind("click.CalculationImpossible");
}

CalcActionButtons.setCalculateObjectPricesState = function()
{
	CalcActionButtons.calculateObjectPricesMode = true;
	$(".HideInCalculateObjectPricesMode").hide();
	$("#CalculateObjectPricesButtonSection").show();
}

CalcActionButtons.clearCalculateObjectPricesState = function()
{
	CalcActionButtons.calculateObjectPricesMode = false;
	$(".HideInCalculateObjectPricesMode").show();
	$("#CalculateObjectPricesButtonSection").hide();
}

CalcActionButtons.SetCaseIDResetOnChange = function(reset)
{
	CalcActionButtons.resetCaseIDOnChange = reset;
}

CalcActionButtons.MoveQuotationToPrivateCabinet = function(caseID, insuranceProductTypeID, privateCabinetHostUrl, isUserAuthenticated, message)
{
	var url;
	if (isUserAuthenticated)
	{
		url = privateCabinetHostUrl + "/calc/" + insuranceProductTypeID + ".wbp";
	}
	else
	{
		url = privateCabinetHostUrl + "/index.wbp";
	}

	var params = { Action: "AddQuotationToPrivateCabinet", CaseID: caseID, InsuranceProductType: insuranceProductTypeID };
	url += "?" + jQuery.param(params);

	if (message != null && message != "")
	{
		ShowMessageAndRedirect(message, url);
	}
	else
	{
		window.location.href = url;
	}

	return false;
}

CalcActionButtons.SetQuotationReadyForInsuranceApplication = function(isReady)
{
	var button = $("#OpenInsuranceApplicationForm");

	if (isReady)
	{
		var handler = function()
		{
			InsuranceApplicationForm.OpenInstance("CalculatorButton");
			return false;
		};

		FormSubmit.SetCustomSubmitHandler(button, handler);
	}
	else
	{
		FormSubmit.RemoveCustomSubmitHandler(button);
	}
}

CalcResultsBlock = function()
{
}

CalcResultsBlock.clearCalculationResults = function(clearCaseID)
{
	var calculatedPremium = $("div.preheader input:eq(0)");

	if (calculatedPremium.val() != null && calculatedPremium.val().length > 0)
	{
		// Убираем сообщение об успешном рассчете.
		$("div.preheader div.userMessage").remove();

		// Убираем нестандартные сообщения, специфичные для калькуляторов.
		$("*.hideOnCalculationReset").remove();

		// Очищаем рассчитанную стоимость.
		calculatedPremium.val("");

		if (clearCaseID)
		{
			// Очищаем CaseID.
			var caseID = $("div.preheader input:eq(1)");
			caseID.val("");
		}

		CalcActionButtons.SetQuotationReadyForInsuranceApplication(false); 
		InsuranceApplicationForm.DeleteInstance();
	}
}

var PopupDialog = function(title, domElement, buttons, width)
{
	var buttonsObj = {};

	for (var i = 0; i < buttons.length; ++i)
	{
		buttonsObj[buttons[i].text] = buttons[i].handler;
	}

	this.elt = this._GenerateContent(title, domElement, buttons);

	this.elt.dialog(
	{
		dialogClass: "PopupDialog",
		autoOpen: false,
		bgiframe: true,
		closeOnEscape: false,
		draggable: false,
		resizable: false,
		height: "auto",
		width: width ? width : "auto",
		position: "center",
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		title: title,
		buttons: null
	});

	//draggable
	var header = $(".header", this.elt);
	header.css("cursor", "move");

	this.elt.parent().draggable({ handle: header });
}

PopupDialog.prototype._GenerateButtons = function(container, buttons)
{
	var div = $("<div align='center'/>");
	var table = $("<table class='PopupDialogButtons' />");
	div.append(table);
	
	var tr = $("<tr />");
	table.append(tr);

	for (var i = 0; i < buttons.length; ++i)
	{
		var buttonElt = $('<div class="doSend"><div class="left"><div class="right"><input type="button" name="ok" value="' + buttons[i].text + '" /></div></div></div>');
		$("input", buttonElt).click(buttons[i].handler);

		var td = $("<td />");
		tr.append(td);
		td.append(buttonElt);
	}

	container.append(div);
}

PopupDialog.prototype._GenerateContent = function(title, domElement, buttons)
{
	var elt = $("<table/>");
	var tbody = $("<tbody />");
	elt.append(tbody)

	var topRow = $("<tr />");
	tbody.append(topRow);

	topRow.append("<td class='topLeft' />");

	var header = $("<td class='header' />");
	header.text(title);

	topRow.append(header);
	topRow.append("<td class='topRight' />");

	var centerRow = $("<tr />");
	tbody.append(centerRow);
	centerRow.append("<td class='contentLeft' />");
	var content = $("<td class='content' />");
	centerRow.append(content);
	centerRow.append("<td class='contentRight' />");

	var bottomRow = $("<tr />");
	tbody.append(bottomRow);

	bottomRow.append("<td class='bottomLeft' />");
	bottomRow.append("<td class='contentBottom' />");
	bottomRow.append("<td class='bottomRight' />");

	content.append(domElement);
	content.append("<div class='separator' />");
	this._GenerateButtons(content, buttons);

	return elt;
}


PopupDialog.prototype.Show = function()
{
	this.elt.dialog('open');
};

PopupDialog.prototype.Hide = function()
{
	this.elt.dialog('close');
};

var ConfirmationPopup = function(title, message, confirmedCallback, cancelledCallback)
{
	var self = this;	

	this.confirmedCallback = confirmedCallback;
	this.cancelledCallback = cancelledCallback;
	
	var p = $("<p style='padding-top:10px'/>");
	p.text(message);
	
	var buttons =
	[
		{
			text: "Да",
			handler: function()
			{
				self.popupDialog.Hide();
				self.confirmedCallback();
			}
		},		
		{
			text: "Нет",
			handler: function()
			{
				self.popupDialog.Hide();
				self.cancelledCallback();
			}
		}
	];
	
	this.popupDialog = new PopupDialog(title, p, buttons, 600);
};

ConfirmationPopup.prototype.Show = function()
{
	this.popupDialog.Show();
};

var ImagePopup = function(title, imageUrl, width)
{
	var self = this;

	var img = $("<img style='text-align:center'/>");
	img.attr("src", imageUrl);

	var buttons =
	[
		{
			text: "Закрыть",
			handler: function()
			{
				self.popupDialog.Hide();
			}
		}
	];

	this.popupDialog = new PopupDialog(title, img, buttons, width);
};

ImagePopup.prototype.Show = function()
{
	this.popupDialog.Show();
};


var OriginalImagePopup = function(smallImageContainer, popupClassName)
{
	var self = this;

	this.popupClassName = popupClassName;

	this.smallImageContainer = smallImageContainer;
	this.smallImageContainer.bind(this.showEventName, function() { self.Show(); });

	var img = $("<img/>");
	
	this.popup = $("<div class='" + this.popupClassName + "' style='display:none'/>");
	this.popup.append(img);
	this.popup.appendTo(this.smallImageContainer);
	this.popup.bgiframe();
}

OriginalImagePopup.prototype =
{
	showEventName: "mouseover.ShowImageZoomPopup",
	popup: null,

	Show: function()
	{
		var self = this;

		this.smallImageContainer.unbind(this.showEventName);

		var smallImage = $("img", this.smallImageContainer);
		var image = $("img", this.popup);
		image.attr("src", smallImage.attr("src"));

		var smallSize = this.GetSmallSize();
		var originalSize = this.GetOriginalSize();

		var pos = this.smallImageContainer.position();
		var left = pos.left - (originalSize.width - smallSize.width) / 2;
		var top = pos.top - (originalSize.height - smallSize.height) / 2;
		this.popup.css("left", left).css("top", top);

		this.popup.mouseout(function() { self.Hide(); });
		
		this.popup.show("scale", { from: smallSize }, "normal");
	},

	Hide: function()
	{
		var self = this;

		this.popup.unbind("mouseout");

		var originalSize = this.GetOriginalSize();
		var percent = (100.0 * this.smallImageContainer.width()) / originalSize.width + 5;
		
		var callback = function()
		{
			self.popup.hide();
			self.smallImageContainer.bind(self.showEventName, function() { self.Show(); });
		};

		this.popup.effect("scale", { mode: 'hide', percent: percent, from: originalSize }, "fast", callback);
	},

	GetSmallSize: function()
	{
		var smallSize =
		{
			width: this.smallImageContainer.width(),
			height: this.smallImageContainer.height()
		};

		return smallSize;
	},

	GetOriginalSize: function()
	{
		var originalSize =
		{
			width: this.popup.width(),
			height: this.popup.height()
		};

		return originalSize;
	}
}

String.IsNullOrEmpty = function(str)
{
	return str == null || str == "";
}

var ConfirmationEventArgs = function(element, confirmCalback, cancelCalback) {
	this.element = element;
	this.confirmCalbackDelegate = confirmCalback;
	this.cancelCalbackDelegate = cancelCalback;
};

ConfirmationEventArgs.prototype = {
	confirm: function() {
		this.confirmCalbackDelegate.call(this.element);
	},
	cancel: function() {
		this.cancelCalbackDelegate.call(this.element);
	}
}