var dBtn = null;
var hTest = null;

Popup = function(){
	// ядро
	this.id_prefix = '';
	this.z_index = 200;
	this.blocked = false;
	this.show = function(hData){
		if(!hData.onlyone || !oPopup.busy()){
			this.mainHandler = null;
			this.onClose = hData.onClose;
			this.save_hints = hData.save_hints;
			var sHtml = this.build(hData);
			var j = $(sHtml).appendTo('body');
			// j.html(sHtml);
			var iWidth = hData.width || 360;
			var iDocWidth = $(window).width();
			var iDocHeight = $(window).height();
			var x = hData.left || Math.round((iDocWidth - iWidth)/2);
			if(hData.offsetX) x += hData.offsetX;
			var y = $(document).scrollTop() + Math.round((iDocHeight - j.height())/2);
			if(y < 0) y = 1;
			y = hData.top || y;
			if(hData.offsetY) y += hData.offsetY;
			var p_offset = oPopup._offset();
			var z_index = hData.z_index || oPopup.getZindex();
			j.css({left: x + p_offset.left + 'px', top: y + p_offset.top + 'px', width: iWidth + 'px', 'z-index': z_index});
			j.hide();
			if(hData.animate) j.fadeIn(); else j.show();
			this.bAnimate = hData.animate;
			this.visible = true;
			this.initEvents(j, hData);
			this.jContainer = j;
			oPopup._add(this);
			this.onShow.apply(this, []);
		}
	};
	
	this.close = function(){
		var t = this.popup ? this.popup : this;
		if(!t.save_hints) $('.popup_alert, .additional_popuphints').hide();
		if(t.onClose) t.onClose();
		if(t.store){
			if(t.bAnimate) t.jContainer.fadeOut(); else t.jContainer.hide();
		} else {
			if(t.bAnimate) t.jContainer.fadeOut( function(){ $(this).remove() } ); else t.jContainer.remove();;
			oPopup._remove(t);
		}
		t.visible = false;
		return false;
	};
	
	this.isIe = function(){
		return ($.browser.msie && ($.browser.version == '5.0' || $.browser.version == '8.0'));
	};
	
	this.blockButtons = function(){
		if(this.isIe()){
			//this.jContainer.find('div.button').addClass('opa30');
		} else {
			this.jContainer.find('div.button').animate({opacity: 0.3}, 400);
		};
		this.blocked = true;
	};
	
	this.unblockButtons = function(){
		if(this.isIe()){
			//this.jContainer.find('div.button').removeClass('opa30');
		} else {
			this.jContainer.find('div.button').animate({opacity: 1}, 400);
		};
		this.blocked = false;
	};
	
	this.showLoading = function(sMsg){
		sMsg = sMsg || 'Подождите...';
		var j = this.jContainer;
		j.find('div.button').hide();
		j.find('div.popup_loading').show().find('span').html(sMsg);
	};
	
	this.hideLoading = function(sMsg){
		var j = this.jContainer;
		j.find('div.button').show();
		j.find('div.popup_loading').hide();
	};
	
	
	
	this.onComboValueChange = function(name, value){};
	this.onShow = function(){};
	
	this.build = function(hData){
		this.id_prefix = hData.prefix;
		if(!this.id_prefix)this.id_prefix='';
		this.handler = hData.handler;
		var sInfo = ''; var sButtons = '';
		for(i=0; i<hData.items.length; i++){
			sInfo += this.buildInput(hData.items[i]);
		}
		if(hData.buttons){
			this.initButtonsWidth(hData);
			for(i=0; i<hData.buttons.length; i++){
				sButtons += this.buildButton(hData.buttons[i], i);
			}
		}
		var sTarget = hData.target ? (' target="'+hData.target+'"') : "";
		var sIframe = '';
		if(hData.iframe){
			sIframe = '<iframe name="'+this.id_prefix + 'popupiframe" id="'+this.id_prefix + 'popupiframe" style="display:none"></iframe>';
			sTarget = 'target="' + this.id_prefix + 'popupiframe' + '"';
		}
		var sAction = hData.action ? (' action="'+hData.action+'"') : "";
		
		var sSubmit = '<input type="submit" style="display:none" />';
		
		var sOnSubmit = hData.onSubmit || 'oPopup.onSubmit()';
		
		if (typeof hData.onComboValueChange == 'function')
			this.onComboValueChange = hData.onComboValueChange;
		
		if (typeof hData.onShow == 'function')
			this.onShow = hData.onShow;
			
		var sLoading = '<div class="popup_loading" style="text-align:center;display:none"><img src="/images/ajax.gif" align="absmiddle" /> <span style="padding-left:10px;font-size:14px">Подождите...</span></div>';
		
		var sHtml = '<form id="'+this.id_prefix+'form"' + sAction + sTarget + 'method="post" enctype="multipart/form-data" onSubmit="return '+sOnSubmit+'"><div class="info">' + sInfo + '</div>'
			+ '<div class="popup_error">Ошибка заполнения формы</div>'
			+ '<div class="button"><div style="margin: 0px auto; display: table; width: '+this.iTotalWidth+'px;">' + sButtons + sSubmit +'</div></div></form>' + sLoading + sIframe;
			
		var sColor = hData.color || 'white';
			
		return '<div class="p_rt"><table class="popup_'+sColor+'" width="100%" cellspacing="0" cellpadding="0"><tr><td class="m1"> </td><td class="m2"> </td><td class="m3"></td></tr><tr><td class="m4"> </td><td class="m5"><div class="pop_y"><div class="pop_x"><a href="#"><img height="9" width="9" src="/images/p_x.gif" class="img_popup_close"/></a></div></div><div>' + sHtml + '</div></td><td class="m6"> </td></tr><tr><td class="m7"> </td><td class="m8"> </td><td class="m9"> </td></tr></table></div>';
	};
	
	this.initButtonsWidth = function(hData){
		var iW = 0;
		for(i=0; i<hData.buttons.length; i++){
			var iWidth = hData.buttons[i].text.length*7.7;
			if(iWidth>iW) iW = iWidth;
		};
		if(iW<50) iW = 50;
		var iTotal = 0;
		for(i=0; i<hData.buttons.length; i++){
			if(!hData.buttons[i].width) hData.buttons[i].width = iW;
			iTotal = iTotal + hData.buttons[i].width + 23;
		}
		this.iTotalWidth = iTotal+5;
	};
	
	this.buildInput = function(hItem){
		if(typeof(hItem)=='string'){
			return hItem;
		} else {
			hItem.pname = this.id_prefix + hItem.name;
			if(!hItem.text) hItem.text = '';
			if(!hItem.type) hItem.type = 'text';
			var sCommon = '<div class="popup_alert" id="popupalert_'+hItem.pname+'"> </div>';
			switch(hItem.type){
				case 'text':
					return sCommon + this.buildText(hItem);
				case 'password':
					return sCommon + this.buildPas(hItem);
				case 'select':
					return sCommon + this.buildSelect(hItem);
				case 'select.visible':
					return sCommon + this.buildSelect(hItem) + this.buildSelectVisible(hItem);
				case 'checkbox':
					return sCommon + this.buildCheckbox(hItem);
				case 'checkboxlist':
					return sCommon + this.buildCheckboxList(hItem);
				case 'textarea':
					return sCommon + this.buildTextarea(hItem);
				case 'file':
					return '<div class="popup_alert popup_alert_file" id="popupalert_'+hItem.pname+'"> </div>' + this.buildFile(hItem);
				case 'radio':
					return sCommon + this.buildRadio(hItem);
				case 'comment':
					return this.buildComment(hItem);
				case 'phone':
					return this.buildPhone(hItem);
			}
		}
	};
	this.buildText = function(hItem){
		if(!hItem.value)hItem.value="";
		if(hItem.visible){if(hItem.visible=='all'){
			var visible='1';var eye = 'on'
		}else{
			var visible='0';var eye = 'off'
		}}
		var sStyle = hItem.style || "";
		var sMaxlength = '';
		if(hItem.maxlength) sMaxlength = ' maxlength = "' + hItem.maxlength + '" ';
		return '<div class="popup_caption">'+hItem.label+'</div>'
			+ '<div class="popup_input" style="'+sStyle+'"><input type="text" id="'+hItem.pname+'" name="'+hItem.pname+'" value="'+hItem.value+'"' + sMaxlength
			+ (hItem.readonly ? 'readonly="true"' : '')
			+'/>'
			+ (hItem.visible ? '<span class="eye eye_'+eye+'" input="text_eye"><input type="text" value="'+visible+'" id="text_eye" name="text_eye" style="display:none"></span>' : '')
			+ '</div>'
			+ (hItem.comment ? '<div class="popup_comment2">'+hItem.comment+'</div>' : "");
	};
	this.buildPas = function(hItem){
		if(!hItem.value)hItem.value="";
		return '<div class="popup_caption">'+hItem.label+'</div>'
			+ '<div class="popup_input"><input type="password" id="'+hItem.pname+'" name="'+hItem.pname+'" value="'+hItem.value+'"/></div>'
			+ (hItem.comment ? '<div class="popup_comment2">'+hItem.comment+'</div>' : "");
	};
	this.buildSelect = function(hItem){
		var sItems = '';
		if(hItem.value && hItem.value!=''){
			for(var i=0;i<hItem.items.length; i++){ if(hItem.items[i][0]==hItem.value) hItem.text = hItem.items[i][1]; }
		}
		var sValue = hItem.value ? hItem.value : '';
		for(var i=0;i<hItem.items.length; i++){
			sItems += '<li title="'+hItem.items[i][1]+'" cvalue="'+hItem.items[i][0]+'" class="comboboxItem">'+hItem.items[i][1]+'</li>';
		}
		this.z_index = this.z_index - 2;
		return '<div class="popup_caption">'+hItem.label+'</div>'
		  + '<div class="popup_select"><span class="select4"><div class="comboboxContainer"><div class="comboboxValueContainer" style="z-index:'+this.z_index+'"><div title="'+hItem.text+'" class="comboboxValueContent" input="'+hItem.pname+'">'+hItem.text+'</div><div class="comboboxDropDownButton"/></div><div class="comboboxDropDownContainer_div" style="height: 144px; display: none; z-index:'+(this.z_index-1)+'"><ul tabindex="0" class="comboboxDropDownContainer">' 
		  + sItems
		  + '</ul></div></div></span><input type="hidden" value="'+sValue+'" id="'+hItem.pname+'" name="'+hItem.pname+'" /></div>';
	};
	this.buildSelectVisible = function(hItem){
		var sValue = hItem.value ? hItem.value : '';
		var html = '<div id="'+hItem.pname+'_groups" '+(sValue=='groups' ? '':'style="display:none"')+
		           '><div class="popup_caption">Группы:</div><div class="groups-container"><img src="/images/ajax.gif" /></div></div>';
	    return html;
	};
	this.buildTextarea = function(hItem){
		if(!hItem.value)hItem.value="";
		var sStyle = hItem.style || "";
		return '<div class="popup_textarea" style="' + sStyle +'">'+hItem.label+'<br/><div><textarea id="'+hItem.pname+'" name="'+hItem.pname+'">'+hItem.value+'</textarea></div></div>';
	};
	this.buildCheckbox = function(hItem){
		if(hItem.important){
			return '<div class="popup_important">'+
				'<div class="lt"><div class="rt">&nbsp;</div></div>'+
				'<div class="ct">'+
				'<div class="popup_checkbox" style="height:auto;padding:0px 13px"><img click1="checkboxshower()" click2="checkboxshower2()" height="16" width="16" src="/images/check_2.gif" style="float: left; margin-right: 6px;" input="'+hItem.pname+'"/><span>'+hItem.label+'</span></div><input type="hidden" value="0" id="'+hItem.pname+'" name="'+hItem.pname+'" />'+
				'</div>'+
				'<div class="lb"><div class="rb">&nbsp;</div></div>'+
			'</div>';
		}else{
			if(hItem.req){
				return '<div class="popup_checkbox checkboxlist_item" style="height:auto;padding:5px 13px;display:none"><img height="16" width="16" src="/images/check_2.gif" style="float: left; margin-right: 6px;" input="'+hItem.pname+'"/><span>'+hItem.label+'</span></div><input type="hidden" value="0" id="'+hItem.pname+'" name="'+hItem.pname+'" />';
			}else{
				return '<div class="popup_checkbox checkboxlist_item"><img class="'+ (hItem.value==1 ? "checked" : "") +'" height="16" width="16" src="/images/check_'+ (hItem.value==1 ? "3" : "2") +'.gif" style="float: left; margin-right: 6px;" input="'+hItem.pname+'"/><span>'+hItem.label+'</span></div><input type="hidden" value="'+ (hItem.value==1 ? "1" : "0") +'" id="'+hItem.pname+'" name="'+hItem.pname+'" />';
			}
		}
	};
	this.buildCheckboxList = function(hItem){
		var sItems = '';
		if(hItem.value && hItem.value!=''){
			for(var i=0;i<hItem.items.length; i++){ if(hItem.items[i][0]==hItem.value) hItem.text = hItem.items[i][1]; }
		}
		var sValue = hItem.value ? hItem.value : '';
		var selected_item='';
		var selected_img=''
		for(var i=0;i<hItem.items.length; i++){
			if(hItem.items[i][0]==hItem.checked_default){
				selected_item = '1';
				selected_img = '/images/check_3.gif';
			}else{
				selected_item = '0';
				selected_img = '/images/check_2.gif';
			};
			sItems += '<div class="popup_checkbox" style="height:auto;padding:5px"><img height="16" width="16" src="'+selected_img+'" style="float: left; margin-right: 6px;" input="community_id_'+hItem.items[i][0]+'"/><span>'+hItem.items[i][1]+'</span></div>'+
				'<input type="hidden" value="'+selected_item+'" id="community_id_'+hItem.items[i][0]+'" name="community_id_'+hItem.items[i][0]+'" />';
		}
		this.z_index = this.z_index - 2;
		return '<div class="popup_caption">'+hItem.label+'</div>' + 
		'<div style="height:150px;width:190px;overflow-x:hidden;overflow-y:scroll">'+
		sItems+
		'</div>';
	};
	this.buildRadio = function(hItem){
		var sItems = '';
		for(var i=0;i<hItem.items.length; i++){
			if(hItem.value==hItem.items[i][0]){addclass='radio_cur'}else{addclass='radio'};
			sItems += '<div class="radio_item fl '+addclass+'" value="'+hItem.items[i][0]+'"><span>'+hItem.items[i][1]+'</span></div>';
		}
		sItems += '<input type="hidden" value="'+hItem.value+'" id="radio_'+hItem.name+'" name="radio_'+hItem.name+'" />';
		
		return '<div class="popup_caption">'+hItem.label+'</div>' + 
		'<div class="radio_block" style="margin-left:120px;">'+
		sItems+
		'<div class="clear"></div></div>';
	};
	this.buildComment = function(hItem){
		return '<div class="popup_comment">'+hItem.label+'</div>';
	};
	this.buildFile = function(hItem){
		return '<div class="popup_file"><div class="input-file" style="width:300px"><label><a class="popup_button" href="#"><span class="as"></span><span class="ss">Обзор</span><span class="sa"></span></a><input type="file" name="'+hItem.pname+'" class="popup_input_file"/></label><var><input type="text" name="my-input-file-path" value="'+hItem.label+'" readonly="readonly" />&nbsp;</var></div></div>'
		+ (hItem.comment ? '<div class="popup_comment2">'+hItem.comment+'</div>' : "");
	};
	this.buildPhone = function(hItem){
		return '<div class="popup_caption">'+hItem.label+'</div><div class="popup_input input_phone" style="margin-left:124px;width:160px;//margin-left:0px"><input class="ph1" type="text" value="" maxlength="3" name="'+hItem.pname+'1" id="'+hItem.pname+'" onkeyup="oPopup.fillJump(this, 3)"><input class="ph2" type="text" value="" maxlength="7" name="'+hItem.pname+'2" id="'+hItem.pname+'" style="width:75px"></div>';
	};
	this.buildButton = function(hItem, i){
		return '<a class="popup_button" href="#" i="'+i+'"><span class="as"/><span class="ss" style="width:'+hItem.width+'px">'
			+ hItem.text
			+ '</span><span class="sa"/></a>';
	};
	this.initEvents = function(oWhere, hData){
		var t = this;
		$('.eye', oWhere).click(function(){
			if($(this).hasClass('eye_on')){
				$(this).addClass('eye_off').removeClass('eye_on');
				$('#'+$(this).attr('input'), t.jContainer).val(0);
			} else {
				$(this).addClass('eye_on').removeClass('eye_off');
				$('#'+$(this).attr('input'), t.jContainer).val(1);
			}
		});
		$('.radio_item', oWhere).click(function(){
			$(this).parents('.radio_block:first').find('.radio_item').removeClass('radio_cur').addClass('radio');
			$(this).removeClass('radio').addClass('radio_cur');
			radioVal=$(this).attr('value');
			$(this).parents('.radio_block:first').find('input').val(radioVal);
		});
		$('.popup_checkbox', oWhere).click(function(){
			var j = $('img',this);
			if(j.hasClass('radio')){
				var sInput = j.attr('input');
				$('img[input="'+sInput+'"]').attr('src','/images/check_2.gif').removeClass('checked');
				j.attr('src','/images/check_3.gif').addClass('checked');
				$('#'+sInput).val(j.attr('value'));
				if(j.attr('click2')){eval(j.attr('click2'))};
			} else {
				if(j.hasClass('checked')){
					j.attr('src','/images/check_2.gif').removeClass('checked');
					$('#'+j.attr('input'), t.jContainer).val(0);
					if(j.attr('click2')){eval(j.attr('click2'))};
				} else {
					j.attr('src','/images/check_3.gif').addClass('checked');
					$('#'+j.attr('input'), t.jContainer).val(1);
					if(j.attr('click1')){eval(j.attr('click1'))};
				}
			}
		});
		$('div.button .popup_button', oWhere).each(function(i){
			if(typeof hData.buttons != 'undefined'){
				var fn = hData.buttons[i].handler;
				if(!fn && oPopup.handler) fn = function(){
					var i = $(this).attr('i');
					t.handler(i);
				};
				if(fn && !t.mainHandler) t.mainHandler = fn;
				if(!fn) fn = t.close;
				this.popup = t;
				$(this).click(fn);
			}
		});
		$('.popup_input_file').each(function(){
			dBtn = this;
			new FileUploadUI(dBtn);
		});
		$('.comboboxValueContainer', oWhere).click(function(ev){
			obj=this.parentNode.parentNode;
			var dis = $('.comboboxDropDownContainer_div',obj).css('display');
			bodyClick();
			cancelBubble(ev);
			if(dis=='none'){
				i=$('.comboboxItem',obj).size()*18;
				if(i>238){i=238};
				$('.comboboxDropDownContainer_div',obj).css('height',i);
				$('.comboboxDropDownContainer_div',obj).show();
			}else{
				$('.comboboxDropDownContainer_div',obj).hide();
			}
		});
		$('.comboboxItem', oWhere).hover(function(){$(this).addClass('comboboxItemHover')},function(){$('.comboboxItem').removeClass('comboboxItemHover')})
		$('.comboboxItem', oWhere).click(function(){
			var obj=this;
			var objt=obj;
			var objtt=this.parentNode;
			$('.comboboxItem',objtt).removeClass('comboboxItemSelect');
			$(this).addClass('comboboxItemSelect');
			obj=this.parentNode.parentNode.parentNode;
			var html = $(this).html();
			$('.comboboxValueContent',obj).html(html);
			$('.comboboxValueContent',obj).attr('title',html);
			$('.comboboxDropDownContainer_div').hide();
			var sValue = $(this).attr('cvalue');
			if(!sValue || sValue==-1) sValue = $(this).attr('title');
			var inputId = $('.comboboxValueContent',obj).attr('input');
			$('#'+inputId, t.jContainer).val(sValue);
			
			if (typeof t.onComboValueChange == 'function')
				t.onComboValueChange.apply(t, [String(inputId).substr(t.id_prefix.length), sValue]);
		});
		$('.img_popup_close', oWhere).each(function(){
			this.popup = t;
			$(this).click(t.close);
		});
		$('input', oWhere).keydown(function(event){
			if(event.keyCode==13 && t.mainHandler){
				t.popup = t;
				t.mainHandler();
				return false;
			}
		});
		
	};
	
	this.getData = function(){
		var hData = {};
		$('input, textarea', this.jContainer).each(function(){
			if(this.name && this.name!='' && this.name!='my-input-file-path'){
				hData[this.name] = this.value;
			}
		});
		return hData;
	};
	
	this.submit = function(){
		this.jContainer.find('form').each(function(){
			this.submit();
		});
	};
	
	this.invalidate = function(hData, sError, autoHints){
		var t = this;
		$('.popup_alert, .additional_popuphints').hide();
		oPopup.initHint();
		for(var i in hData){
			var sPname = this.id_prefix + i;
			$('#popupalert_'+sPname, this.jContainer).fadeIn().attr('mytitle', hData[i]).hover(
				function(){
					var p = $(this).offset();
					oPopup.jHint.html($(this).attr('mytitle')).css({left: p.left + 23, top: p.top-5}).fadeIn();
				},
				function(){
					oPopup.jHint.fadeOut();
				}
			);
			if(autoHints){
				var p = $('#popupalert_'+sPname, this.jContainer).offset();
				var j = oPopup.jHint.clone().appendTo('body');
				j.html(hData[i]).css({left: p.left + 23, top: p.top-5}).fadeIn().addClass('additional_popuphints');
			}
		}	
		if(sError && sError!=''){
			this.jContainer.find('.popup_error').html(sError).show();
		} else {
			this.jContainer.find('.popup_error').hide();
		}
	};
	
		
	// пользовательские функции
	
	this.popupTest1 = function(){
		this.show({
			prefix: 'album',
			action:'/update.html',
			iframe: true,
			items:[
				{type:'text', label:'Название альбома:', name:'name', eye : true, comment: 'Название есть название, без название что это за альбом?'},
				{type:'select', label:'Категория альбома:', name:'cat', text: 'Выберите...',
					items: [ [1, 'Природа'], [2, 'Техника'], [3, 'Автомобили'] ]
				},
				{type:'select', label:'Категория 2 альбома:', name:'cat', text: 'Выберите...',
				items: [ [1, 'Природа'], [2, 'Техника'], [3, 'Автомобили'] ]
				},
				{type:'checkbox', label:'Со всем согласен:', name:'agry'},
				{type:'comment', label:'Не торопитесь со всем соглашаться!'},
				{type:'textarea', label:'Добавить комментарий:', name:'comment'},
				{type:'file', label:'Укажите картинку', name:'image'},
				{type:'comment', label:'Большое количество оптимизаций, в основном касающихся рейтинга и текущих штурмов. Изменилась формула начисления количество денег, которые один человек может получить во время штурма. Теперь количество зависит от уровня персонажа.'}
			],
			buttons:[ {text:'Ок', handler: function(){ hTest = oPopup.getData() } }, {text:'Отмена'} ]
		});
		 this.invalidate({'name':'Не заполнено', 'image':'Картинка не указана'}, 'Не заполнены обязательные поля');
	};
	
	this.alert = function(sText, pwidth, hData){
		hData = hData || {};
		if(!pwidth){
			this.show({ items:[ sText ], buttons:[ {text:'Ок'} ], animate: hData.animate, z_index: 100000});
		}
		else{
			this.show({ items:[ sText ], buttons:[ {text:'Ок'} ], animate: hData.animate, z_index: 100000, width: pwidth});
		}
	};
	
	this.alertWithCallback = function(sText, fnCallback, buttonText){
		if(!sText) sText='';
		if(!buttonText) buttonText = 'Да';
		this.fnCallback = fnCallback;
		this.show({
			items:[ sText ],
			buttons:[ {text:buttonText, handler: function(){
				this.popup.close();
				if(this.popup.fnCallback) this.popup.fnCallback();
				return false;
				
			} }]
		});
	};
	
	this.question = function(sText, fnCallback){
		if(!sText) sText='';
		this.fnCallback = fnCallback;
		this.show({
			items:[ sText ],
			buttons:[ {text:'Да', handler: function(){
				this.popup.close();
				if(this.popup.fnCallback) this.popup.fnCallback(true);
				return false;
				
			} }, {text:'Нет', handler: function(){
				this.popup.close();
				if(this.popup.fnCallback) this.popup.fnCallback(false);
				return false;
			}} ]
		});
	};

	this.questionSec = function(sText, fnCallback, sYes, sNo){
		if(!sText) sText='';
		if(!sYes) sYes='Да';
		if(!sNo) sNo='Нет';
		this.fnCallback = fnCallback;
		this.show({
			items:[ sText ],
			buttons:[ {text:sYes, handler: function(){
				this.popup.close();
				if(this.popup.fnCallback) this.popup.fnCallback(true);
				return false;
				
			} }, {text:sNo, handler: function(){
				this.popup.close();
				if(this.popup.fnCallback) this.popup.fnCallback(false);
				return false;
			}} ]
		});
	};

	this.inputText = function(sText, sValue, fnCallback){
		if(!sText) sText='';
		this.fnCallback = fnCallback;
		this.show({
			prefix: 'input_text_',
			items:[ {type:'text', label: sText, name:'text', value: sValue} ],
			buttons:[ {text:'Ок', handler: function(){
					var s = $('#input_text_text').val();
					oPopup.close();
					if(oPopup.fnCallback) oPopup.fnCallback(s);
			}} ]
		});
	};
	
	this.comment = function(){
		this.show({
			prefix: 'add_comment_',
			items:[ {type:'textarea', label:'Добавить комментарий:', name:'comment'} ],
			buttons:
				[ {text:'Отправить', handler: function(){
					alert('Комментарий: ' + $('#add_comment_comment').val());
					oPopup.close();
				}}]
		});
	};
	
};

