var myDomain = document.domain;
var nRandom = Math.round(Math.random() * 100000);
var demand, demand_type, demand_object_type;

function view_tr(name)
{
    $("tr[class*='type']").hide();
    
    $("tr[class*='" + name + "']").show();
    
    $("tr:visible > td").removeClass();    
    $("tr:visible:even > td").toggleClass("color1");    
    $("tr:visible:odd > td").toggleClass("color2");
    
    required_fields(name);
}

function required_fields(name)
{
    $("tr[class*='required']").children('td').children('input, select').each (function () {
        $(this).rules("remove");
    });
    
    $("tr[class='required']").children('td').children('input, select').each (function () { 
        if ($(this).attr('name') == 'form[price]')
        {
            if (demand_type == 'farmingliving' || demand_type == 'rentliving')
            {
                $(this).rules("add", {
                    'required': true, 
    		        'check_price': true
                });
            }
            else 
            {
                $(this).rules("add", {
                    'required': true
                });
            }
        }
        else if ($(this).attr('name') == 'form[email]')
        {
            $(this).rules("add", {
                'email': true
            });
        }
        else 
        {
            $(this).rules("add", {
                'required': true
            });
        }
    });
    $("tr[class*='required'][class*='" + name + "']").children('td').children('input, select').each (function () { 
        if ($(this).attr('name') == 'form[rooms_str]' && demand_type == 'rentliving')
        {
            $(this).rules("add", {
                'required': true, 
		        'check_rooms': true
            });
        }
        else 
        {
            $(this).rules("add", {
                'required': true
            });
        }
    });
}

var mobile_code = ['901', '903', '904', '905', '906', '909', '911', '921', '929', '931', '950', '951', '952', '953', '960', '961', '962', '963', '964', '965', '981'];

