/**
	function applyVoucher()
	function applyPoints()
	function calculateSupplementTotal(quantity, obj)
	function plus_supplement(obj, maxValue) 
	$('.minus_supplements').click(function() 
	$('.supplement_number input').blur(function()
**/

var exchangeRate;
var USD_CURR = 1.4035;
var GBP_CURR = 0.868180131;
var SELECTED_CURR = 0;
var CURR_SYMBOL = [];
CURR_SYMBOL['GBP'] = "&pound;";
CURR_SYMBOL['USD'] = "&#36;";

	function applyVoucher() {
		
		var finalTotal = $('#finalTotal').html(); // this is not an input field
		var preReductionsTotal = $('#preReductionsTotal').val();
		var fromDate = $('.mealplan_selection_container input[name="from_date"]').val();
		var hotelId = $('.mealplan_selection_container input[name="hotel_id"]').val();
		var mealPlanId = $('.mealplan_selection_container input[name="meaplan_id[1]"]:checked').val(); // not sure if we need this
		var rooms = $('.mealplan_selection_container input[name="rooms"]').val();	// we need this for the special offer to check on rooms
		var toDate = $('.mealplan_selection_container input[name="to_date"]').val();
		var voucherCode = $('#voucher').val();
		var points = $('#pointsUsed').val();
		var paymentMethod = $('.mealplan_selection_container input[name="payment_method"]:checked').val();
				
		var serialized_data = serialiseData();  // serialiseData defined below + '&finalTotal=' + finalTotal
		
		// get the cost of the total via ajax
		var params = '?action=getVoucher&code=' + voucherCode + '&points=' + points + '&fromDate=' + fromDate + '&hotelId=' + hotelId + '&toDate=' + toDate + '&preReductionsTotal=' + preReductionsTotal + '&paymentMethod=' + paymentMethod + '&data=' + serialized_data;
		
		var response =  ajax_request(params); 
		eval(response);
		
	} // end applyVoucher(voucherCode) 
	
	
	function applyPoints() {
		
		var hotelId = $('.mealplan_selection_container input[name="hotel_id"]').val();
		var finalTotal = $('#finalTotal').html(); // this is not an input field
		var preReductionsTotal = $('#preReductionsTotal').val();	
		var paymentMethod = $('.mealplan_selection_container input[name="payment_method"]:checked').val();
		var customerId = $('#cId').val();			
		var fromDate = $('.mealplan_selection_container input[name="from_date"]').val();
		var points = $('#pointsUsed').val();
		var toDate = $('.mealplan_selection_container input[name="to_date"]').val();
		var voucherCode = $('#voucher').val();
		
		var serialized_data = serialiseData();  
		
		// get the cost of the total via ajax
		var params = '?action=getTotalWithPoints&points=' + points + '&voucherCode=' + voucherCode + '&fromDate=' + fromDate + '&hotelId=' + hotelId  + '&toDate=' + toDate + '&preReductionsTotal=' + preReductionsTotal + '&paymentMethod=' + paymentMethod + '&customerId=' + customerId + '&data=' + serialized_data;
		
		var response =  ajax_request(params); 
		eval(response);
		
		if (voucherCode.length > 0) {
			// voucher exists, jump to there because that takes into account points
			applyVoucher();
		}
		
	} // end applyPoints() 


	function calculateSupplementTotal(quantity, obj) {
		// grab the values that we can non-arrayed values from the input
		var from_date = $('.mealplan_selection_container input[name="from_date"]').val();
		var to_date = $('.mealplan_selection_container input[name="to_date"]').val();
		
		// grab the values that will be put into an array that will be serialised
		var data = new Array();
		data['adults'] = new Array();
		data['children'] = new Array();
		$('.mealplan_selection_container input[name^="adults"]').each(function(i){
			var adults_name = $(this).attr('name');
			var adults_index = adults_name.substring(7, 8);
			data['adults'][adults_index] = $(this).val();
		});
		
		$('.mealplan_selection_container input[name^="children"]').each(function(i){
			var children_name = $(this).attr('name');
			var children_index = children_name.substring(9, 10);
			data['children'][children_index] = $(this).val();
			
		});
		
		// serialise the data in the arrays
		var serialized_data = urlencode(serialize(data));			
		
		// get the supplementId from the name 
		if (obj.is(':checkbox')) {
			var supplementId = obj.val();	
		}
		else {
			// get the supplementId from the name 
			var supplementInputName = $(obj).parent().parent().find('.supplement_number input').attr('name');
			var supplementIdStart = supplementInputName.search(/\]\[/i) + 2; //[\d]{2}
			var numberChars = supplementInputName.length - supplementIdStart -1;
			var supplementId = supplementInputName.substr(supplementIdStart, numberChars);
			//alert('name' + supplementInputName + ', start: ' + supplementIdStart + ', num chars ' + numberChars);
		}
		
		// get the cost of the total via ajax
		var params = '?action=getSupplementItemTotal&qty=' + quantity + 'name' + supplementInputName + '&supplementId=' + supplementId + '&fromDate=' + from_date + '&toDate=' + to_date + '&data=' + serialized_data;
		return ajax_request(params); 
		
	} // end calculateSupplementTotal(quantity, obj) 


	// taken from grecian park - functions.js
	function convertTotal() {
		
		var currency_obj = document.getElementById('currency_dropdown');
		SELECTED_CURR = currency_obj.options[currency_obj.selectedIndex].text; // retrieves three character currency code
		
		getRate("EUR", SELECTED_CURR); // this puts the exchange in the global exchangeRate variable
		var currency = exchangeRate; //was var currency = currency_obj.options[currency_obj.selectedIndex].value;
		
		var currency_total = $('#finalTotal').html(); 
		if (currency_total.indexOf("</strike>") != -1) {
			// in case we're discounting e.g. if 5% on total or voucher etc
			currency_total = currency_total.substring(currency_total.indexOf("</strike>") + 9);	
		}
		// convert
		var converted_total = currency_total * currency;
		
		// display
		$('#converted_total').html(CURR_SYMBOL[SELECTED_CURR] + "" + converted_total.toFixed(2));

	} // end convertTotal()

	// from https://gist.github.com/265014
	function getRate(from, to) {
		var script = document.createElement('script');
		script.setAttribute('src', "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+from+to+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=parseExchangeRate");
		document.body.appendChild(script);

	}

	function parseExchangeRate(data) {
		var name = data.query.results.row.name;
	 	exchangeRate = parseFloat(data.query.results.row.rate, 10);
	}
  
	function showCurrencyConverter() {
		var select_usd = "";
		var select_gbp = "";
		if (SELECTED_CURR == "USD") {
			select_usd = "selected";
		}
		else {
			select_gbp = "selected";
		}
		$('#converter_holder').html("<select onchange='convertTotal();' name='currency_dropdown' id='currency_dropdown'><option value='"+USD_CURR+"' "+select_usd+">USD</option><option value='"+GBP_CURR+"' "+select_gbp+">GBP</option></select>");
		//convertTotal();
		
	} // end showCurrencyConverter
	// end taken from grecian park


	/* this is called when the + is clicked */
	function plus_supplement(obj, maxValue) {
		var value = parseInt($(obj).parent().parent().find('.supplement_number input').val());
		
		// grab the values that we can non-arrayed values from the input
		var from_date = $('.mealplan_selection_container input[name="from_date"]').val();
		var to_date = $('.mealplan_selection_container input[name="to_date"]').val();
		
		// grab the values that will be put into an array that will be serialised
		var data = new Array();
		data['adults'] = new Array();
		data['children'] = new Array();
		$('.mealplan_selection_container input[name^="adults"]').each(function(i){
			var adults_name = $(this).attr('name');
			var adults_index = adults_name.substring(7, 8);
			data['adults'][adults_index] = $(this).val();
		});
		
		$('.mealplan_selection_container input[name^="children"]').each(function(i){
			var children_name = $(this).attr('name');
			var children_index = children_name.substring(9, 10);
			data['children'][children_index] = $(this).val();
			
		});
		
		// serialise the data in the arrays
		var serialized_data = urlencode(serialize(data));
		
		// get the supplementId from the name 
		var supplementInputName = $(obj).parent().parent().find('.supplement_number input').attr('name');
		var supplementIdStart = supplementInputName.search(/\]\[/i) + 2; //[\d]{2}
		var numberChars = supplementInputName.length - supplementIdStart -1;
		var supplementId = supplementInputName.substr(supplementIdStart, numberChars);
		//alert('name' + supplementInputName + ', start: ' + supplementIdStart + ', num chars ' + numberChars);
		
		// get the room number from the name
		var roomNumberStart = supplementInputName.search(/[\d]/i);
		var roomNumberEnd = supplementInputName.search(/]/i);
		var roomNumber = supplementInputName.substr(roomNumberStart, roomNumberEnd - roomNumberStart); //alert(roomNumber);

		// was there an error before?
		if ($('#supplementError' + roomNumber + supplementId).length) {
		    // an error occurred previously, remove the error
		    $('#supplementError' + roomNumber + supplementId).remove();
		}
		
		if (value < maxValue) {
			// quantity of supplement is within acceptable quantities
			value++; 
			$(obj).parent().parent().find('.supplement_number input').val(value);
			// get the new cost total for the supplement via ajax
			var quantity = value;
			var params = '?action=getSupplementItemTotal&qty=' + quantity + '&supplementId=' + supplementId + '&fromDate=' + from_date + '&toDate=' + to_date + '&data=' + serialized_data;
			var supplementTotal = ajax_request(params); 

		}
		else {
			// value typed in is greater than the maxValue, set it to the maxValue
			$(this).val(maxValue);	
			
			// get the new cost total for the supplement via ajax
			var quantity = maxValue;
			var params = '?action=getSupplementItemTotal&qty=' + quantity + '&supplementId=' + supplementId + '&fromDate=' + from_date + '&toDate=' + to_date + '&data=' + serialized_data;
			var supplementTotal = ajax_request(params); 
			
			// make a note so that the user knows what happened
			$('#supplementTitle' + roomNumber + supplementId).append('<span class="red" id="supplementError' + roomNumber + supplementId + '">Maximum number allowed is ' + maxValue + '</span>');
		}		
		
		// display the new total for this supplement
		$('#supplementItemTotal' + roomNumber + supplementId).html('&euro;' + supplementTotal);		
		
	} // end plus_supplement(obj, maxValue)


	function serialiseData() {
		// grab the values that will be put into an array that will be serialised
		var data = new Array();
		data['adults'] = new Array();
		data['children'] = new Array();
		data['infants'] = new Array();
		data['room'] = new Array();
		data['mealplan_id'] = new Array();
		data['quantity'] = new Array();
		data['supplement_id'] = new Array();
		$('.mealplan_selection_container input[name^="adults"]').each(function(i){
			var adults_name = $(this).attr('name');
			var adults_index = adults_name.substring(7, 8);
			data['adults'][adults_index] = $(this).val();
		});
		
		$('.mealplan_selection_container input[name^="children"]').each(function(i){
			var children_name = $(this).attr('name');
			var children_index = children_name.substring(9, 10);
			data['children'][children_index] = $(this).val();
			
		});
		$('.mealplan_selection_container input[name^="infants"]').each(function(i){
			var infants_name = $(this).attr('name');
			var infants_index = infants_name.substring(8, 9);
			data['infants'][infants_index] = $(this).val();
			
		});
		
		$('.mealplan_selection_container input[name^="room"]').each(function(i){
			var room_name = $(this).attr('name');
			var room_index = room_name.substring(5, 6);
			if (room_index != '') {
				data['room'][room_index] = $(this).val();
			}
		});
		
		/*---------------------------MEALPLANS----------------------------------*/
		
		$('.mealplan_selection_container input[name^="meaplan_id"]').each(function(i){
			if($(this).is(':checked')){
				var mealplan_name = $(this).attr('name');
				var mealplan_index = mealplan_name.substring(11, 12);
				data['mealplan_id'][mealplan_index] = $(this).val();
			}
		});
		
		/*------------------------SUPPLEMENTS------------------------------------------*/
		
		var quantity_no = 0;
		var name = '';
		var supplement_name_value = new Array();
		var room_no  = 0;
		var this_supplement_id = 0;
		var i = 0;
		// this is for supplements with input text (i.e. can select a quantity)
		// data['quantity'] keeps the quantity for the supplement (in this case value of input)
		// data['supplement_id'] keeps the ids for the supplement (in this case the second [] in name)
		$('.mealplan_selection_container input[name^="quantity"]').each(function(i){ //alert('3');
			quantity_no = $(this).val(); 
			if(parseInt(quantity_no) >0){
			
				name = str_replace('][', '-', $(this).attr('name'));
				name = str_replace('quantity','',name);
				name = str_replace(']','',name);
				name = str_replace('[','',name); //alert('4 - '+name);
				
				supplement_name_value = explode("-", name); //alert('4.5 '+quantity_no);
				
				room_no = supplement_name_value[0];
				this_supplement_id = supplement_name_value[1]; //alert(is_array(data['quantity'][room_no]));
				if (!is_array(data['quantity'][room_no])) {
					data['quantity'][room_no] = new Array();
					data['quantity'][room_no][i] = new Array();
					data['quantity'][room_no][i][this_supplement_id] = new Array();
				}
				else {
					if (!is_array(data['quantity'][room_no][i])) {
						data['quantity'][room_no][i] = new Array();
						data['quantity'][room_no][i][this_supplement_id] = new Array();
					}
					else {
						if (!is_array(data['quantity'][room_no][i][this_supplement_id])) {
							data['quantity'][room_no][i][this_supplement_id] = new Array();
						}	
					}
				}
				
				if (!is_array(data['supplement_id'][room_no])) {
					// there are no supplements for this room, create all the sub arrays
					data['supplement_id'][room_no]= new Array();
					data['supplement_id'][room_no][i] = new Array();
				}
				else {
					// this room has some supplements already
					data['supplement_id'][room_no][i] = new Array();
				}
				
				data['supplement_id'][room_no][i] = this_supplement_id;
				data['quantity'][room_no][i][this_supplement_id] = quantity_no;
				i++;
				//alert(serialize(data['quantity'])); //alert(serialize(data['supplement_id']));
			}
		});
		
		// this is for supplements with checkbox 
		// data['quantity'] keeps the quantity for the supplement (in this case will be 1)
		// data['supplement_id'] keeps the ids for the supplement (in this case the value of the input)
		$('.mealplan_selection_container input[name^="supplement_id"]').each(function(i){
			var supplements_name = ''; //alert(this_supplement_id); this_supplement_id  = 0;

			if ($(this).is(':checked')) {
				
				supplements_name = $(this).attr('name');
				this_supplement_id = $(this).val(); //alert(supplements_name);
				room_no = supplements_name.substring(14, 15);  //supplements_name in the form of 'supplement_id[1][]'
				
				if (!is_array(data['supplement_id'][room_no])) {
					// there are no supplements for this room, create all the sub arrays
					data['supplement_id'][room_no] = new Array();
					data['supplement_id'][room_no][i]= new Array();
					// also create the array for the quantity
					data['quantity'][room_no] = new Array();
					data['quantity'][room_no][i] = new Array();
					data['quantity'][room_no][i][this_supplement_id] = new Array();
				}
				else { //alert('room has some supplements ' + i);
					i = data['supplement_id'][room_no].length;
					// this room has some supplements already
					data['supplement_id'][room_no][i] = new Array();
					data['supplement_id'][room_no][i][this_supplement_id] = new Array();
					// check if it has the array for the quantity
					if (!is_array(data['quantity'][room_no])) {
						data['quantity'][room_no] = new Array();
					}
					if (!is_array(data['quantity'][room_no][i])) {
						data['quantity'][room_no][i] = new Array();
					}
				}
				data['supplement_id'][room_no][i] = this_supplement_id; 
				data['quantity'][room_no][i][this_supplement_id] = 1; // added this because subsequent functions (specifically supplement_pricing_cost_breakdown) don't seem to account for qty if checkbox. vu
				//alert(data['supplement_id'][room_no][i] + ' ' + data['quantity'][room_no][this_supplement_id]);
				i++;
			}
		});
		
		// serialise the data in the arrays
		return urlencode(serialize(data));
		
	} // end function serialiseData()

	

