var _textCustomerName = null;
var _textEmail = null;
var _textConfirmEmail = null;
var _textStartDay = null;
var _textStartMonth = null;
var _dropDownStartYear = null;
var _textEndDay = null;
var _textEndMonth = null;
var _dropDownEndYear = null;
var _dlBicicleNumber = null;
var _textPhone = null;
var _ddlGPSCount = null;
var _dlGuide = null;
var _textDeliveryPlace = null;
var _buttonSave = null;
var _itemsContainer = null;
var _txtCaptcha = null;
var _successTable = null;
var _inputTable = null;
var _startMonthPrevValue = 0;
var _endMonthPrevValue = 0;

function pageLoad(e) {
    _textCustomerName = $get(_textCustomerNameID);

    if (_textCustomerName) {
        $addHandler(_textCustomerName, 'blur', _textCustomerName_blur);
    }

    _txtCaptcha = $get(_txtCaptchaID);
    
    if (_txtCaptcha) {
        $addHandler(_txtCaptcha, 'blur', _txtCaptcha_blur);
    }

    _textEmail = $get(_textEmailID);

    if (_textEmail) {
        $addHandler(_textEmail, 'blur', _textEmail_blur);
    }

    _textConfirmEmail = $get(_textConfirmEmailID);

    if (_textConfirmEmail) {
        $addHandler(_textConfirmEmail, 'blur', _textConfirmEmail_blur);
    }

    _textStartDay = $get(_textStartDayID);

    if (_textStartDay) {
        $addHandler(_textStartDay, 'change', _textStartDay_change);
        $addHandler(_textStartDay, 'keypress', _textDay_keypress);
    }

    _textStartMonth = $get(_textStartMonthID);

    if (_textStartMonth) {
        $addHandler(_textStartMonth, 'change', _textStartMonth_change);
        $addHandler(_textStartMonth, 'keypress', _textDay_keypress);
        _startMonthPrevValue = parseInt(_textStartMonth.value);
    }
    
    _dropDownStartYear = $get(_dropDownStartYearID);

    if (_dropDownStartYear) {
        $addHandler(_dropDownStartYear, 'change', _dropDownStartYear_change);
    }

    _textEndDay = $get(_textEndDayID);

    if (_textEndDay) {
        $addHandler(_textEndDay, 'change', _textEndDay_change);
        $addHandler(_textEndDay, 'keypress', _textDay_keypress);
    }

    _textEndMonth = $get(_textEndMonthID);

    if (_textEndMonth) {
        $addHandler(_textEndMonth, 'change', _textEndMonth_change);
        $addHandler(_textEndMonth, 'keypress', _textDay_keypress);
        _endMonthPrevValue = parseInt(_textEndMonth.value);
    }
    
    _dropDownEndYear = $get(_dropDownEndYearID);

    if (_dropDownEndYear) {
        $addHandler(_dropDownEndYear, 'change', _dropDownEndYear_change);
    }
    
    _dlBicicleNumber = $get(_dlBicicleNumberID);
    _textPhone = $get(_textPhoneID);
    _ddlGPSCount = $get(_ddlGPSCountID);
    _dlGuide = $get(_dlGuideID);
    _textDeliveryPlace = $get(_textDeliveryPlaceID);
    _buttonSave = $get(_buttonSaveID);

    if (_dlBicicleNumber) {
        $addHandler(_dlBicicleNumber, 'change', _dlBicicleNumber_change);
    }

    if (_buttonSave) {
        $addHandler(_buttonSave, 'click', _buttonSave_click);
    }

    _itemsContainer = $get('itemsContainer');
    _successTable = $get(_successTableID);
    _inputTable = $get(_inputTableID);
}

