var BorderColorNormal = "#c7c7c7";
var BorderColorError = "#ff7301";
var intImageCounter = 1;

function MakeRequest(request) {
    var http_request = false;
    if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            http_request = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch (e) {
            try {
                http_request = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch (e) {}
        }
    }

    if (!http_request) {
        alert('Для корректной работы скрипта, интернет-обозреватель должен поддерживать XMLHTTP-запросы.');
        return false;
    } else {
        http_request.open('POST', 'request.php', false);
        http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http_request.send(request);
		return http_request.responseXML;
	}
}

function ShowAlert(element, text_alert) {
    element.style.borderColor = BorderColorError;
    element.focus();
    alert(text_alert);
}

function Form_onsubmit() {
    var regexpMail = /^[\w\.-]+@[\w\.-]+\.[a-z]{2,4}$/i;
    var regexpСode = /^\d{5}$/;
    var rxHotelsID = /^\d{1,8}$/;
    var oName = document.getElementById('hotels_name');
    var oPhone = document.getElementById('hotels_phone');
    var oMail = document.getElementById('hotels_mail');
    var oText = document.getElementById('hotels_text');
    var oCode = document.getElementById('hotels_code');
    var oHotelsID = document.getElementById('hotels_id');
    var oButton = document.getElementById('submit_button');
    var boolButtonEnable = true;
    oButton.disabled = true;
    oName.style.borderColor = BorderColorNormal;
    oPhone.style.borderColor = BorderColorNormal;
    oMail.style.borderColor = BorderColorNormal;
    oText.style.borderColor = BorderColorNormal;
    oCode.style.borderColor = BorderColorNormal;
    if (oName.value.length < 1) {
        ShowAlert(oName, 'Пожалуйста, введите ваше имя.');
    } else if (oPhone.value.length < 1 && oMail.value.length < 1) {
        ShowAlert(oPhone, 'Пожалуйста, введите номер телефона или E-mail.');
    } else if (oMail.value.length > 0 && !regexpMail.test(oMail.value)) {
        ShowAlert(oMail, 'Пожалуйста, введите корректный адрес электронной почты.');
    } else if (oText.value.length < 1) {
        ShowAlert(oText, 'Пожалуйста, напишите текст письма.');
    } else if (!regexpСode.test(oCode.value)) {
        ShowAlert(oCode, 'Пожалуйста, введите корректный код подтверждения.');
    } else if (rxHotelsID.test(oHotelsID.value)){
        var request = 'page=hotels_contact&name=' + encodeURIComponent(oName.value)
            + '&phone=' + encodeURIComponent(oPhone.value)
            + '&mail=' + encodeURIComponent(oMail.value)
            + '&text=' + encodeURIComponent(oText.value)
            + '&code=' + encodeURIComponent(oCode.value)
            + '&hotels_id=' + oHotelsID.value
            + '&order_from=' + encodeURIComponent(GetCookie('user_from'));
        var oXMLDoc = MakeRequest(request);
        var oRootNode = oXMLDoc.getElementsByTagName('root').item(0);
        if (oRootNode.hasChildNodes()) {
            var oXMLReturn = oRootNode.getElementsByTagName('return').item(0).firstChild;

            switch(oXMLReturn.data) {
            case 'cookie':
                alert('Для отправки письма, в интернет-обозревателе должны быть включены Куки (Cookie).');
                break;
            case 'code':
                ShowAlert(oCode, 'Введите корректный код подтверждения.');
                break;
            case 'done':
                boolButtonEnable = false;
                oText.value = '';
                oCode.value = '';
                RefreshImage(false);
                oButton.disabled = true;
                alert('Ваше сообщение успешно отправлено\n'
                    + 'и если оно требует ответа, Вы получите его в течение суток.');
                DisabledButton(9);
                break;
            default :
                alert('Во время отправки письма произошла ошибка. Попробуйте повторить попытку.');
            }
		}
    }
    if (boolButtonEnable != false) oButton.disabled = false;
}

function DisabledButton(counter) {
	var oButton = document.getElementById('submit_button');
	if (counter > 0) {
		oButton.value = 'Подождите (' + counter-- + ')';
		window.setTimeout('DisabledButton(' + counter + ')', 1000);
	} else {
		oButton.disabled = false;
		oButton.value = 'Отправить';
	}
}

function ResetBorderColor(element) {
    element.style.borderColor = BorderColorNormal;
}

function TextLength(sID, iMax) {
    var oText = document.getElementById(sID);
    var oInfo = document.getElementById(sID + '_info');
    if (oText.value.length > iMax) {
        oText.value = oText.value.substring(0, iMax);
    	oText.style.borderColor = BorderColorError;
        alert('Количество символов не может быть больше ' + iMax + '!');
    }
    if (oText.value.length > iMax - 50) {
        oInfo.innerHTML = ', осталось символов: ' + (iMax - oText.value.length);
    } else {
        oInfo.innerHTML = '';
	}
}

function RefreshImage(bCodeFieldFocus) {
    var oCode = document.getElementById('hotels_code');
    document.getElementById('image').src = '/img/image.php?' + intImageCounter++;
    if (bCodeFieldFocus == true) oCode.focus();
}

function HotelsImg(id) {
    var ExtraImgTD = document.getElementById('extra_img_td');
    var ExtraImgLeft = document.getElementById('extra_img_left');
    var ExtraImgRight = document.getElementById('extra_img_right');
    var FotoInfoSpan = document.getElementById('foto_info_span');
    var iCountImg = extra_img.length;
    ExtraImgTD.innerHTML = '';
    FotoInfoSpan.innerHTML = '';

    var oImg = document.createElement('img');
    ExtraImgTD.appendChild(oImg);
    oImg.src = '/img/ext/' + extra_img[id]['img'];
    oImg.alt = extra_img[id]['alt'];
    oImg.style.cursor = 'pointer';
    oImg.onclick = function () { window.open('/hotels-img-' + extra_img[id]['id'] + '.html', null,
        'width=' + extra_img[id]['img_width'] + ', height=' + extra_img[id]['img_height'] + ', status=no'); };

    ExtraImgLeft.innerHTML = '';
    ExtraImgLeft.style.cursor = 'auto';
    ExtraImgLeft.title = '';
    if (id > 0) {
        var oImg = document.createElement('img');
        ExtraImgLeft.appendChild(oImg);
        oImg.src = '/img/arrow-back.gif';
        oImg.alt = 'Предыдущее';
        ExtraImgLeft.onclick = function () { HotelsImg(id - 1); };
        ExtraImgLeft.style.cursor = 'pointer';
        ExtraImgLeft.title = 'Предыдущее';
    }

    ExtraImgRight.innerHTML = '';
    ExtraImgRight.style.cursor = 'auto';
    ExtraImgRight.title = '';
    if (id < iCountImg - 1) {
        var oImg = document.createElement('img');
        ExtraImgRight.appendChild(oImg);
        oImg.src = '/img/arrow-forward.gif';
        oImg.alt = 'Следующее';
        ExtraImgRight.onclick = function () { HotelsImg(id + 1); };
        ExtraImgRight.style.cursor = 'pointer';
        ExtraImgRight.title = 'Следующее';
    }

    if (iCountImg > 1) {
        FotoInfoSpan.innerHTML = (parseInt(id) + 1) + ' из ' + iCountImg;
    }
}
