/* Updates result pages cheapest price info. Is always called after sorting by price. Thus the cheapest price should
	be the first visible price in page. */
function updateCheapestPrice(i_page) {
	var s_text;
  	var div_parent;

	switch (i_page) {
		case 1:	s_text = "Halvin lento ";			div_parent = "results_info_box";	priceclass = '.f_price'; break;
		case 2:	s_text = "Halvin auto ";			div_parent = "c_results_info_box";	priceclass = '.c_price'; break;
  		case 3:	s_text = "Halvin hotelli ";			div_parent = "h_results_info_box";	priceclass = '.h_price'; break;
  		case 4:	s_text = "Halvin lento + hotelli ";	div_parent = "fh_results_info_box";	priceclass = '.fh_price'; break;
		case 5:	s_text = "Halvin äkkilähtö ";	div_parent = "lmh_results_info_box"; priceclass = '.lmh_price'; break;
		default: break;
	}

	// Find out	the first visible element in #results_list, if not car search
	if (i_page != 2) {
		var children = $("#results_list > div:visible:first"); // jQuery parent > child, :visible
	} else {
		var children = $("#car_result_0"); // actually only gets the first (and cheapest) from small cars category
	}
	// alert(children.text());
	if (children.length) { // children contains stuff, continue updating cheapest price
		var s_price = children.find("div" + priceclass).text();
		
		var a_price = s_price.split(" ");
		var i_price = a_price[0].replace('.',',');
		
		if (i_page == 3) { //hotel results, deeplink is in different div (h_prices_table's second tr, first is headers)
			// selects second tr in h_price_table
			// Get entire HTML content of the table
			var table_rows = $("#results_list > div:visible:first .h_prices_table").html();
			var urlpos = table_rows.search("redirect_popup");
			var substr1 = table_rows.substring(urlpos);
			urlpos = substr1.search(';"');
			var s_url = substr1.substring(0, urlpos);
			// First two &amp; must be changed back to & so redirect.php works
			s_url = s_url.replace("&amp;stamp", "&stamp");
			s_url = s_url.replace("&amp;url", "&url");
			// .attr("onclick")
			// alert(table_onclick);
			//second tr's onclick, that contains the deeplink
			// var table_onclick = table_rows.getAttribute('onclick');
			// // var table_onclick = jQuery.html(table_rows);
			// var a_url = table_onclick.split(" "); //split to get rid of event.cancelBubble=true;
			// var s_url = a_url[1]; //contains deeplink
			// alert(s_url);
		} else {
			var s_url = children[0].getAttribute("onclick");
		}
		// var a_comma_price = i_price.split("."); //split decimal number to integers and decimals
		
		// Start creating elements
		var results_cheapest_elem = document.createElement("div");
		results_cheapest_elem.setAttribute("id","results_cheapest");

		//create p
		var child_p = document.createElement("p");

		//create br
		var child_br = document.createElement("br");

		//create a
		var child_a = document.createElement("a");
		var text_a = document.createTextNode(s_text);
		
		child_a.setAttribute("href","javascript:;");
		child_a.setAttribute("onclick",s_url);

		//create span
		var child_span = document.createElement("span");
		child_span.className = "cheap_price";
		// var price_span = a_comma_price[0] + "," + a_comma_price[1] +" &euro;";
		var price_span = i_price +" &euro;";
// 		var text_span = document.createTextNode(price_span);
		child_span.innerHTML = price_span;

		//add elements to correct structure
// 		child_span.appendChild(text_span); 	//span's text
		child_a.appendChild(text_a);		//a's text
		if (i_page == 4) {
			child_a.appendChild(child_br);	//rowbreak
		}
		child_a.appendChild(child_span);	//a's span
		child_p.appendChild(child_a);		//p's a
		results_cheapest_elem.appendChild(child_p); //all inside div

		//take old results_cheapest and replace with new one
		var old_cheap = document.getElementById("results_cheapest");
		document.getElementById(div_parent).replaceChild(results_cheapest_elem,old_cheap);
	} else { // if there were no results, this is empty - do not create links 
 		var res_cheapest = "\n\t\t\t<p>"+s_text+"<span class='cheap_price'>- &euro;</span></p>\n\t\t";
	
		//substitute the old results_cheapest content with the new cheapest price
		document.getElementById("results_cheapest").innerHTML = res_cheapest;
	}
} 

/* Updates result pages total results info. Is always called on bodyload. */
function updateResultsTotal(results_total, i_page) {
	
  	var div_name = "results_searchinfo";
	if (i_page == 3) {
		var word = "Hotelleja";
	} else {
		var word = "Tuloksia";
	}
	
 	// if results
 	if (results_total > 0) {
		// substitute the old total results
		new_html = "\n\t\t\t<p>"+word+" yhteensä <span id='results_number'>"+results_total+"</span> kpl.</p>"
			+"\n\t\t\t<p>Haku on valmis.</p>"
			+"\n\t\t\t<p class='top_spacer'>Hinnat ovat kokonaishintoja.</p>";
		document.getElementById(div_name).innerHTML = new_html;
	} else { //no results, no link
		//substitute the old total results
		new_html = "\n\t\t\t<p>"+word+" yhteensä <span id='results_number'>0</span> kpl.</p>\n\t\t"
			+"\n\t\t\t<p>Haku on valmis.</p>\n\t\t";
		document.getElementById(div_name).innerHTML = new_html;
	}
}

/* Updates result pages heading when search is finished. Is always called after sorting by price.*/
function updateResultsHeading(i_page, i_rows) {
	
	//heading can be in a different styled div, is a class style
	var div_name = ".results_heading";
	
	//so far only cars have a different heading
	switch(i_page){
		case 2: 	div_name = ".results_heading_cars_small"; break;
		default:	break;
	}

	var new_heading;
	if (i_rows > 0) {
		//only in flights
		if($("#fly_checkbox_direct").length) {
			if($("#fly_checkbox_direct").is(':checked')) {
				new_heading = "Hakutulokset - Suorat lennot";
			} else {
				new_heading = "Hakutulokset";
			}
		} else {
			new_heading = "Hakutulokset";
			switch(i_page){
				case 2: 	new_heading = "Pienet autot";	break;
				default:	break;
			}
		}
		//substitute the old heading content with the new heading
// 		var vanha = $(div_name).html();
// 		alert(vanha+", "+new_heading);
		$(div_name).html(new_heading);
// 		document.getElementById(div_name).innerHTML = new_heading;

		//make tax_info div visible, must be only one tax_info
// 		document.getElementById('tax_info').style.display = 'inline';
	}
	
	else { //no results
		//only in flights
		if($("#fly_checkbox_direct").length) {
			if($("#fly_checkbox_direct").is(':checked')) {
				new_heading = "Ei tuloksia - Suorat lennot";
			} else {
				new_heading = "Ei tuloksia";
			}
		} else {
			new_heading = "Ei tuloksia";
			switch(i_page){
				case 2: 	new_heading = "Pienet autot - Ei tuloksia";	break;
				default:	break;
			}
		}
	
		//substitute the old heading content with the new heading
		$(div_name).html(new_heading);
	}
}