$(document).ready(function() {
	showCurrencyConverter();

	$('.mealplan_selection_container input[type^="radio"]').each(function(i){
		
		if($(this).is(':checked')){
			$(this).parent().removeClass('radio_input_bg').addClass('radio_input_bg_on');
		}else{
			$(this).parent().removeClass('radio_input_bg_on').addClass('radio_input_bg');
		}
	     
	});
	
	
	$('.mealplan_selection_container input[type^="radio"]').click(function() {
		var name = $(this).attr('name');
		$('.mealplan_selection_container input[name^="'+name+'"]').each(function(i){
			
			if($(this).is(':checked')){
				$(this).parent().removeClass('radio_input_bg').addClass('radio_input_bg_on');
			}else{
				$(this).parent().removeClass('radio_input_bg_on').addClass('radio_input_bg');
			}
	      
		});
	});
	
	$('.minus_supplements').click(function() {
		var value = parseInt($(this).parent().parent().find('.supplement_number input').val());
		
		// get the supplementId from the name 
		var supplementInputName = $(this).parent().parent().find('.supplement_number input').attr('name');
		var supplementIdStart = supplementInputName.search(/\]\[/i) + 2; //[\d]{2}
		var numberChars = supplementInputName.length - supplementIdStart -1;
		var supplementId = supplementInputName.substr(supplementIdStart, numberChars);
		
		// get the room number from the name
		var roomNumberStart = supplementInputName.search(/[\d]/i);
		var roomNumberEnd = supplementInputName.search(/]/i);
		var roomNumber = supplementInputName.substr(roomNumberStart, roomNumberEnd - roomNumberStart);
		
		if (value > 0){
			value--;
			$(this).parent().parent().find('.supplement_number input').val(value);
			
			var quantity = value;
			// grab the values that we can non-arrayed values from the input
			var from_date = $('.mealplan_selection_container input[name="from_date"]').val();
			var to_date = $('.mealplan_selection_container input[name="to_date"]').val();
			
			// grab the values that will be put into an array that will be serialised
			var data = new Array();
			data['adults'] = new Array();
			data['children'] = new Array();
			$('.mealplan_selection_container input[name^="adults"]').each(function(i){
				var adults_name = $(this).attr('name');
				var adults_index = adults_name.substring(7, 8);
				data['adults'][adults_index] = $(this).val();
			});
			
			$('.mealplan_selection_container input[name^="children"]').each(function(i){
				var children_name = $(this).attr('name');
				var children_index = children_name.substring(9, 10);
				data['children'][children_index] = $(this).val();
				
			});
			// serialise the data in the arrays
			var serialized_data = urlencode(serialize(data));
			
			// get the cost of the total via the ajax
			var params = '?action=getSupplementItemTotal&qty=' + quantity + '&supplementId=' + supplementId + '&fromDate=' + from_date + '&toDate=' + to_date + '&data=' + serialized_data;
			var supplementTotal = ajax_request(params); 
			// finally! display the new total for this supplement
			$('#supplementItemTotal' + roomNumber + supplementId).html('&euro;' + supplementTotal);
		}
		else {
			// value is less than 0 //alert('Cannot go below 0');
			// set quantity to 0
			$(this).val('0');	
			
			// set total for supplement to 0
			$('#supplementItemTotal' + roomNumber + supplementId).html('&euro;0.00');
			
			if ($('#supplementError' + roomNumber + supplementId).length) {
			    // an error occurred previously but now we're ok so remove the error
			    $('#supplementError' + roomNumber + supplementId).remove();
			}
			
			// make a note so that the user knows what happened
			$('#supplementTitle' + roomNumber + supplementId).append('<span class="red" id="supplementError' + roomNumber + supplementId + '">Cannot choose less than 0 of this supplement.</span>');
		}
		calculate_update_total(); // calculate_update_total defined in general.js
		
	});	// end $('.minus_supplements').click
	
	
	// this is for the input field of supplement number
	$('.supplement_number input').change(function() {
		var value = parseInt($(this).val());
		
		// get the supplementId from the name 
		var supplementInputName = $(this).parent().parent().find('.supplement_number input').attr('name');
		var supplementIdStart = supplementInputName.search(/\]\[/i) + 2; //[\d]{2}
		var numberChars = supplementInputName.length - supplementIdStart -1;
		var supplementId = supplementInputName.substr(supplementIdStart, numberChars);
		
		// get the room number from the name
		var roomNumberStart = supplementInputName.search(/[\d]/i);
		var roomNumberEnd = supplementInputName.search(/]/i);
		var roomNumber = supplementInputName.substr(roomNumberStart, roomNumberEnd - roomNumberStart);

		if ($('#supplementError' + roomNumber + supplementId).length) {
		    // an error occurred previously so overwrite the error
		    $('#supplementError' + roomNumber + supplementId).remove();
		}
			
		if (value >= 0){
			var maxValue = $(this).attr('title');
			
			// grab the values that we can non-arrayed values from the input
			var from_date = $('.mealplan_selection_container input[name="from_date"]').val();
			var to_date = $('.mealplan_selection_container input[name="to_date"]').val();
			
			// grab the values that will be put into an array that will be serialised
			var data = new Array();
			data['adults'] = new Array();
			data['children'] = new Array();
			$('.mealplan_selection_container input[name^="adults"]').each(function(i){
				var adults_name = $(this).attr('name');
				var adults_index = adults_name.substring(7, 8);
				data['adults'][adults_index] = $(this).val();
			});
			
			$('.mealplan_selection_container input[name^="children"]').each(function(i){
				var children_name = $(this).attr('name');
				var children_index = children_name.substring(9, 10);
				data['children'][children_index] = $(this).val();
				
			});
			// serialise the data in the arrays
			var serialized_data = urlencode(serialize(data));
			
			if (value <= maxValue) {
				// value is less than the max Value, proceed
				var quantity = value;
				
				// get the new cost total for the supplement via ajax
				var params = '?action=getSupplementItemTotal&qty=' + quantity + '&supplementId=' + supplementId + '&fromDate=' + from_date + '&toDate=' + to_date + '&data=' + serialized_data;
				var supplementTotal = ajax_request(params); 
				
			} // end if the new value is less than the max value
			else {
				// value typed in is greater than the maxValue, set it to the maxValue
				$(this).val(maxValue);
				
				// get the new cost total for the supplement via ajax
				var quantity = maxValue;
				var params = '?action=getSupplementItemTotal&qty=' + quantity + '&supplementId=' + supplementId + '&fromDate=' + from_date + '&toDate=' + to_date + '&data=' + serialized_data;
				var supplementTotal = ajax_request(params); 
				
				// tell the user why he's not seeing desired quantities
				$('#supplementTitle' + roomNumber + supplementId).append('<span class="red" id="supplementError' + roomNumber + supplementId + '">Maximum number allowed is ' + maxValue + '</span>');
				
			}
		
		}
		else {
			// value is less than 0, set quantity to 0, set total to 0
			$(this).val('0');	
			supplementTotal = 0;
			
			// tell the user why he's not seeing desired quantities
			$('#supplementTitle' + roomNumber + supplementId).append('<span class="red" id="supplementError' + roomNumber + supplementId + '">Cannot choose less than 0 of this supplement.</span>');
			
		}
		
		// display the new total for this supplement
		$('#supplementItemTotal' + roomNumber + supplementId).html('&euro;' + supplementTotal);
		
		calculate_update_total();
	});	// end on blur of input
	
	/*
	$('.plus_supplements').click(function() {
		var value = parseInt($(this).parent().parent().find('.supplement_number input').val());
		if(value < 5){
			value++;
			$(this).parent().parent().find('.supplement_number input').val(value);
		}else{
			//alert('Cannot book more than 5');
		}
	});	
	*/
	/*
	$('.mealplan_selection_container input[name^="supplement_id"]').each(function(i){
      $(this).click(function() {
	      	var name = $(this).attr('name');
			var index = name.substring(14, 15);
			//alert(index);
			var text = '';
	      	$('.mealplan_selection_container input[name^="supplement_id['+index+']"]').each(function(i){
	      		if($(this).is(':checked')){
	      			var name = $(this).attr('name');
					var index = name.substring(14, 15);
	      			//alert($(this).parent().parent().find('.extra_selection_title').html());
	      			text = text + $(this).parent().parent().find('.extra_selection_title').html()+", ";
				}
			});
			//alert(text);
			$('#supplement'+index).html(text);
			//$('#supplement'+index).append(text);
      	});
	});
	*/
});


