var SNIPPET_DIR = "./assets/snippets/search/";
var REQUEST_DIR = SNIPPET_DIR+"ajax/";

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


function ajax_request(params){
	
	//var j = jQuery.noConflict();
	var txt;
	var html = jQuery.ajax({
			type: 'POST',
			url: REQUEST_DIR+'actions.php'+params,
			data: params,
			cache: false,
			//better to use async false - blocks the browser when the request is active
			async: false,
			success: function(txt){
				txt = txt.replace(/\n/g, '');
				txt = txt.replace(/\r/g, '');
				txt = txt.replace(/\t/g, '');
			}
	}).responseText;
	return html;
}


function calculate_update_total(){
	
	var voucherCode = $('#voucher').val();
	var pointsUsed = $('#pointsUsed').val();
	var from_date = $('.mealplan_selection_container input[name="from_date"]').val();
	var to_date = $('.mealplan_selection_container input[name="to_date"]').val();
	var hotel_id = $('.mealplan_selection_container input[name="hotel_id"]').val();
	var rooms = $('.mealplan_selection_container input[name="rooms"]').val();
	var paymentPlan = $('.mealplan_selection_container input[name="payment_method"]:checked').val();
	var mealPlanId = $('.mealplan_selection_container input[name="meaplan_id[1]"]:checked').val();
	
	var data = new Array();
	data['adults'] = new Array();
	data['children'] = new Array();
	data['mealplan_id'] = new Array();
	data['room'] = new Array();
	data['infants'] = new Array();
	data['supplement_id']= new Array();
	data['quantity']= new Array();
	/*---------------------------COMMON----------------------------------*/
	$('.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();
			//alert(room_index);
		}
	});
	
	/*---------------------------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++;
		}
	});
	
	var serialized_data = urlencode(serialize(data));	//alert(serialized_data);
	var params = "?action=get_mealplan_pricing&hotel_id="+hotel_id+"&from_date="+from_date+"&to_date="+to_date+"&data="+serialized_data;
	//alert(index);
	//$('#bord_basis_room'+index).html($(this).parent().parent().find('.extra_selection_title').html());
	
	
	// deal with the pricing here
	var new_total = ajax_request(params); //alert(new_total);
	
	var pointsFieldUsed = false;
	if (typeof pointsUsed != "undefined") {
		if (pointsUsed.length > 0) {
			pointsFieldUsed = true;	
		}
	}
	
	var voucherFieldUsed = false;
	if (typeof voucherCode != "undefined") {
		if (voucherCode.length > 0) {
			voucherFieldUsed = true;	
		}
	}	
	

	if (!voucherFieldUsed && !pointsFieldUsed) {
		
		// no voucher field and no points field
		$('#preReductionsTotal').val(new_total);
		$('span .total_price_replace').html(new_total);
		var discounted_total = parseFloat(new_total) - ((parseFloat(new_total) * 5) / 100)
		$('.total_price_with_discount').html(number_format( discounted_total, 2, '.', '' ));

		// added this. vu 20110310 alert(paymentPlan);
		if (paymentPlan != 'half') {
			var finalTotal = '<strike>' + number_format(new_total, 2, '.', '' ) + '</strike> ' + number_format(discounted_total, 2, '.', '' ); 
			$('#finalTotal').html(finalTotal);
		}
		else {
			$('#finalTotal').html(new_total);	
		}
	}
	else {
		// either there's a voucher code or there's a points to be redeemed
		var existingTotal = $('#preReductionsTotal').val();
		
		if (existingTotal != new_total) {
			// there's been a change to the fundamental base price of the stay either via supplements or mealplans
			
			// update the hidden total for pre voucher and points 20110502 vu. 
			$('#preReductionsTotal').val(new_total);	
		
			$('span .total_price_replace').html(new_total);
			var discounted_total = parseFloat(new_total) - ((parseFloat(new_total) * 5) / 100)
			$('.total_price_with_discount').html(number_format( discounted_total, 2, '.', '' ));	

		} // end whether there's a change in the base price
		
		if ((typeof voucherCode != "undefined") && !pointsFieldUsed) {
			// apply the voucher if there is one in the voucher code and we aren't going to get to the applyPoints function
			// if we get to applyPoints, we'll check for apply voucher
			applyVoucher();	
		} // end if there is a voucher to be taken into account
		
		if (typeof pointsUsed != "undefined") {
			if (pointsUsed.length > 0) {
				// apply the points if there is one in the points input
				applyPoints();	
			} // end if we're using points
		} // end if pointsUsed is a field ie if we're logged in
		
	} // end whether voucher or points has a value

	// deal with the rate information in the right hand col
	var rateInformationBeginning = 'Rates are inclusive of all applicable taxes and ';
	var rateInformationEnd = ' meal plan';
	var rateInformationText = rateInformationBeginning + 'buffet breakfast.';
	if (mealPlanId != 0) {
		var params = "?action=getMealPlanText&mealplan_id=" + mealPlanId;
		// deal with the pricing here
		rateInformationText = rateInformationBeginning + ajax_request(params) + rateInformationEnd; //alert(new_total);	
	}
	$('#rateInformation').html(rateInformationText);
	
	if (document.getElementById('currency_dropdown') != null) {
		convertTotal();
	} 	
} // end calculate_update_total()


function convertPrices() {

	var from = 'EUR';
	var to = document.getElementById('displayCurrency').options[document.getElementById('displayCurrency').selectedIndex].value;
	$.ajax({
			type: "GET",
    		contentType: "application/json; charset=utf-8",
            url: "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",
            dataType: 'jsonp',
            jsonp: 'callback',
            success: function(data) {
		        var name = data.query.results.row.name; // "USD to SEK"
			    var toCurrency = name.substring(name.indexOf('to') + 3, name.length);
			    var rate = parseFloat(data.query.results.row.rate, 10); // parseFloat() parses a string, returns a floating point number.
				var currencySymbols = {'USD': "$", 'EUR':"&#8364;", 'GBP': "&#163;", 'RUB': 'RUB '};
				$('.currencySymbol').html(currencySymbols[toCurrency]); // replace the symbols
				// for each amount, replace the amount
				$('.currencyAmount').each(function(index) {
					var displayAmount = $(this).attr('rel') * rate;
				    $(this).text(addCommas(displayAmount.toFixed(2)));
				});
				// show the information
				$('#currencyInformation').show();
				// remember the currency we want to display
				var params = '?action=setCurrency&value=' + toCurrency + '&session_id=' + document.getElementById('session_id').value;
				var setCurrency = ajax_request(params);
		    },
		    error: function(xhr, textStatus, errorThrown) {
		    	alert('Sorry, cannot convert at the moment. Please try again later');
		        //$("#status").val("Unavailable: " + textStatus);
		    }
        });
} // end convertPrices()


function get_hotels_dropdown(obj){
	
	var town_id = obj.value; 	//alert(town_id);
	params = "?action=get_hotel_dropdown&town_id="+town_id;
	var new_select = ajax_request(params);
	
	if(new_select != ''){
		var select_holder = document.getElementById('hotel_select');
		select_holder.innerHTML = new_select;
	}

}  // end  get_hotels_dropdown(obj)

function get_hotels_bottom_dropdown(obj){
	
	var town_id = obj.value; 	//alert(town_id);
	params = "?action=get_hotel_dropdown&town_id="+town_id;
	var new_select = ajax_request(params);
	
	if(new_select != ''){
		var select_holder = document.getElementById('bottom_hotel_select');
		select_holder.innerHTML = new_select;
	}

}  // end  get_hotels_dropdown(obj)

function filterSearchResults() {

	var params = '?action=filterSearchResults';
	
	var from_date = $('#filters input[name="from_date"]').val();
	var to_date = $('#filters input[name="to_date"]').val();
	var hotel_id = $('#filters input[name="hotel_id"]').val();
	if (typeof(hotel_id) == "undefined") { hotel_id = 0; }
	var town_id = $('#filters input[name="town_id"]').val();
	if (typeof(town_id) == "undefined") { town_id = 0; }
	var rooms = $('#filters input[name="rooms"]').val();
	
	var data = new Array();
	data['adults'] = new Array();
	data['children'] = new Array();
	data['infants'] = new Array();
	data['room'] = new Array();
	data['holiday_type_id'] = new Array();
	data['star_rating_id'] = new Array();
	
	$('#filters 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();
	});
	
	$('#filters 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();
	});
	
	$('#filters 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();
	});
	
	$('#filters 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();
				//alert(room_index);
			}
	});
		
	$('#filters input[name^="holiday_type_id"]:checked').each(function(i){
		var inputName = $(this).attr('name');
		var index = inputName.substring(inputName.search(/\[/)+ 1,inputName.search(/\]/)); // get the stuff inside the square brackets
		data['holiday_type_id'][index] = $(this).val();
	});
		
	$('#filters input[name^="star_rating_id"]:checked').each(function(i){
		var inputName = $(this).attr('name'); 
		var index = inputName.substring(inputName.search(/\[/)+ 1,inputName.search(/\]/)); // get the stuff inside the square brackets
		data['star_rating_id'][index] = $(this).val();
	});
	
	var serialized_data = urlencode(serialize(data));	//alert(serialized_data);
	var params = '?action=filterSearchResults&hotel_id=' + hotel_id + '&from_date=' + from_date + '&to_date=' + to_date +  '&rooms=' + rooms +  '&town_id=' + town_id + '&data=' + serialized_data;
	
	// display a please wait
	$('#searchResults').html('<div id="loading-image"><img src="assets/templates/site/images/ajax-loader.gif" alt="Loading..." /><br />Loading, please wait.</div>');
	$('#filters input:submit').attr('disabled', 'disabled');
	$('#holidayStylesFilter').css('display', 'none');
	$('#ratingsFilter').css('display', 'none');
	
	var newSearchResults = ajax_request(params);
	
	if (newSearchResults != ''){
		// we have search results
		// display the search results
		var searchResultsHolder = document.getElementById('searchResults');
		searchResultsHolder.innerHTML = newSearchResults;
		// get the holiday styles and the star ratings for the count
		var params = '?action=getStarRatings' + '&town_id=' + town_id + '&data=' + serialized_data;
		// enable the apply buttons
		$('#filters input:submit').attr('disabled', '');
	}	
}

//http://www.hunlock.com/blogs/Mastering_Javascript_Arrays#quickIDX34
function isArray(testObject) {   
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

$(document).ready(function() {
	
	$('.click_rate_analisys').click(function() {
			$(this).parent().find('.rate_analysis_toggle').slideToggle();
	});
	
	//MEALPLANS AND SUPPLEMENTS CLICKS
	$('.mealplan_selection_container input[name^="supplement_id"]').click(function() {
		calculate_update_total();
		var supplementId = $(this).val();
		
		// get the room number from the name
		var supplementInputName = $(this).attr('name');
		var roomNumberStart = supplementInputName.search(/[\d]/i);
		var roomNumberEnd = supplementInputName.search(/]/i);
		var roomNumber = supplementInputName.substr(roomNumberStart, roomNumberEnd - roomNumberStart); //alert(roomNumber);
		
		if ($(this).attr('checked')) {
			var supplementTotal = calculateSupplementTotal(1, $(this));
		}
		else {
			var supplementTotal = '0.00';	
		}
		$('#supplementItemTotal' + roomNumber + supplementId).html('&euro;' + supplementTotal);
	});
	
	$('.mealplan_selection_container input[name^="meaplan_id"]').click(function() {
		//$(this).attr('checked');
		calculate_update_total();
		
	});
	
	$('.mealplan_selection_container input[name^="quantity"]').click(function() {
		calculate_update_total();
	});
	
	$('.plus_supplements').click(function() {	//alert('1');
		calculate_update_total();
	});
	
	/* moved this to mealplans because the updated value wasn't being registered. vu 20110411
	$('.minus_supplements').click(function() { //alert('2');
		calculate_update_total();
	});*/
	
	$('.mealplan_selection_container input[name^="payment_method"]').click(function() {
		calculate_update_total();
	});
	
	//MEALPLANS AND SUPPLEMENTS LOADED CHECKED (SELECTED)
	if($('.mealplan_selection_container input[name^="supplement_id"]').is(':checked') || $('.mealplan_selection_container input[name^="meaplan_id"]').is(':checked')){
		calculate_update_total();
	}
	
	$('#filters input:checkbox').click(function() {
		filterSearchResults();
	});
	
	$('.supplement_number input').change(function() {	//alert('1');
		calculate_update_total();
	});
	
	/*
	$('.mealplan_selection_container input[name^="meaplan_id"]').each(function(i){
      $(this).click(function() {
		var name = $(this).attr('name');
		var index = name.substring(11, 12);
		
		var hotel_id = $('.mealplan_selection_container input[name="hotel_id"]').val();
		var adults = $('.mealplan_selection_container input[name^="adults['+index+']"]').val();
		var children = $('.mealplan_selection_container input[name^="children['+index+']"]').val();
		var from_date = $('.mealplan_selection_container input[name="from_date"]').val();
		var to_date = $('.mealplan_selection_container input[name="to_date"]').val();
		var mealplan_id = $(this).val();
		
		
		alert(hotel_id);
		alert(adults);
		alert(children);
		alert(from_date);
		alert(to_date);
		alert(mealplan_id);
		
		
		var params = "?mealplan_id="+mealplan_id+"&action=get_mealplan_pricing&room="+index+"&hotel_id="+hotel_id+"&adults="+adults+"&children="+children+"&infants="+'0'+"&from_date="+from_date+"&to_date="+to_date;
		//alert(index);
		$('#bord_basis_room'+index).html($(this).parent().parent().find('.extra_selection_title').html());
		var mealplan_pricing = ajax_request(params);
		alert(mealplan_pricing);
		$('#bord_basis_price').html(mealplan_pricing);
		
		//when clicking add up all the checked boxes like on the supplements
		
		});
      
	});*/

	$('.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);
      	});
	});
	
});

		function load_hotel_booknow(townid,hotelid){
			var obj = document.getElementsByName("town_id")[0]
			for(var i=0; i<obj.options.length; i++){
			    if(obj[i].value == townid){
		      	obj.selectedIndex = i;
		    	}
			}

			get_hotels_dropdown(obj);

			var obj2 = document.getElementsByName("hotel_id")[0];
			for(var i=0; i<obj2.options.length; i++){
			    if(obj2[i].value == hotelid){
			      obj2.selectedIndex = i;
		    	}
			}
			
			document.getElementsByName('from_date')[0].focus();
		}