/* Compares by price. */
function compareNumbers(array_a, array_b) {
	
	//parse the string values in inner arrays to decimals
	var f_number_a = parseFloat(array_a[1]);
	var f_number_b = parseFloat(array_b[1]); //f_number_b = parseInt(array_b[1],10) parses as int
	
	if (f_number_a < f_number_b) return -1; //Second number is greater
	if (f_number_a > f_number_b) return 1; //First number is greater
	
	if (array_a[2] > array_b[2]) { // these are indexes from DOM structure or partner names from ALT attrs
		return 1; // index for array_a is bigger, make sure it is after array_b
	} else {
		return -1;
	}
}


/* Compares first by partner name, secondary by price. */
function comparePartner(array_a, array_b) {

	//get the string values in inner array
	var s_a = array_a[1];
	var s_b = array_b[1];
	
	//compare by partner name
	if (s_a < s_b)
		return -1;

	if (s_a > s_b)
		return 1;
	
	//if same partner then compare by price
	//parse the string values in inner arrays to decimals
	var f_number_a = parseInt(array_a[2],10);
	var f_number_b = parseInt(array_b[2],10);

	if (f_number_a < f_number_b) return -1; 
	if (f_number_a > f_number_b) return 1; 
	
	//if neither is bigger, they're equal
	return 0;
}


/* Compares first by departure time and then by price. */
// Does not care about the date (depture time (there) is always on the same user chosen date).
function compareDeparture(array_a, array_b) {

	//get the string values in inner array
	var s_a = array_a[1];
	var s_b = array_b[1];
	
	//compare by departure time
	if (s_a < s_b) {
		return -1
	}
	if (s_a > s_b){
		return 1;
	} else {
		//if same departure then compare by return departure
		//not currently in use!
/*		//get the string values in inner array
		var s_c = array_a[2];
		var s_d = array_b[2];
	
		//compare by departure time
		if (s_c < s_d) {
			return -1
		}
		if (s_c > s_d){
			return 1;
		*/	
		//if same return time compare by price
// 		} else {

		//compare by price
		//parse the string values in inner arrays to decimals
		f_number_a = parseInt(array_a[3],10);
		f_number_b = parseInt(array_b[3],10);

		if (f_number_a < f_number_b) return -1; 
		if (f_number_a > f_number_b) return 1; 

		//if neither is bigger, they're equal
		return 0;
	
// 		}
	}
}

// This function only shows an info div that tells user that JS is working. Actual toggleDirect must be
// called inside setTimeOut as follows so that div will be displayed.
function showHiddenMessage() {
$(document).ready(function() { // jQuery thingie to wait for the document to be ready
	document.getElementById("js_in_progress").style.display = 'block';
	setTimeout(function() { 
		toggleDirectFlights();
	}, 0); 
});
}

function checkFlightFilters() {
$(document).ready(function() {
	document.getElementById("js_in_progress").style.display = 'block';
	
	setTimeout(function() { 
		applyFlightFilters();
	}, 0);
});
}

/* Sorts results by price. i_page tells which result page called the function:
	(1 = flights, is sorted using toggleDirectFlights()!), 2 = cars, 3 = hotels, 4 = flight+hotel, 5 = lmh.
	Is called after result page loads to sort the results.
*/
function sortPrice(i_page) {
	var row_count = 0;
	var a_rows = getAllResultElements(i_page);
	row_count = a_rows.length;
		
	if (row_count > 0 && i_page > 2) { // continue sorting if there was result rows (even one is enough)
		//create the results array
		var a_results = new Array(row_count);
		var row;
		var s_price;

		//go through results and store them in array
		for (var j=0; j < row_count; j++) {
			a_results[j] = new Array();
			a_rows[j].style.display = 'block';
			row = $(a_rows[j]);
			switch(i_page) {
				case 3:
					s_price = new String(row.find("div.h_price").text()); /* JQuery find( expr ) */
					break;
				case 4:
					s_price = new String(row.find("div.fh_price").text()); /* JQuery find( expr ) */
					break;
				case 5:
					s_price = new String(row.find("div.lmh_price").text()); /* JQuery find( expr ) */
					break;
				default:
					break;
			}
			
			//separate the integer value from euro sign and store the integer
			var a_price = s_price.split(" ");
	
			//store result row object, price for this row and ID for this row in an array
			a_results[j][0] = row;
			a_results[j][1] = a_price[0].replace(',','.'); //save as 00.00 so js can sort them correctly
			a_results[j][2] = j;
		}
	
		//sort the results array
		a_results.sort(compareNumbers);
		
		var dom_results2 = $("#results_list");
		dom_results2.empty();

		var rowcolor_id = 0;
		for (var k=0; k < a_results.length; k++) { // loop result rows
			var result_row = a_results[k][0]; // select one result row, JQuery element
						
			var s_class = ""; var s_hover = ""; //choose right styles for row to these vars
			
			// resolve which color the row is, different color for odd and even rows
			if (i_page > 2) {
				if (rowcolor_id % 2 == 0) {
					switch(i_page) {
						case 3: s_class = "hotels_a";	s_hover = "hotels_hover";	break;
						case 4: s_class = "fh_a";		s_hover = "fh_hover";		break;
						case 5: s_class = "lmh_a";		s_hover = "lmh_hover";		break;
						default: break;
					}
				} else {
					switch(i_page) {
						case 3: s_class = "hotels_b";	s_hover = "hotels_hover";	break;
						case 4: s_class = "fh_b";		s_hover = "fh_hover";		break;
						case 5: s_class = "lmh_b";		s_hover = "lmh_hover";		break;
						default: break;
					}
				}
			
				result_row.className = s_class;
				result_row.hover(
					function () { $(this).addClass(s_hover); },
					function () { $(this).removeClass(s_hover); }
				);
				
				rowcolor_id++;
			}
			// append row to results_list
			dom_results2.append(result_row);
		}

		//update cheapest price, heading and total results texts
		updateCheapestPrice(i_page);
		updateResultsHeading(i_page, row_count);
		updateResultsTotal(row_count, i_page);
				
	} else { //no result rows
		updateCheapestPrice(i_page);
		updateResultsHeading(i_page, row_count);
		updateResultsTotal(row_count, i_page);
	}
}