function validate() {
    var isValid = true;

    if (!validateRequired(_textCustomerName)) {
        isValid = false;
    }

    if (!validateRequired(_textEmail)) {
        isValid = false;
    }

    if (!validateRegex(_textEmail, /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) {
        isValid = false;
    }

    if (!validateRequired(_textConfirmEmail)) {
        isValid = false;
    }

    if (!validateCompare(_textConfirmEmail, _textEmail)) {
        isValid = false;
    }

    if (!validateRequired(_txtCaptcha)) {
        isValid = false;
    }

    var selectedGPSCount = parseInt(_ddlGPSCount.options[_ddlGPSCount.selectedIndex].value);
    var selectedBicicleNumber = parseInt(_dlBicicleNumber.options[_dlBicicleNumber.selectedIndex].value);

    if ((selectedGPSCount <= 0) &&
        (selectedBicicleNumber <= 0)) {
        alert(_missingSelectionText);
        isValid = false;
    }
    else {
        if (selectedBicicleNumber > 0) {
            for (var i = 0; i < selectedBicicleNumber; i++) {
                var inputCyclistName = $get('txtCyclistName_' + i);

                if (inputCyclistName) {
                    if (!validateRequired(inputCyclistName)) {
                        isValid = false;
                    }
                }

                var inputCyclistHeight = $get('txtCyclistHeight_' + i);

                if (inputCyclistHeight) {
                    if (!validateRequired(inputCyclistHeight)) {
                        isValid = false;
                    }
                    else {
                        if (!validateRegex(inputCyclistHeight, /^\d+$/)) {
                            isValid = false;
                        }
                    }
                }
            }
        }
    }

    return isValid;
}

function bindItems(itemsCount) {
    var cnl = _itemsContainer.childNodes.length;

    if (Sys.Browser.name != 'Microsoft Internet Explorer') {
        for (var i = 0; i < cnl; i++) {
            if (typeof (_itemsContainer.removeChild) == 'function') {
                _itemsContainer.removeChild(_itemsContainer.childNodes[i]);
            }
        }
    }
    else {
        _itemsContainer.innerHTML = '';
    }

//    if ((typeof (_itemsContainer.removeChild) == 'function') &&
//	    (_itemsContainer.childNodes.length > 0)) {
//        _itemsContainer.removeChild(_itemsContainer.childNodes[0]);
//    }
    
    var table = document.createElement('table');
    var tbody = document.createElement('tbody');

    var headerTr = document.createElement('tr');

    var cyclistNameTd = document.createElement('td');
    cyclistNameTd.innerHTML = _cyclistNameText;
    var cyclistHeightTd = document.createElement('td');
    cyclistHeightTd.innerHTML = _cyclistHeightText;
    var bikeTypeTd = document.createElement('td');
    bikeTypeTd.innerHTML = _bikeTypeText;
    var genderTd = document.createElement('td');
    genderTd.innerHTML = _maleFemaleText;
    var notesTd = document.createElement('td');
    notesTd.innerHTML = _notesText;

    headerTr.appendChild(cyclistNameTd);
    headerTr.appendChild(cyclistHeightTd);
    headerTr.appendChild(bikeTypeTd);
    headerTr.appendChild(genderTd);
    headerTr.appendChild(notesTd);

    tbody.appendChild(headerTr);

    for (var i = 0; i < itemsCount; i++) {
        var tr = document.createElement('tr');

        var cyclistNameTd2 = document.createElement('td');
        var inputCyclistName = document.createElement('input');
        inputCyclistName.setAttribute('type', 'text');
        inputCyclistName.setAttribute('id', 'txtCyclistName_' + i);
        cyclistNameTd2.appendChild(inputCyclistName);
        var inputCyclistNameError = document.createElement('span');
        inputCyclistNameError.setAttribute('id', 'txtCyclistName_' + i + 'Error');
        inputCyclistNameError.innerHTML = _fieldErrorText;
        inputCyclistNameError.setAttribute('style', 'display : none;');
        cyclistNameTd2.appendChild(inputCyclistNameError);

        var cyclistHeightTd2 = document.createElement('td');
        var inputCyclistHeight = document.createElement('input');
        inputCyclistHeight.setAttribute('type', 'text');
        inputCyclistHeight.setAttribute('id', 'txtCyclistHeight_' + i);
        cyclistHeightTd2.appendChild(inputCyclistHeight);
        var inputCyclistHeightError = document.createElement('span');
        inputCyclistHeightError.setAttribute('id', 'txtCyclistHeight_' + i + 'Error');
        inputCyclistHeightError.innerHTML = _fieldErrorText;
        inputCyclistHeightError.setAttribute('style', 'display : none;');
        cyclistHeightTd2.appendChild(inputCyclistHeightError);

        var bikeTypeTd2 = document.createElement('td');

        var ddl = document.createElement('select');
        ddl.setAttribute('id', 'selBicycleType_' + i);
        
        for (var k = 0; k < _bicycleTypes.length; k++) {
            var option = document.createElement('option');
            option.setAttribute('value', _bicycleTypes[k].ID);
            option.innerHTML = _bicycleTypes[k].Name;
            ddl.appendChild(option);
        }

        bikeTypeTd2.appendChild(ddl);
        
        var genderTd2 = document.createElement('td');
        var cbMale = document.createElement('input');
        cbMale.setAttribute('type', 'radio');
        cbMale.setAttribute('name', 'gender' + i);
        cbMale.setAttribute('id', 'cbMale_' + i);
        cbMale.setAttribute('checked', 'checked');
        genderTd2.appendChild(cbMale);
        var maleLabel = document.createElement('label');
        maleLabel.innerHTML = _maleText;
        genderTd2.appendChild(maleLabel);
        
        var cbFemale = document.createElement('input');
        cbFemale.setAttribute('type', 'radio');
        cbFemale.setAttribute('name', 'gender' + i);
        cbFemale.setAttribute('id', 'cbFemale_' + i);
        genderTd2.appendChild(cbFemale);
        var femaleLabel = document.createElement('label');
        femaleLabel.innerHTML = _femaleText;
        genderTd2.appendChild(femaleLabel);
        
        var notesTd2 = document.createElement('td');
        var inputNotes = document.createElement('textarea');
        inputNotes.setAttribute('type', 'text');
        inputNotes.setAttribute('id', 'txtNotes' + i);
        notesTd2.appendChild(inputNotes);
        
        tr.appendChild(cyclistNameTd2);
        tr.appendChild(cyclistHeightTd2);
        tr.appendChild(bikeTypeTd2);
        tr.appendChild(genderTd2);
        tr.appendChild(notesTd2);
        tbody.appendChild(tr);
    }

    table.appendChild(tbody);
    _itemsContainer.appendChild(table);
}

function _buttonSave_click(e) {
    cancelBubbling(e);
    var isValid = validate();

    if (isValid) {
        var r = new DFBike.Library.Entities.Reservation();

        r.customerName = _textCustomerName.value;
        r.deliveryPlace = _textDeliveryPlace.value;
        r.email = _textEmail.value;
        r.endDate = new Date(parseInt(_dropDownEndYear.options[_dropDownEndYear.selectedIndex].value),
                             parseInt(_textEndMonth.value) - 1,
                             parseInt(_textEndDay.value));
        r.GPSCount = parseInt(_ddlGPSCount.options[_ddlGPSCount.selectedIndex].value);
        r.guide = parseInt(_dlGuide.options[_dlGuide.selectedIndex].value);
        r.id = 0;
        r.phone = _textPhone.value;
        r.startDate = new Date(parseInt(_dropDownStartYear.options[_dropDownStartYear.selectedIndex].value),
                               parseInt(_textStartMonth.value) - 1,
                               parseInt(_textStartDay.value));
        
        var selectedBicicleNumber = parseInt(_dlBicicleNumber.options[_dlBicicleNumber.selectedIndex].value);
        var details = new Array();
        
        for (var i = 0; i < selectedBicicleNumber; i++) {
            var detail = new DFBike.Library.Entities.ReservationDetail();
            detail.id = 0;
            
            var inputCyclistName = $get('txtCyclistName_' + i);

            if (inputCyclistName) {
                detail.name = inputCyclistName.value;
            }

            var inputCyclistHeight = $get('txtCyclistHeight_' + i);

            if (inputCyclistHeight) {
                detail.customerHeight = parseInt(inputCyclistHeight.value);
            }

            var selBicycleType = $get('selBicycleType_' + i);

            if (selBicycleType) {
                detail.bicycleType = { 'id': parseInt(selBicycleType.options[selBicycleType.selectedIndex].value),
                    'name': '',
                    'enabled': true
                };
            }

            var cbMale = $get('cbMale_' + i);

            if (cbMale &&
                cbMale.checked) {
                detail.gender = 1;
            }

            var cbFemale = $get('cbFemale_' + i);

            if (cbFemale &&
                cbFemale.checked) {
                detail.gender = 2;
            }

            var txtNotes = $get('txtNotes' + i);

            if (txtNotes) {
                detail.notes = txtNotes.value;
            }

            Array.add(details, detail);
        }

        r.details = details;

        suspendLayout();
        AppServices.CreateRequest(r, _captchaKey, _txtCaptcha.value, onSuccess, onError);
    }
}

function suspendLayout() {
    var d = $get('loadingDiv');

    if (!d) {
        d = document.createElement('div');
        d.style.width = get_windowSize().width + 'px';
        d.style.height = get_windowSize().height + 'px';
        d.style.zIndex = 9999;
        d.style.position = 'absolute';
        d.id = 'loadingDiv';
        d.style.backgroundColor = 'black';
        d.style.opacity = 0.2;
        d.style.left = 0;
        d.style.top = 0;
        d.style.filter = 'alpha(opacity=' + 2 * 10 + ')';
        document.forms[0].appendChild(d);
    }

    d.style.display = '';
}

function resumeLayout() {
    var d = $get('loadingDiv');

    if (d) {
        d.style.display = 'none';
    }
}

function onSuccess(result) {
    if (result == -1) {
        handleError(_txtCaptcha, false);
        alert(_anErrorHasOccurredText);
    }
    else if (result > 0) {
        _inputTable.style.display = 'none';
        _successTable.style.display = '';
    }
    else {
        alert(_anErrorHasOccurredText);
    }
    
    resumeLayout();
}

function onError(error) {
    alert(_anErrorHasOccurredText);
    resumeLayout();
}

function validateRequired(el) {
    var isValid = true;

    if (!el ||
        (el.value.trim() == '')) {
        isValid = false;
    }

    handleError(el, isValid);
    return isValid;
}

function validateCompare(el1, el2) {
    var isValid = true;

    if (!el1 ||
        !el2 ||
        (el1.value.trim() != el2.value.trim())) {
        isValid = false;
    }

    handleError(el1, isValid);
    return isValid;
}

function validateRegex(el, regex) {
    var isValid = true;
    
    if (!el) {
        isValid = false;
    }
    else {
        isValid = regex.test(el.value);
    }

    handleError(el, isValid);
    return isValid;
}

function handleError(element, isValid) {
    var el = $get(element.id + 'Error');

    if (el) {
        el.style.display = isValid ? 'none' : '';
    }
}

function cancelBubbling(e) {
    if (e) {
        if (e.preventDefault) {
            e.preventDefault();
        }
        else {
            e.cancelBubble = true;
            e.returnValue = false;
        }
    }

    return false;
}

function isBissextile(year) {
    return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? true : false);
}

