function ge()
{
  var ea;
  for( var i = 0; i < arguments.length; i++ ) {
    var e = arguments[i];
    if( typeof e == 'string' ){
      e = document.getElementById(e);
	}
    if( arguments.length == 1 ){
      return e;
	}
    if( !ea ){
      ea = new Array();	
	}
    ea[ea.length] = e;
  }
  return ea;
}

function ajax(type,data,onReadyFunction)
{
	if(type==0)
	{
		var req = new JsHttpRequest();
	    req.onreadystatechange = function() {
	        if (req.readyState == 4) {
	        	ajaxResult(req.responseJS,req.responseText);
	        	if(onReadyFunction!=undefined){
	        		window.eval(onReadyFunction);
	        	}
	        }
	    }
            req.open(null, '/form/ajax.php?ajax=arr', true)
	    req.send(data);
	}
	else if(type==1)
	{
		var formData = ge(data);
		var req = new JsHttpRequest();
                $("#submit2").attr('disabled', 'disabled');
                $("#submit2").attr('value', 'Отправка');
		    req.onreadystatechange = function() { 
		        if (req.readyState == 4) {
                        $("#submit2").removeAttr('disabled');
                        $("#submit2").attr('value', 'Отправить');
		        	ajaxResult(req.responseJS,req.responseText);
					if(onReadyFunction!=undefined){
		        		window.eval(onReadyFunction);
		        	}
		    	           
		        }
		    }
		    req.open(null, '/form/index.php?ajax=arr', true);
		    req.send( {q: formData} );
	}
}

function ajaxResult(result,error)
{
	if(error)
	{
		$("#debug").html(error);
	}
	
	if(result)
	{
		for(key in result)
		{		
			var tmp = result[key];

			if(tmp["type"]=="html")
			{ 
				$(tmp["id"]).html(tmp["content"]);
			}
			else if(tmp["type"]=="addClass")
			{
				$(tmp["id"]).addClass(tmp["class"]);
			}
			else if(tmp["type"]=="removeClass")
			{
				$(tmp["id"]).removeClass(tmp["class"]);
			}
			else if(tmp["type"]=="show")
			{
				$(tmp["id"]).show();
			}
			else if(tmp["type"]=="hide")
			{
				$(tmp["id"]).hide();
			}
			else if(tmp["type"]=="winLocReload")
			{
				window.location.reload(false);
			}
			else if(tmp["type"]=="winLocHref")
			{
				window.location.href=tmp["href"];
			}
			else if(tmp["type"]=="val")
			{
				if(tmp["subtype"]=="+")
				{
					var buf = $(tmp["id"]).val();
					$(tmp["id"]).val(buf+tmp["val"]);
				}
				else
				{
					$(tmp["id"]).val(tmp["val"]);
				}
			}
			else if(tmp["type"]=="attr")
			{
				$(tmp["id"]).attr(tmp["attr"],tmp["val"]);
			}
			else if(tmp["type"]=="alert")
			{
				openMessage(tmp["text"]);
			}
			else if(tmp["type"]=="setTimeout")
			{
				setTimeout(tmp["eval"],tmp["time"]);
			}
			else if(tmp["type"]=="outer")
			{
				ge(tmp["id"]).outerHTML =tmp["content"];
			}
			else if(tmp["type"]=="value")
			{
				ge(tmp["id"]).value =tmp["content"];
			}
			else if(tmp["type"]=="append")
			{
				$("#"+tmp["id"]).append(tmp["content"]);
			}
			else if(tmp["type"]=="prepend")
			{
				$("#"+tmp["id"]).prepend(tmp["content"]);
			}
			else if(tmp["type"]=="arr")
			{			
				globals[tmp["id"]] =tmp["content"];
			}
			else if(tmp["type"]=="style")
			{
				ge(tmp["id"]).style[tmp["stype"]]=tmp["value"];
			}			
			else if(tmp["type"]=="submit")
			{
				$(tmp["id"]).submit();
			}				
		}
	}
}


function send()
{
	if(check_form())
	{	
		ajax(1,"onorder");
	}
}


function check_form()
{	
	var phone = $('#phone').val();
	var name = $('#name').val();
	var mail = $('#mail').val();

	var reg_phone = new RegExp('^[0-9\+ \-]+$');
	var reg_name = new RegExp('^[a-zA-Zа-яА-Я-_0-9 ]+$');
	$('p.error').html('');
	if($('#marka').val()==0)
	{
		$('p.error').html('Выберите Марку автомобиля.');
		return false;
	}
	else if($('#model').val()==0)
	{ 
		$('p.error').html('Выберите Модель автомобиля.');
		return false;
	}
        else if($('#probeg').val()=='')
	{ 
		$('p.error').html('Поле Пробег обязательно для заполнения.');
		return false;
	}
	else if(name!="" && !reg_name.test(name))
	{
		$('p.error').html('Поле Имя может содержать только символы русского и ангийского алфавита, цифры.');
		return false;
	}
	if(name!="" && !reg_name.test(name))
	{
		$('p.error').html('Поле Имя может содержать только символы русского и ангийского алфавита, цифры.');
		return false;
	}
	else if(mail=="" && phone!="" && !reg_phone.test(phone))
	{
		$('p.error').html('Поле Телефон может содержать только символы "пробел", цифры, - и +');
		return false;
	}
	else if(mail=="" && phone!="" && !ValidatePhone())
	{
		$('p.error').html('Поле Телефон введено не в правильном формате.');
		return false;
	}
	else if(mail!="")
	{
		if(!checkmail(mail))
		{
			$('p.error').html('Электронная почта введена не верно.');
			return false;
		}
	}
	else if(phone=="")
	{
		$('p.error').html('Поле Телефон обязательно к заполнению.');
		return false;
	}
	return true;
}

function checkmail(value) 
{
	var reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
	
	if (!value.match(reg)) 
	{
		return false; 
	}
	return true;
}

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 7;

function isInteger(s)
{var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function trim(s)
{var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
function stripCharsInBag(s, bag)
{var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
var bracket=3
strPhone=trim(strPhone)
if(strPhone.indexOf("+")>1) return false
if(strPhone.indexOf("-")!=-1)bracket=bracket+1
if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
var brchr=strPhone.indexOf("(")
if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function ValidatePhone(){
	var Phone = $('#phone').val();
	if ((Phone==null)||(Phone=="")){
		return false;
	}
	if (checkInternationalPhone(Phone)==false){
		return false;
	}
	return true
 }
 
 function cars()
 {
 	var options = {};
 	options['mod'] = "order";
 	options['a'] = "get_models";
 	options['marka'] = $('#marka').val();
 	
 	ajax(0,options);
 }
 
 var files = 1;
 
 function add_file()
 {
 	if(files<8)
 	{
 		$('#files').prepend('<input type="file" id="photo" name="photo[]" />');
 		files++;
 	}
 } 
 function remove_file()
 {
 	if(files>1)
 	{
 		files--;
 		
 		$('#files').html('');
 		
 		for(i=1;i<=files;i++)
 		{
 			$('#files').prepend('<input type="file" id="photo" name="photo[]" />');
 		}
 		 			
 		$('#files').append('<button onclick="remove_file();return false;">-</button> <button onclick="add_file();return false;">+</button>');
 	}
 }
 
 $(document).ready(function(){
 	 	
 	var options = {};
 	options['mod'] = "order";
 	options['a'] = "get_marks";
 	
 	ajax(0,options);
 });