/* Sorts by departure time. The departure of return flight is not compared. */
/* 25.3.09 works somewhat correctly, doesn't seem to hide results and hoover works. Look through with care to see if functions that are called are necessary and still working correctly. */
function sortFlightsDeparture() {

if (document.getElementById("results_list")) {
	// Check whether toggleDirectFlights checkbox is checked or not
	if ($("#fly_checkbox_direct").is(':checked')) { // JQuery is() :checked
		var b_checkbox = true;
	} else {
		var b_checkbox = false;
	}
	
	var b_both = true; // assume round trip search was made
	if ($("#fly_radio_route_selection_2").is(':checked')) { // JQuery is() :checked, if checked, one-way flight
		var b_both = false;
	}
	
	$('div.topic_hidden_prices').remove(); // remove all <div class='moreprices'> if there were any
	
	// Find all result elements. Depending when user clicked this, results might be ordered by other criteria than
	// price and some of the results might be hidden.
	var a_results = getAllResultElements(1);
	var row_count = a_results.length;
	
	var a_directs = new Array();
	var a_indirects = new Array();
	var i_directs = 0;
	var i_indirects = 0;
	
	if (b_checkbox == true) { // user wants to see only direct flights
		// Get direct and indirect flights to their own arrays 
		for (var i=0; i < row_count; i++) {
			var row = $(a_results[i]);
			// var s_direct_there = new String(row.find("div.f_stops:first").text()); // JQuery find( expr )
			var s_direct_there = row.find("div.f_stops:first").text(); // JQuery find( expr )
			if (s_direct_there != "suora") {
				a_indirects[i_indirects] = row;
				i_indirects++;
			} else {
				if (b_both == true) { // two-way flight
					// var s_direct_back = new String(row.find("div.f_stops:last").text()); // JQuery find( expr )
					var s_direct_back = row.find("div.f_stops:last").text(); // JQuery find( expr )
					if (s_direct_back != "suora") {
						a_indirects[i_indirects] = row;
						i_indirects++;
					} else {
						a_directs[i_directs] = row; // both segments were direct flights
						i_directs++;
					}
				} else { 
					a_directs[i_directs] = row; // only segment in one-way flight was direct
					i_directs++;
				}
			}
		}
	} else { // checkbox was unchecked, handle all results
		i_directs = row_count;
		a_directs = a_results;
	}
	
	// Then, order the results by departure that are in a_directs and hide the results that are in a_indirects. 
	// Works in all cases.
	a_results = new Array();
	var s_price;
	var s_partner;
	var s_departure;
	var a_price;
	for (var j=0; j < i_directs; j++) {
		a_results[j] = new Array();
		row = $(a_directs[j]);
		s_price = new String(row.find("div.f_price").text()); // JQuery find( expr )
		s_partner = row.find('img:first').attr('alt');
		s_departure = new String(row.find("div.f_departure").text());
		a_price = s_price.split(" ");
		a_results[j][0] = row;
		a_results[j][1] = s_departure;
// 		a_results[j][2] = s_departure_back; //not in use now
		a_results[j][3] = a_price[0].replace(',','.');
	}
	a_results.sort(compareDeparture); // sort these results by departure
	
	var dom_result_list = $("#results_list");
	dom_result_list.empty();
	
	// Collate these results. Set some variables first
	var i_row_color_id = 0;
	var prev_price; var current_price; var next_price;
	var prev_partner; var current_partner; var next_partner;
	var b_display_link_to_other_flight_times;
	var b_newprice;
	
	//color result rows and append to result_list
	for (i = 0; i < a_results.length; i++) {
		
		if (i_row_color_id % 2 == 0) {
			s_classname = 'flights_a';
		} else {
			s_classname = 'flights_b';
		}
		a_results[i][0].show();
		
		a_results[i][0].removeClass(); // remove current classname
		a_results[i][0].addClass(s_classname); // set new classname 
		// Also, change onmouseover and onmouseout with jQuery's hover()
		a_results[i][0].hover(
			function () { $(this).addClass('flights_hover'); },
			function () { $(this).removeClass('flights_hover'); }
		);
		
		// var new_result_row = a_results[i][0];
		dom_result_list.append(a_results[i][0]);
		
		i_row_color_id++;
	}
	
	// Don't forget to append all those results that are in 'a_indirect'
	for (i = 0; i < i_indirects; i++) {
		a_indirects[i].removeClass();
		a_indirects[i].addClass('flights_c');
		a_indirects[i].hide();
		dom_result_list.append(a_indirects[i]);
	}
}
}

function toggleHidResults(ids, rowid) {
	$(document).ready(function() { // jQuery thingie to wait for the document to be ready
		var idsStr=new String(ids);
		var a_ids = idsStr.split(",");
		
		for (var a_id = 0; a_id < a_ids.length; a_id++) {
			// This toggles the hidden flight results that have same price as their 'parent'
			// $('#flight_result_' + a_ids[a_id]).toggle(); // easy but unfortunately slow jQuery toggle
			var hiddenDivName = "flight_result_" + a_ids[a_id];
			var hiddenDiv = document.getElementById(hiddenDivName);
			if (hiddenDiv.style.display == "block")
				hiddenDiv.style.display = "none";
			else
				hiddenDiv.style.display = "block";
		}
		
		// These two should toggle the text that informs the user to display or hide results
		// $('#moreprices_show_'+rowid).toggle(); // easy but unfortunately slow jQuery toggle
		// $('#moreprices_hide_'+rowid).toggle(); // easy but unfortunately slow jQuery toggle
		var morepricesText_Show = document.getElementById("moreprices_show_" + rowid);
		
		if (morepricesText_Show.style.display == "none") {
			morepricesText_Show.style.display = "block";
			document.getElementById("moreprices_hide_" + rowid).style.display = "none";
		} else {
			morepricesText_Show.style.display = "none";
			document.getElementById("moreprices_hide_" + rowid).style.display = "block";
		}	
	} );
}

function ShowHidCars(type, linkdiv) {
// $(document).ready(function() { // jQuery thingie to wait for the document to be ready
	$('#'+type +' div:hidden').show();
	$('#'+linkdiv).css('display', 'none');
// } );
}

