var selectedParagraph = null;

function sendForm(id)
{
    $('[id^=error]').html('');
    var qString = $("#" + id).serialize();
    $.post("/ajax/reg.php", qString, function(data){
        var obj = $.parseJSON(data);
        if(obj.error)
        {
            $('#error' + obj.errorID).html(obj.error);
        }
        else if(obj.responce)
        {
            if(obj.responce == 'finish')
            {
                location.href = '/cabinet.php';   
            }
            else
            {
                $('#regForm').html(obj.responce);
            }    
        }
        else
        {
            $('#error').html('Ошибка передачи данных');    
        } 
    });
}

$(document).ready(function(){ 

    $('.date').datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: false, prevText: 'Назад', nextText: 'Далее', firstDay: 1, defaultDate:'2011-01-01', minDate: '2011-01-01', maxDate: '2011-12-31'});
    $('.date').datepicker( "option", "dayNames", ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'] );
    $('.date').datepicker( "option", "dayNamesMin", ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'] ); 
    $('.date').datepicker( "option", "monthNames", ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'] );
    $('.date').datepicker( "option", "monthNamesShort", ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'] );
         
    $('.tips').cluetip({splitTitle: '|', clickThrough: true}).click(function(){
        //$(document).trigger('hideCluetip');
    });
    
    $('#okrug').live('change', function(){
        var id = $(this).val();
                  
        if(id == 0)
        {
            $('#regionList').html('');
        }
        else
        {
            $.get("/ajax/reg.php", 'getRegionList=' + id, function(data){
                $('#regionList').html(data);    
            });
        }
    }); 
    

    $('#punkt').live('change', function(){
        
        selectedParagraph = this.value;
        
        $('#customerTR').attr('className', 'hid');
        $('#customerSelect').html('');
        
        $('#departmentTR').attr('className', 'hid');
        $('#departmentSelect').html('');
        
        $('#sectionTR').attr('className', 'hid');
        $('#sectionSelect').html('');
        
        $.get("/ajax/reg.php", 'getFinanceStatus=' + this.value, function(data){
            if(data == 0)
            {
                $('#noform').attr('className', 'hid');    
            }
            else
            {
                $('#noform').attr('className', 'vis');    
            }        
        });
            
        $.get("/ajax/reg.php", 'getPunktInfo=' + this.value, function(data){
            $('#punktInfo').html(data);        
        });
        
        
        $.get("/ajax/reg.php", 'getPunktCustomers=' + this.value, function(data){
            
            var customers = new Object();
            var customerArr = new Array();
            
            customers = $.parseJSON(data);
                       
            var num = 0;
            for(i in customers)
            {   
                customerArr[num] = new Array(i, customers[i]['name']);
                num++;    
            }
            
            if(customerArr.length == 1)
            {
                customerSelectID = 0;
                $('#customerSelect').html(customerArr[0][1] + '<input type="hidden" name="customer" value="' + customerArr[0][0] + '">');    
            }
            
            $('#customerTR').attr('className', 'vis');
            
            if(customerSelectID !== null)
            {
                var departmentSelect = new Array();
                var num = 0;
                for(i in customers)
                {   
                    if(num == customerSelectID)
                    {
                        var index = 0;
                        for(k in customers[i]['department'])
                        {
                            departmentSelect[index] = new Array(k, customers[i]['department'][k]['name']);
                            index++;
                        }
                    }
                    num++;    
                }
                
                if(departmentSelect.length == 1)
                {
                    departmentSelectString = departmentSelect[0][1] + '<input type="hidden" name="department" value="' + departmentSelect[0][0] + '">';
                }   
                else if(departmentSelect.length > 1)
                {
                    departmentSelectString = '';
                    departmentSelectString += '<select id="department" name="department">';
                    departmentSelectString += '<option value="0" selected="selected" disabled="disabled">Выберите департамент</option>';
                    for(i in departmentSelect)
                    {
                        departmentSelectString += '<option value="' + departmentSelect[i][0] + '">' + departmentSelect[i][1] + '</option>';
                    }
                    departmentSelectString += '</select>';
                }
                else
                {
                    return 0;
                }
                
                $('#departmentSelect').html(departmentSelectString);
                $('#departmentTR').attr('className', 'vis');
            }      
        }); 
        
    });

    $('#department').live('change', function(){
        $.get("/ajax/reg.php", 'getDepartmentSection&punkt=' + selectedParagraph + '&department=' + this.value, function(data){               
            if(data !== '')
            {
                $('#sectionTR').attr('className', 'vis');
                $('#sectionSelect').html(data);    
            }        
        });        
    });  

    
    $('.type').live('change', function() {
        var type = $(this).attr('value');
        $('#error').html('');
        if(type == 'ORG')
        {
            $('#orgInfo').attr('style', 'display: block;');
            $('#fizInfo').attr('style', 'display: none;');
        }
        else
        {
            $('#fizInfo').attr('style', 'display: block;');
            $('#orgInfo').attr('style', 'display: none;');
        }
    });
    
    $('#name').keyup(function(){
        var max = parseInt($(this).attr('maxlength')); 
        var count = max - $(this).val().length;
        if(count < 0)
        {
            var subString = $(this).val().substr(0, max);
            $(this).val(subString);
        }
        else
        {
            $('#count').html(count);
        }
    });
    
    $('#programm').change(function(){
        if(this.value)
        {
            $.get("/ajax/reg.php", 'getProgrammInfo=' + this.value, function(data){
                $('#programmInfo').html(data);        
            });
            
            $.get("/ajax/reg.php", 'getPunktList=' + this.value, function(data){
                $('#punktNameSelect').html(data);        
            });
            
            $('#punktNameTR').attr('className', 'vis');          
            $('#customerTR').attr('className', 'hid');
            $('#departmentTR').attr('className', 'hid');
            $('#noform').attr('className', 'vis');
            $('#customerNameSelect').html('');
            $('#punktInfo').html('');
            $('#departmentSelect').html('');   
        }
        else
        {
            $('#punktNameTR').attr('className', 'hid');
        }
    });
    
    $('.requestType').change(function(){
        
        str = $('#name').val();
        str = str.replace(/Проведение противоаварийных работ на объекте культурного наследия/, '');
        str = str.replace(/Проведение ремонтно-реставрационных работ на объекте культурного наследия/, '');
        str = str.replace(/Разработка проектной документации для ремонтно-реставрационных работ на объекте культурного наследия/, '');
        
        $('#name').val(str);
            
        if(this.value == 0)
        {
            $('.hidSmetaUpLoad').attr('className', 'visSmetaUpLoad');
            $('.visMoreUpload').attr('className', 'hidMoreUpload');
            $('#nameTypeInfo').attr('style', 'color: #990000; display: none;');
        }
        else
        {   
            $('.visSmetaUpLoad').attr('className', 'hidSmetaUpLoad');
            $('#nameTypeInfo').attr('style', 'color: #990000; display: block;');
                        
            switch(this.value)
            {
                case '1':
                $('#name').val('Проведение противоаварийных работ на объекте культурного наследия' + str);
                break;
                
                case '2':
                $('#name').val('Проведение ремонтно-реставрационных работ на объекте культурного наследия' + str);
                break;
                
                case '3':
                $('#name').val('Разработка проектной документации для ремонтно-реставрационных работ на объекте культурного наследия' + str);
                break;
            }
            
            $('.hidMoreUpload').attr('className', 'visMoreUpload');    
        }
    }); 
});

function reloadImage()
{
    var link = "/captcha/captcha.php?sid=" + Math.random();
    $('#siimage').attr('src', link);
}

function delTmpFile(type, file)
{
    $.get("/ajax/delFile.php", 'delTmpFile&type=' + type + '&file=' + file, function(data){
        $("#" + type + "Result").html(data);    
    });        
}

function createUploadObj(type)
{
    new AjaxUpload('#' + type, {
      action: '/ajax/upload.php',
      name: type,
      autoSubmit: true,
      responseType: false,
      onSubmit: function(file, extension) {        
          $("#" + type + "Status").html('Загружаем ' + file); 
      },
      onComplete: function(file, response) {
          $("#" + type + "Status").html(''); 
          $("#" + type + "Result").html(response);       
      }
    });
}

function uploadReady()
{
    $(document).ready(function(){  
        createUploadObj('desc');
        createUploadObj('smeta');
        createUploadObj('img');
        createUploadObj('perechen');
        createUploadObj('objectinfo');
        createUploadObj('reestr'); 
        
        //createUploadObj('smetarealize');
        //createUploadObj('proekt');
        //createUploadObj('ved');
        //createUploadObj('smetacalc');
        //createUploadObj('act'); 
    }); 
}

function getRequestByNumber()
{
    var qString = $("#getRequestByNumber").serialize();
    $.get("/ajax/request.php", qString, function(data){
        $('#result').html(data);
    });
}

function getRequestByLocation()
{
    var qString = $("#getRequestByLocation").serialize();
    $.get("/ajax/request.php", qString, function(data){
        $('#result').html(data);
    });
}

function passwordRecovery()
{
    var qString = $("#passwordRecovery").serialize();
    $.post("/ajax/recovery.php", qString, function(data){
        $('#result').html(data);
    });    
}

var id_menu = '0'; // id всплывающего подменю
var timerOn = false;
var timerID; // переменная таймера
var delay=500; // задержка в мс

// получение абсолютных координат объекта
function getPosX(obj)
{
   var curleft = 0;
   if (obj.offsetParent)
   {
      while (obj.offsetParent)
      {
         curleft += obj.offsetLeft;
         obj = obj.offsetParent;
      }
   }
   else if (obj.x)
   {
      curleft += obj.x;
   }
   return curleft;
}

function getPosY(obj)
{
   var curtop = 0;
   if (obj.offsetParent)
   {
      while (obj.offsetParent)
      {
         curtop += obj.offsetTop;
         obj = obj.offsetParent;
      }
   }
   else if (obj.x)
   {
      curtop += obj.x;
   }
   return curtop;
}

// вывод подменю
function showMenu(id, obj)
{
    if (id==id_menu || id_menu=='0') {} else { document.getElementById(id_menu).style.display = 'none';}
    id_menu = id;
    var object=document.getElementById(id_menu);
    hideMenuAll(id_menu);
    object.style.display = 'block';
    object.style.position = 'absolute';
    object.style.left=getPosX(obj);
    object.style.top=getPosY(obj)+17;
    stopTime();
}

// вывод подменю
/*
function showMenu2(id, obj)
{
    if (id==id_menu || id_menu=='0') {} else { document.getElementById(id_menu).style.display = 'none';}
    id_menu = id;
    var object2=document.getElementById(id_menu);
    hideMenuAll(id_menu);
    object2.style.display = 'block';
    object2.style.position = 'absolute';
    object2.style.left=getPosX(obj)+180;
    object2.style.top=getPosY(obj);
    stopTime();
}
*/
// скрытие подменю
function hideMenuAll(id)
{
   var object=document.getElementById(id_menu);
   object.style.display = 'none';
   stopTime ();
}

function hideMenu()
{
   startTime ();
}

// включение задержки скрытия подменю
function startTime()
{
   if (timerOn == false)
   {
      timerID=setTimeout( "hideMenuAll(id_menu)" , delay);
      timerOn = true;
   }
}

// Сброс параметров
function stopTime()
{
   if (timerOn)
   {
      clearTimeout(timerID);
      timerID = null;
      timerOn = false;
   }
}
/*
// вывод подменю в левом меню
startList = function() {
      if (document.all&&document.getElementById) {
            navRoot = document.getElementById("nav");
            for (i=0; i<navRoot.childNodes.length; i++) {
                  node = navRoot.childNodes[i];
                  if (node.nodeName=="LI") {
                        node.onmouseover=function() {
                              this.className+=" over";
                        }
                        node.onmouseout=function() {
                              this.className=this.className.replace (" over", "");
                        }
                  }
            }
      }
}*/
//window.onload=startList;