// оPopup теперь представляет собой объект для обратной совместимости, упрощения некоторых вызовов управления всеми попапами
oPopup = {
	z_index: 800,
	items: [],
	stores: {},
	alert: function(sText, hData){
		var p = new Popup();
		p.alert(sText, null, hData);
		return p;
	},
	alert2: function(sText, pwdate, hData){
		var p = new Popup();
		p.alert(sText, pwdate, hData);
		return p;
	},
	show: function(hData){
		this.closeAll();
		if(hData.store){
			if(!this.stores[hData.store]){
				var p = new Popup();
				p.show(hData);
				p.store = hData.store;
				this.stores[hData.store] = p;
			} else {
				var p = this.stores[hData.store];
				p.jContainer.show();
			}
		} else {
			var p = new Popup();
			p.show(hData);
		}
		return p;
	},
	showStored: function(hData){
		if(hData.store){
			if(!this.stores[hData.store]){
				var p = new Popup();
				p.show(hData);
				p.store = hData.store;
				this.stores[hData.store] = p;
			} else {
				var p = this.stores[hData.store];
				p.jContainer.show();
			}
		} else {
			var p = new Popup();
			p.show(hData);
		}
		return p;
	},
	question: function(sText, fnCallback){
		var p = new Popup();
		p.question(sText, fnCallback);
		return p;
	},
	alertWithCallback: function(sText, fnCallback, buttonText){
		var p = new Popup();
		p.alertWithCallback(sText, fnCallback, buttonText);
		return p;
	},
	getZindex: function(){
		return 800;
	},
	
	buildSelectSmall : function(hItem){
		var sItems = '';
		for(var i=0;i<hItem.items.length; i++){
			sItems += '<li title="'+hItem.items[i][1]+'" cvalue="'+hItem.items[i][0]+'" class="comboboxItem">'+hItem.items[i][1]+'</li>';
		}
		this.z_index = this.z_index - 2;
		return '<span class="select5"><div class="comboboxContainer"><div class="comboboxValueContainer" style="z-index:'+this.z_index+'"><div title="'+hItem.text+'" class="comboboxValueContent" input="'+hItem.pname+'">'+hItem.text+'</div><div class="comboboxDropDownButton"/></div><div class="comboboxDropDownContainer_div" style="height: 144px; display: none; z-index:'+(this.z_index-1)+'"><ul tabindex="0" class="comboboxDropDownContainer">' 
		  + sItems
		  + '</ul></div></div></span><input type="hidden" value="'+hItem.value+'" id="'+hItem.pname+'" name="'+hItem.pname+'" />';
	},
	
	popupTest1: function(){
		var p = this.show({
			prefix: 'album',
			action:'/update.html',
			iframe: true,
			items:[
				{type:'text', label:'Название альбома:', name:'name', eye : true, comment: 'Название есть название, без название что это за альбом?'},
				{type:'select', label:'Категория альбома:', name:'cat', text: 'Выберите...',
					items: [ [1, 'Природа'], [2, 'Техника'], [3, 'Автомобили'] ]
				},
				{type:'select', label:'Категория 2 альбома:', name:'cat', text: 'Выберите...',
				items: [ [1, 'Природа'], [2, 'Техника'], [3, 'Автомобили'] ]
				},
				{type:'checkbox', label:'Со всем согласен:', name:'agry'},
				{type:'comment', label:'Не торопитесь со всем соглашаться!'},
				{type:'textarea', label:'Добавить комментарий:', name:'comment'},
				{type:'file', label:'Укажите картинку', name:'image'},
				{type:'comment', label:'Большое количество оптимизаций, в основном касающихся рейтинга и текущих штурмов. Изменилась формула начисления количество денег, которые один человек может получить во время штурма. Теперь количество зависит от уровня персонажа.'}
			],
			buttons:[ {text:'Ок', handler: function(){
				oPopup.question('Вы уверены?', function(b){
					if(b) oPopup.alert('Вы уверены'); else oPopup.alert('Вы не уверены');
				});
				return false;
			} }, {text:'Отмена'} ]
		});
		p.invalidate({'name':'Не заполнено', 'image':'Картинка не указана'}, 'Не заполнены обязательные поля');
	},
	onSubmit : function(){
		return false;
	},
	_add: function(p){
		this.items.push(p);
	},
	_remove: function(p){
		var items = [];
		for(var i=0; i<this.items.length; i++){
			if(p!=this.items[i]) items.push(this.items[i]);
		}
		this.items = items;
	},
	_offset: function(){
		var cnt = this.items.length;
		return ({left: cnt * 16, top: cnt * 16});
	},
	close: function(){
		if(this.items.length > 0){
			var item = this.items[this.items.length-1];
			item.close();
		}
	},
	closeAll: function(){
		var items = [];
		for(var i=0; i<this.items.length; i++) items.push(this.items[i]);
		for(var i=0; i<items.length; i++) items[i].close();
	},
	free: function(){
		return (this.items.length == 0);
	},
	busy: function(){
		return (!this.free());
	},
	count: function(){
		return this.items.length;
	},
	initHint: function(){
		if(!this.jHint) this.jHint = $('<div class="popup_hint"></div>').appendTo('body');
	},
	help: function(obj, sText, iWidth, offsetX, offsetY){
		if(obj!=this.helpobj || !this.helppopup || !this.helppopup.visible){
			if(this.helppopup){
				this.helppopup.close();
				this.helppopup = null;
			}
			var pos = $(obj).offset();
			var p = new Popup();
			iWidth = iWidth || 250;
			p.show({ color: 'pur', left: pos.left + 80, top: pos.top-20, width: iWidth, items:[ sText ], z_index:20000, offsetX:offsetX, offsetY:offsetY });
			this.helppopup = p;
			this.helpobj = obj;
		} else {
			this.helpobj = null;
			this.helppopup.close();
			this.helppopup = null;
		}
	},
	fillJump: function(obj, limit){
		var j = $(obj);
		var s = j.val();
		if(s.length>=limit) j.next().each(function(){
			this.focus();
		});
	}
}

function checkboxshower(){
	$('.checkboxlist_item').show();
}
function checkboxshower2(){
	$('.checkboxlist_item').hide();
	$('#popupalert_copyright').hide();
	$('#popupalert_rules').hide();
}