function toggleCalendar(calendar_id_1, calendar_id_2) {
	$('#'+calendar_id_1).toggle(); // http://www.prototypejs.org/api/element/toggle

	//if oneway is selected, don't toggle cal 2
	if(document.getElementById('fly_radio_route_selection_2')) {
		//to know which radiobutton is selected you must use checked as below (has values true and false)
		//readAttribute('checked') only tells default selection, not the current state!
		var oneway_sel = document.getElementById('fly_radio_route_selection_2').checked;

		if (oneway_sel == true) {
			//don't show calendar 2
		}
		else { //both ways is selected
			$('#'+calendar_id_2).toggle();
		}
	}

	//change input that tell's whether calendars are showing or not,
	//value 0 means they're hidden, value 1 means they're showing
	var cal_status = $('#cal_status').val();
	if (cal_status == 0) {
		//change status on 
		$('#cal_status').val('1');
		//substitute the old total results
		var div_name = "calendar_link_text";
		var new_html = "&nbsp;Piilota kalenterit";
		document.getElementById(div_name).innerHTML = new_html;
	} else {
		//change status off
		$('#cal_status').val('0');
		var div_name = "calendar_link_text";
		var new_html = "&nbsp;Näytä kalenterit";
		document.getElementById(div_name).innerHTML = new_html;
	}
}

/* Return all result elements in a page as an array of elements. Gets the element with jQuery */ 
function getAllResultElements(i_page) {
	switch(i_page) {
		// adding #results_list before each div does not seem to affect performance
		case 1:
			// var rl = $("#results_list");
			// var a_rows = rl.find("div.flights_a,div.flights_b,div.flights_c,div.flights_d"); break;
			var a_rows = $(".flights_a,.flights_b,.flights_c,.flights_d"); break;
		case 2: var a_rows = $("div.cars_a,div.cars_b,div.cars_c,div.cars_d"); break;
  		case 3: var a_rows = $("div.hotels_a,div.hotels_b");	break;
  		case 4: var a_rows = $("div.fh_a,div.fh_b");			break;
		case 5: var a_rows = $("div.lmh_a,div.lmh_b");			break;
		default: var a_rows = new Array(); break;
	}
	// You can easily get row count with a_rows.length;
	return (a_rows);
}

/* Return visible result elements in a page as an array of elements. Gets the element with jQuery */ 
function getVisibleResultElements(i_page) {
	switch(i_page) {
		case 1: 
			var a_rows = $("div.flights_a:visible,div.flights_b:visible,div.flights_c:visible,div.flights_d:visible");
			break;
		case 2: var a_rows = $("div.cars_a:visible,div.cars_b:visible"); 		break;
  		case 3: var a_rows = $("div.hotels_a:visible,div.hotels_b:visible");	break;
  		case 4: var a_rows = $("div.fh_a:visible,div.fh_b:visible");			break;
		case 5: var a_rows = $("div.lmh_a:visible,div.lmh_b:visible");			break;
		default: var a_rows = new Array(); break;
	}
	// You can easily get row count with a_rows.length;
	return (a_rows);
}

/* Return hidden result elements in a page as an array of elements. Gets the element with jQuery */ 
function getHiddenResultElements(i_page) {
	switch(i_page) {
		case 1: 
			var a_rows = $("div.flights_a:hidden,div.flights_b:hidden,div.flights_c:hidden,div.flights_d:hidden");
			break;
		case 2: var a_rows = $("div.cars_a:hidden,div.cars_b:hidden"); 		break;
  		case 3: var a_rows = $("div.hotels_a:hidden,div.hotels_b:hidden");	break;
  		case 4: var a_rows = $("div.fh_a:hidden,div.fh_b:hidden");			break;
		case 5: var a_rows = $("div.lmh_a:hidden,div.lmh_b:hidden");			break;
		default: var a_rows = new Array(); break;
	}
	// You can easily get row count with a_rows.length;
	return (a_rows);
}

/* This can be called anytime when the collating of prices is wanted, useful mainly only after sorting by price
 Also fixes the row colors, so they can be left as they are before this
 Second parameter is optional. It is the array of result elements and it can be passed to this
*/
function collateResults(i_page, a_rows) {
	// First, remove all <div class='moreprices'> if there were any
	$('div.topic_hidden_prices').remove();
	
	// Then, get all visible result elements
	// var a_res = getVisibleResultElements(i_page);
	var a_res = a_rows;

	// set vars for for
	var i_row_color_id = 0;
	var prev_price;
	var current_price;
	var b_display_link_to_other_flight_times;
	var b_newprice;
		
	// Start collating logic
	for (var i=0; i < a_res.length; i++) {
		b_display_link_to_other_flight_times = false;
		s_id_list = '*';
		s_current_id = a_res[i].getAttribute("id");
		a_current_id = s_current_id.split("_");
		current_id = a_current_id[a_current_id.length-1];
		this_result_id = current_id;
		current_price = $('#resultprice_'+current_id).text();
		// current_partner = $('#flight_result_'+current_id+' .f_partner:first img:first').attr('alt'); // slow
		// current_partner = $('#flight_result_'+current_id+' img:first').attr('alt');
		current_partner = $('#flight_result_'+current_id+' img:first').attr('alt');
		var j = i+1;
		if (j < a_res.length) {
			s_next_id = a_res[j].getAttribute("id");
			a_next_id = s_next_id.split("_");
			next_id = a_next_id[a_next_id.length-1];
			next_price = $('#resultprice_'+next_id).text();
			next_partner = $('#flight_result_'+next_id+' img:first').attr('alt');
		} else {
			next_price = '';
		}
		
		while (next_price == current_price && current_partner == next_partner) {
			b_display_link_to_other_flight_times = true;
			if (s_id_list == '*') {
				s_id_list = next_id;
			} else {
				s_id_list = s_id_list +','+ next_id;
			}
						
			current_id = next_id;
			// current_price and current_partner are already correct
			j++;
			if (j < a_res.length) {
				s_next_id = a_res[j].getAttribute("id");
				a_next_id = s_next_id.split("_");
				next_id = a_next_id[a_next_id.length-1];
				next_price = $('#resultprice_'+next_id).text(); // eventually either price changes or the result list ends
				next_partner = $('#flight_result_'+next_id+' img:first').attr('alt');
			} else {
				next_price = '';
			}
		}
		
		if (prev_price == current_price && prev_partner == current_partner) {
			// $(a_res[i]).hide();
			a_res[i].style.display = 'hide';
			b_newprice = false;
			if (i_row_color_id % 2 == 0) { 
				s_classname = 'flights_c';
			} else {
				s_classname = 'flights_d';
			}
		} else {
			b_newprice = true;
			i_row_color_id++;
			if (i_row_color_id % 2 == 0) {
				s_classname = 'flights_a';
			} else {
				s_classname = 'flights_b';
			}
			prev_price = current_price;
			prev_partner = current_partner;
		}
		
		a_res[i].className = s_classname; // change classname attribute
		// Also, change onmouseover and onmouseout with jQuery's hover()
		$('#flight_result_'+this_result_id).hover(
			function () { $(this).addClass('flights_hover'); },
			function () { $(this).removeClass('flights_hover'); }
		);
		// $('#flight_result_'+this_result_id).attr('onmouseover',"(this.className)='flights_hover';");
		// $('#flight_result_'+this_result_id).attr('onmouseout',"(this.className)='"+ s_classname +"';");
		
		// if ($('#moreprices_' + this_result_id).text().length > 1) {
		// 	$('#moreprices_' + this_result_id).empty();
		// }
		
		// if (i < 4) {
		// 	alert(prev_price +"\n"+ current_price +"\n"+ prev_partner +"\n"+ current_partner +"\n"+ 
		// 		b_newprice +"\n"+ b_display_link_to_other_flight_times);
		// }
		
		if (b_newprice && b_display_link_to_other_flight_times) {
			$(a_res[i]).append("<div class='topic_hidden_prices' id='moreprices_" + this_result_id
				+ "' onclick=\"event.cancelBubble=true; toggleHidResults('" + s_id_list + "','" + this_result_id
				+ "');\"><div id='moreprices_show_" + this_result_id 
				+ "'><img src='images/price_arrow_down.gif' alt='' /> Näytä muut ajat</div><div id='moreprices_hide_"
				+ this_result_id + "' style='display: none;'><img src='images/price_arrow_up.gif' alt='' />"
				+ " Piilota muut ajat</div></div>");
		}
	}
}

