DataDisplay = function(filterName)
{
  this.actualPage = 1;	
  this.progress = 0;
  this.progressCounter = 0;
  this.progressInterval = false;

  this.actualResult = new Array();
  this.recordPerPage = 10;
  this.filterList = new Array();

  this.supplierList = new Array();
  this.airLineList = new Array();
  this.stopList = new Array();
  this.ticketList = new Array();
   
  this.otherDepartList = new Array();
  this.listPageViewId = new Array('pageView1', 'pageView2');
  this.listPageViewInfo = new Array('pageInfo1', 'pageInfo2');

  this.results = new Array();
  
  this.addFilter =  function(type, value)
  {
	  this.filterList[this.filterList.length] = new Array(type, value);
	  this.actualResult = this.resultsFiltrate();
	  this.actualResult = this.resultsFiltrate();
	  this.actualPage = 1;
	  this.makePageBar();
	  this.displayResult();
  }
 
  this.removeFilter =  function(type, value)
  {
	  temp = new Array();
	  for(i=0;i<this.filterList.length;i++)
		  if(!(this.filterList[i][0]==type && this.filterList[i][1] == value))
			  temp[temp.length] = this.filterList[i];
	  this.filterList = temp;
	  this.actualResult = this.resultsFiltrate();
	  this.actualPage = 1;
	  this.makePageBar();
	  this.displayResult();

  }

  this.dialogBox = false;
  this.showStops = function(id, type)
  {
	/*
     [0] => Array
     (
         [department] => Array
             (
                 [airport_code] => BHX
                 [airport_name] => Birmingham International Airport
                 [airline] => 
                 [date_time] => 2009-11-20 06:00
                 [flight_number] => 
                 [terminal] => 
                 [plain_name] => 
             )

         [arrival] => Array
             (
                 [airport_code] => AMS
                 [airport_name] => Amsterdam Schiphol Airport
                 [airline] => 
                 [date_time] =>  08:15
                 [flight_number] => 
                 [terminal] => 
                 [plain_name] => 
             )

     )
  */
    var result = this.results[id];

	var stops_out = "<table cellspacing=5>"; 
	for (i in result[type])
	{
	  var dep = result[type][i]['department'];
	  var arr = result[type][i]['arrival'];

	  stops_out += "<tr>";
	  
	  stops_out += "<td valign=top>";
	  stops_out += "<div><b>Departure:</b><br><b>Airport</b> "+dep.airport_name.substring(0, 25)+" ("+dep.airport_code+")</div>";

	  if (dep.airline)		stops_out += "<div><b>Airline:</b> "+dep.airline+"</div>";
	  if (dep.date_time)	stops_out += "<div><b>Date/Time:</b> "+dep.date_time+"</div>";
	  if (dep.flight_number)	stops_out += "<div><b>Flight number:</b> "+dep.flight_number+"</div>";
	  if (dep.terminal)		stops_out += "<div><b>Terminal:</b> "+dep.terminal+"</div>";
	  if (dep.plain_name)	stops_out += "<div><b>Plane name:</b> "+dep.plain_name+"</div>";
	  stops_out += "<br><br></td>";
	  
	  stops_out += "<td valign=top>";
	  stops_out += "<div><b>Arrival</b><br><b>Airport:</b> "+arr.airport_name.substring(0, 25)+" ("+arr.airport_code+")</div>";
	  
	  if (arr.airline)		stops_out += "<div><b>Airline:</b> "+arr.airline+"</div>";
	  if (arr.date_time)	stops_out += "<div><b>Date/Time:</b> "+arr.date_time+"</div>";
	  if (arr.flight_number)stops_out += "<div><b>Flight number:</b> "+arr.flight_number+"</div>";
	  if (arr.terminal)		stops_out += "<div><b>Terminal:</b> "+arr.terminal+"</div>";
	  if (arr.plain_name)	stops_out += "<div><b>Plane name:</b> "+arr.plain_name+"</div>";
	  stops_out += "</td>";
	  
	  stops_out += "</tr>";
	}
	stops_out += "</table>"; 

  var out ='<div id="results_description">'+
           '<div class="fltlft">'+
                '<dl>'+
                    '<dt class="price">&pound;'+number_format(result.Price, 2, '.', '')+'</dt>'+
                    '<dd><a href="#"><img src="http://xml.fly.co.uk/images/supplierlogos/'+result.SuplierCode+'.gif" alt="'+result.SuplierCode+'"/></a></dd>'+ 
                '</dl>'+
          '</div>'+
          '<div class="fltlft">'+
                '<dl>'+
                    '<dt>'+result[type][0].department.airport_name.substring(0, 15)+' ('+result[type][0].department.airport_code+')</dt>'+
                    '<dd>'+result[type][0].department.flight_number+'</dd>'+
                    '<dd>to '+result[type][ result[type].length - 1].arrival.airport_name.substring(0, 15)+' ('+result[type][ result[type].length -1 ].arrival.airport_code+')</dd>'+
                '</dl>'+
            '</div>'+
            '<div class="fltlft">'+
            	'<a href="#"><img src="http://xml.fly.co.uk/images/airline_thumbnails/'+result.airline+'.png"  alt="'+result.airline+'" /></a>'+
            '</div>'+
         '</div>'+
         '<div class="fltlft">'+stops_out+'</div>';

	var titleText = "Journey Details (" + result['SuplierCode']+")";

	moreInformationLink = result.Link;

	if ( !this.dialogBox)
	{
		$("#dialog").dialog({
			bgiframe: true,
			title: titleText,
			resizable: true,
			height:350,
			width:640,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'More Information': function()
				{
				   window.open(moreInformationLink,'moreInformation');
				   $(this).dialog('close');
				},
				Cancel: function()
				{
					$(this).dialog('close');
				}
			}
		});

		this.dialogBox = $("#dialog");
	}

	else
	{
	  this.dialogBox.data('title.dialog', titleText); 
	  this.dialogBox.dialog('open');
	}
	this.dialogBox.html(out);

	this.dialogBox.data('title.dialog', titleText); 

  }

  this.makeOneResult = function(data, indexID)
  {
	  if(data.flightBA)
		  returnRoute =  '<dl>'+
          					'<dt>'+data.flightBA[0].department.airport_name.substring(0, 12)+' ('+data.flightBA[0].department.airport_code+')</dt>'+
          					'<dd>'+data.flightBA[0].department.flight_number+'</dd>'+
          					'<dd>to '+data.flightBA[data.flightBA.length-1].arrival.airport_name.substring(0, 15)+' ('+data.flightBA[data.flightBA.length-1].arrival.airport_code+'))</dd>'+
							'<dd>'+
								((data.flightBA.length > 1)? ('<a href="#" onClick="Display.showStops('+indexID+', \'flightBA\')">Stops '+(data.flightBA.length-1)+'</a>'):'')+
								((data.flightBA.length == 1)? ('<a href="#" onClick="Display.showStops('+indexID+', \'flightBA\')">Flight details</a>'):'')+
							'</dd>'+
      					'</dl>';
	  else 
		  returnRoute = '<dl>'+
		  					'<dt>&nbsp;</dt>'+
		  					'<dd>&nbsp;</dd>'+
		  					'<dd>&nbsp;</dd>'+
		  				'</dl>';

	  oneResult = '<!--result-->'+          
        '<div id="results_description">'+
           '<div class="fltlft">'+
                '<dl>'+
                    '<dt class="'+ ((data.Price > 1000 || data.Price.indexOf(',') == 1)?'price_big':'price') +'">&pound;'+number_format(data.Price, 2, '.', '')+'</dt>'+
                    '<dd><a href="#"><img src="http://xml.fly.co.uk/images/supplierlogos/'+data.SuplierCode+'.gif" alt="'+data.SuplierCode+'"/></a></dd>'+                    
                '</dl>'+
          '</div>'+	            
          '<div class="fltlft">'+
                '<dl>'+
                    '<dt>'+data.flightAB[0].department.airport_name.substring(0, 15)+' ('+data.flightAB[0].department.airport_code+')</dt>'+
                    '<dd>'+data.flightAB[0].department.flight_number+'</dd>'+
                    '<dd>to '+data.flightAB[data.flightAB.length-1].arrival.airport_name.substring(0, 15)+' ('+data.flightAB[data.flightAB.length-1].arrival.airport_code+')</dd>'+
                    '<dd>'+
						((data.flightAB.length > 1)? ('<span class="link" onClick="Display.showStops('+indexID+', \'flightAB\')">Stops '+(data.flightAB.length-1)+'</span>'):'')+
						((data.flightAB.length == 1)?('<span class="link" onClick="Display.showStops('+indexID+', \'flightAB\')">Flight details</span>'):'')+
					'</dd>'+
                '</dl>'+
            '</div>'+
            '<div class="fltlft">'+returnRoute+'</div>'+            
            '<div class="fltlft">'+
            	'<a href="#"><img src="http://xml.fly.co.uk/images/airline_thumbnails/'+data.airline+'.png"  alt="ba" /></a>'+
            '</div>'+
            '<div class="fltrt">'+    
                '<div id="block">'+
                	'<a href="'+data.Link+'" class="getflight_rollover" target="_blank">View Flights</a> </div>'+      
            '</div>'+        
         '</div><!--end result-->';	

	return oneResult;  
  }

  
  this.oneFiltrate = function(list, element, price, link)
  {
	  
	  find = false;
	  for(i=0;i<list.length;i++)
	  {
		  if(list[i][0] == element)
		  {
			//alert(element);  
			find=true;
			if(parseFloat(list[i][1]) > parseFloat(price))
			{
				
				list[i] = new Array(element, price, link);
			}
		  }
	  }
	  if(!find)
		  list[list.length] = new Array(element, price, link);

	  return list;
	  
  }

  this.hasFilter = function(result)
  {
	  for(i=0;i < this.filterList.length;i++)
	  {
		  if(this.filterList[i][0] == 'carrier')
			  if(result.SuplierCode == this.filterList[i][1])
				  return true;
		  if(this.filterList[i][0] == 'airline')
			  if(result.airline == this.filterList[i][1])
				  return true;
		  if(this.filterList[i][0] == 'stop')
		  {
			  stopNum = result.flightAB.length;
			  if(stopNum < 2) stopName = 'Direct';
			  else if(stopNum == 2) stopName = 'One';
			  else if(stopNum > 2) stopName = 'More';
			  if(stopName == this.filterList[i][1])
				  return true;
		  }
		  if(this.filterList[i][0] == 'depart')
			  if(result.flightAB[0].department.airport_name.substring(0, 15) == this.filterList[i][1])
				  return true;
		  if(this.filterList[i][0] == 'ticket')
			  if(result.classType != this.filterList[i][1])
				  return true;
			 
	  }
	  return false;
  }

  this.showAdds = function(ads_results)
  {
  	  var out = "";
	  for (var index in ads_results)
	  {
  	    out += '<div class="cola-content cola-bgdiff">'+
 		  '<dl>'+
		    '<dt><a href="'+ads_results[index]['mlink']+'" target="_blank">'+ads_results[index]['title']+'</a></dt>'+
		    '<dd>'+ads_results[index]['desc']+'</dd>'+
		  '</dl>'+
		'</div>';
	  }

	  _$('sponsoredAds').style.display = "block";
	  _$('sponsoredAds').innerHTML = out;
  }

  this.resultsFiltrate = function()
  {
	  listReturn = new Array()
	  for (var index in this.results)
		  if(!this.hasFilter(this.results[index]))
			  listReturn[listReturn.length] = index;

	  return listReturn;
  }

  this.updateProgressBar = function()
  {

	  if (this.progress > this.progressCounter)
		this.progressCounter += 2;
	  else
	    clearInterval(this.progressInterval);

	  $("#progressbar").progressbar('value',  Display.progressCounter);
  }

  this.updateResults = function(results, progress)
  {
	  this.progress = progress;

	  clearInterval(this.progressInterval);
	  this.progressInterval = setInterval("Display.updateProgressBar()", 10);

	  if(results.data.length)
	  {
		  _$('waitPage').style.display = 'none'; 
		  _$('resultPage').style.display = '';
		  for (var index in results.data)
		  {
		  
			  this.results[this.results.length] = results.data[index];
			  this.supplierList = this.oneFiltrate(this.supplierList, results.data[index].SuplierCode, results.data[index].Price, results.data[index].Link);
			  this.airLineList = this.oneFiltrate(this.airLineList, results.data[index].airline, results.data[index].Price, results.data[index].Link);
			  stopNum = results.data[index].flightAB.length;
			  if(stopNum < 2) stopName = 'Direct';
			  else if(stopNum == 2) stopName = 'One';
			  else if(stopNum > 2) stopName = 'More';
			  this.stopList = this.oneFiltrate(this.stopList, stopName, results.data[index].Price,results.data[index].Link );
			  this.ticketList = this.oneFiltrate(this.ticketList, results.data[index].classType, results.data[index].Price, results.data[index].Link);
			  this.otherDepartList = this.oneFiltrate(this.otherDepartList, results.data[index].flightAB[0].department.airport_name.substring(0, 15), results.data[index].Price, results.data[index].Link);
		  }
	
		  this.results.sort(function(a,b){return (a.Price-b.Price);})
		  this.actualResult = this.resultsFiltrate();
		  this.actualPage = 1;
		  this.makePageBar();
		  this.displayResult();
	
		  this.makeFilter('carrier', this.supplierList, 'supplierlogos');
		  this.makeFilter('airline', this.airLineList, 'airline_thumbnails');
		  
		  this.makeFilter('stop', this.stopList, '');
		  this.makeFilter('depart', this.otherDepartList, '');

		  this.makeTicketFilter('ticketTypes', this.ticketList);
		  _$('NumOfFlight').innerHTML = this.actualResult.length;	  
	  }

	  if(progress == 100) 
	  {
		  _$("progressbar").style.display = 'none';
		  if(!this.results.length)
		  {
			  _$('waitPage').style.display = 'none'; 
			  _$('notFoundPage').style.display = '';
		  }
	  }
  }

  
  
  this.displayResult = function()
  {
	  _$('resultContener').innerHTML = '';
	  
	  
	  if(this.actualResult.length)
	  {
		  for(i=(this.actualPage - 1)*this.recordPerPage;i<this.actualResult.length && i < (this.actualPage)*this.recordPerPage;i++ )
			  _$('resultContener').innerHTML += this.makeOneResult(this.results[this.actualResult[i]], this.actualResult[i]);
	  }
	  else
		  _$('resultContener').innerHTML = '<span style="font-size:14px; padding:16px; color:red;"><center>Sorry there were no results for your filter.</center></span>';
  }

  this.makeFilter = function(id, list, image_dir)
  {
	  
	  list.sort(function(a,b){return (a[1]-b[1]);});
	  if(list.length > 1)
	  {
		  filterHtml = '';
		  if(image_dir)
			  for(i=0;i<list.length;i++)
			  {
				  filterHtml +=
					  		'<!--  START-->'+             
					  		'<div class="checkbox"><input name="#" id="#" value="#" onClick="if(this.checked)Display.removeFilter(\''+id+'\', \''+list[i][0]+'\');else Display.addFilter(\''+id+'\', \''+list[i][0]+'\');" checked="checked" type="checkbox"/></div>'+   
					  		'<div class="carrierlabel"><a href="#"><img src="http://xml.fly.co.uk/images/'+image_dir+'/'+list[i][0]+'.png"  alt="'+list[i][0]+'" /></a></div>'+
					  		'<div class="best_price"><a target="_blank" href="'+list[i][2]+'">&pound;'+number_format(list[i][1], 2, '.', ',')+'</a></div>'+
					  		'<!--  END--><div class="clearBoth"></div>';
			  }
		  else
			  for(i=0;i<list.length;i++)
			  {
				  filterHtml +=
					  		'<!--  START-->'+             
					  		'<div class="checkbox"><input name="#" id="#" value="#" onClick="if(this.checked)Display.removeFilter(\''+id+'\', \''+list[i][0]+'\');else Display.addFilter(\''+id+'\', \''+list[i][0]+'\');" checked="checked" type="checkbox"/></div>'+   
					  		'<div class="otherlabel"><label>'+list[i][0]+'</label></div>'+
					  		'<div class="best_price"><a target="_blank" href="'+list[i][2]+'">&pound;'+number_format(list[i][1], 2, '.', ',')+'</a></div>'+
					  		'<!--  END--><div class="clearBoth"></div>';
			  }

	     _$(id+'Field').style.display = '';	 
		 _$(id+'Result').innerHTML = filterHtml;	 
	  }
	  else
		  _$(id+'Field').style.display = 'none';	 
  }

  
  

  this.getClassTicket = function(value)
  {
	  temp = new Array();
	  for(i=0;i<this.filterList.length;i++)
		  if(this.filterList[i][0]!='ticket')
			  temp[temp.length] = this.filterList[i];
	  this.filterList = temp;

	  if(value == 'all')
	  {
		  _$('ticketIDAll').className = 'selected';
		  for(i=0;i<this.ticketList.length;i++) _$('ticketID'+i).className = 's_tab';
	  }
	  else
	  {
		  this.filterList[this.filterList.length] = new Array('ticket', value);

		  _$('ticketIDAll').className = 's_tab';
		  for(i=0;i<this.ticketList.length;i++)
		  {
			  if(this.ticketList[i][0] == value)
				  _$('ticketID'+i).className = 'selected';
			  else
				  _$('ticketID'+i).className = 's_tab';
				  
			  
		  }
	  }
	  

	  this.actualResult = this.resultsFiltrate();
	  this.actualPage = 1;
	  this.makePageBar();
	  this.displayResult();

  }
  
  
  this.makeTicketFilter = function(id, list)
  {
	 /*
	  * 
	  * 
	  * 
	  * 
				<li><a href="#" class="s_tab">Premium Economy</a></li>
				<li><a href="#" class="s_tab">Business</a></li>
				<li><a href="#" class="s_tab">First</a></li>
			</ul>
	  * 
	  * 
	  * 
	  */ 
	  
	  if(list.length > 1)
	  {
		  filterHtml = '<ul class="clear"><li><a href="#" id="ticketIDAll" onClick="Display.getClassTicket(\'all\');" class="selected">All Ticket types</a></li>';
		  for(i=0;i<list.length;i++)
		  {
			  filterHtml += '<li><a href="#" id="ticketID'+i+'" onClick="Display.getClassTicket(\''+list[i][0]+'\');" class="s_tab">'+list[i][0]+'</a></li>';
		  }
		  
		  filterHtml += '</ul>';
		  _$(id).style.display = '';
		  _$(id).innerHTML = filterHtml;
		  
		  
		  
	  }
	  else
		  _$(id).style.display = 'none';	 
  }

  this.makePageBar = function()
  { 
	  numPages = Math.ceil(this.actualResult.length / this.recordPerPage);
	  if(numPages <= 5)
		  startPage = this.actualPage - 5; 
	  else if(numPages - this.actualPage <= 1 && numPages > 5)
		  startPage = numPages - 4;
	  else 
		  startPage = this.actualPage - 2; 
		  

	  if(startPage < 1) startPage = 1;
	  
	  for(j=0;j<this.listPageViewId.length;j++)
	  {	
		  pageHtml = '';
		  
		  if (this.actualPage != 1)
			  pageHtml += '<a href="#pageInfo1" onClick="Display.prevPages()">&laquo; prev</a> ';
		  else if(numPages > 1)
			  pageHtml += '&laquo; prev ';
		  
			  if (numPages > 5)
		      {
				  if(this.actualPage > 3)
				      pageHtml += '<a href="#pageInfo1" id="'+this.listPageViewId[j]+'1"  onClick="Display.displayPages(1)">1</a> ';
			      if(this.actualPage > 4 && numPages > 6)
  				 	  pageHtml += '... ';
			  }
		  
          if (numPages > 1)
          {
			  for(i=startPage;i<=numPages && i-startPage < 5;i++)
			  {
				  if(i == this.actualPage)
					  pageHtml += '<a href="#pageInfo1" id="'+this.listPageViewId[j]+i+'" style="color:black;" onClick="Display.displayPages('+i+')">'+i+'</a> ';
				  else
					  pageHtml += '<a href="#pageInfo1" id="'+this.listPageViewId[j]+i+'" onClick="Display.displayPages('+i+')">'+i+'</a> ';
			  }
          }

          
          if(numPages > 5)
          {
			  if (this.actualPage <  numPages - 3 && numPages != 6)
				  pageHtml += '... ';
			  if (this.actualPage < numPages - 2)
				  pageHtml += '<a href="#pageInfo1" id="'+this.listPageViewId[j]+numPages+'" onClick="Display.displayPages('+numPages+')">'+numPages+'</a> ';
          }
		  
          if(this.actualPage < numPages && numPages != 0)
	  		  pageHtml += '<a href="#pageInfo1" onClick="Display.nextPages()">next &raquo;</a>';
	  	  else if(numPages > 1)
	  		  pageHtml += 'next &raquo;';

		  _$(this.listPageViewId[j]).innerHTML = pageHtml;
	  }

	  var pag_to = ((this.actualPage)*this.recordPerPage);
	  if (pag_to > this.actualResult.length)
	    pag_to = this.actualResult.length;

	  textPageInfo = 'Showing '+((this.actualPage-1)*this.recordPerPage+1)+' to '+pag_to+' of '+this.actualResult.length+' flights.';
	  
	  if(numPages)
		  for(j=0;j<this.listPageViewInfo.length;j++)
		  {
			  _$(this.listPageViewInfo[j]).style.display = '';
			  _$(this.listPageViewInfo[j]).innerHTML = textPageInfo;
		  }
	  else
		  for(j=0;j<this.listPageViewInfo.length;j++)
		  {
			  _$(this.listPageViewInfo[j]).style.display = 'none';
		  }
  }
  
  this.displayPages = function(numPage)
  {
	  this.actualPage = numPage;
	  this.makePageBar();
	  this.displayResult();

  }

  this.prevPages = function()
  {
	  this.actualPage--;
	  this.makePageBar();
	  this.displayResult();
	  
	  
  }
  
  this.nextPages = function()
  {
	this.actualPage++;
	this.makePageBar();
    this.displayResult();
  }
  
}

function number_format( number, decimals, dec_point, thousands_sep ) 
{
      var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
      var d = dec_point == undefined ? "," : dec_point;
      var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
      var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
      return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}


