var ALL_BLOCKER_ERRORS = [];
var BLOCKER_ERRORS = null; 
var RESERVATION_IN_PROCESS = false;
var FORM_IS_BEING_SUBMITTED = false;

var flexApp = null;
var flexApp_busy = false;
function flash_removeRent(property_id, from_date, to_date) {
    if(flexApp) {
        if (flexApp_busy) {
            setTimeout("flash_removeRent('"+property_id+"','"+from_date+"','"+to_date+"')", 1000);  // FlexApp busy, try again after 250 milliseconds
        } else {
            var from_d = from_date.split('-');
            var to_d = to_date.split('-');
            flexApp.removeReservation(property_id, from_d[0], from_d[1], from_d[2], to_d[0], to_d[1], to_d[2]);
        }
    }
}
function on_addRent() {
    flexApp_busy = false;
    if(flexApp) {
        var from_date = flexApp.getCurReservation_FromDate();
        var to_date = flexApp.getCurReservation_ToDate();
        var property_id = flexApp.getCurReservation_PropertyID();
        var adults = flexApp.getCurReservation_Adults();
        var children = flexApp.getCurReservation_Children();
        var gift = flexApp.getGift();
        get_reservation(property_id, from_date, to_date, adults, children, gift);
    }
}
function on_errRent() {
    flexApp_busy = false;
}
function on_removeAllRents() {
	ALL_BLOCKER_ERRORS = [];
    var container = $('p_properties');
    container.empty();
    check_continue_button();
}
function on_bookNow() {
    flexApp_busy = false;
    if(flexApp) {
        populate_submit_form();
    }
}
function on_ready() {
    flexApp_busy = false;
    if (flexApp) {
        var total_predefined = predefined_reservations.length;
        for(var i=0;i<total_predefined; i++) {
            var pr = predefined_reservations[i];
            var from_d = pr[1].split('-');
            var to_d = pr[2].split('-');
            flexApp.addReservation(pr[0], from_d[0], from_d[1], from_d[2], to_d[0], to_d[1], to_d[2], pr[5]);
        }
    }
}
function on_loadPOFinish() {
    flexApp_busy = false;
}
function on_loadFault() {
    flexApp_busy = false;
}
function on_busy() {
    flexApp_busy = true;
}
function predefined() {
    if(FABridge && FABridge.mybridge) {
	    flexApp = FABridge.mybridge.root();
	}
	if(flexApp) {
	    flexApp.addEventListener('loadPOFinish', on_loadPOFinish);
	    flexApp.addEventListener("addRent", on_addRent);
	    flexApp.addEventListener("errRent", on_errRent);
	    flexApp.addEventListener('clearRents', on_removeAllRents);
	    flexApp.addEventListener('loadFault', on_loadFault);
	    flexApp.addEventListener('bookNow', on_bookNow);
	    flexApp.addEventListener('ready', on_ready);
	    flexApp.addEventListener('busy', on_busy);
	    flexApp.initLoading();
	}
    var total_predefined = predefined_reservations.length;
    for(var i=0;i<total_predefined; i++) {
        var pr = predefined_reservations[i];
        get_reservation(pr[0], pr[1], pr[2], pr[3], pr[4], (predefined_gift != null ? predefined_gift : ''));
    }
    if (predefined_gift != null && flexApp) {
        flexApp.setGift(predefined_gift);
    }
    if (predefined_adult != null && flexApp) {
        flexApp.setAdults(predefined_adult);
    }
    if (predefined_children != null && flexApp) {
        flexApp.setChilds(predefined_children);
    }
}

function check_continue_button() {
    var pb = $('p_properties');
    var sb = $('submit_button'); 
    var bb = $('back_button_block');
    var fd_bl = $('flat_discount_block'); 
	sb.style.display = pb.childNodes.length ? 'block' : 'none';
	if(bb) {
	   bb.style.display = pb.childNodes.length ? 'none' : 'block';
	}
	if(fd_bl && !pb.childNodes.length) {
	   fd_bl.style.display = 'none';
	}
}
function remove_reserve(i) {
	var e = $('reserve-n'+i);
	flash_removeRent($('f_property_'+i).value, $('f_from_date_'+i).value, $('f_to_date_'+i).value);
	ALL_BLOCKER_ERRORS[i] = null;
    if(e) {
        e.getParent().removeChild(e);
    }
	check_continue_button();
}