// function flightsAfterLoad(i_results) {
// 	updateCheapestPrice(1);
// 	updateResultsHeading(1, i_results);
// 	updateResultsTotal(i_results, '1');	
// }

/* Function that applies selected filters to results */
function applyFlightFilters() {
	// var start = new Date().getTime();
	var rl = $('#results_list');
	if (rl.length) {
		var fly_return_trip = true; // assume round trip search was made
		var out_classname = '.f_outbound';
		if ($("#flight_result_1 .f_outbound_only").length) { // if exists, one-way flight
			fly_return_trip = false;
			out_classname = '.f_outbound_only';
		}
		
		// find out what filters are now set
		if ($("#fly_out_deptimes_1").is(':checked'))	var fly_out_deptimes_1 = true;
		else											var fly_out_deptimes_1 = false;
		
		if ($("#fly_out_deptimes_2").is(':checked'))	var fly_out_deptimes_2 = true;
		else											var fly_out_deptimes_2 = false;
		
		if ($("#fly_out_deptimes_3").is(':checked'))	var fly_out_deptimes_3 = true;
		else											var fly_out_deptimes_3 = false;
		
		if ($("#fly_out_arrtimes_1").is(':checked'))	var fly_out_arrtimes_1 = true;
		else											var fly_out_arrtimes_1 = false;
		
		if ($("#fly_out_arrtimes_2").is(':checked'))	var fly_out_arrtimes_2 = true;
		else											var fly_out_arrtimes_2 = false;
		
		if ($("#fly_out_arrtimes_3").is(':checked'))	var fly_out_arrtimes_3 = true;
		else											var fly_out_arrtimes_3 = false;
		
		if ($("#fly_out_stops_0").is(':checked'))	var fly_out_stops_0 = true;
		else										var fly_out_stops_0 = false;
		
		if ($("#fly_out_stops_1").is(':checked'))	var fly_out_stops_1 = true;
		else										var fly_out_stops_1 = false;
		
		if ($("#fly_out_stops_n").is(':checked'))	var fly_out_stops_n = true;
		else										var fly_out_stops_n = false;
		
		if (fly_return_trip) {
			if ($("#fly_ret_deptimes_1").is(':checked'))	var fly_ret_deptimes_1 = true;
			else											var fly_ret_deptimes_1 = false;
			
			if ($("#fly_ret_deptimes_2").is(':checked'))	var fly_ret_deptimes_2 = true;
			else											var fly_ret_deptimes_2 = false;
			
			if ($("#fly_ret_deptimes_3").is(':checked'))	var fly_ret_deptimes_3 = true;
			else											var fly_ret_deptimes_3 = false;
			
			if ($("#fly_ret_arrtimes_1").is(':checked'))	var fly_ret_arrtimes_1 = true;
			else											var fly_ret_arrtimes_1 = false;
			
			if ($("#fly_ret_arrtimes_2").is(':checked'))	var fly_ret_arrtimes_2 = true;
			else											var fly_ret_arrtimes_2 = false;
			
			if ($("#fly_ret_arrtimes_3").is(':checked'))	var fly_ret_arrtimes_3 = true;
			else											var fly_ret_arrtimes_3 = false;
			
			if ($("#fly_ret_stops_0").is(':checked'))	var fly_ret_stops_0 = true;
			else										var fly_ret_stops_0 = false;
			
			if ($("#fly_ret_stops_1").is(':checked'))	var fly_ret_stops_1 = true;
			else										var fly_ret_stops_1 = false;
			
			if ($("#fly_ret_stops_n").is(':checked'))	var fly_ret_stops_n = true;
			else										var fly_ret_stops_n = false;
		}
		
		var a_results = getAllResultElements(1); // Find all result elements
		var row_count = a_results.length;
		
		var i=0;
		if ($("#flight_result_0 .tag_cheapest_direct").length) {
			$("#flight_result_0").remove(); // this is special result that can be hidden
			i=1;
		}
		
		var displayed_results = 0;
		for (i; i < row_count; i++) { // see if this result should be shown or not
			
			var showthis = false;
			var row = $(a_results[i]);
			
			var out_deptime = row.find(out_classname + " .f_departure").text();
			out_deptime = out_deptime.substring(0,2) * 1;
			
			if (fly_out_deptimes_1 && out_deptime < 9)
				showthis = true;
			else if (fly_out_deptimes_2 && out_deptime >= 9 && out_deptime < 16) 
				showthis = true;
			else if (fly_out_deptimes_3 && out_deptime >= 16)
				showthis = true;
			
			// if (i == 64) { alert(out_deptime + "\n1 showthis "+showthis); }
			
			if (showthis) { // continue filtering only if there is match from previous filters
				showthis = false;
				var out_arrtime = row.find(out_classname + " .f_arrival").text();
				
				out_arrtime = out_arrtime.substring(0,2) * 1;
				
				if (fly_out_arrtimes_1 && out_arrtime < 9)
					showthis = true;
				else if (fly_out_arrtimes_2 && out_arrtime >= 9 && out_arrtime < 16)
					showthis = true;
				else if (fly_out_arrtimes_3 && out_arrtime >= 16)
					showthis = true;
			}
			
			// if (i == 64) { alert(out_arrtime + "\n2 showthis "+showthis); }
			
			if (showthis) { // apply more filters
				showthis = false;
				var stops = row.find(out_classname + " .f_stops").text();
				stops = stops.charAt(0);
				
				if (fly_out_stops_0 && stops == 's')
					showthis = true;
				else if (fly_out_stops_1 && stops == '1')
					showthis = true;
				else if (fly_out_stops_n && stops > 1)
					showthis = true;
			}
			
			// if (i == 64) { alert(stops + "\n3 showthis "+showthis); }
			
			if (fly_return_trip) {
				if (showthis) { // apply more filters
					showthis = false;
					var ret_deptime = row.find(".f_return .f_departure").text();
					ret_deptime = ret_deptime.substring(0,2) * 1;
								
					if (fly_ret_deptimes_1 && ret_deptime < 9)
						showthis = true;
					else if (fly_ret_deptimes_2 && ret_deptime >= 9 && ret_deptime < 16) 
						showthis = true;
					else if (fly_ret_deptimes_3 && ret_deptime >= 16)
						showthis = true;
				}
				
				// if (i == 64) { alert(ret_deptime + "\n4 showthis "+showthis); }
				
				if (showthis) { // apply more filters
					showthis = false;
					var ret_arrtime = row.find(".f_return .f_arrival").text();
					ret_arrtime = ret_arrtime.substring(0,2) * 1;
					
					if (fly_ret_arrtimes_1 && ret_arrtime < 9)
						showthis = true;
					else if (fly_ret_arrtimes_2 && ret_arrtime >= 9 && ret_arrtime < 16)
						showthis = true;
					else if (fly_ret_arrtimes_3 && ret_arrtime >= 16)
						showthis = true;
				}
				
				// if (i == 64) { alert(ret_arrtime + "\n5 showthis "+showthis); }
				
				if (showthis) { // apply more filters
					showthis = false;
					stops = row.find(".f_return .f_stops").text();
					stops = stops.charAt(0);
					
					if (fly_ret_stops_0 && stops == 's')
						showthis = true;
					else if (fly_ret_stops_1 && stops == '1')
						showthis = true;
					else if (fly_ret_stops_n && stops > 1)
						showthis = true;
				}
				
				// if (i == 64) { alert(stops + "\n6 showthis "+showthis); }
			}
			
			if (showthis) {
				// remove <div class='topic_hidden_prices'> (and their nested elements) if there were any
				row.find('.topic_hidden_prices').remove();
				
				if (displayed_results % 2 == 0)
					row.attr('class', 'flights_a');
				else
					row.attr('class', 'flights_b');
				
				displayed_results++;
			} else {
				row.attr('class', 'flights_c');
			}
		}
		
		// Update upper part of the page. Some optimizations can likely be made
		updateResultsTotal(displayed_results, '1');
		updateCheapestPrice(1);
		updateResultsHeading(1,displayed_results);
	
		// Hide the info about ongoing ordering
		document.getElementById("js_in_progress").style.display = 'none';
	}
	
	// var end = new Date().getTime();
	// var time = end - start;
	// alert("function total time: "+time);
}