$(document).ready( function () {
	$('#mainmenu').droppy();
	
	$('.hide').css('cursor', 'pointer');
	$('.hide').each(function () {
	    var div_id = '#div_' + $(this).attr('id');
	    $(div_id).hide();
	    $(this).bind('click', function () {
    	    if ($(div_id).css('display') == 'none')
    	    {
    	        $(div_id).show();
    	    }
    	    else
    	    {
    	        $(div_id).hide();
    	    }
    	});
	});

    if (demand == true)
    {
        var mess = 0;
        
    	$.validator.addMethod("cod", function(value) {
            var filter = /^([0-9]+)$/i;
    		var result = filter.test(value) && (value.length == 3 || value.length == 5);// ? true :false;
    		
    		if (result && demand_type == 'farmingliving')
    		{
    		   for (var i = 0; i < mobile_code.length; i++)
    		   {
                    if (mobile_code[i] == value)
                    {
                        result = false;
                    }
    		   }
    		}

    		return result;
    	}, 'Некорретный код.');
    	
    	$.validator.addMethod("phone", function(value) { 
    	    var result = (value.length == 5 || value.length == 7) ? true :false;
    	    
    	    if (result && demand_type == 'farmingliving')
    	    {
    	        if ($('input[name="form[phone_code]"]').val() == '812' && (value.substring(0, 1) == '9' || value.substring(0, 3) == '715' || value.substring(0, 3) == '716'))
    	        {
                    result = false;
    	        }
    	    }
    		return result;
    	}, 'Некорретный номер телефона.');
     	
    	$.validator.addMethod("check_phone", function(value) { 
    	    var result = false;
    	    
    	    var url = "http://" + myDomain + "/system/data.php";
    	    var data = nRandom + "&action=check_phone&form[phone]=" + value + "&cod=" + $('input[name="form[phone_code]"]').val() + "&type=" + demand_type;
    	    
            $.ajax({
               type: "POST",
               url: url,
               data: data,
               async: false,
               success: function(msg){
                    result = msg == 'true' ? true : false;
               }
             });    	  
               
    	    return result;
    	}, 'Эта форма для частных лиц, перезвоните по тел. 387-86-87.');
    	
    	$.validator.addMethod("email", function(value) { 
    	    res = !$('#that_new').attr('checked') || value != '';
    	    if (value != '') 
    	    {
                var filter = /^[A-Za-z0-9]+[-_\.]*\w*@\w+-?\w*\.[\.\-_A-Za-z0-9]*[a-z]{2,4}$/i;
                res = filter.test(value);
    	    }
    	    return (res);
    	}, 'Введите корретный e-mail для рассылки.');
    	
    	$.validator.addMethod("check_rooms", function(value) { 
            var filter = /^([0-9]{1,2})(-[0-9]{1,2})?$/i;
            res = filter.test(value);

    	    return res;
    	}, 'Неверный формат поля');
    	
    	$.validator.addMethod("check_price", function(value) { 
    	    var res = false;
    	    var regions = '';
    	    var rooms = '';
    	    if (demand_type == 'farmingliving')
    	    {
    	        regions = "&region_id=" + $('select[name="form[district_id]"]').val();
    	        rooms = $('input[name="form[rooms]"]').val();
    	    }
    	    else 
    	    {
    	        $('select[name*="form[district_id]"] > option:selected').each(function() {
    	            regions += "&region_id[]=" + $(this).val();
    	        });
    	        rooms = parseInt($('input[name="form[rooms_str]"]').val());
    	    }
    	    
    	    if ($('input[name="form[lease_period]"]:checked').val() == 1 && ($('#type').val() == 'appartment' || $('#type').val() == 'room') && regions != '')
    	    {
        	    var url = "http://" + myDomain + "/system/data.php";
        	    var data = nRandom + "&action=check_price&demand_type=" + demand_type + "&type=" + $('#type').val() + regions + "&rooms=" + rooms + "&price=" + value;
        	    
                $.ajax({
                   type: "POST",
                   url: url,
                   data: data,
                   async: false,
                   success: function(msg){
                        if (msg != '0')
                        {
                            $('#min_price').html(msg);
                            var str_type = $('#type').val() == 'appartment' ? 'квартиры' : 'комнаты';
                            $('#min_price_type').html(str_type);
                            if (demand_type == 'rentliving')
                            {
                                $('#rgn').html($('select[name*="form[district_id]"] > option:selected').length > 1 ? 'выбранных районах' : 'выбранном районе');
                            }
                            $('#price_error').show();
                            
                            res = false;
                        }
                        else 
                        {
                            $('#price_error').hide();
                            res = true;
                        }
                   }
                 });
    	    }
    	    else 
    	    {
    	        res = true;
    	    }
    	    return res;
    	}, 'Неверно задана цена.');
    	
        $("#SendForm").validate({
    		rules: {
    		    'form[phone_code]': {
    		        'required': true, 
    		        'cod': true
    		    }, 
    		    'form[phone]': {
                    'required': true, 
    		        'phone': true, 
    		        'check_phone': true
                }
    		},
    		errorPlacement: function(error, element) {
                var index = element.parent('td').children('input, select').index(element);
    		    element.parent('td').children('p:eq(' + index + ')').empty();
                error.appendTo( element.parent('td').children('p:eq(' + index + ')') );
            }/*, 
            success: function(element) {
                var index = element.parent('td').children('input, select').index(element);
                element.parent('td').children('p:eq(' + index + ')').empty();
            }*/
        });
            
        $('#type').bind('change', function () {
            view_tr($(this).val());
            if (demand_type == 'farmingliving' || demand_type == 'rentliving')
            {
                $('#price_error').hide();
                $('p.color_red').html('');
            }
        });
    
        view_tr(demand_object_type);
           
        switch (demand_type) 
        {
            case 'farmingliving': 
            case 'rentliving': 
                $('input[name="form[lease_period]"][value="1"]').bind('click', function () {
                    $('#sp_price').html('руб./мес.')
                });                
                $('input[name="form[lease_period]"][value="2"]').bind('click', function () {
                    $('#sp_price').html('руб./сут.')
                }); 
                break;
        }
    }
});

jQuery.extend(jQuery.validator.messages, {
        required: "Это поле необходимо заполнить",
        remote: "Исправьте это поле чтобы продолжить",
        email: "Введите правильный email адрес.",
        url: "Введите верный URL.",
        date: "Введите правильную дату.",
        dateISO: "Введите правильную дату (ISO).",
        number: "Введите число.",
        digits: "Введите только цифры.",
        creditcard: "Введите правильный номер вашей кредитной карты.",
        equalTo: "Повторите ввод значения еще раз.",
        accept: "Пожалуйста, введите значение с правильным расширением.",
        maxlength: jQuery.format("Нельзя вводить более {0} символов."),
        minlength: jQuery.format("Должно быть не менее {0} символов."),
        rangelength: jQuery.format("Введите от {0} до {1} символов."),
        range: jQuery.format("Введите число от {0} до {1}."),
        max: jQuery.format("Введите число меньше или равное {0}."),
        min: jQuery.format("Введите число больше или равное {0}.")
});

function showPage(form_name, n)
{
	var obj = eval('document.getElementById("' + form_name + '")');
    obj.start.value = n;
	obj.action.value = '';
    obj.target = '_top';
	obj.submit();
}

function printPage(form_name, n)
{
	var obj = eval('document.getElementById("' + form_name + '")');
	obj.start.value = n;
	obj.action.value = 'print';
    obj.target = '_blank';
	obj.submit();
}

