function add_org_form(del_name) {
  var coll = $('#orgs_coll').find('.org_form');
  var id = coll.eq(coll.length-1).attr('id');
  id = Number(id.substring(9, id.length)) + 1;
  var pat = /orgs\[0\]/;
  var form = $("#org_form_0").clone();

  var legend = form.find('legend').html();
  form.find('legend').html(legend + ' (<a href="javascript:void(0)" onClick="del_org_form(this)">'+del_name+'</a>)');

  form.find('.flexbox').html();

  form.find('input').each(function() {
    var name = $(this).attr('name');
    var iid = $(this).attr('id');
    name = name.replace(pat, "orgs["+id+"]")
    iid = iid.replace(pat, "orgs["+id+"]")
    $(this).attr('name', name).attr('id', iid).val('');
  });
  form.find('textarea').each(function() {
	    var name = $(this).attr('name');
	    var iid = $(this).attr('id');
	    name = name.replace(pat, "orgs["+id+"]");
	    iid = iid.replace(pat, "orgs["+id+"]");
	    $(this).attr('name', name).attr('id', iid).val('');
  });
  form.find('label').each(function() {
    $(this).attr('for', $(this).attr('for').replace(pat, "orgs["+id+"]"));
  });
  
  lang = $('#ses_lang').val();
  if (lang == 'ru') {
	  mainF = '';
	  dopF  = '_en';
  } else {
	  dopF  = '';
	  mainF = '_en';
  }
  form.find('input#orgid_0').attr('id', 'orgid_'+id);
  form.find('label[for="post'+mainF+'_0"]').attr('for', 'post'+mainF+'_'+id);
  form.find('input#post'+mainF+'_0_1').attr('id', 'post'+mainF+'_'+id+'_1');
  form.find('input#post'+mainF+'_0_1_en').attr('id', 'post'+mainF+'_'+id+'_1_en');
  form.find('input#post'+mainF+'_0_2').attr('id', 'post'+mainF+'_'+id+'_2');
  form.find('input#post'+mainF+'_0_2_en').attr('id', 'post'+mainF+'_'+id+'_2_en');
  form.find('div#field_div_post'+mainF+'_0_1_en').attr('id', 'field_div_post'+mainF+'_'+(id+1)+'_1_en');
  form.find('div#field_div_post'+mainF+'_0_2_en').attr('id', 'field_div_post'+mainF+'_'+(id+1)+'_2_en');
  
  form.find('a#orgs0tm_href_1').attr('id', 'orgs'+id+'tm_href')
							 .show()		
							 .removeAttr('onclick')
  							 .click(function() {
  								 add_dop_field('post'+mainF+'_'+(id+1)+'_1_en', this, 0)});
  form.find('a#orgs0tm_href_2').attr('id', 'orgs'+id+'tm_href')
  						      .show()
							 .removeAttr('onclick')
							 .click(function() {
								 add_dop_field('post'+mainF+'_'+(id+1)+'_2_en', this, 0)});
  
  form.find('div#field_div_post'+mainF+'_'+(id+1)+'_1_en').hide();
  form.find('div#field_div_post'+mainF+'_'+(id+1)+'_2_en').hide();
  form.find('div#field_div_post'+mainF+'_'+(id+1)+'_1_en').find('a').removeAttr('onclick')
  							.click(function() {
  								dop_field_translate('post'+mainF+'_'+id+'_1', 'post'+mainF+'_'+id+'_1_en', this, lang)});
  form.find('div#field_div_post'+mainF+'_'+(id+1)+'_2_en').find('a').removeAttr('onclick')
							.click(function() {
								dop_field_translate('post'+mainF+'_'+id+'_2', 'post'+mainF+'_'+id+'_2_en', this, lang)});
  //form.find('a[class=dop_field2]').parent().hide();
  form.find('a[class=dop_field2]').each(function() {
	    iid = $(this).parent().hide().attr('id').replace('0', id);
	    $(this).parent().attr('id', iid);
	    iid = $(this).parent().find(':input').attr('id').replace('0', id);
	    $(this).parent().find(':input').attr('id', iid);
	    oncAttr = $(this).attr('onClick') + '';
	    iid = oncAttr.replace('0', id);
	    $(this).attr('onClick', iid);
	    //$(this).removeAttr('onclick').click(function() {	
				//dop_field_translit('orgs'+id+iid+mainF, 'orgs'+id+iid+dopF, this, lang)});
  });
  /*
  idDop2Div = form.find('a[class=dop_field2]').parent().hide().attr('id').replace('0', id);
  form.find('a[class=dop_field2]').parent().attr('id', idDop2Div);
  idDop2I = form.find('a[class=dop_field2]').parent().find('input').attr('id').replace('0', id);
  form.find('a[class=dop_field2]').parent().find('input').attr('id', idDop2I);
  idDop2I.replace('_en', '');
  cl = form.find('a[class=dop_field2]').attr('onClick');
  form.find('a[class=dop_field2]').removeAttr('onclick').click(function() {	
	  							dop_field_translit('orgs'+id+idDop2I+mainF, 'orgs'+id+idDop2I+dopF, this, lang)});
  */
  //idDop2 = form.find('a[class=dop_field2]').parent().find('input').attr('id').replace('0', id);
  //form.find('a[class=dop_field2]').parent().attr('id', idDop2);
  form.find('a[class=dop_field]').each(function() {
    	iid = $(this).attr('id').replace('_href', '');
    	if (iid)
    		form.find("#"+iid).attr('id', iid.replace('0', id));
    	//$(this).parent().find(':input').attr('id', iid);
	    	//$(this).parent().find(':input').attr('id', iid);
	     });

  form.find('a[class=dop_field]').show()  							     
	  							 .removeAttr('onclick')
								 .click(function() {
									 if ($(this).parent().find(':input').attr('child'))
										 add_dop_field($(this).parent().find(':input').attr('child').replace('0', id), this)});

  //form.find('input[type=crud_dop_field_par]').hide();
  //$('#orgs'+id+'tm_href').removeAttr('onclick');
    form.find('div').each(function() {
    $(this).attr('id', $(this).attr('id').replace(pat, "orgs["+id+"]"));
  });

  form.find('.addorg').show();
  form.find('script').html('');
  form.appendTo('#orgs_coll').attr('id', 'org_form_'+id);
  form.find('.form').hide();
  //$("input#orgid_"+id).autocomplete($("base").attr("href")+"persons/json_orgname_suggest");

  form.find('.autoComDiv').find("input").autocomplete({
	  			serviceUrl: '/persons/json_orgname_suggest',
	  			noCache: true,
				width: "350"
	});
}

function del_org_form(o)
{
  $(o).parent().parent().remove()
}

function show_form(o)
{
  var p = $(o).parent().parent().parent()
  var id = p.attr('id');
  id = Number(id.substring(9, id.length))
  p.find('.addorg').hide();
  p.find('.form').show("slow");
    
	//clear form
	p.find('.form').find("input").val("");
	p.find('.form').find("textarea").val("");
	p.find('.form').find("input[type=checkbox]").attr("checked", "");
	p.find('.form').find('input#post_'+id).val(p.find('.addorg').find('input#post_'+id).val());
	p.find('.form').find('input#post_'+id).val(p.find('.addorg').find('input#post_'+id).val());
        var lang_det = jQuery.trim(p.find('.form').find('label[for="orgs['+id+'][country_id]"]').text());
        if(lang_det == 'Страна *' || lang_det == "Страна") {
            p.find('.form').find('input.country_code').val("7");
            p.find('.form').find('input.country_field').val("Россия");
        }
        p.find('.form').find('input.country_field').autocomplete({
    		serviceUrl: 'organizations/json_country_suggest',
    		onSelect: function(value, data){
				$.ajax({url:$("base").attr("href") + "organizations/json_select_country/" + data})
		}});
        p.find('.form').find('input.region_field').autocomplete({
    		serviceUrl: 'organizations/json_region_suggest',
    		onSelect: function(value, data){
			$.ajax({url:$("base").attr("href") + "organizations/json_select_region/" + data})
        }});
        p.find('.form').find('input.city_field').autocomplete({
    		serviceUrl: 'organizations/json_city_suggest',
    		onSelect: function(value, data){
			$.ajax({url:$("base").attr("href") + "organizations/json_select_city/" + data})
        }});
}