/* Function that shows only direct flights or shows all flights. Also used to sort flights. 
	Collates the same partner's same priced results. */
function toggleDirectFlights() {
if (document.getElementById("results_list")) {
	var start = new Date().getTime();
	// Check did user check or uncheck toggleDirectFlights checkbox
	if ($("#fly_checkbox_direct").is(':checked')) { // JQuery is() :checked
		var b_checkbox = true;
	} else {
		var b_checkbox = false;
	}
	
	var b_both = true; // assume round trip search was made
	if ($("#fly_radio_route_selection_2").is(':checked')) { // JQuery is() :checked, if checked, one-way flight
		var b_both = false;
	}
	
	$('#results_list div.topic_hidden_prices').remove(); // remove all <div class='moreprices'> if there were any
	// $('div.topic_hidden_prices').remove(); // remove all <div class='moreprices'> if there were any
	
	// Find all result elements. Depending when user clicked this, results might be ordered by other criteria than
	// price and some of the results might be hidden.
	var a_results = getAllResultElements(1);
	var row_count = a_results.length;
	
	var a_directs = new Array();
	var a_indirects = new Array();
	var i_directs = 0;
	var i_indirects = 0;
	
	if (b_checkbox == true) { // user wants to see only direct flights
		// Get direct and indirect flights to their own arrays 
		for (var i=0; i < row_count; i++) {
			var row = $(a_results[i]);
			// var s_direct_there = new String(row.find("div.f_stops:first").text()); // JQuery find( expr )
			var s_direct_there = row.find("div.f_stops:first").text(); // JQuery find( expr )
			if (s_direct_there != "suora") {
				a_indirects[i_indirects] = row;
				i_indirects++;
			} else {
				if (b_both == true) { // two-way flight
					// var s_direct_back = new String(row.find("div.f_stops:last").text()); // JQuery find( expr )
					var s_direct_back = row.find("div.f_stops:last").text(); // JQuery find( expr )
					if (s_direct_back != "suora") {
						a_indirects[i_indirects] = row;
						i_indirects++;
					} else {
						a_directs[i_directs] = row; // both segments were direct flights
						i_directs++;
					}
				} else { 
					a_directs[i_directs] = row; // only segment in one-way flight was direct
					i_directs++;
				}
			}
		}
	} else { // checkbox was unchecked
		i_directs = row_count;
		a_directs = a_results;
	}
	
	// Then, order the results that are in a_directs and hide the results that are in a_indirects. Works in all cases.
	a_results = new Array();
	var s_price;
	var s_partner;
	for (var j=0; j < i_directs; j++) {
		a_results[j] = new Array();
		row = $(a_directs[j]);
		s_price = new String(row.find("div.f_price").text()); // JQuery find( expr )
		s_partner = row.find('img:first').attr('alt');
		var a_price = s_price.split(" ");
		a_results[j][0] = row;
		a_results[j][1] = a_price[0].replace(',','.');
		a_results[j][2] = s_partner; // compareNumbers can use this to sort by partner name after it has sorted by price
	}
	a_results.sort(compareNumbers); // sort these results by price
	
	// var kaikkiHinnat = '';
	// for (j=0; j < i_directs; j++) {
	// 	kaikkiHinnat = kaikkiHinnat + "j: " + j + "  - " + a_results[j][1] + "\n";
	// }
	// alert(kaikkiHinnat);
	
	var dom_result_list = $("#results_list");
	dom_result_list.empty();
	
	// Collate these results. Set some variables first
	var i_row_color_id = 0;
	var prev_price; var current_price; var next_price;
	var prev_partner; var current_partner; var next_partner;
	var b_display_link_to_other_flight_times;
	var b_newprice;
		
	for (i = 0; i < a_results.length; i++) {
		b_display_link_to_other_flight_times = false;
		s_id_list = '*';
		s_current_id = a_results[i][0].attr("id");
		a_current_id = s_current_id.split("_");
		current_id = a_current_id[a_current_id.length-1];
		this_result_id = current_id;
		current_price = a_results[i][1];
		// current_partner = $('#flight_result_'+current_id+' .f_partner:first img:first').attr('alt'); // slow
		// current_partner = $('#flight_result_'+current_id+' img:first').attr('alt');
		// current_partner = new String(a_results[i][0].find('img:first').attr('alt'));
		current_partner = a_results[i][0].find('img:first').attr('alt');
		j = i+1;
		if (j < a_results.length) {
			s_next_id = a_results[j][0].attr("id");
			a_next_id = s_next_id.split("_");
			next_id = a_next_id[a_next_id.length-1];
			next_price = a_results[j][1];
			// next_partner = $('#flight_result_'+next_id+' img:first').attr('alt');
			// next_partner = new String(a_results[j][0].find('img:first').attr('alt'));
			next_partner = a_results[j][0].find('img:first').attr('alt');
		} else {
			next_price = '';
		}
			
		while (next_price == current_price && current_partner == next_partner) {
			b_display_link_to_other_flight_times = true;
			if (s_id_list == '*') {
				s_id_list = next_id;
			} else {
				s_id_list = s_id_list +','+ next_id;
			}
						
			current_id = next_id;
			// current_price and current_partner are already correct
			j++;
			if (j < a_results.length) {
				s_next_id = a_results[j][0].attr("id");
				a_next_id = s_next_id.split("_");
				next_id = a_next_id[a_next_id.length-1];
				next_price = a_results[j][1]; // eventually either price changes or the result list ends
				next_partner = a_results[j][0].find('img:first').attr('alt');
			} else {
				next_price = '';
			}
		}
		
		if (prev_price == current_price && prev_partner == current_partner) {
			// a_res[i].style.display = 'hide';
			b_newprice = false;
			if (i_row_color_id % 2 == 0) { 
				s_classname = 'flights_c';
			} else {
				s_classname = 'flights_d';
			}
			a_results[i][0].hide();
		} else {
			b_newprice = true;
			i_row_color_id++;
			if (i_row_color_id % 2 == 0) {
				s_classname = 'flights_a';
			} else {
				s_classname = 'flights_b';
			}
			a_results[i][0].show();
			prev_price = current_price;
			prev_partner = current_partner;
		}
		
		a_results[i][0].removeClass(); // remove current classname
		a_results[i][0].addClass(s_classname); // set new classname 
		// Also, change onmouseover and onmouseout with jQuery's hover()
		a_results[i][0].hover(
			function () { $(this).addClass('flights_hover'); },
			function () { $(this).removeClass('flights_hover'); }
		);
		
		if (b_newprice == true && b_display_link_to_other_flight_times == true) {
			a_results[i][0].append("<div class='topic_hidden_prices' id='moreprices_" + this_result_id
				+ "' onclick=\"event.cancelBubble=true; toggleHidResults('" + s_id_list + "','" + this_result_id
				+ "');\"><div id='moreprices_show_" + this_result_id 
				+ "'><img src='images/price_arrow_down.gif' alt='' /> Näytä muut ajat</div><div id='moreprices_hide_"
				+ this_result_id + "' style='display: none;'><img src='images/price_arrow_up.gif' alt='' />"
				+ " Piilota muut ajat</div></div>");
		}
		// var new_result_row = a_results[i][0];
		dom_result_list.append(a_results[i][0]);
		
		// alert ("i " + i + " j " + j + "\nprevs: " + prev_price + " *" + prev_partner + "*\ncurrs: " 
		// 	+ current_price + " *" + current_partner + "*\nnexts: " + next_price + " *" + next_partner + "*");
		// if (i < 2) {	alert(a_results[i][0].html())	}
	}
	
	// Don't forget to append all those results that are in 'a_indirect'
	for (i = 0; i < i_indirects; i++) {
		a_indirects[i].removeClass();
		a_indirects[i].addClass('flights_c');
		a_indirects[i].hide();
		dom_result_list.append(a_indirects[i]);
	}
	
	// Call updateCheapestPrice and updateResultsTotal
	updateResultsTotal(i_directs, '1');
	updateCheapestPrice(1);
	updateResultsHeading(1,i_directs)

	// Hide the info about ongoing ordering
	document.getElementById("js_in_progress").style.display = 'none';
	
	var end = new Date().getTime();
	var time = end - start;
	// alert("rows: "+ row_count +"\nfunction total time: "+time);
}
}