function disable_continue_button(){
	var button = $("submit_reservations_button");
	if(button){
		button.disabled = 'disabled';
		button.removeClass("button_one");
		button.addClass("button_disabled");
	}
}
function enable_continue_button(){
	var button = $("submit_reservations_button");
	if(button){
		button.removeProperty('disabled');
		button.addClass("button_one");
		button.removeClass("button_disabled");
	}
}

var reserve_index = 0;
function get_reservation(property_id, from_date, to_date, adult, children, gift, index_to_use) {
	BLOCKER_ERRORS = null;
	RESERVATION_IN_PROCESS = true;
	var index = reserve_index;
	if (index_to_use){
		index = index_to_use;
	}
	else{
		reserve_index++;
		index = reserve_index;
	}
	ALL_BLOCKER_ERRORS[index] = BLOCKER_ERRORS;
	var e = new Ajax(AJAX_URL,{
		method: 'get',
		data: {
			'do' : 'reserve',
			'from_date' : from_date,
			'to_date' : to_date,
			'property_id' : property_id,
			'adult' : adult,
			'children' : children,
			'index' : index,
			'gift' : gift
		}
	});
	show_element(property_id + "-throbber");
	disable_continue_button();
	e.addEvent('onComplete', function(o){
		var res = Json.evaluate(o)
		hide_element(property_id + "-throbber");
		if (res.error){
			error(res.error);
		}
		else{
			$("error_msg").empty();
			var old_index = res.reserve_index;
			var first_load = false;
			if (!$('reserve-n' + old_index)){
				var container = $('p_properties');
				var prop = new Element('div',{
					'id':'reserve-n' + index,
					'class' : 'reserve'
				});
				var total = '15.0';
				var html = res['html'];
				var fd_bl = $('flat_discount_block'); 
				if(fd_bl && res['flat_discount']) {
					var fd_el = $('flat_discount_element');
					if(fd_el) {
						fd_el.innerHTML = '<span>' + res['currency']['code'] + '</span> (' + res['flat_discount'] + ')';
						fd_bl.style.display = 'block';
					}
				} else if(fd_bl){
				 fd_bl.style.display='none';
				}
				prop.innerHTML = html;
				container.appendChild(prop);
				check_continue_button();
				first_load = true;
			}
			else{
				var prop = $('reserve-n' + index);
				if (res.html){
					prop.innerHTML =res.html;
				}
			}
			if (res.adults_errors || res.children_errors){
				BLOCKER_ERRORS = true;
			}
			else {
				BLOCKER_ERRORS = false; 
			}
			ALL_BLOCKER_ERRORS[index] = BLOCKER_ERRORS;
			if (!first_load){
				var adults_input = $(res.property_or_room_id + '-adults');
				var children_input = $(res.property_or_room_id + '-children');
				if (res.adults_errors){
					if (adults_input){
						adults_input.addClass('error');
						if ($(res.property_or_room_id + '-adults-error_msg')){
							var error_message = $(res.property_or_room_id + '-adults-error_msg');
							error_message.addClass('form-error');
							error_message.setText(res.adults_errors.join('; '));
						}
					}
				}
				else{
					if (adults_input){
						adults_input.removeClass('error');
						if ($(res.property_or_room_id + '-adults-error_msg')){
							$(res.property_or_room_id + '-adults-error_msg').setText('');
						}
					}
				}
				if (res.children_errors){
					if (children_input){
						children_input.addClass('error');
						if ($(res.property_or_room_id + '-children-error_msg')){
							var error_message = $(res.property_or_room_id + '-children-error_msg');
							error_message.addClass('form-error');
							error_message.setText(res.children_errors.join('; '));
						}
					}
				}
				else{
					if (children_input){
						children_input.removeClass('error');
						if ($(res.property_or_room_id + '-children-error_msg')){
							$(res.property_or_room_id + '-children-error_msg').setText('');
						}
					}
				}
			}
			RESERVATION_IN_PROCESS = false;
			if (FORM_IS_BEING_SUBMITTED){
				FORM_IS_BEING_SUBMITTED = false;
				populate_submit_form();
			}
			enable_continue_button();
		}
	});
	e.request();
}
function re_reserve(property_id, from_date, to_date, index){
	var gift = '';
	var adults = 0;
	var children = 0;
	if(flexApp) {
        children = flexApp.getChilds();
        adults = flexApp.getAdults();
        gift = flexApp.getGift();
    } else {
        if(predefined_gift != null)
            gift = predefined_gift;
    }
	if ($(property_id + '-adults')){
		adults = $(property_id + '-adults').getProperty('value');
	}
	if ($(property_id + '-children')){
		children = $(property_id + '-children').getProperty('value');
	}
	get_reservation(property_id, from_date, to_date, adults, children, gift, index);
}