function show_addorg(o)
{
  var p = $(o).parent().parent()
  p.find('.addorg').show("slow");
  p.find('.form').hide();
  p.find('.addorg').find('.flexbox').html('');
  p.find('.addorg').find('.flexbox').flexbox($("base").attr("href")+"persons/json_orgname_suggest",{
				initialValue: "",
				width: "400"
	});
  var id = p.attr('id');
  id = Number(id.substring(9, id.length))
	p.find('.addorg').find('.flexbox').find("input[type=hidden]").attr("name", 'orgs['+id+'][orgid_add]');
}

var rmFieldset = function() {
  if($(this).css('display') == 'none')
    $(this).remove();
}

function submit_form()
{
  $('#reg_form').find('.addorg').each(rmFieldset);
  $('#reg_form').find('.form').each(rmFieldset);
  $('#reg_form').submit();
}

function showUserReg(ch)
{
	if ($(ch).attr('checked')) $('#userRegDiv').show("slow");
	else $('#userRegDiv').hide("slow");
}

function autoLogin(f)
{
	if ($("#useEmail").is(':checked'))
		$("#username").val($(f).val());
}

function autoDopTransit(par, ch)
{
	$(":input[name='"+ch+"']").val(ru2en.translit($(par).val()));
}

function autoLoginChange(ch)
{
	if ($(ch).is(':checked')) {
		$("#username").val($("#email").val());
		$("#username").css("color" , "gray");
		$("#username").attr("readonly", true);
	} else {
		$("#username").css("color" , "black");
		$("#username").attr("readonly", false);
	}
}

$(document).ready(function showRegForm() {
	if (window.noShowRegForm === undefined){
		$('#reg_form').show();
	}
});

function delCheckedChild(childArr, orgId, name) {
	for (var i=0; i<=childArr.length; i++){
		$('#orgs_'+orgId+'__branch__'+name+'__'+childArr[i]+'_').removeAttr('checked');
	}
}

function addCheckedParent(parArr, orgId, name) {
	for (var i=0; i<=parArr.length; i++){
		$('#orgs_'+orgId+'__branch__'+name+'__'+parArr[i]+'_').attr('checked', 'true');
	}
}

var ru2en = {
		ru_str : "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя",
		en_str : ['A','B','V','G','D','E','JO','ZH','Z','I','J','K','L','M','N','O','P','R','S','T',
		          'U','F','H','C','Ch','Sh','Shh',String.fromCharCode(35),'I',String.fromCharCode(39),'Je','Ju',
		          'Ja','a','b','v','g','d','e','jo','zh','z','i','j','k','l','m','n','o','p','r','s','t','u','f',
		          'h','c','ch','sh','shh',String.fromCharCode(35),'i',String.fromCharCode(39),'je','ju','ja'],
		translit : function(org_str) {
			var tmp_str = [];
			for(var i = 0, l = org_str.length; i < l; i++) {
				var s = org_str.charAt(i), n = this.ru_str.indexOf(s);
				if(n >= 0) { tmp_str[tmp_str.length] = this.en_str[n]; }
				else { tmp_str[tmp_str.length] = s; }
			}
			return tmp_str.join("");
		}
}


function add_dop_field(child, t, h)
{
	$(t).hide();	
	//$('#field_div_'+child).width($('#field_div_'+child).parent().width());
	//$('#field_div_'+child).width("200");
	if (h === undefined)
		$('#field_div_'+child).height('auto');
	else 
		$('#field_div_'+child).height(0);
	//$(t).parent().height($(t).parent().height()+15);
	//$('#field_div_'+child).after("<br clear='all'>");
	$('#field_div_'+child).css('visibility', 'visible');
	$('#field_div_'+child).hide();
	$('#field_div_'+child).fadeIn("slow");
	if ($(t).parent('div').find(':input').is("input")){
		$(t).parent('div').css("float", "left");
		$(t).parent('div').width("250");
	}
}

function dop_field_translit(par, child, t, lang)
{	
	if (lang == 'ru' && $("#"+par).val())
		$("#"+child).val(ru2en.translit($("#"+par).val()));
	else
		dop_field_translate(par, child, t, lang);
}

function dop_field_translate(par, child, t, lang)
{
	//alert(par); alert(child);
	if($("#"+par).val()) {
		langTo = (lang == 'ru') ? 'en' : 'ru';
		$("#"+child).css({'background-color': '#ffe'});
		$.translate($("#"+par).val(), lang, langTo, {
			  complete: function(translation){
				$("#"+child).val(translation);
				$("#"+child).css({'background-color': 'white'});
			  }
		});
	}
}