$(document).ready(function() { // jQuery thingie to wait for the document to be ready
	/* FLIGHT RESULT FILTERING - filter by: departure time, arrival time, number of stops.
	should filter also the following: waiting time, total flight time */
	
	// At first, is this flight result?
	if ($("#flight_result_1").length) { // there should be at least 2 flight results for this to make sense
		// How wide viewport is available?
		if ($(window).width() >= 1400) {   // returns width of browser viewport
			$('#results_filter .header_for_horizontal_filter').hide();
			$('#results_filter .header_for_vertical_filter').show();
			
			$('#results_filter .filterset_horizontal').each(function(){
					$(this).attr({ 'class': 'filterset_vertical', 'style': 'margin-left: 0;' });
			});
			
			$('#results_filter .filterset_subtopic_horizontal').attr('class', 'filterset_subtopic_vertical');
			
			$('#results_filter .results_filter_container_horizontal').attr('class', 'results_filter_container');
		}
		$('#results_filter input').change(function() {	checkFlightFilters();		});
	}
	
	// We could loop the entire flight result structure, like this:
	// if ($("#flight_result_0").length) {
	// 	var start = new Date().getTime();
	// 	var test = '';
	// 	var fr_counter = 0;
	// 	while ($("#flight_result_"+fr_counter).length) {
	// 		// Normal way: Look up the results with jQuery
	// 		// test = $("#flight_result_"+fr_counter+" .f_outbound .f_departure").text();
	// 		// test += "\n" + $("#flight_result_"+fr_counter+" .f_return .f_departure").text();
			
	// 		// var outstops = $("#flight_result_"+fr_counter+" .f_outbound .f_stops").text();
	// 		// outstops = outstops[0];
	// 		// var retstops = $("#flight_result_"+fr_counter+" .f_return .f_stops").text();
	// 		// retstops = retstops[0];
	// 		// var fr_price = $("#flight_result_"+fr_counter+" .f_price").text();
	// 		// test += "\n" + outstops + " " + retstops + " price " +fr_price;
			
	// 		// BETTER WAY: store one result to variable and use only it afterwards
	// 		var fr_current = $("#flight_result_"+fr_counter);
	// 		test = fr_current.find(".f_outbound .f_departure").text();
	// 		test += "\n"+ fr_current.find(".f_return .f_departure").text();
						
	// 		var outstops = fr_current.find(".f_outbound .f_stops").text();
	// 		outstops = outstops[0];
	// 		var retstops = fr_current.find(".f_return .f_stops").text();
	// 		retstops = retstops[0];
						
	// 		var fr_price = fr_current.find(".f_price").text();
	// 		test += "\n" + outstops + " " + retstops + " price " +fr_price;
			
	// 		fr_counter++;
	// 	}
		
	// 	var end = new Date().getTime();
	// 	var time = end - start;
	// 	test += "\n loop total time: "+time+" ms, iteration count "+fr_counter;
	// 	// alert(test);
	// }
	
	/* FLIGHT RESULT FILTERING ENDS */
	
	
	if ($("#results_sponsored").length > 0) {
		/* Adds hover style to a sponsored row. */
		var s_hover = "flights_sponsored_hover";
		
		$(".flights_sponsored").hover(
			function () { $(this).addClass(s_hover); },
			function () { $(this).removeClass(s_hover); }
		);
	}
	
	if ($("#store_own_search").length) {
		/* This stores data to Cookie when requested */
		var curCookie = jQuery.cookie('PopResults'); // read current PopResults cookie
		if (curCookie == null)
			return;
		
		if ($("#own_search_id_updated").length) {
			$("#own_search_stored2").show();
			return;
		}
		
		var search_id = $("#sid").text();
		search_id = jQuery.trim(search_id);
		if (search_id == "")
			return;

		// NOTE even if array that is result of split() is empty, its length will be 1
		var a_curCookie = curCookie.split('**');
		var own_searches = a_curCookie[0].split('*'); 
		var latest_searches = a_curCookie[1].split('*');
		
		var max_nr_own_searches = 30;
		
		if (own_searches.length >= max_nr_own_searches) {
			$("#own_searches_full").show();
		} else {
			$("#store_own_search").show();
			$("#store_own_search").click(function () {
				var new_cookie_val = search_id;
				if (own_searches[0].length > 2) {
					for (cookie_i = 0; cookie_i < own_searches.length; cookie_i++) {
						new_cookie_val += '*' + own_searches[cookie_i];
					}
				}
				
				if (latest_searches[0].length > 2) {
					new_cookie_val += '*';
					for (cookie_i = 0; cookie_i < latest_searches.length; cookie_i++) {
						new_cookie_val += '*' + latest_searches[cookie_i];
					}
				} else {
					new_cookie_val += '**';
				}
				
				jQuery.cookie('PopResults', new_cookie_val, {expires: 30, path: '/'} );
				
				// alert("Old cookie:\n" + curCookie);
				// alert("Cookie now:\n" + jQuery.cookie('PopResults'));
				
				$("#store_own_search").hide();
				$("#own_search_stored").show();
			});
		}
	}
	
	/* Hotels results only */
	// if ($("#h_results_top_area").length) {
		//Opens dialog for hotel images layer
		// var $dialog = $('<div></div>')
		// .html('This dialog will show every time!')
		// .dialog({
		// 	autoOpen: false,
		// 	title: 'Basic Dialog'
		// });
		// // h_details_image_div
		// $(".results_heading").click(function(event) {
		// 	$dialog.dialog('open');
		// 	// prevent the default action, e.g., following a link
		// 	return false;
		// });
		// $(".h_details_image_div").click(function(event) {
				// alert('Test');
			// $dialog.dialog('open');
			// event.preventDefault();
			// prevent the default action, e.g., following a link
			// return false;
		// });
	// }
} );

