/** 
 * Author and Version Information {{{
 * author: Neil Lock http://www.moneysavingexpert.com
 *
 * class: Results for Mobile Recyling Prototype 1.6.0
 *
*/

var MobileResults = Class.create();

MobileResults.prototype = { // {{{
  Version: '1.3.0',
  REQUIRED_PROTOTYPE: '1.6.0',

  initialize: function (id, param) { // {{{
  	// check whether we have the appropiate javascript libraries
  	this.PROTOTYPE_CHECK();
	this.options = param ? param : {};
    this.getResults(id);
	}, // }}}
  
  
  getResults: function(val) { // {{{
	
	this.sInp = val
	
	var p = this;
  	//var input	= this.sInp; // send the converted new value (comma)
  	//clearTimeout(this.ajID); // ajax id timer
  	this.ajID = setTimeout( function () {p.doAjaxRequest(p.sInp)});
  	
  }, // }}}
  convertVersionString: function (versionString){ // {{{
      var r = versionString.split('.');
      return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
  }, // }}}

  PROTOTYPE_CHECK: function() { // {{{
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       (this.convertVersionString(Prototype.Version) < 
        this.convertVersionString(this.REQUIRED_PROTOTYPE)))
       throw("AutoComplete requires the Prototype JavaScript framework >= " +
        this.REQUIRED_PROTOTYPE);
  }, // }}}



  doAjaxRequest: function (input) { // {{{
  	// do we need to call a function to recreate the url?
  	if (typeof this.options.script == 'function')
  		var url = this.options.script(encodeURIComponent(this.sInp));
  	else
  		var url = this.options.script+this.options.varname+'='+encodeURIComponent(this.sInp);
  	
  	if(!url) return false;
  
 
  
  
  
  
  var p = this;
  $("mobile_results").addClassName('loading');
  
  var options = {
  		method: "get",
  		onSuccess: function (req) { // {{{
  		 
  		   $("mobile_results").removeClassName('loading');
		   p.setResults(req,input);
  		}, // }}}

  		onFailure: function (status) { // {{{
        } // }}}
    }
  	
  	this.shownotworking=1;
  	this.showworking = 1;
  	this.sortedby='phoneprice';
  	new Ajax.Request(url, options);
  }, // }}}

 
  setResults: function (req, input){// {{{
	var jsondata = eval('(' + req.responseText + ')');
    this.aRes = jsondata.results;
	this.createOutput(this.aRes);
	
  }, // }}}
 
 
  
  getSorted: function(columnname){
  	
  if(columnname=='review_level'){
 	 return this.aRes.sortBy(
		function(result) {
			
				return result['review_level'];
			
		}
	).reverse().sortBy(function(result) {
			return result[columnname];
		}).reverse();
  }
  else{
  	return this.aRes.sortBy(
		function(result) {
			
				return result['review_level'];
			
		}
	).sortBy(function(result) {
			return result[columnname];
		}).reverse();
  }
  
  
  
	
  },
  
  sortOutput: function(column){
	this.sortedby=column	
	  this.createOutput(this.getSorted(column));
  },// }}}
  
  
 showHideColumns: function(column){
 	if(column=='notworking'){
		if(this.shownotworking==1){
			this.shownotworking=0;
		}
		else{
			this.shownotworking=1;
		}
	}		
 	else{
		if(this.showworking==1){
			this.showworking=0;
		}
		else{
			this.showworking=1;
		}
	} 	
 	
 	this.createOutput(this.aRes)
   
  },
  

  createOutput:function (arr){
 
    $("mobile_results").innerHTML='';
 
  	
  	// if no results, and showNoResults is false, do nothing
  	if (arr.length == 0 ) return false;
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	var table_curved_header =this.createDOMElement('div', {id:'table_curved_header'});
 	
 	
 	
 	var rpt = this.createDOMElement('div',{className:'rpt'}, "",true);
 	var left = this.createDOMElement('div',{className:'left'}, "",true);
 	rpt.appendChild(left);
 	var right = this.createDOMElement('div',{className:'right'}, "",true);
 	
 	//var div = this.createDOMElement('div', {className:'workingcheckbox'});
 	//var working = this.createHideColumnBlocks('Show Working:','working',this.showworking,false);
 	//var notworking = this.createHideColumnBlocks('Show Not Working:','notworking',this.shownotworking, true);
 	
 	//div.appendChild(working);
 	//div.appendChild(notworking);
 	//right.appendChild(div);
 	
 	
 	
 	
 	
 	left.appendChild(right);
 	table_curved_header.appendChild( rpt )
 			
 
 	
 	$("mobile_results").appendChild(table_curved_header);
 	var table = this.createDOMElement('table', {id:'result_table',className:'result_table_row', cellpadding:'0', cellspacing:'0', width:'518px'});
 	
 	var t_body = this.createDOMElement('tbody', {});
 	
 	
 	
 	
 	
 	var tr_header2 = this.createDOMElement('tr', {className:'column_header'});
 	
 	
 	var retailer	= this.createDOMElement('td',{className:'retailer_header', rowSpan:"2", width:'148'}); 
 	retailer.appendChild(this.createDOMElement('span',{className:'headings'}, '&nbsp;',true));
	tr_header2.appendChild(retailer);
 	
 	
	
	
	var workingphones	= this.createDOMElement('td',{colSpan:'2'}); 
    workingphones.appendChild(this.createDOMElement('div',{className:'headings'}, '<img src="http://images2.moneysavingexpert.com/images/recycling/accept.png" align="top" \/> <span style="color:#104919;">Working Price<\/span>',true));
   
	
	if(this.showworking)
	tr_header2.appendChild(workingphones);

	var nonworkingphones	= this.createDOMElement('td',{colSpan:'2'}); 
    nonworkingphones.appendChild(this.createDOMElement('div',{className:'headings'}, '<img src="http://images2.moneysavingexpert.com/images/recycling/delete.png" align="top" \/> <span style="color:#7d2034;">Non-working Price<\/span>',true));
	
	if(this.shownotworking)
	tr_header2.appendChild(nonworkingphones);
	
	
	
	
	var reliability	= this.createDOMElement('td',{className:'retailer_header',width:'80'}); 
 	reliability.appendChild(this.createDOMElement('span',{className:'headings'}, 'Provider Reliability'));
	
	
	tr_header2.appendChild(reliability);
	
	
	
 	t_body.appendChild(tr_header2);
    table.appendChild(t_body);
 	
 	
 	
 
 
 
 	var tr_header = this.createDOMElement('tr', {className:'column_header'});
 	 	
 	
 	var phoneprice	= this.createDOMElement('td',{className:'column_header',width:'58'}); 
    phoneprice.appendChild(this.createDOMElement('div',{className:'headings'}, 'Cash'));
    phoneprice.appendChild(this.createSortableLinkHeaders('Sort By', 'phoneprice'));
    
    var voucheramount	= this.createDOMElement('td',{className:'column_header',width:'58'}); 
	voucheramount.appendChild(this.createDOMElement('div',{className:'headings', align:'center'}, 'Voucher'));
    voucheramount.appendChild(this.createSortableLinkHeaders('Sort By', 'voucheramount'));
    
    
	var notworkingprice	= this.createDOMElement('td',{className:'column_header', width:'58'}); 
	notworkingprice.appendChild(this.createDOMElement('div',{className:'headings'}, 'Cash'));
    notworkingprice.appendChild(this.createSortableLinkHeaders('Sort By', 'notworkingprice'));
	
  
	
	
	
	
	
	var voucheramountnotworking	= this.createDOMElement('td',{className:'column_header', width:'58'}); 
 	voucheramountnotworking.appendChild(this.createDOMElement('div',{className:'headings',align:'center'}, 'Voucher'));
    voucheramountnotworking.appendChild(this.createSortableLinkHeaders('Sort By', 'voucheramountnotworking'));
 	
 	var relaiability_sort	= this.createDOMElement('td',{className:'column_header', width:'80'}); 
 	relaiability_sort.appendChild(this.createDOMElement('div',{className:'headings'}, '<br/>',true));
 	/*relaiability_sort.appendChild(this.createSortableLinkHeaders('Sort By', 'review_level'));
  	*/
    if(this.showworking)
	    tr_header.appendChild(phoneprice);	
	if(this.showworking)
    	tr_header.appendChild(voucheramount);
   	if(this.shownotworking)
   		tr_header.appendChild(notworkingprice);
  	if(this.shownotworking)
	    tr_header.appendChild(voucheramountnotworking);
    
    tr_header.appendChild(relaiability_sort);
    
    
    
    
    var showdirect=0;
 	if(showdirect){
		var directLink	= this.createDOMElement('td',{className:'directlink'}); 
		directLink.appendChild(this.createDOMElement('span',{className:'headings'}, 'Direct Link'));
		tr_header.appendChild(directLink);
	}	
	
    
    
    
    t_body.appendChild(tr_header);
    table.appendChild(t_body);
 	
 	
 	var tr_row	= this.createDOMElement('tr'); 
    var tr_body = this.createDOMElement('tbody', {});
    
    
   
	
 	var sortedbyclass='';
    for (var i=0,l = arr.length; i<l; i++){
      	
      	var tr_row	= this.createDOMElement('tr'); 
      	var tr_body = this.createDOMElement('tbody', {});

      	
      	
      	
      	sortedbyclass='';
      	if(this.sortedby == 'retailer'){
      		sortedbyclass='sortedby';
      	}
      	var retailer	= this.createDOMElement('td',{className:'retailer'}, this.createRetailerLink(arr[i]),true);
      	
      	if(arr[i].phoneprice==0){
      		var phoneprice_val = "-";
      		var price_class = "na";
      	
      	}
      	else{
      		if(!this.isInteger(arr[i].phoneprice)){
      			var phoneprice_val="&pound;"+this.roundNumber(arr[i].phoneprice);
      		}
      		else{
      			var phoneprice_val="&pound;"+arr[i].phoneprice;
      		}
      		var price_class = "pricefigure";
      	}
      	
      	var pp_span = this.createDOMElement('span',{className:price_class}, phoneprice_val, true)
      	
      	sortedbyclass='';
      	if(this.sortedby == 'phoneprice'){
      		sortedbyclass=' sortedby';
      	}
      	var phoneprice	= this.createDOMElement('td',{className:price_class+sortedbyclass}); 
      	phoneprice.appendChild(pp_span);
      	
      	
      	
      	if(arr[i].notworkingprice==0){
      		var notworkingprice_val = "-";
      		var price_class = "na";
      	
      	}
      	else{
      		
      		if(!this.isInteger(arr[i].notworkingprice)){

			var notworkingprice_val="&pound;"+this.roundNumber(arr[i].notworkingprice);


      		}
      		else{
      			var notworkingprice_val="&pound;"+arr[i].notworkingprice;
      		}
      		
      		var price_class = "pricefigure";
      	}
      	
      	var np_span = this.createDOMElement('span',{className:price_class}, notworkingprice_val, true);
      	
      	sortedbyclass='';
      	if(this.sortedby == 'notworkingprice'){
      		sortedbyclass=' sortedby';
      	}
      	var notworkingprice	= this.createDOMElement('td',{className:'notworkingprice'+sortedbyclass}); 
     	notworkingprice.appendChild(np_span);
     	
     	
     	if(arr[i].voucheramount==0){
      		var voucheramount_val = "-";
      		var price_class = "na";
      	
      	}
      	else{
      		if(!this.isInteger(arr[i].voucheramount)){
			if (arr[i].retailer=='Mopay') { var voucheramount_val="Up to &pound;"+this.roundNumber(arr[i].voucheramount)+'<br \/> ('+arr[i].voucherdetail+')'; }
      			else {var voucheramount_val="&pound;"+this.roundNumber(arr[i].voucheramount)+'<br \/> ('+arr[i].voucherdetail+')'; }
      		}
      		else{
			if (arr[i].retailer=='Mopay') { var voucheramount_val="Up to &pound;"+arr[i].voucheramount+'<br \/> ('+arr[i].voucherdetail+')'; }
      			else {var voucheramount_val="&pound;"+arr[i].voucheramount+'<br \/> ('+arr[i].voucherdetail+')';}
      		}
      		var price_class = "pricefigure";
      	}
      	
      	var va_span = this.createDOMElement('span',{className:price_class}, voucheramount_val, true)
     	
     	sortedbyclass='';
      	if(this.sortedby == 'voucheramount'){
      		sortedbyclass=' sortedby';
      	}
     	var voucheramount	= this.createDOMElement('td',{className:'voucheramount'+sortedbyclass}); 
     	voucheramount.appendChild(va_span);
     	
     	if(arr[i].voucheramountnotworking==0){
      		var voucheramountnotworking_val = "-";
      		var price_class = "na";
      	
      	}
      	else{
      		if(!this.isInteger(arr[i].voucheramountnotworking)){
      			if (arr[i].retailer=='Mopay') { var voucheramountnotworking_val="Up to &pound;"+this.roundNumber(arr[i].voucheramountnotworking)+' <br \/>('+arr[i].voucherdetail+')'; }
			else { var voucheramountnotworking_val="&pound;"+this.roundNumber(arr[i].voucheramountnotworking)+' <br \/>('+arr[i].voucherdetail+')'; }
      		}
      		else{
      			if (arr[i].retailer=='Mopay') { var voucheramountnotworking_val="Up to &pound;"+arr[i].voucheramountnotworking+' <br \/>('+arr[i].voucherdetail+')'; }
			else { var voucheramountnotworking_val="&pound;"+arr[i].voucheramountnotworking+' <br \/>('+arr[i].voucherdetail+')'; }

      		}
      		var price_class = "pricefigure";
      	}
      	
      	var vanw_span = this.createDOMElement('span',{className:price_class}, voucheramountnotworking_val, true)
     	
     	sortedbyclass='';
      	if(this.sortedby == 'voucheramountnotworking'){
      		sortedbyclass=' sortedby';
      	}
     	var voucheramountnotworking	= this.createDOMElement('td',{className:'voucheramountnotworking'+sortedbyclass});
     	voucheramountnotworking.appendChild(vanw_span);
     	
     	
      	
     	
     	
     	
     	tr_row.appendChild(retailer);
    
    	if(this.showworking)
	    	tr_row.appendChild(phoneprice);
	    if(this.showworking)
     		tr_row.appendChild(voucheramount);
     	
     	if(this.shownotworking)
	     	tr_row.appendChild(notworkingprice);
     	if(this.shownotworking)
     		tr_row.appendChild(voucheramountnotworking);
     	
     	if(showdirect){
     		var directlink	= this.createDOMElement('td',{className:'retailer'}, this.createDirectLink(arr[i]),true);
     		tr_row.appendChild(directlink);
		}
		
		sortedbyclass='';
      	if(this.sortedby == 'review_level'){
      		sortedbyclass=' sortedby';
      	}
     	var reviewlink	= this.createDOMElement('td',{className:'review'+sortedbyclass}, this.createReliabilityRow(arr[i]),true);
     	tr_row.appendChild(reviewlink);
     	
     	tr_body.appendChild(tr_row);
     	table.appendChild(tr_body);
      }
     
     //div.appendChild(this.createDOMElement('div',{className:'clear'},'',true));
 
    $("mobile_results").appendChild(table);
    
    
    var footnote = this.createDOMElement('div',{className:'footnote'}, 'This information is computer generated, MoneySavingExpert.com can not be responsible for any errors.  Always double check the price before committing.');
    $("mobile_results").appendChild(footnote);
    
   //var footnote2 = this.createDOMElement('div',{className:'footnote'}, 'Ratings are editorially based on a mixture of forum feedback, historical user emails and how efficiently providers have resolved problems when asked by us.');
   //$("mobile_results").appendChild(footnote2);

    var companys = this.createDOMElement('div',{className:'footnote',id:'companys-list'}, companyList,true);
    $("mobile_results").appendChild(companys);
    var script = this.createDOMElement('div',{}, '',true);
	$("mobile_results").appendChild(script);

    
   
   
  }, //}}}
  
  roundNumber: function(num) {
	var result =  num.toFixed(2)  
	return result;
  },
  createRetailerLink: function (arr){
  	var span = this.createDOMElement('span',{className:'retailer_link'});
  	if(arr.affiliateurl!=""){
  		var a 	= this.createDOMElement('a',{href:arr.affiliateurl, target:'_blank', className:"retailerlink"});
		var text = this.createDOMElement('span',{}, arr.retailer+"*",true); // type of, properties, output, isHTML?
		a.appendChild(text); // add the object span into the link
		span.appendChild(a);
  	}
  	else if (arr.url!=""){
  		var a 	= this.createDOMElement('a',{href:arr.url, target:'_blank', className:"retailerlink" });
		var text = this.createDOMElement('span',{}, arr.retailer,true); // type of, properties, output, isHTML?
		a.appendChild(text);
		span.appendChild(a);
  	
  	}
  	else{
  		var text = this.createDOMElement('span',{}, arr.retailer,true); // type of, properties, output, isHTML?
  		span.appendChild(text);
  	}

	if(arr.extradetail!=""){
  		var extradetail = this.createDOMElement('span',{}, arr.extradetail,true); // type of, properties, output, isHTML?
  	       span.appendChild(document.createElement('br'));
  		span.appendChild(extradetail);
	} 	

  	return span;
  },
  
  createReliabilityRow:function(arr){
  	
  	var image="";
  	/*if(arr.review_level==1){
  		image ="<a href='"+arr.discussion_thread+"' style='text-decoration:none;' target='_blank'><img src='http://images2.moneysavingexpert.com/images/recycling/haha_32.png' width='32px' border=0/><br/><span style='color:#028714;text-decoration:underline; font-size:8pt;'>Good feedback<\/span><\/a>";
  		
  	}
  	else if(arr.review_level==0){
  		image ="<a href='"+arr.discussion_thread+"' style='text-decoration:none;' target='_blank'><img src='http://images2.moneysavingexpert.com/images/recycling/question.png' width='32px' border=0/><br/><span style='text-decoration:underline;color:#f69728; font-size:8pt;'>Limited feedback<\/span><\/a>";
  	}
  	*/
  		image ="<a href='"+arr.discussion_thread+"' style='text-decoration:none;' target='_blank'><img src='http://images2.moneysavingexpert.com/images/recycling/speech.png' width='32px' border=0/><br/><span style='text-decoration:underline;color:#22a4db; font-size:8pt;'>Add/Read Feedback<\/span><\/a>";

  	
  	var span = this.createDOMElement('span',{className:'direct_link'}, image, true);
 
	return span;
  },
  
  isInteger:function isInteger(s) {
		return (s.toString().search(/^-?[0-9]+$/) == 0);
  },

  createDirectLink:function(arr){
  	var span = this.createDOMElement('span',{className:'direct_link'});
  	if(arr.offer_url!=null){
  		var a 	= this.createDOMElement('a',{href:arr.offer_url, target:'_blank' });
		var text = this.createDOMElement('span',{}, 'Visit' ,true); // type of, properties, output, isHTML?
		a.appendChild(text); // add the object span into the link
		span.appendChild(a);
  	}
   //	else{
  	//	var text = this.createDOMElement('span',{}, 'visit',true); // type of, properties, output, isHTML?
  		//span.appendChild(text);
  	//}
  	
  	return span;
  },
  createHideColumnBlocks: function(text,columnname, status,help){
	var span = this.createDOMElement('span',{})
	if(status==1)
		var input 	= this.createDOMElement('input',{type:"checkbox",checked:"checked",defaultChecked:'defaultChecked'});
	else
		var input 	= this.createDOMElement('input',{type:"checkbox"});
	var text = this.createDOMElement('span',{}, text,true); // type of, properties, output, isHTML?
	
	input.onclick = function () { // {{{
	
			 hideColumn(columnname);
			  return false; 
			}; // }}}
	span.appendChild(text);
	if(help){
    
   	 var tmp = "<a href=\"javascript:void(0)\" onclick=\"javascript:loadBottomHelpInfo('"+columnname+"');\" style=\"padding-left:5px;\"><img src=\"http://images2.moneysavingexpert.com/images/recycling/qmark.gif\" border=0 width=\"15\" align=\"absmiddle\"></a>";
    	var helphtml=this.createDOMElement('span',{}, tmp,true); // type of,
    	var displaydiv=this.createDOMElement('div',{id:'display_'+columnname}, '',true); // type of,
    	span.appendChild(helphtml);
    	span.appendChild(displaydiv);
    }
	span.appendChild(input);		
    
    
   // var br=this.createDOMElement('span',{}, "<br\/>",true); 
    //span.appendChild(br);

    return span;
  
  } ,
  
  
  
  createEmptyTD:function(){
  	var emptytd = this.createDOMElement('td',{className:''});
 	emptytd.appendChild(this.createDOMElement('span',{className:''}, '&nbsp;',true));
 	return emptytd;
  },
  
  createSortableLinkHeaders: function (text,sortby){
  
    var arrow='';
    var a 	= this.createDOMElement('a',{href:'#'});
	var linktext = text;
	var span = this.createDOMElement('span',{className:'sortby'}, linktext,true); // type of, properties, output, isHTML?
	a.appendChild(span); // add the object span into the link
	a.onclick = function () { // {{{
	
			 sortBy(sortby);
			  return false; 
			}; // }}}
    
    
    if(this.sortedby == sortby)
    	arrow= "<img src='http://images2.moneysavingexpert.com/images/travelmoney/bullet_arrow_down.png' border=0>&nbsp;";
 
  
  	var span_return=this.createDOMElement('span',{},arrow,true);
    span_return.appendChild(a)
    
    return span_return;
   
  
  } ,
  
  
  createDOMElement: function ( type, attr, cont, html ) { // {{{
    var ne = document.createElement( type );
	
    if (!ne)
      return 0;
    if (type=="table"){
    	ne.setAttribute("cellpadding", 0);
		ne.setAttribute("cellspacing", 3);
		ne.setAttribute("width", "518px");
		ne.setAttribute("height", "");
		ne.setAttribute("border", 1);
		ne.setAttribute("bordercolor", "#3d3e3f");
		
		
		
    }  
    if(type=="td"){
    	for (var a in attr){
     		ne.setAttribute(a,attr[a]);
     		
  
    	}
		
    }
     if (type=="input"){
     
     	for (var a in attr){
     		ne.setAttribute(a,attr[a]);
     		
  
    	}
		
    }  
    for (var a in attr)
      ne[a] = attr[a];
    
    var t = typeof(cont);
    
    if (t == "string" && !html)
      ne.appendChild( document.createTextNode(cont) );
    else if (t == "string" && html)
      ne.innerHTML = cont;
    else if (t == "object")
      ne.appendChild( cont );

    return ne;
  } // }}}

} // }}}

// vim: set filetype=javascript foldmethod=marker foldlevel=5:
