
//---------------------------------------------------- POPULATE RESULTS TABLE -----------------------------------
function insertRow(id)
{
	$("#tbody").append("<tr id='row" + id + "'></tr>");
}

function insertData(i, data)
{
	$("#row" + i).append("<td>" + data + "</td>");
}

function noData()
{
	$("#tbody").empty();
	$("#pagecount").empty();
	$("#debugurl").empty();
	$("#prev").empty();
	$("#next").empty();
	$("#tbody").append("<tr><td align='center' colspan='9'>We are currently working to build relationships with appropriate clinics offering this procedure.</td></tr>");
}

function viewDetails(id, clinic, treatmentPrice)
{
	var currency = $("#currency :selected").val();
	var name = clinic.name;
	
	$("#tbody").append("<tr id='row" + id + "a'><td colspan='8' class='viewdetails'><a onClick='insertClinicRow(" + id + ", "+treatmentPrice+"); return false' href='#'><strong>Click here to <span class='darkblue'>view clinic profile</span> (expands down) &gt;&gt;</strong></a></td><td class='enquiry'><a href='#' onclick='showEnquiryForm("+id+",\""+name+"\",\"enquiryForm\",\"enquiryFormDiv\",600,600,\""+currency+"\","+treatmentPrice+")'>MAKE&nbsp;ENQUIRY</a></td></tr>");	
}

//Insert table row for slide down clinic details
function insertClinicRow(id, price)
{
	$('#treatmentPrice').val(price);
	if ($("#clinic" + id).hasClass("active"))
		{
			detailsSlide(id);
		}

	else
		{
			$("#row" + id + "a").after("<tr id='clinic" + id + "details'><td colspan='12'><div id='clinic" + id + "' class='detailscontainer'></div></td></tr>");
			populateDetails(id, "overview");
			
		}return false;
}

//slide to reveal clinic details
function detailsSlide(id)
{
	$("#clinic" + id).slideToggle("slow", function ()
	    {
		    if (!$("#clinic" + id).hasClass("active"))
			     {
				    $("#clinic" + id + "details").remove();
			     }
	     }
	 );
	$("#clinic" + id).toggleClass("active");
	return false;
}

//populate clinic details
function populateDetails(id, page)
{
var url = "/clinic/" + id; 
	$.ajax({
	         
		   //url: "/assets/"+page+".html",

           url: url,

           success: function(html)
	           { 
					$("#loading").hide();
					var clinic =$("#clinic"+id);
			   
		           
				           clinic.append(html);
			           
					clinic.children(".cliniccontent").hide();
					$("#overview"+id).show();
					
					detailsSlide(id);
					
	           }
	       
	       });
}
function clinicNav(section, clinic) {
	$("#clinic"+clinic).children(".cliniccontent").hide();
	$("#"+section).show();
}

function slidetoggle(id) {
		
		$("#" + id).slideToggle("slow");
		return false;
}

function boxSlide(id)
{
	$("#" + id).slideToggle("slow");
	$("#" + id).toggleClass("active");

	if ($("#" + id).hasClass("active"))
		{
			$("#" + id + "button").children("span").text("Close");
			$("#" + id + "button").children("img").attr({

            src: "/assets/images/search/close.jpg",

            title: "Minimize",

            alt: "Minimize"
			        });
		} 

	else
		{
			$("#" + id + "button").children("span").text("Expand");
			$("#" + id + "button").children("img").attr({

            src: "/assets/images/search/expand.jpg",

            title: "Maximize",

            alt: "Maximize"
			        });
		}

	return false;
}

function pageselectCallback(page_id, jq)
{
	getResults(page_id);
}

//Flag to only populate price slider once
minmaxFlag = false;
function populateTbl(totalresults, pagenumber)
{
	//populate price slider with max and min prices
	var maximumPrice = parseInt(response["maxprice"]);
	var minimumPrice = parseInt(response["minprice"]);
	
	if (minmaxFlag == false )
		{
			$("#pricefield").children(".sliderComponent").remove();
			var increment = (maximumPrice - minimumPrice) / 18;
			$("#valueA").empty();
			$("#valueB").empty();
			$("#valueA").append("<option value=" + minimumPrice + " selected='selected'>" + minimumPrice + "</option>");
			$("#valueB").append("<option value=" + minimumPrice + ">" + minimumPrice + "</option>");

			for (i = 1;i < 19;i++)
				{
					var price = Math.round(minimumPrice + (increment * i));
					$("#valueA").append("<option value=" + price + ">" + price + "</option>");
				}

			for (i = 1;i < 18;i++)
				{
					var price = Math.round(minimumPrice + (increment * i));
					$("#valueB").append("<option value=" + price + ">" + price + "</option>");
				}

			$("#valueB").append("<option value=" + maximumPrice + " selected='selected'>" + maximumPrice + "</option>");
			minmaxFlag = true
			//price slider
		$('select#valueA, select#valueB').accessibleUISlider({width: 213});
	
		
		             }

	             //empty table data
	             $("#tbody").empty();

	$("#pagecount").empty();

	$("#debugurl").empty();

	$("#prev").empty();

	$("#next").empty();

	//check for length of results
	// Create pagination element
	$("#Pagination").pagination(totalresults, {

                                current_page: pagenumber,

                                num_edge_entries: 2,

                                items_per_page: 20,

                                callback: pageselectCallback
	                            });

	//insert table rows
	var checked = false;
	var countrySelected = true;
	$('#consultation input[@type=checkbox]').filter(':checked').each(function ()
	        {
		        checked=true;
	        }
	)
	var country = $("#country :selected").val();
	if (country==null || country==""){
		countrySelected=false;
	}
	
	for (i = 0;i < response.items.length;i++)
		{
			insertRow(i);
			//insert data into table cells
			$("#row" + i).append("<td>" + response.items[i]["name"] + "<br />" + response.items[i]["country"] + "</td>");
			$("#row" + i).append("<td>" + response.symbol + " " + response.items[i]["price"] + "</td>");
			$("#row" + i).append("<td>" + response.items[i]["flight_time"] + "</td>");
			//Add room included tick or cross
			if (response.items[i]["roominclusive"] == "false")
				{
					$("#row" + i).append("<td><img src='/assets/images/search/small_cross.jpg' alt='No' /></td>");
				}

			else
				{
					$("#row" + i).append("<td><img src='/assets/images/search/small_tick.jpg' alt='Yes' /></td>");
				}
			//Add Drop off tick or cross
			if (response.items[i]["drop_off"] == "false")
				{
					$("#row" + i).append("<td><img src='/assets/images/search/small_cross.jpg' alt='No' /></td>");
				}

			else
				{
					$("#row" + i).append("<td><img src='/assets/images/search/small_tick.jpg' alt='Yes' /></td>");
				}
			//Add Pre Post ticks or crosses
			if (response.items[i]["consultation"] == "PREPOST")
				{
					$("#row" + i).append("<td><img src='/assets/images/search/small_tick.jpg' alt='Yes' /></td>");
					$("#row" + i).append("<td><img src='/assets/images/search/small_tick.jpg' alt='Yes' /></td>");
				}
			else if(response.items[i]["consultation"] == "PRE")
				{
					$("#row" + i).append("<td><img src='/assets/images/search/small_tick.jpg' alt='Yes' /></td>");
					$("#row" + i).append("<td><img src='/assets/images/search/small_cross.jpg' alt='No' /></td>");
				}
			else if(response.items[i]["consultation"] == "POST")
				{
					$("#row" + i).append("<td><img src='/assets/images/search/small_cross.jpg' alt='No' /></td>");
					$("#row" + i).append("<td><img src='/assets/images/search/small_tick.jpg' alt='Yes' /></td>");
				}
			else if(response.items[i]["consultation"] == "" && !checked && !countrySelected)
				{
					$("#row" + i).append("<td>Use 'Advanced Criteria' to view</td>");
					$("#row" + i).append("<td>Use 'Advanced Criteria' to view</td>");
				}
			else if(response.items[i]["consultation"] == "" && countrySelected)
			{
				$("#row" + i).append("<td><img src='/assets/images/search/small_cross.jpg' alt='No' /></td>");
				$("#row" + i).append("<td><img src='/assets/images/search/small_cross.jpg' alt='No' /></td>");
			}
			//Add doc experience data	
			var expData = "";

			for (var k in response.items[i]["doc_exp"])
				{
					if (expData == "")
						{
							expData = response.items[i]["doc_exp"][k];
						}

					else
						{
							expData = expData + ", " + response.items[i]["doc_exp"][k];
						}
				}
			if(expData != ""){
			$("#row" + i).append("<td>" + expData + "</td>");
			}else{
			$("#row" + i).append("<td> - </td>");
			}
			var accredData = "";

			for (var k in response.items[i]["accreds"])
				{
					if (accredData == "")
						{
							accredData = response.items[i]["accreds"][k];
						}

					else
						{
							accredData = accredData + ", " + response.items[i]["accreds"][k];
						}
				}
			if(accredData != ""){
			$("#row" + i).append("<td>" + accredData + "</td>");
			}else {
			$("#row" + i).append("<td> - </td>");
			}
			//$("#row"+i).append("<td>"+response.items[i]["treatmentDays"]+"</td>");
			/*if(response.items[i]["roominclusive"]===false) {
								$("#row"+i).append("<td><img src='/assets/images/search/tick.gif' alt='' /></td>");
							}	*/
			var clinicId = response.items[i]["clinicid"];
			viewDetails(clinicId, response.items[i], response.items[i]["price"]);
		}
}

//function to select countries OR uk cities for preferred destinations
function treatmentDestination(loc)
{
	if (loc == "uk")
		{
			$('#countryleft input[@type=checkbox]').filter(':checked').each(function ()
			        {
				        $(this).attr('checked', '');
			        }
			 );
		}

	if (loc == "abroad")
		{
			$('#countryright input[@type=checkbox]').filter(':checked').each(function ()
			        {
				        $(this).attr('checked', '');
			        }

			                                                                );
		}

	getResults(0);
}

//detect if price slider moves so that price is added to search URL
priceFlag = false;
function checkPriceSlider(slider)
{
	var handleId = slider.handle.attr('id');

	if (handleId == "handle_valueA" || handleId == "handle_valueB" )
		{
			priceFlag = true;
		}

	getResults(0);
}

currencyFlag = false;
//if currency is changed, currency is added to URL
function checkCurrencyChange()
{
	//flag indicates that price details should be added to URL
	priceFlag = false;
	//flag indicates new min and max values and slider needs re-populating
	minmaxFlag = false;
	currencyFlag = true;
	getResults(0);
}

//get cities from selected country
function getCities()
{
	var countrycode = $("#startcountry").val();
	$.ajax({

           type: "GET",

           url: "/cities.do?countryid=" + countrycode,

           success: function(msg)
	           {
					$("#loading").hide();
		           response = JSON.parse(msg, function (key, value)
		                                 {
			                                 var type;

			                                 if (value && typeof value === 'object')
				                                 {
					                                 type = value.type;

					                                 if (typeof type === 'string' && typeof window[type] === 'function')
						                                 {
							                                 return new (window[type])(value);
						                                 }
				                                 }

			                                 return value;
		                                 }

		                                );
		           $("#startLoc").html("");
				   $("#startLoc").append("<option value=''>The city I live closest to</option>");
		           $.each(response.items, function(i, val)
		                  {

			                  $("#startLoc").append("<option value='" + this.code + "'>" + this.name + "</option>");

		                  }

		                 );

	           }
	       });
}

function getOriginCities()
{
	var countrycode = $("#startcountry").val();
	$.ajax({

           type: "GET",

           url: "/origincities.do?countryid=" + countrycode,

           success: function(msg)
	           {
					$("#loading").hide();
		           response = JSON.parse(msg, function (key, value)
		                                 {
			                                 var type;

			                                 if (value && typeof value === 'object')
				                                 {
					                                 type = value.type;

					                                 if (typeof type === 'string' && typeof window[type] === 'function')
						                                 {
							                                 return new (window[type])(value);
						                                 }
				                                 }

			                                 return value;
		                                 }

		                                );
		           $("#startLoc").html("");
				   $("#startLoc").append("<option value=''>The city I live closest to</option>");
		           $.each(response.items, function(i, val)
		                  {

			                  $("#startLoc").append("<option value='" + this.code + "'>" + this.name + "</option>");

		                  }

		                 );

	           }
	       });
}

url = "";
//-------------------------------------------------- AJAX FUNCTION (getResults) -----------------------------
function getResults(pagenumber, uri)
{
	//search criteria variables
	

	if (uri != null && uri != "")
		{
			url = uri;
		}

	else
		{
			//pull values from search sliders and dropdowns
			var treatment = treatmentCode; //$("#valueA :selected").text();
			var minprice = $("#valueA :selected").text();
			var maxprice = $("#valueB :selected").text();
			var currency = $("#currency :selected").val();
			var minflight = $("#valueC :selected").val();
			var maxflight = $("#valueD :selected").val();
			var startloc = $("#startLoc :selected").val();
			var pre = $("#pre :selected").text();
			var post = $("#post :selected").text();

			//filter through checked countries for prefferred destination
			var countries = "";
			$('#countries input[@type=checkbox]').filter(':checked').each(function ()
			        {
				        countries = countries + (this.value) + ",";
			        }

			                                                               );
			countries = countries.substring(0, countries.length - 1);

			//filter through checked uk cities for prefferred destination
			var ukCities = "";
			$('#ukcities input[@type=checkbox]').filter(':checked').each(function ()
			        {
				        ukCities = ukCities + (this.value) + ",";
			        }

			                                                                );
			ukCities = ukCities.substring(0, ukCities.length - 1);

			//pre AND/OR post consultation
			var prepost = "";
			$('#consultation input[@type=checkbox]').filter(':checked').each(function ()
			        {
				        prepost = prepost + (this.value) + ",";
			        }

			                                                                );

			//pre post consultation country
			var prepostCountry = $("#country :selected").val();


			//---------------------------------------- CREATE SEARCH URL ------------------------------------
			//minimum URL allowed
			url = "/search/" + treatment + "/";
			//add flight details if starting location is selected

			if (startloc != "")
				{
					url += startloc + "/" + minflight + "/" + maxflight + "/";
				}

			//add price details if slider has moved
			if (priceFlag == true)
				{
					url += minprice + currency + "/" + maxprice + currency + "/";
				}else if(currencyFlag ==true) {
					url += currency + "/" + currency + "/";
				}
			
			
			//add prefferred destination countries OR UK cities
			if (countries != "" || ukCities!="")
				{
					
					url += "c:" + countries ;
					if (ukCities!=""){
						url +=  ","+ukCities;
					}
					url+="/";
				}

			
			//add pre post details IF country has been chosen
			if (prepost == "" && prepostCountry != "")
				{
					url += "any," + prepostCountry + "/" + pagenumber;
				}

			else if(prepost != "" && prepostCountry != "")
				{
					url += prepost + prepostCountry + "/" + pagenumber;
				}
			else
				{
					url += pagenumber;
				}
			
		}

	//----------------------------------------------- JQUERY AJAX -------------------------
	
	$("#loading").ajaxStart(function(){
		$(this).show();
	});

	$.ajaxSetup(
	    {
        beforeSend:
	        function(xhr)
	        {
		        xhr.setRequestHeader( "x-search-result-type", "text/json" );
	        }
	    }

	);

	$.ajax({

           type: "GET",

           url: url,

           success: function(msg) 
	           { 
			   $("#loading").hide();
		           response = JSON.parse(msg, function (key, value)
		                                 {
			                                 var type;

			                                 if (value && typeof value === 'object')
				                                 {
					                                 type = value.type;

					                                 if (typeof type === 'string' && typeof window[type] === 'function')
						                                 {
							                                 return new (window[type])(value);
						                                 }
				                                 }

			                                 return value;
		                                 }

		                                );

		           var totalresults = response.total;
		           var numberofpages = Math.ceil(totalresults / 20);
				   if(totalresults != 0) {
		           populateTbl(totalresults, pagenumber);
				   } else {
				   noData();
				   }
		           
		           $("#debugurl").append("Search URL = " + url);
				   
	           },

           error: function()
	           {
		           $("#tbody").empty();
		           $("#debugurl").empty();
		           $("#debugurl").append("Search URL = " + url);
	           }
	       });


}

function provideUrl() {
	showSendToFriend(url)
}