function printAllPage(form_name)
{
	var obj = eval('document.getElementById("' + form_name + '")');
	obj.start.value = 0;
	obj.action.value = 'printall';
    obj.target = '_blank';
	obj.submit();
}

function printSelectedPage(form_name)
{
	var obj = eval('document.getElementById("' + form_name + '")');
	obj.start.value = 0;
	obj.action.value = 'printselected';
        obj.target = '_blank';
	obj.submit();
}

function sortPage(form_name)
{
	var obj = eval('document.getElementById("' + form_name + '")');
	obj.sort.value = obj.sorttype.value;
	obj.action.value = '';
    obj.target = '_top';
	obj.submit();
}

function sortordPage(form_name)
{
	var obj = eval('document.getElementById("' + form_name + '")');
	obj.sort_ord.value = obj.sortordtype.value;
	obj.action.value = '';
    obj.target = '_top';
	obj.submit();
}

function set_path(form_name)
{
	var obj = eval('document.getElementById("' + form_name + '")');
    var action = obj.action;
    var and = '?';
    if(obj.length > 0) 
    {
        for(var i=0; i<obj.length; i++) 
        {
            if(obj[i].type == 'checkbox')
            {
                if(obj[i].checked == true && obj[i].name != 'r1' && obj[i].name != 'r2' && obj[i].name != 'r3' && obj[i].name != 'r4')
                {
                    
                    action = action + and + obj[i].name + '=' + obj[i].value;
                    and = '&';
                }
            }
            else if(obj[i].name != '' && obj[i].value != '')
            {
                action = action + and + obj[i].name + '=' + obj[i].value;
                and = '&';
            }
        }
    }
    obj.action = action;
}

function MySelectAll(type)
{
  var val = 0;
  if (document.submitForm.checkall.checked == 1) val = 1;
  else val = 0;

    var old;
    var prefix = "selectedID_" + type + "=";
    var cookieStartIndex = document.cookie.indexOf(prefix);
    if (cookieStartIndex == -1)
        old = '';
    else
    {
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
        if (cookieEndIndex == -1)
            cookieEndIndex = document.cookie.length
        old  = unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
    }
    var cook = old;
    
  var i = 0;
  while (i < document.submitForm.elements.length)
  {
    if (document.submitForm.elements[i].type == 'checkbox' && document.submitForm.elements[i].name == 'selectedID[]')
    {
         document.submitForm.elements[i].checked = val;
    
        if(val == 1)
        {
            cook = cook + document.submitForm.elements[i].value + "::";
        }
        else
        {
            var arStartIndex = 0;
            ar_id = new Array();
            var j = 0;
            cook = '';
            
            while (old != '')
            {
                var arEndIndex = old.indexOf('::');
                ar_id[j] = old.substring(arStartIndex, arEndIndex);
                old = old.substring(arEndIndex + 2, old.length);
                
                if(ar_id[j] != document.submitForm.elements[i].value)
                    cook = cook + ar_id[j] + "::";
                    
                j++;
            }        
            old = cook;
        }
    }
    i++;
  }
  document.cookie = "selectedID_" + type + "=" + cook + ";path=/;";        
}

function cook(id, type)
{
    var elem = document.getElementById("selectedID"+id);

    var old;
    var prefix = "selectedID_" + type + "=";
    var cookieStartIndex = document.cookie.indexOf(prefix);
    if (cookieStartIndex == -1)
        old = '';
    else
    {
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
        if (cookieEndIndex == -1)
            cookieEndIndex = document.cookie.length
        old  = unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
    }

    if(elem.checked == true)
    {        
        document.cookie = "selectedID_" + type + "=" + old + id + "::;path=/;";        
    }
    else
    {
        var arStartIndex = 0;
        ar_id = new Array();
        var i = 0;
        var cook = '';
        
        while (old != '')
        {
            var arEndIndex = old.indexOf('::');
            ar_id[i] = old.substring(arStartIndex, arEndIndex);
            old = old.substring(arEndIndex + 2, old.length);
            
            if(ar_id[i] != id)
                cook = cook + ar_id[i] + "::";
                
            i++;
        }
        
        document.cookie = "selectedID_" + type + "=" + cook + ";path=/;";  
    }    
}

function rem_cook(type)
{
    document.cookie = "selectedID_" + type + "=0;expires=1;";        
    
    var i = 0;
    while (i < document.submitForm.elements.length)
    {
        if (document.submitForm.elements[i].type == 'checkbox' && document.submitForm.elements[i].name == 'selectedID[]')
        {
            document.submitForm.elements[i].checked = false;
        }
        i++;
    }
}

function rem_row (id)
{
    $.get("http://" + myDomain + "/note.php?action=rem_row&id=" + id, function(data){
    	$('#result').html(data);
    });
}