function getMonthDays(month, year) {
    var result = 0;

    switch (month) {
        case 1:
            result = 31;
            break;
        case 2:
            result = isBissextile(year) ? 28 : 29;
            break;
        case 3:
            result = 31;
            break;
        case 4:
            result = 30;
            break;
        case 5:
            result = 31;
            break;
        case 6:
            result = 30;
            break;
        case 7:
            result = 31;
            break;
        case 8:
            result = 31;
            break;
        case 9:
            result = 30;
            break;
        case 10:
            result = 31;
            break;
        case 11:
            result = 30;
            break;
        case 12:
            result = 31;
            break;
    }

    return result;
}

function _textDay_keypress(e) {
    var charCode = e.charCode || e.keyCode;

    if ((charCode < 48) || (charCode > 57))
        cancelBubbling(e);
}

function _textStartDay_change(e) {
    if (!/^\d+$/.test(_textStartDay.value)) {
        cancelBubbling(e);
    }

    var year = parseInt(_dropDownStartYear.options[_dropDownStartYear.selectedIndex].value);
    var month = parseInt(_textStartMonth.value);
    adjustDays(year, month, _textStartDay);
}

function _textStartMonth_change(e) {
    if (!/^\d+$/.test(_textStartMonth.value)) {
        cancelBubbling(e);
    }

    var m = parseInt(_textStartMonth.value);

    if ((m < 1) || (m > 12)) {
        cancelBubbling(e);
        _textStartMonth.value = _startMonthPrevValue;
    }
    else {
        _startMonthPrevValue = m;
        var year = parseInt(_dropDownStartYear.options[_dropDownStartYear.selectedIndex].value);
        adjustDays(year, m, _textStartDay);
    }
}

