var gl = 0;
var uploadify_load = true;
$(document).ready(function(){    $("#registrations").hide();
    $("#vost_dostup").hide();
    //--------------------------------------------------------------------------
	$("#link_reg").bind('click', function () {
	  $("#login").hide();
	  $("#vost_dostup").hide();
      $("#registrations").show('slow', function() {
                     // Animation complete.
                   });

      return false;
	});
	//--------------------------------------------------------------------------
	$("#vost_parol").bind('click', function () {
	  $("#login").hide();
	  $("#registrations").hide();
      $("#vost_dostup").show('slow', function() {
                     // Animation complete.
                   });

      return false;
	});
	//--------------------------------------------------------------------------
	$("#vost_dostup_button").bind('click', function () {	  if ($("#mail").val() == '') { alert('Заполние поле "E-mail"'); $("#mail").addClass('no_paste'); return false;} else $("#mail").removeClass('no_paste');

	  $.post('vost_dostup.php', { 'mail': $("#mail").val() }, function(data) {
      	var arrData = data.split('|');
      	if (arrData[1] == 'false') alert(arrData[0]);
      	else
      	 {
      	    alert(arrData[0]);
      		document.location = '/login.html';
      	 }
      	});
	  return false;
	});
	//--------------------------------------------------------------------------
    $("#reg_button").bind('click', function () {
      if ($("#name").val() == '') { alert('Заполние поле "Имя"'); $("#name").addClass('no_paste'); return false;} else $("#name").removeClass('no_paste');
	  if ($("#tel").val() == '') { alert('Заполние поле "Телефон"'); $("#tel").addClass('no_paste'); return false;} else $("#tel").removeClass('no_paste');
	  if ($("#email").val() == '') { alert('Заполние поле "Адрес Электронной почты"'); $("#email").addClass('no_paste'); return false;} else $("#email").removeClass('no_paste');
	  if ($("#parol").val() == '') { alert('Заполние поле "Пароль"'); $("#parol").addClass('no_paste'); return false;} else $("#parol").removeClass('no_paste');
	  if ($("#parol").val() != $("#return_parol").val()) { alert('Пароли не совпадают'); $("#return_parol").addClass('no_paste'); return false;} else $("#return_parol").removeClass('no_paste');

      $.post('add_user.php', $("#registrations form").serialize(), function(data) {      	var arrData = data.split('|');
      	if (arrData[1] == 'false') alert(arrData[0]);
      	else
      	 {
      	    alert(arrData[0]);
      		document.location = '/login.html';
      	 }
      	});
      return false;
    });
    //--------------------------------------------------------------------------
    $("#add_office_button").bind('click', function () {
	  if ($("#id_kat").val() == '0') { alert('Выберите Метро'); $("#id_kat").addClass('no_paste'); return false;} else $("#id_kat").removeClass('no_paste');
	  if ($("#adrec").val() == '') { alert('Заполние поле "Адрес"'); $("#adrec").addClass('no_paste'); return false;} else $("#adrec").removeClass('no_paste');
	  if ($("#obch_ploshad").val() == '') { alert('Заполние поле "Общая площадь"'); $("#obch_ploshad").addClass('no_paste'); return false;} else $("#obch_ploshad").removeClass('no_paste');
	  if ($("#price").val() == '') { alert('Заполние поле "Стоимость"'); $("#price").addClass('no_paste'); return false;} else $("#price").removeClass('no_paste');
	  if ($("#opis").val() == '') { alert('Заполние поле "Описание"'); $("#opis").addClass('no_paste'); return false;} else $("#opis").removeClass('no_paste');
      if ($("#id_office").val() > 0)
       {       	 if (confirm('Изменение требует повторной модерации. Продолжить?')) { } else return false;
       }
      $.post('add_office.php', $("#add_office form").serialize(), function(data) {      	var arrData = data.split('|');
      	if (arrData[2] == 'false') alert(arrData[0]);
      	else
      	 {
      	    if ($('#fileQueue').html())
      	    {
      	    $('#uploadify').uploadifySettings('scriptData', {'id' : arrData[0],'md5' : arrData[1]});
      		$('#uploadify').uploadifyUpload();
      		}
      		else
      		{
      		//alert(arrData[0]);
      		document.location = '/login.html';
      		}
      	 }
      	});
      return false;
	});
    //--------------------------------------------------------------------------
    $("#min_pic img").bind('click', function () {    	var big_img = $("#big_pic img").attr('src');
    	$("#big_pic img").attr('src', $(this).attr('src'));
    	$(this).attr('src', big_img);
    });
    //--------------------------------------------------------------------------
    $("#map_canvas").hide();
    $("#link_map_canvas").bind('click', function () {
    	$("#map_canvas").show();
        initialize();
        GUnload();
    	return false;
    });
    //--------------------------------------------------------------------------
    $(".del_office").bind('click', function () {
     if (confirm('Вы действительно хотите удалить?'))
      {
        var href = $(this).attr('href');
        gl = $(this).parents("TR");

        $.post(href, { 'par': '1' }, function(data) {
      	var arrData = data.split('|');
      	if (arrData[1] == 'false') alert(arrData[0]);
      	else
      	 {
      		alert(arrData[0]);
      		gl.hide();
      	 }
      	});
      }
    	return false;
    });
    //--------------------------------------------------------------------------
    $(".edit_office").bind('click', function () {
        var href = $(this).attr('href');
        document.location = href;

    	return false;
    });
    //--------------------------------------------------------------------------
    $("#uploadify").uploadify({
		'uploader'       : '/uploadify/scripts/uploadify.swf',
		'script'         : '/uploadify/scripts/uploadify.php',
		'cancelImg'      : '/uploadify/cancel.png',
		'folder'         : 'img',
		'queueID'        : 'fileQueue',
		'auto'           : false,
		'multi'          : true,
		'queueSizeLimit' : 8,
		'SizeLimit'      : 20000,
		'buttonImg'      : '/images/loading_jq.gif',
		'width'          : 177,
		'height'         : 11,
		'fileDesc'       : '*.jpg;*.gif;',
		'fileExt'        : '*.jpg;*.gif;',
		'onComplete'  	 : function(event,queueID,fileObj,response,data) {if(response) uploadify_load = true; else  uploadify_load = false;},
		'onAllComplete'  : function(event,data) {if(uploadify_load) document.location = '/login.html'; }
	});

    //--------------------------------------------------------------------------
    $(".primery_office").html('Поднять объявление');
    $(".primery_office").bind('click', function () {        $("#color_office_a1").hide();
        $("#spec_office_a1").hide();
        var id = $(this).attr('id');
        $(this).attr('href', '#primery_office');

        $("#primery_office_a1").show();
        var t = '<b>Поднять объявление ( #'+id+' )</b> – ваше объявление займет первую строчку в поиске, его увидят в 3-5 раз больше целевых людей, которым подходят параметры вашего помещения.<br><br><br>';
        t += 'Отправьте со своего мобильного телефона SMS-сообщение с текстом <span style="color:red; font-size:16px;">90</span><span style="color:blue; font-size:16px;">7575</span><span style="color:red; font-size:16px;">'+id+'</span><br>на короткий номер <span style="color:blue; font-size:16px;">1899</span> (стоимость услуги - 3$)<br><br>';
        t += '<b>Вы можете оплатить услугу по Webmoney</b><br>';
        t += '<a href="https://light.webmoney.ru/pci.aspx?purse=R397912174208&amount=90&method=GET&desc=w000377+|907575|'+id+'&url=http%3A%2F%2Fa1agregator.ru">Webmoney Lite</a><br>';
        t += '<a href="wmk:paylink?purse=R397912174208&amount=90&method=GET&desc=w000377+|907575|'+id+'&url=<http://a1agregator.ru>">Webmoney Classic</a><br>';
        t += '<br>';
        t += 'Подробнее с тарифами вы можете ознакомиться <a target=_blank href="http://www.a1agregator.ru/main/abonent/4846/1899">здесь</a>. В случае возникновения проблем с оплатой, воспользуйтесь, пожалуйста, <a href="http://www.arenda-house.com/contact.html">обратной связью</a> (срок ответа - не более 1 суток).';
        $("#primery_office_a1").children('p').html(t);

    });
    $("#primery_office_a1_hide").bind('click', function () {
        $("#primery_office_a1").hide();
    });
    //--------------------------------------------------------------------------
    $(".color_office").html('Выделить цветом');
    $(".color_office").bind('click', function () {    	$("#primery_office_a1").hide();
    	$("#spec_office_a1").hide();
        var id = $(this).attr('id');
        $(this).attr('href', '#color_office');

        $("#color_office_a1").show();
        var t = '<b>Выделить цветом объявление ( #'+id+' )</b> – хорошая возможность обратить внимание именно на своё объявление, позволяет в несколько раз ускорить процесс сдачи помещения.<br><br><br>';
        t += '<b>Вы можете оплатить услугу по Webmoney</b><br>';
        t += '<a href="https://light.webmoney.ru/pci.aspx?purse=R397912174208&amount=90&method=GET&desc=w000377+|908585|'+id+'&url=http%3A%2F%2Fa1agregator.ru">Webmoney Lite</a><br>';
        t += '<a href="wmk:paylink?purse=R397912174208&amount=90&method=GET&desc=w000377+|908585|'+id+'&url=<http://a1agregator.ru>">Webmoney Classic</a><br>';
        t += '<br>';
        t += 'Отправьте со своего мобильного телефона SMS-сообщение с текстом <span style="color:red; font-size:16px;">90</span><span style="color:blue; font-size:16px;">8585</span><span style="color:red; font-size:16px;">'+id+'</span><br>на короткий номер <span style="color:blue; font-size:16px;">1899</span> (стоимость услуги - 3$)<br><br>';
        t += 'Подробнее с тарифами вы можете ознакомиться <a target=_blank href="http://www.a1agregator.ru/main/abonent/4846/1899">здесь</a>. В случае возникновения проблем с оплатой, воспользуйтесь, пожалуйста, <a href="http://www.arenda-house.com/contact.html">обратной связью</a> (срок ответа - не более 1 суток).';

        $("#color_office_a1").children('p').html(t);

    });
    $("#color_office_a1_hide").bind('click', function () {
        $("#color_office_a1").hide();
    });
    //--------------------------------------------------------------------------
    $(".spec_office").html('Закрепить в спец. предложениях');
    $(".spec_office").bind('click', function () {    	$("#primery_office_a1").hide();
    	$("#color_office_a1").hide();
        var id = $(this).attr('id');
        $(this).attr('href', '#spec_office');

        $("#spec_office_a1").show();
        var t = '<b>Закрепить в спец. предложениях объявление ( #'+id+' )</b> – воспользовавшись этой услугой, ваше объявление моментально попадет в «спец. блок», который размещен вверху каждой странице. Вы получите в 12-15 раз больше показов и ощутимый рост звонков по отдельно взятому объявлению.<br><br><br>';
        t += 'Отправьте со своего мобильного телефона SMS-сообщение с текстом <span style="color:red; font-size:16px;">90</span><span style="color:blue; font-size:16px;">9595</span><span style="color:red; font-size:16px;">'+id+'</span><br>на короткий номер <span style="color:blue; font-size:16px;">5537</span> (стоимость услуги - 5$)<br><br>';
        t += '<b>Вы можете оплатить услугу по Webmoney</b><br>';
        t += '<a href="https://light.webmoney.ru/pci.aspx?purse=R397912174208&amount=90&method=GET&desc=w000377+|909595|'+id+'&url=http%3A%2F%2Fa1agregator.ru">Webmoney Lite</a><br>';
        t += '<a href="wmk:paylink?purse=R397912174208&amount=90&method=GET&desc=w000377+|909595|'+id+'&url=<http://a1agregator.ru>">Webmoney Classic</a><br>';
        t += '<br>';
        t += 'Подробнее с тарифами вы можете ознакомиться <a target=_blank href="http://www.a1agregator.ru/main/abonent/4846/5537">здесь</a>. В случае возникновения проблем с оплатой, воспользуйтесь, пожалуйста, <a href="http://www.arenda-house.com/contact.html">обратной связью</a> (срок ответа - не более 1 суток).';
        $("#spec_office_a1").children('p').html(t);

    });
    $("#spec_office_a1_hide").bind('click', function () {
        $("#spec_office_a1").hide();
    });

    //--------------------------------------------------------------------------

    //--------------------------------------------------------------------------
});







