var request;
var dest;
var arOnLoad = new Array();
var inter;
var arAction = new Array();

function addArrayAction(f)
{
     arAction[arAction.length] = f; 
}
function doArrayAction()
{
	var v;
	for (i=0; i<arAction.length; i++) {
		v = arAction[i];
		delete arAction[i];
		eval(v);
	}
	arAction = new Array();
}


function get(id)
{
    return document.getElementById(id);
}

function addArrayLoad(f)
{
    arOnLoad[arOnLoad.length] = f;
}

function doArrayLoad()
{
    for (i=0; i<arOnLoad.length; i++) {
        eval(arOnLoad[i]);
    }
}

function getClientHeight()
{
    return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function getClientWidth()
{
    return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}

function ShowAlert(n,t)
{
    var htm='';
    htm += '<table id="dialog_tb">';
    htm += '<tr><td id="dialog_title">'+n+'</td></tr>';
    htm += '<tr><td id="dialog_text">'+t+'</td></tr>';
    htm += '<tr><td id="dialog_close"><a href="/" onclick="CloseDialog(); return false;">Закрыть сообщение</a></td></tr>';
    htm += '</table>';
    showDialog(htm, 400, 300);
}

function showDialog(html,w,h)
{

    var wt = getClientWidth();
    var ht = getClientHeight();
    var L = Math.ceil((wt-w)/2);
    var T = Math.ceil((ht-h)/2)+eval(document.documentElement.scrollTop||document.body.scrollTop);

    var htm='';
    htm += '<div id="place_dialog"></div>';
    htm += '<div id="dialog">' + html + '</div>';
  
    get('place_point').innerHTML = htm;
//alert(12);
    get('place_dialog').style.width = wt + 'px';
    get('place_dialog').style.height = eval(document.documentElement.scrollHeight||document.body.scrollHeight) + 'px';
    get('dialog').style.left = L + 'px';
    get('dialog').style.top = T + 'px';
}


function CloseDialog()
{
    parent.get('place_point').innerHTML = '';
}

function ConfirmDialog(txt, url)
{
    var htm='';
    htm += '<table id="dialog_tb">';
    htm += '<tr><td id="dialog_title" style="padding-bottom: 10px;">'+txt+'</td></tr>';
    htm += '<tr><td id="dialog_close"><table cellpadding="0" cellspacing="0" width="100%"><tr><td align="left"><a href="'+url+'" return false;">Подтвердить</a></td><td align="right"><a href="/" onclick="CloseDialog(); return false;">Отмена</a></td></tr></table></td></tr>';
    htm += '</table>';
    showDialog(htm, 400, 300);
}



function inCart(id)
{
  
    var htm='';
    htm += '<table id="dialog_tb">';
    htm += '<tr><td id="dialog_text" align="center"><img src="/templates/pictures/preloader.gif"></td></tr>';
    htm += '<tr><td id="dialog_close"><table cellpadding="0" cellspacing="0" width="100%"><tr><td align="left"><a href="/order/" onclick="showInCart();">Перейти в Ваш заказ</a></td><td align="right"><a href="/" onclick="CloseDialog(); showInCart(); return false;">Закрыть сообщение</a></td></tr></table></td></tr>';
    htm += '</table>';
    showDialog(htm, 350, 300);
   
    loadHTML('/scripts/loadhtml.php?act=add_cart&id='+id, 'dialog_text');
    
}


function checkRequest()
{
    if (window.XMLHttpRequest){
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        request = new ActiveXObject("Microsoft.XMLHTTP");
        if(!request) request = new ActiveXObject("Msxml2.XMLHTTP");
    }
}

function processStateChange()
{
    if (request.readyState == 4){
        contentDiv = document.getElementById(dest);
        if (request.status == 200){
            response = request.responseText;
            contentDiv.innerHTML = response;
            //doArrayLoad();
            doArrayAction();
        } else {
            //alert("Error: Status "+request.status);
            contentDiv.innerHTML = "Error: Status "+request.status;
            response = request.responseText;
            contentDiv.innerHTML = response;
        }
    }
}

function loadHTML(URL, destination)
{
    dest = destination;
    checkRequest();
    if (request) {
        request.onreadystatechange = processStateChange;
        request.open("GET", URL, true);
        request.send();
    }
    return true;
}

function showInCart()
{
    loadHTML('/scripts/loadhtml.php?act=in_cart', 'in_cart');
}

function CheckValue(i)
{
    if(i.value && i.value!=0 && !Number(i.value) || i.value==0 ){
        i.style.background = '#efcaca';
        i.focus();
        ShowAlert('Внимание!','Вводите целые числа без пробелов, больше нуля');
        return false;
    }else{
        i.style.background = '#ffffff';
        return true;
    }
}

function numBreak(str) {
    var arr = str.toString().split('');
    var startCount = arr.length % 3;
    if(startCount == 0) startCount += 3;
    for(i = startCount; i < arr.length; i += 3+1) {
        arr.splice(i, 0, "&nbsp;");
    }
    return arr.join('');
}

function reCountCart(num, idp){
        if(inter) window.clearInterval(inter);
        inter=setTimeout("reCountCartDo(\'"+num+"\', \'"+idp+"\')", 300);
}

function reCountCartDo( num, idp ){
   
        loadHTML('/scripts/loadhtml.php?act=recount_cart&id='+idp+'&num='+num, 'in_cart');
        addArrayAction('saveParam()');
      
}

function resultAdd(d)
{
    //saveParam();
    get('ok_'+d).innerHTML = 'Параметры применены';
    setTimeout(function(){
        get('ok_'+d).innerHTML = '';
    }, 500);
}

function getCheckedRadio(f,n){
	var r = document.getElementById(f).elements[n];
    for( var i=0; i<=r.length; i++) {
		if(r[i].checked) {
			return r[i].value;
		}
    }
}

function checkedRadio(f,n,v){
	var r = document.getElementById(f).elements[n];
    for( var i=0; i<=r.length; i++) {
		if(r[i].value == v){
			r[i].checked = true;
		}else{
			r[i].checked = false;
		}
    }
}

function arrayIndexOf(arr, x) {
  if (arr instanceof Array) {
    for(var i = 0; i < arr.length; i++) {
       if (arr[i] == x) {
          return i;
       }
     }
  }
  return -1;
}

function inArray(arr, x) { return arrayIndexOf(arr, x) != -1; }


function check_city(ct)
{
	if (ct=='other'){
		document.getElementById('select_action_city').style.display = 'none';
		document.getElementById('select_action_other').style.display = 'block';
		document.getElementById('select_action_other').getElementsByTagName('input')[0].checked = true;
		document.getElementById('del_city').value = '' ;
        document.getElementById('del_city').readOnly=false;
	}else{
		document.getElementById('select_action_other').style.display = 'none';
		document.getElementById('select_action_city').style.display = 'block';
		document.getElementById('select_action_city').getElementsByTagName('input')[0].checked = true; 
		document.getElementById('del_city').value = document.getElementById('name_'+ct).innerHTML ;
        document.getElementById('del_city').readOnly=true;
	}
	check_action(getCheckedRadio('orderF','action'));
}

function check_action(ac)
{
	if( inArray(action_city, ac) ){
		document.getElementById('select_pay_cash').style.display = 'block';
		document.getElementById('select_pay_cash').getElementsByTagName('input')[0].checked = true;
		document.getElementById('select_pay_post').style.display = 'none';
	}else{
		document.getElementById('select_pay_cash').style.display = 'none';
		document.getElementById('select_pay_other').getElementsByTagName('input')[0].checked = true;
		if( inArray(action_post, ac) ){
			document.getElementById('select_pay_post').style.display = 'block';
		}else{
			document.getElementById('select_pay_post').style.display = 'none';
			document.getElementById('select_pay_other').getElementsByTagName('input')[0].checked = true;
		}
	}
	if (ac=='reserve'){
        document.getElementById('del_adress').style.display = 'none';
	}else{
        document.getElementById('del_adress').style.display = 'block';
	}
	
	saveParam();
}

function saveParam()
{
    var city = getCheckedRadio('orderF','city');
    var action = getCheckedRadio('orderF','action');
    var pay = getCheckedRadio('orderF','pay');
    loadHTML('/scripts/loadhtml.php?act=param&pay='+pay+'&city='+city+'&action='+action, 'build_table');
}

function sendErrorPage (event)
{
    if (!document.getElementById) return;

    if (window.event) var event = window.event;
    if (!event.ctrlKey) return;

    var text = (document.selection) ? document.selection.createRange().text : window.getSelection().toString();
    if (!text) return;

    var key = ((event.keyCode) ? event.keyCode : (event.which) ? event.which : null);
    if (key != 0x0D || text.length<4 && flagError) return;

    if (text.length>250) {
        ShowAlert('Внимание!','Вы выбрали слишком большой объем текста. Максимум 250 символов.');
        return;
    }

    var url = document.URL;

    var htm='';
    htm += '<table id="dialog_tb">';
    htm += '<tr><td id="dialog_title">Отправить сообщение?</td></tr>';
    htm += '<tr><td id="dialog_text" style="padding-bottom: 10px;"><b>Страница:</b><br>' + url + '<br><br><b>Ошибка в тексте:</b><br>"' + text + '"</td></tr>';
    htm += '<tr><td id="dialog_close"><table cellpadding="0" cellspacing="0" width="100%"><tr><td align="left"><a href="/" onclick="sendErrorMessage (\''+url+'\', \''+text+'\'); return false;">Отправить</a></td><td align="right"><a href="/" onclick="CloseDialog(); return false;">Отмена</a></td></tr></table></td></tr>';
    htm += '</table>';
    showDialog(htm, 400, 500);
}

function sendErrorMessage (url, text)
{
    checkRequest();
    if (request){
        request.onreadystatechange = sendResult;
        request.open("GET", '/scripts/senderror.php?url='+encodeURI(url)+'&text='+encodeURI(text), true);
        request.send();
    }
}

function sendResult()
{
	if (request.readyState == 4){
		if (request.status == 200){
			if(request.responseText=='ok'){
				ShowAlert('Ваше сообщение отправлено!','Спасибо за внимание к сайту');
			}else{
                                ShowAlert('Ваше сообщение не отправлено!','К сожалению Ваше сообщение не отправлено по техническим причинам!<br>Повторите попытку позже или обратитесь к администрации.<br>Спасибо за внимание к сайту!');
			}
		}
	}
}

function checkOrderForm()
{
    email=document.getElementById('email').value;
    var exmail=/^[a-z\.\-_0-9]+@[a-z\.\-_0-9]+\.[a-z]{2,}$/i;
    if (email && !exmail.test(email)){
        ShowAlert('Внимание!','Адрес электронной почты был введен некорректно!');
        return false;
    }

    if( !document.getElementById('name').value ||
        !document.getElementById('adstat').value ||
        !document.getElementById('phone').value
        ){
        ShowAlert('Внимание!','Не заполнены обязательные к заполнению поля!');
        return false;
    }

}

function shDiv(M)
{
  	if(!document.getElementById)	return

    var menu = document.getElementById(M);
    if (menu.style.display=="none") {
  		menu.style.display=''
	} else {
  		menu.style.display="none";
	}
}

function saveValue(n,v){
    loadHTML('/scripts/loadhtml.php?act=save_value&name='+n+'&value='+encodeURI(v.value), 'place_point');
}


document.onkeydown = sendErrorPage;
window.onload = doArrayLoad;