function _textEndDay_change(e) {
    if (!/^\d+$/.test(_textEndDay.value)) {
        cancelBubbling(e);
    }

    var year = parseInt(_dropDownEndYear.options[_dropDownEndYear.selectedIndex].value);
    var month = parseInt(_textEndMonth.value);
    adjustDays(year, month, _textEndDay);
}

function _textEndMonth_change(e) {
    if (!/^\d+$/.test(_textEndMonth.value)) {
        cancelBubbling(e);
    }

    var m = parseInt(_textEndMonth.value);

    if ((m < 1) || (m > 12)) {
        cancelBubbling(e);
        _textEndMonth.value = _endMonthPrevValue;
    }
    else {
        _endMonthPrevValue = m;
        var year = parseInt(_dropDownEndYear.options[_dropDownEndYear.selectedIndex].value);
        adjustDays(year, m, _textEndDay);
    }
}

function adjustDays(year, month, el) {
    var maxDays = getMonthDays(month, year);
    var v = parseInt(el.value);

    if (v > maxDays) {
        el.value = maxDays;
    }
}

function _dropDownEndYear_change(e) {
    var year = parseInt(_dropDownEndYear.options[_dropDownEndYear.selectedIndex].value);
    var month = parseInt(_textEndMonth.value);
    adjustDays(year, month, _textEndDay);
}