function blocker_errors_index(){
	res = -1;
	var i = 0;
	for (i = 0; i < ALL_BLOCKER_ERRORS.length; i++){
		if (ALL_BLOCKER_ERRORS[i] == true){
			res = i;
			break;
		}
	}
	return res;
}

function populate_submit_form() {
	var errors_index = blocker_errors_index();
	if (RESERVATION_IN_PROCESS == true){
		FORM_IS_BEING_SUBMITTED = true;
		return false
	}
	else{ 
		if (errors_index != -1){
			if(flexApp && flexApp.showMessage){
				flexApp.showMessage('Please fill in guests info', 'To continue, '+
						'scroll down the page and fill in the total number of adults '+
						'and children in your group.  The total cost of the '+
						'reservation will then be updated and you can continue '+
						'with the reservation. ')
			}
			if ($(errors_index + '_please_fill_in_block')){
				$(errors_index + '_please_fill_in_block').removeClass('display-none');
			}
			else{
				alert("Please correct errors marked in red.");
			}
			return false;
		}
	}
	//return false;
    var s_form = new Element('form',{
        'action': '',
        'method': 'get'
    });
    var inputs = $ES('div#p_properties input');
    var inputs_length = inputs.length;
    for(var i=0;i<inputs_length;i++) {
        
	        var s_input = new Element('input', {
	            'type': 'hidden',
	            'name': inputs[i].name,
	            'value': inputs[i].value
	        });
	        s_form.appendChild(s_input);
        
    }
    var children = 0;
    var adults = 1;
    var gift = '';
    var tax = '';
    if(flexApp) {
        children = flexApp.getChilds();
        adults = flexApp.getAdults();
        gift = flexApp.getGift();
        tax = flexApp.getTaxexemption();
    } else {
        if(predefined_gift != null)
            gift = predefined_gift;
        if(predefined_children != null)
            children = predefined_children;
        if(predefined_adult != null)
            adults = predefined_adult;
        if(predefined_tax != null)
            tax = predefined_tax;
    }
    var s_children_input = new Element('input', {
        'type' : 'hidden',
        'name' : 'children',
        'value' : children
    });
    s_form.appendChild(s_children_input);
    var s_adults_input = new Element('input', {
        'type' : 'hidden',
        'name' : 'adults',
        'value' : adults
    });
    s_form.appendChild(s_adults_input);
    var s_gift_input = new Element('input', {
        'type' : 'hidden',
        'name' : 'gift',
        'value' : gift
    });
    s_form.appendChild(s_gift_input);
    var s_tax_input = new Element('input', {
        'type' : 'hidden',
        'name' : 'tax_exemption',
        'value' : tax
    });
    s_form.appendChild(s_tax_input);
    var copy_el = ['id-back_referer','id-query_string'];
    for(var j=0;j<copy_el.length;j++){
        var el = $(copy_el[j]);
        if(el) {
	        s_form.appendChild(new Element('input', {
                'type': 'hidden',
                'name': el.name,
                'value': el.value
            }));
        }
    }
    if (predefined_theme_pk != null && predefined_theme_pk != ''){
    	var s_theme_input = new Element('input', {
            'type' : 'hidden',
            'name' : 'theme',
            'value' : predefined_theme_pk
        });
        s_form.appendChild(s_theme_input);
    }
    var s_submit_input = new Element('input', {
        'type': 'hidden',
        'name': 'submit_reservations',
        'value': 'Submit'
    });
    s_form.appendChild(s_submit_input);
    document.body.appendChild(s_form);
    s_form.submit();
    return false;
}

function error(msg) {
	//alert(msg);
    var e = $('error_msg');
    if(e) { 
        e.innerHTML = msg;
    }
}
function init_page() {
    if($('flashcontrol') && FABridge) {
        FABridge.addInitializationCallback("mybridge", predefined);
    } else {
        predefined();
    }
}
Window.addEvent('domready', init_page);
window.addEvent('beforeunload', function(){
	if ($('flashobj')){
		var destroyed = $('flashobj').remove();
	}
});