function toggleHotelDetails(hid, forceOpen) {
	var smallHeight = "147px";
	var largeHeight = "290px"; // hotels_la height + 40px!
	
	var resultDiv = $("#hotel_result_"+hid);
	var smallDiv = $("#hotel_small_"+hid);
	var detailsDiv = $("#hotel_details_"+hid);
	
	if (forceOpen) {
		smallDiv.hide();
		resultDiv.height(largeHeight);
		detailsDiv.show();
	} else {
		detailsDiv.toggle();
		smallDiv.toggle();
	}
	
	if (smallDiv.is(':visible'))
		resultDiv.height(smallHeight);
	else {
		resultDiv.height(largeHeight);
		// also display images
		var hid_photos = $("#hotel_details_"+hid +" .hidden_photos").text(); // this is json_encoded string
		hid_photos = jQuery.trim(hid_photos);
		if (hid_photos != "") {
			var obj = jQuery.parseJSON(hid_photos); // image URLs to JS object
			var html_pics = '';
			for (var i = 0; i < obj.length ; i++) { // obj[i] contains a single URL to picture
				html_pics += "\n\t\t<img class='h_photo_list' src='"+ obj[i] +"' alt='More photos' />";
			}
			$("#hotel_details_"+hid +" .h_details_image_div").append(html_pics);
			// If user clicks more than once, it creates more and more pictures
			$("#hotel_details_"+hid +" .hidden_photos").text(" "); // this removes string that contained img urls
		}
	}
}


function showMarkers(max) {
	//show the correct amount of markers
	if(hotelMarkers.length == max);	//don't do anything
	else if((max == 0 && hotelMarkers.length == 30) || hotelMarkers.length < max)	//missing markers (probably), add them
		addMarkers(max);
	else
		toggleMarkerVisibility(max);	//just hide or show existing markers

	//rewrite the text and link
	//showing all the markers
	if(max == 0) {
		$("#show_all_markers_div").hide();
		$("#show_some_markers_div").show();
	}
	//showing only max markers
	else {
		$("#show_some_markers_div").hide();
		$("#show_all_markers_div").show();
	}
}



function open_image_dialog(hotel_name, hid) {
	var images = $("#hotel_details_"+ hid +" .h_details_image_div").html();
	var dialog = $("<div></div>")
		.html(images)
			.dialog({
			autoOpen: false,
			title: hotel_name, 
			width: 800, 
			height: 600,
			closeText: 'sulje ',
			draggable: false, 
			modal: true
		});
	dialog.dialog('open');
}