function _dropDownStartYear_change(e) {
    var year = parseInt(_dropDownStartYear.options[_dropDownStartYear.selectedIndex].value);
    var month = parseInt(_textStartMonth.value);
    adjustDays(year, month, _textStartDay);
}

function _textCustomerName_blur(e) {
    validateRequired(_textCustomerName);
}

function _textEmail_blur(e) {
    validateRequired(_textEmail);
    validateRegex(_textEmail, /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/);
}

function _textConfirmEmail_blur(e) {
    validateRequired(_textConfirmEmail);
    validateCompare(_textConfirmEmail, _textEmail);
}

function _txtCaptcha_blur(e) {
    validateRequired(_txtCaptcha);
}

function _dlBicicleNumber_change(e) {
    var itemsCount = parseInt(_dlBicicleNumber.options[_dlBicicleNumber.selectedIndex].value);
    bindItems(itemsCount);
}

function get_windowSize() {
    var h = 0;

    if (typeof (document.height) != 'undefined') {
        h = document.height;
    }
    else if (document.compatMode &&
             (document.compatMode != 'BackCompat')) {
        h = document.documentElement.scrollHeight;
    }
    else if (document.body &&
             (typeof document.body.scrollHeight != 'undefined')) {
        h = document.body.scrollHeight;
    }

    var w = 0;

    if (typeof (document.width) != 'undefined') {
        w = document.width;
    }
    else if (document.compatMode &&
             (document.compatMode != 'BackCompat')) {
        w = document.documentElement.scrollWidth;
    }
    else if (document.body &&
             (typeof document.body.scrollWidth != 'undefined')) {
        w = document.body.scrollWidth;
    }

    return { 'width': w, 'height': h };
}