function getContents () {
    var map_movie3 = window.document.map_movie3;
    if (map_movie3.GetVariable("sname")) {
     var metro_str = map_movie3.GetVariable("sname");
     return metro_str;
    } else {
     alert('Вы не выбрали ни одной станции метро на карте');
     return false;
    }
}

 function disableds (rad, inp)
     {
     	var inputs = document.getElementById(inp);
     	var radios = document.getElementById(rad);
        if (radios.checked) inputs.disabled=0;
        else inputs.disabled=1;
     }
 function checkForm (form)
     {
		var text = '';
		var c = 0;
		while (form[c])
		 {
		    //alert(form[c].name +' - ' + form[c].type +' - ' + form[c].value);
		    if (form[c].type == 'text' || form[c].type == 'textarea' || form[c].type == 'select-one' || form[c].type == 'hidden' || form[c].type == 'radio' || form[c].type == 'checkbox')
		     {
                  if (form[c].id=='yes' && form[c].value=='')
                   {
                   	   alert('Заполние поле "'+ form[c].title +'"');
                   	   form[c].style.background='#F7E920';
                   	   form[c].focus();
                   	   return 0;
                   }
                  else if (form[c].id=='yes') form[c].style.background='#ffffff';
		     	  //alert(form[c].name + ' - ' + form[c].id);
		     	  if (form[c].type == 'radio')
		     	   {
		     	   	if (form[c].checked) text += form[c].title + ':\t' + form[c].value + '\n';
		     	   }
		     	  else
		     	   {
		     	  	if (!form[c].disabled) text += form[c].title + ':\t' + form[c].value + '\n';
		     	   }
		     }
			c++;
		 }
		 post_mail(text, form);
	 }
 function post_mail (text, form)
          {
                 var url = '/mail.php';
                 var param = null;
                 this.http = get_http();
                 this.working = false;

                 // Запрос
		         if (!this.working && this.http)
		          {
		            var http = this.http;
					var method = "POST";
					this.http.open(method, url, true);
					if (method == "POST")
					{
					  param = 'text=' + text + '&title=' + form.title;
					  param = encodeURI(param);
					  this.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					  this.http.setRequestHeader("Content-length", param.length);
					  this.http.setRequestHeader("Connection", "close");
					}
		            //прикрепляем к запросу функцию-обработчик
		            //событий
		            this.http.onreadystatechange = function()
		             {
			            // 4 - данные готовы для обработки
		                if (http.readyState == 4)
		                  {
		                    value = http.responseText;
		                    this.working = false;

                                form.style.display = 'block';
			                	form.innerHTML = value;

		                  }else
		                  {
                             form.innerHTML = '<center><img src="/images/ProgressBar.gif"></center>';
		                  }
		             }
		            this.working = true;
		            this.http.send(param);
		          }
		         if(!this.http)
		          {
		              alert('Ошибка при создании XMLHTTP объекта!')
		          }

          }


          function get_http()
		  {
		    if (window.XMLHttpRequest) {
		        try {
		            return new XMLHttpRequest();
		        } catch (e){}
		    } else if (window.ActiveXObject) {
		        try {
		            return new ActiveXObject('Msxml2.XMLHTTP');
		        } catch (e){}
		        try {
		            return new ActiveXObject('Microsoft.XMLHTTP');
		        } catch (e){}
		    }
		    return null;
		  }