<!-- main.js - used by minisite only, not webapp -->

window.addEvent('domready', function(){

  //Sets cookie to show user has logged in - for support pages testing
  Cookie.set("truphone_user", true,{path:"/",duration: 30});

	// Dynamic module initialisation
	prepPage();
	
	// Main nav configuration
	var navIndex = -1;
	var subNavIndex = -1;
	
	var folder = location.href.split("/")[3];
	var folder2 = location.href.split("/")[4];
	var folder3 = location.href.split("/")[5];
	//var li;
	
	switch(folder) {
		case "":
			navIndex = 0;
				break;
		
			case "about_us":
				navIndex = 1;
				break;

			case "local-anywhere":
			  navIndex = 2;
			break;
			
			case "applications":
				navIndex = 3;
				
				// show subnav
				//$$('#main_nav #sub_nav').toggleClass('mobileapps');
				
				// and shift the content down
				//$$('#pnl_content').toggleClass('allowSubnav');
				
				switch(folder2)
				{
				case "":
				  subNavIndex = 0;
					break;
					
				case "services":
				  subNavIndex = 1;
					break;
					
				case "devices":
				  subNavIndex = 2;
				  var manufacturer = location.href.split("/")[5];
					//Set nav on the left side
					var li;
					if (li = document.getElementById("li_" + manufacturer)) {
					li.className = "selected";
					var as = li.getElementsByTagName("a");
					if (location.href.split("/")[6].match("download")) {
					  as[1].className = "on";
					} else if (location.href.split("/")[6].match("support")) {
					  as[2].className = "on";
					} else if (location.href.split("/")[6].match("phones")) {
					  as[3].className = "on";
					} else {
					  as[0].className = "on";
					}
					}
					break;
					
				case "pricing":
				  subNavIndex = 3;
				    var package = location.href.split("/")[5];
					//alert(package)
					//document.getElementById("li_" + package).className = 'selected';
					switch(package)
					{
						case "free_calls.html":
						var li = document.getElementById("li_free_calls");
						li.className = 'selected';
						var as = li.getElementsByTagName("a");
						as[0].className = "on";
						break
						
						case "truunlimited.html":
						var li = document.getElementById("li_truunlimited");
						li.className = 'selected';
						var as = li.getElementsByTagName("a");
						as[0].className = "on";
						break
						
						case "truphone_anywhere.html":
						var li = document.getElementById("li_truphone_anywhere");
						li.className = 'selected';
						var as = li.getElementsByTagName("a");
						as[0].className = "on";
						break
						
						case "assumptions.html":
						var li = document.getElementById("li_assumptions");
						li.className = 'selected';
						var as = li.getElementsByTagName("a");
						as[0].className = "on";
						break
					}
					break;
					
				case "support":
				  subNavIndex = 4;
				  	var manufacturer = location.href.split("/")[5];
					//Set nav on the left side
					var li;
					if (li = document.getElementById("li_" + manufacturer)) {
					li.className = "selected";
					var as = li.getElementsByTagName("a");
					if (location.href.split("/")[6].match("support")) {
					  as[1].className = "on";
					} else if (location.href.split("/")[6].match("user_guides")) {
					  as[2].className = "on";
					} else if (location.href.split("/")[6].match("faqs")) {
					  as[3].className = "on";
					} else if (location.href.split("/")[6].match("request")) {
					  as[4].className = "on";
					} else if (location.href.split("/")[6].match("troubleshooting")) {
					  as[5].className = "on";
					} else if (location.href.split("/")[6].match("service_numbers")) {
					  as[6].className = "on";
					} else {
					  as[0].className = "on";
					}
					}
					break;
					
				case "shop":
				  subNavIndex = 5;
					break;
				}
				break;
			
			case "business":
			  navIndex = 4;
			break;
		
		
		

      
	  //Set phones boxes to same height
      try {
        var maxHeight = 0;
        var divs = $("pnl_main").getElementsByTagName("div");
        var divsLength = divs.length;
        for (var i = 0; i < divsLength; i++) {
          if (divs[i].className.match("phones_box_content") && divs[i].scrollHeight > maxHeight) {
            maxHeight = divs[i].scrollHeight;
          }
        }
        for (var i = 0; i < divsLength; i++) {
          if (divs[i].className.match("phones_box_content")) {
            divs[i].style.height = maxHeight + "px";
          }
        }
      } catch (e) {}
			break;
		case "pricing":
		  navIndex = 999;
		  //Set nav on the left side
      try {
		    var section;
        /*if (section = location.href.split("/")[4].split(".")[0]) {
          $("li_" + section).className = "selected";
          $("li_" + section).getElementsByTagName("a")[0].innerHTML += " >";
        }*/
      } catch (e) {}
			break;

		case "support":
		  navIndex = 999;
		  /*var manufacturer = location.href.split("/")[4];
		  //Set nav on the left side
		  var li;
      if (li = document.getElementById("li_" + manufacturer)) {
		    li.className = "selected";
		    var as = li.getElementsByTagName("a");
        if (location.href.split("/")[5].match("support")) {
		      as[1].innerHTML += " >";
		    } else if (location.href.split("/")[5].match("user_guides")) {
		      as[2].innerHTML += " >";
		    } else if (location.href.split("/")[5].match("faqs")) {
		      as[3].innerHTML += " >";
		    } else if (location.href.split("/")[5].match("contact")) {
		      as[4].innerHTML += " >";
		    } else if (location.href.split("/")[5].match("troubleshooting")) {
		      as[5].innerHTML += " >";
		    } else if (location.href.split("/")[5].match("service_numbers")) {
		      as[6].innerHTML += " >";
		    } else {
		      as[0].innerHTML += " >";
		    }
      }*/
      //Set home page boxes to same height
      try {
        var maxHeight = 0;
        var divs = $("pnl_main").getElementsByTagName("div");
        var divsLength = divs.length;
        for (var i = 0; i < divsLength; i++) {
          if (divs[i].className.match("single") && divs[i].scrollHeight > maxHeight) {
            maxHeight = divs[i].scrollHeight;
          }
        }
        for (var i = 0; i < divsLength; i++) {
          if (divs[i].className.match("single")) {
            divs[i].style.height = maxHeight + "px";
          }
        }
      } catch (e) {}
      //Hide some links if truphone_user cookie not set
      if (Cookie.get("truphone_user") != "true") {
        if (document.getElementById("li_" + manufacturer + "_troubleshooting")) {
          document.getElementById("li_" + manufacturer + "_troubleshooting").style.display = "none";
        }
        if (document.getElementById("li_" + manufacturer + "_service_numbers")) {
          document.getElementById("li_" + manufacturer + "_service_numbers").style.display = "none";
        }
        if (document.getElementById("li_" + manufacturer + "_known_issues_forum")) {
          document.getElementById("li_" + manufacturer + "_known_issues_forum").style.display = "none";
        }
        if (document.getElementById("div_troubleshooting")) {
          document.getElementById("div_troubleshooting").style.display = "none";
        }
        if (document.getElementById("div_known_issues_forum")) {
          document.getElementById("div_known_issues_forum").style.display = "none";
        }
      }      
			break;
		case "shop":
		  navIndex = 999;
			break;
		  default:
		
		case "press":
		  navIndex = 5;
			break;
  
		case "stuff":
		  navIndex = 6;
			break;
			
		
	}

  //For main_nav nav (no longer an image nav)
	var els = $("main_nav").getChildren();
	if (navIndex > -1) {
		//$$('#main_nav li#home').toggleClass('selected');
		els[navIndex].toggleClass('selected');
	  //var img = els[navIndex].getElementsByTagName("img")[0];
    //img.src = img.src.replace(".png","_down.png");
	  //els.splice(navIndex,1);
  }
  /*var elsLength = els.length;
  for (var i = 0; i < elsLength; i++) {
    var img = els[i].getElementsByTagName("img")[0];
    img.onmouseover = function() {this.src = this.src.replace("_over","").replace(".png","_over.png")};
    img.onmouseout = function() {this.src = this.src.replace("_over","")};
  }*/
  
  var els2 = $("sub_nav").getChildren();
  if (subNavIndex > -1) {
		els2[subNavIndex].toggleClass('selected');
  }
 
  
  // Set up boxes - widths of header/footer and height of separators
  var boxDivs = document.getElementsByTagName('div');
  var boxDivsLength = boxDivs.length;
  for (var i = 0; i < boxDivsLength; i++) {
    if (boxDivs[i].className.match("centre")) {
      boxDivs[i].style.width = (boxDivs[i].parentNode.scrollWidth - 20) + "px";
    } else if (boxDivs[i].className.match("box_content")) {
      boxDivs[i].style.width = (boxDivs[i].parentNode.scrollWidth - 2) + "px";
    } else if (boxDivs[i].className.match("column") && boxDivs[i].parentNode.className.match("triple")) {
      boxDivs[i].style.width = ((boxDivs[i].parentNode.scrollWidth - (3 * (8 + 8) + 2)) / 3 - 2) + "px";
    } else if (boxDivs[i].className.match("list_text")) {
      //This sets the width on the text div in the icon/text combos
      var parentWidth = boxDivs[i].parentNode.scrollWidth;
      if (boxDivs[i].parentNode.getElementsByTagName("img").length > 0) {
	      var iconWidth = boxDivs[i].parentNode.getElementsByTagName("img")[0].scrollWidth;
	      boxDivs[i].style.width = (parentWidth - iconWidth - 21) + "px";
      }
      boxDivs[i].style.marginLeft = "20px";
    }
  }
  for (var i = 0; i < boxDivsLength; i++) {
    if (boxDivs[i].className.match("separator")) {
      boxDivs[i].innerHTML = "&nbsp;";
      boxDivs[i].style.height = (boxDivs[i].parentNode.scrollHeight - 4) + "px";
    }
  }
  
  //Home page tariff tabs
	if (document.getElementById('trustandard_tab') && document.getElementById('trusaver_tab')) {
		if (document.getElementById('trustandard_tab').addEventListener){
			document.getElementById('trustandard_tab').addEventListener("click", function() {
				HideAllRatesBoxes();
				document.getElementById('trustandard_tab').className='on';
				document.getElementById('pnl_trustandard_rates').style.display='';
			}, false);
			document.getElementById('trusaver_tab').addEventListener("click", function() {
				 HideAllRatesBoxes();
				 document.getElementById('trusaver_tab').className='on';
				 document.getElementById('pnl_trusaver_rates').style.display='';
			}, false);
			document.getElementById('truunlimited_tab').addEventListener("click", function() {
				  HideAllRatesBoxes();
				  document.getElementById('truunlimited_tab').className='on';
				  document.getElementById('pnl_truunlimited_rates').style.display='';
			}, false);
		} else if (document.getElementById('trustandard_tab').attachEvent){
			document.getElementById('trustandard_tab').attachEvent("onclick", function() {
				HideAllRatesBoxes();
				document.getElementById('trustandard_tab').className='on';
				document.getElementById('pnl_trustandard_rates').style.display='';
            });
			document.getElementById('trusaver_tab').attachEvent("onclick", function() {
              HideAllRatesBoxes();
              document.getElementById('trusaver_tab').className='on';
              document.getElementById('pnl_trusaver_rates').style.display='';
            });
			document.getElementById('truunlimited_tab').attachEvent("onclick", function() {
              HideAllRatesBoxes();
              document.getElementById('truunlimited_tab').className='on';
              document.getElementById('pnl_truunlimited_rates').style.display='';
             });
		}
	}
  
	// FAQs module initialisation
	var faqsContent = $$('ul.faqlist li');
	if(faqsContent.length != 0){
		new buildFaqsContent(faqsContent,$$('div.questioncontainer'),$$('div.questioncontainer img.button'),$$('div.answercontainer'),$$('div.answercontainer img.button'));
	}

	// Tabbed content initialisation
	var tabbedContent = $$('div.tabcontent');
	if(tabbedContent.length != 0){
		new buildTabbedContent($$('ul.tabbednav a'),tabbedContent);
		new buildFlagContent($$('p.seeall'),$$('p.closeall')); // Flag content initialisation
	}

	// Support list show hide initialisation
	var supportContent = $$('ul.questionlist li');
	if(supportContent.length != 0){
		new buildSupportContent(supportContent);
	}

	// Class to swap all currency items when page loads and when the currency changes
	new swapCurrencyAssets();

	//truUnlimited rate table
	var tuRate=new TURateDisplayer();

	///===========================
	//altogether code
	var affpos=window.location.href.indexOf('?truaff=');
	if (affpos>=0){
		var affval=window.location.href.substr(affpos+'?truaff='.length);
		
		Cookie.set("adnetwork", affval,{path:"/",duration: 30});
	}
	
});

function HideAllRatesBoxes() {
  document.getElementById('trustandard_tab').className='';
  document.getElementById('trusaver_tab').className='';
  document.getElementById('truunlimited_tab').className='';
  document.getElementById('pnl_trustandard_rates').style.display='none';
  document.getElementById('pnl_trusaver_rates').style.display='none';
  document.getElementById('pnl_truunlimited_rates').style.display='none';
}

var swapCurrencyAssets = new Class({
	initialize: function(){
		
		this.currency = Cookie.get('truphone_current_currency');
		
		//console.log(this.currency);
		
		imgTogglers = $$('img.pricetoggle');
		if(imgTogglers.length > 0){
			imgTogglers.each(function(el,i){
				this.updateImg(el,i);
			}.bind(this));
		}
	},
	updateImg: function(el,i){
		var s = el.getProperty('src');
		var a = el.getProperty('alt');		

		if(this.currency != 'GBP'){
			s = s.replace(/uk.jpg/,'us.jpg');
			s = s.replace(/uk.png/,'us.png');
			a = a.replace(/ 3p/g,' 6c');
			a = a.replace(/ 5p/g,'10c');
			a = a.replace(/15p/g,'30c');
			a = a.replace(/25p/g,'50c');
			a = a.replace(/10p/g,'20c');
		} else {
			s = s.replace(/us.jpg/,'uk.jpg');
			s = s.replace(/us.png/,'uk.png');
			a = a.replace(/ 6c/g,' 3p');
			a = a.replace(/10c/g,' 5p');
			a = a.replace(/30c/g,'15p');
			a = a.replace(/50c/g,'25p');
			a = a.replace(/20c/g,'10p');
		}
		el.setProperty('src',s);
		el.setProperty('alt',a);
	}
});
	
var buildTabbedContent = new Class({
	initialize: function(contentLinks,contentPanels){
	
		// hide each content panel
		contentPanels.each(function(el,i){
			el.addClass('hidden');
		});
		
		// configure each link
		contentLinks.each(function(el,i){
			el.getParent().removeClass('selected');
			el.addEvents({
				'click':function(e){
					contentLinks.each(function(el,i){ el.getParent().removeClass('selected'); });
					
					el.getParent().addClass('selected');
					contentPanels.each(function(el,i){ el.addClass('hidden'); });
					contentPanels[i].removeClass('hidden');
					e = new Event(e).stop();
				}
			});
		});
		
		//initial view
		if(location.href.match('#')){
			var elementId = location.href.split('#');
			var elementToShow = elementId[(elementId.length-1)];
			if($(elementToShow)){
				$(elementToShow).removeClass('hidden');
				contentLinks.each(function(el,i){
					if(el.getProperty('href').match(elementToShow)){ el.getParent().toggleClass('selected'); }
				});
			} else {
				contentPanels[0].removeClass('hidden');
				contentLinks[0].getParent().toggleClass('selected');
			}
		} else {
			contentPanels[0].removeClass('hidden');
			contentLinks[0].getParent().toggleClass('selected');
		}
		
	}
});

var buildSupportContent = new Class({
	initialize: function(intContentPanels){
		
		var contentPanels = new Array();
		intContentPanels.each(function(el,i){
			if(el.getParent().hasClass('questionlist')){ contentPanels.include(el); }
		});
		
		var contentLinks = contentPanels.map(function(el){ return el.getChildren()[0]; });
		var contentCloseLinks = contentPanels.map(function(el){ return el.getChildren()[1].getChildren()[el.getChildren()[1].getChildren().length-1]; });
		var contentBlock = contentPanels.map(function(el){ return el.getChildren()[1]; });
		var contentSlides = contentBlock.map(function(el){ return new Fx.Slide(el).hide(); });
		
		contentLinks.each(function(el,i){
			el.addEvent('click', function(e){
				contentSlides[i].slideIn();
				el.addClass('hidden');
				e = new Event(e).stop();
			});
		});
		
		contentCloseLinks.each(function(el,i){
			el.addEvent('click', function(e){
				contentSlides[i].slideOut();
				contentLinks[i].removeClass('hidden');
				e = new Event(e).stop();
			});
		});
	
		//initial view
		//contentSlides[0].slideIn();
		//contentLinks[0].addClass('hidden');
		
	}
});

var buildFlagContent = new Class({
	initialize: function(seeLinks,closeLinks){
		
		if(seeLinks.length == closeLinks.length){
						
			seeLinks.each(function(el,i){
				var contentSlide = new Fx.Slide(el.getNext()).hide();
				this.createSeeLink(el,i,contentSlide);
				this.createCloseLink(closeLinks[i],i,contentSlide);
			}.bind(this));

		}
		
	},
	createSeeLink: function(el,i,slide){
		var lnkText = el.innerHTML;
		el.empty();
		var anc = new Element('a',{'href':'','class':'seeall'}).setHTML(lnkText).injectInside(el);
		anc.addEvent('click', function(e){
			slide.slideIn();
			e = new Event(e).stop();
		});
	},
	createCloseLink: function(el,i,slide){
		var anc = new Element('a',{'href':'','class':'closeall'}).setHTML('Close');
		el.replaceWith(anc);
		anc.addEvent('click', function(e){
			slide.slideOut();
			e = new Event(e).stop();
		});
	}
});

var buildFaqsContent = new Class({
	initialize: function(faqsContentStart,questionContainers,questionButtons,answerContainers,answerButtons){
		
		var faqsContent = new Array();
		faqsContentStart.each(function(el,i){
			if(el.getParent().hasClass('faqlist')){ faqsContent.include(el) }
		});
		
		questionButtons.each(function(el,i){
			var oSrc = el.getProperty('src');
			var nSrc = oSrc.replace(/btn-answer-s.gif/,'btn-answer.gif');
			el.setProperty('src',nSrc);
		});

		var contentSlides = answerContainers.map(function(el){ return new Fx.Slide(el).hide(); });

		faqsContent.each(function(el,i){
			this.addOpeningEvents(questionButtons[i],i,contentSlides[i]);
			this.addClosingEvents(answerButtons[i],i,questionButtons[i],contentSlides[i]);
		}.bind(this));
	},
	//May need to adjust this for new button states
	addOpeningEvents: function(el,i,slide){
		el.addEvents({
			'mouseover': function(e){
				var oSrc = el.getProperty('src');
				var nSrc = oSrc.replace(/btn-answer.gif/,'btn-answer-o.gif');
				el.setProperty('src',nSrc);
			},
			'mouseleave': function(e){
				var oSrc = el.getProperty('src');
				var nSrc = oSrc.replace(/btn-answer-o.gif/,'btn-answer.gif');
				el.setProperty('src',nSrc);
			},
			'click': function(e){
				slide.slideIn();
				var oSrc = el.getProperty('src');
				var nSrc = oSrc.replace(/btn-answer-o.gif/,'btn-answer-s.gif');
				el.setProperty('src',nSrc);
				e = new Event(e).stop();
			}
		});
	},
	addClosingEvents: function(el,i,btn,slide){
		el.addEvents({
			'mouseover': function(e){
				var oSrc = el.getProperty('src');
				var nSrc = oSrc.replace(/btn-close.gif/,'btn-close-o.gif');
				el.setProperty('src',nSrc);
			},
			'mouseleave': function(e){
				var oSrc = el.getProperty('src');
				var nSrc = oSrc.replace(/btn-close-o.gif/,'btn-close.gif');
				el.setProperty('src',nSrc);
			},
			'click': function(e){
				slide.slideOut();
				var oSrc = btn.getProperty('src');
				var nSrc = oSrc.replace(/btn-answer-s.gif/,'btn-answer.gif');
				btn.setProperty('src',nSrc);
				e = new Event(e).stop();
			}
		});
	}
});

function prepPage() {
  // this executes once all html is loaded  
  var currency = new CurrencyManager({
    formObjID: 'form_currency'
  , ddlObjID: 'current_currency'
  , btnObjID: 'currency_submit'
  , cookieName: 'truphone_current_currency'
  });
  
  if($('form_tariff')){
	  var tariff = new TariffManager({
	    formObjID: 'form_tariff'
	  , ddlParent: 'pnl_tariff_country'
	  , ddlObjID: 'tariff_country'
	  , pnlInfoObjID: 'pnl_show_tariff'
	  , tariffAssetPath: '/app/tariff-lookup'
	  , ddlParent2: 'pnl_tariff_country2'
	  , ddlObjID2: 'tariff_country2'
	  , pnlInfoObjID2: 'pnl_show_tariff2'
	  , tariffAssetPath2: '/app/tariff-lookup2'
	  , ddlParent3: 'pnl_tariff_country3'
	  , ddlObjID3: 'tariff_country3'
	  , pnlInfoObjID3: 'pnl_show_tariff3'
	  , tariffAssetPath3: '/app/tariff-lookup3'
	  , cookieName: 'truphone_current_currency'
	  });
  }

  // setup the download box if the holding element is there
  if($("form_download")) {
    var download = new DownloadManager({
      formObjID: 'form_download', countriesAssetPath: '/July2010/shared/js/countries.txt'
    , ddlParent: 'pnl_download_country', txtParent: 'pnl_download_number', txtNumber: 'gsm_number', btnObj: 'install_submit'
    , ddlObjID: 'country_id', txtCodeObjID: 'international_prefix', cookieName: 'truphone_current_download_country'
    , resultCookieName: 'truphone_installation_result'
    });
    download.initPinkTickBasedOnCookie();
  }

  // setup the download box if the holding element is there
  if($("form_register")) {
    var download = new RegisterManager({
      formObjID: 'form_register', countriesAssetPath: '/July2010/shared/js/countries.txt'
    , ddlParent: 'pnl_register_country'
    , ddlObjID: 'country'
    });
  }
}


var FormManager = new Class({

  options: {
    formObjID: false    // DOM element or id of the currency form
  }
  
, initialize: function(options) {
    this.setOptions(options);
    
    // transform the requiered options values into elements if passed as ids - if nothing passed, then grabs the first form in the page
    this.formObj        = this.options.formObjID    ? ($type(this.options.formObjID) == 'element'     ? this.options.formObjID :    $(this.options.formObjID)) :    false;
    
    //if (!$chk(this.formObj))
    //  alert('FormManager reports no form exists in DOM.');
 }

, createOption: function(ddlParent, name, val, selectedValue) {
    var opt = new Element('option', {'value': val}).setHTML(name);
    if (val == selectedValue) { opt.setProperty('selected', 'selected'); }
    opt.injectInside(ddlParent);
  }

, createDropDown: function(ddlName, labelText, cssClass, parentEl) {
    new Element('label', { 'for': ddlName, 'class': 'label' }).setHTML(labelText).injectInside(parentEl);
    var ddl = new Element('select', {id: ddlName, 'class': $chk(cssClass) ? cssClass : ''}).injectInside(parentEl);
    return ddl;
  }
  
, createTextBox: function(txtName, cssClass, parentEl) {
    return new Element('input', {id: txtName, 'type': 'text', 'class': $chk(cssClass) ? cssClass : ''}).injectBefore(parentEl);
  }
  
, createButton: function(btnName, cssClass, parentEl) {
    return new Element('input', {id: btnName, 'type': 'button', 'class': $chk(cssClass) ? cssClass : ''}).injectAfter(parentEl);
  }
 
 , createImgButton: function(btnName, cssClass, imgSrc, parentEl) {
    return new Element('input', {id: btnName, 'type': 'image', 'src': imgSrc, 'class': $chk(cssClass) ? cssClass : ''}).injectAfter(parentEl);
  }
  
});
FormManager.implement(new Options);

var CurrencyManager = FormManager.extend({

  // this class stores the currency value from the dropdown in a cookie for use by the  manager
  
  options: {
    ddlObjID: false     // DOM element or id of the currency drop down
  , cookieName: false   // name of currency cookie
  }
  
, initialize: function(options) {
	this.parent(options);
    this.setOptions(options);

    // Insert the currency dropdown in place of corner_nav_last (note main.js applies to minisite only,
    // so we won't get this dropdown on the webapp pages)
    new Ajax(
        "/July2010/shared/include/currency_select.html",
        {
            method: "get",
            parameters: "",
            onFailure: function(response) {
                // console.log('Error ' + response.status + ' -- ' + response.statusText);
            },
            onSuccess: function(responseHTML) {
				var cornerNavLast = document.getElementById("corner_nav_last")
				if (cornerNavLast) { cornerNavLast.innerHTML = responseHTML; }
				
				
				this.ddlObj = this.options.ddlObjID ? ($type(this.options.ddlObjID) == 'element' ? this.options.ddlObjID : $(this.options.ddlObjID)) : $('current_currency');

                this.cookieName = this.options.cookieName;
    
                // attach change event to dropdown
				if (this.ddlObj) {
					this.ddlObj.addEvent('change', this.updateCurrency.bind(this));
	
					// if there is no cookie, it's first visit, so set it based on the selected value, GBP
					if (!$chk(Cookie.get(this.cookieName)))
					  this.updateCurrency();
					else
					  this.setCurrencyDropdownFromCookie();
	
					this.setMsgBasedOnCurrency();
				}
            }.bind(this)
        }).request();
  }

  // this method sets the currency cookie based on the dropdown and sets the messages
, updateCurrency: function() {
	this.setMsgBasedOnCurrency();
    Cookie.set(this.cookieName, this.ddlObj.options[this.ddlObj.options.selectedIndex].value,{path:"/",duration: 30});
	
	
	if ($chk($('flash_pricing'))) {
		togglePricingFlash(Cookie.get(this.cookieName));
	}
	
	new swapCurrencyAssets();

  if($('form_tariff')){
	  var tariff = new TariffManager({
	    formObjID: 'form_tariff'
	  , ddlParent: 'pnl_tariff_country'
	  , ddlObjID: 'tariff_country'
	  , pnlInfoObjID: 'pnl_show_tariff'
	  , tariffAssetPath: '/app/tariff-lookup'
	  , ddlParent2: 'pnl_tariff_country2'
	  , ddlObjID2: 'tariff_country2'
	  , pnlInfoObjID2: 'pnl_show_tariff2'
	  , tariffAssetPath2: '/app/tariff-lookup2'
	  , ddlParent3: 'pnl_tariff_country3'
	  , ddlObjID3: 'tariff_country3'
	  , pnlInfoObjID3: 'pnl_show_tariff3'
	  , tariffAssetPath3: '/app/tariff-lookup3'
	  , cookieName: 'truphone_current_currency'
	  });
  }
  if ($('truUnlimitedSettingBox')) {
	  tariffAutoTopupManager.initialize(tariffAutoTopupManager.options);
  }
  if ($('tariffCountryDropDown')) {
	  tariffAutoTopupManager.initialize(tariffAutoTopupManager.options);
  }

  }
  
, setMsgBasedOnCurrency: function(){
	var opt;
	var sameCurrencyObjs=document.getElements(".Currency");
	for (opt=0;opt<sameCurrencyObjs.length;opt++){
		sameCurrencyObjs[opt].style.display="none";
	}
	var curCurrency=$('current_currency').value;
	
	var allCurrencyControllers=document.getElements("."+curCurrency);
	for (opt=0;opt<allCurrencyControllers.length;opt++){
		allCurrencyControllers[opt].style.display="inline";
	}
}
  // this method sets the dropdown based on the cookie value
, setCurrencyDropdownFromCookie: function() {
    // get options into an array to repopulate the dropdown
    var options = [];
    for (i = 0; i < this.ddlObj.options.length; i++) {
      options.push({'val': this.ddlObj.options[i].value, 'name': this.ddlObj.options[i].innerHTML});
    }
    // now empty the dropdown and repopulate
    this.ddlObj.empty();
    for (i = 0; i < options.length; i++) {
      this.createOption(this.ddlObj, options[i].name, options[i].val, Cookie.get(this.cookieName));
    }
  }
  
});

var TariffManager = FormManager.extend({

  // this class takes the value in the currency cookie as set by the currencyManager instance and renders the tariff information
  // from the json data specified by the retrieved currency

  options: {
    tariffAssetPath: false, tariffAssetPath2: false // this is the path to the file that contains json country data [ {code: 'GB', name: 'United Kingdom', dial: 44}, .. ]
  , ddlParentObj: false, ddlParentObj2: false       // DOM element or id of the html element that will hold the tariff dropdown
  , ddlObjID: false, ddlObjID2: false               // desired DOM id of the html country dropdown that will be created and populated based on the countries in the retrieved tariff data
  , pnlInfoObjID: false, pnlInfoObjID2: false       // DOM element or id of the html element that will show the tariff data
  , cookieName: false
  }
  
, initialize: function(options) {
	  this.parent(options);
    this.setOptions(options);
    
    this.tariffAssetPath = this.options.tariffAssetPath;
    this.tariffAssetPath2 = this.options.tariffAssetPath2;
    this.cookieName = this.options.cookieName;
    this.tariffData = null;

    this.ddlObjID = this.options.ddlObjID  ? this.options.ddlObjID : $('tariff_country');
    this.pnlInfoObj   = this.options.pnlInfoObjID  ? ($type(this.options.pnlInfoObjID) == 'element' ? this.options.pnlInfoObjID : $(this.options.pnlInfoObjID)) : $('pnl_show_tariff');
    this.ddlParentObj = this.options.ddlParent    ? ($type(this.options.ddlParent) == 'element'     ? this.options.ddlParent :    $(this.options.ddlParent)) :    $('pnl_tariff_country');
    
	this.ddlObjID2 = this.options.ddlObjID2  ? this.options.ddlObjID2 : $('tariff_country2');
    this.pnlInfoObj2   = this.options.pnlInfoObjID2  ? ($type(this.options.pnlInfoObjID2) == 'element' ? this.options.pnlInfoObjID2 : $(this.options.pnlInfoObjID2)) : $('pnl_show_tariff2');
    this.ddlParentObj2 = this.options.ddlParent2    ? ($type(this.options.ddlParent2) == 'element'     ? this.options.ddlParent2 :    $(this.options.ddlParent2)) :    $('pnl_tariff_country2');

	this.ddlObjID3 = this.options.ddlObjID3  ? this.options.ddlObjID3 : $('tariff_country3');
    this.pnlInfoObj3   = this.options.pnlInfoObjID3  ? ($type(this.options.pnlInfoObjID3) == 'element' ? this.options.pnlInfoObjID3 : $(this.options.pnlInfoObjID3)) : $('pnl_show_tariff3');
    this.ddlParentObj3 = this.options.ddlParent3    ? ($type(this.options.ddlParent3) == 'element'     ? this.options.ddlParent3 :    $(this.options.ddlParent3)) :    $('pnl_tariff_country3');
       
    this.ajaxReq = new Ajax(this.tariffAssetPath, {
      method: 'get'
	  , data: 'currency=' + (Cookie.get(this.cookieName) == 'GBP' ? 'GBP' : 'USD')
    , onSuccess: this.initCountries.bind(this)
    , onFailure: function(){}
    }).request();
  }
  
, initCountries: function() {
    this.tariffData = Json.evaluate(arguments[0]);
	  if ($defined(this.tariffData)) {
      this.ddlParentObj.empty();
      this.ddlParentObj2.empty();
	  this.ddlParentObj3.empty();
      this.ddlObj = this.createDropDown(this.options.ddlObjID, '', '', this.ddlParentObj);
      this.ddlObj2 = this.createDropDown(this.options.ddlObjID2, '', '', this.ddlParentObj2);
	  this.ddlObj3 = this.createDropDown(this.options.ddlObjID3, '', '', this.ddlParentObj3);

      for(i = 0; i < this.tariffData.prices.length; i++) {
        this.createOption(this.ddlObj, this.tariffData.prices[i].c, i, null);
        this.createOption(this.ddlObj2, this.tariffData.prices[i].c, i, null);
		this.createOption(this.ddlObj3, this.tariffData.prices[i].c, i, null);
        if (this.tariffData.prices[i].c == "USA") {
          this.ddlObj.value = i;
          this.ddlObj2.value = i;
		  this.ddlObj3.value = i;
        }
      }
      this.ddlObj.addEvent('change',this.bindDropdown.bind(this));
      this.ddlObj2.addEvent('change',this.bindDropdown2.bind(this));
	  this.ddlObj3.addEvent('change',this.bindDropdown3.bind(this));
      this.showTariff(this);
	  }
  }

, bindDropdown: function(options) {
  this.ddlObj2.value = this.ddlObj.value;
  this.ddlObj3.value = this.ddlObj.value;
      this.showTariff(this);
}
, bindDropdown2: function(options) {
  this.ddlObj.value = this.ddlObj2.value;
  this.ddlObj3.value = this.ddlObj2.value;
      this.showTariff(this);
}
, bindDropdown3: function(options) {
  this.ddlObj.value = this.ddlObj3.value;
  this.ddlObj2.value = this.ddlObj3.value;
      this.showTariff(this);
}

, showTariff: function(options) {
	if (($('pnl_trusaver_rates') && 
		($('pnl_trusaver_rates').style.display == ''))) {
		// We're on the pricing page (not the home page) and we're showing TruSaver
		this.ddlObj.selectedIndex = this.ddlObj2.selectedIndex;
	}
    var data = this.tariffData.prices[this.ddlObj.selectedIndex].p;
	
	var cs = '';
	if (this.tariffData.currency == 'GBP'){
		cs = '\u00A3';  //£
	} else if(this.tariffData.currency == 'USD'){
		cs = '\u0024';  //$
	} else if(this.tariffData.currency == 'ROW'){
		cs = '\u0024';  //$
	}

  var html = '<table class="data"><thead><th></th><th>Per Minute From:</th></thead>' +
    '<tr><th>Landlines</th><td id="' + this.ddlObjID + '_landlines">' + cs + data.flat.f + '</td></tr>' +
    '<tr><th>Mobiles</th><td id="' + this.ddlObjID + '_mobiles">' + cs + data.flat.m + '</td></tr>' +
    '<tr><th>SMS</th><td id="' + this.ddlObjID + '_sms">' + cs + data.flat.s + '</td></tr>' +
    '<tr><th>Truphones</th><td id="' + this.ddlObjID + '_truphones">FREE</td></tr></table>';
    
  var html2 = '<table class="data"><thead><th></th><th>Per Minute From:</th></thead>' +
    '<tr><th>Landlines</th><td id="' + this.ddlObjID2 + '_landlines">' + cs + data.tier2.f + '</td></tr>' +
    '<tr><th>Mobiles</th><td id="' + this.ddlObjID2 + '_mobiles">' + cs + data.tier2.m + '</td></tr>' +
    '<tr><th>SMS</th><td id="' + this.ddlObjID2 + '_sms">' + cs + data.tier2.s + '</td></tr>' +
    '<tr><th>Truphones</th><td id="' + this.ddlObjID2 + '_truphones">FREE</td></tr></table>';

  var html3 = '<table class="data"><thead><th colspan="2">Per Minute From:</th></thead>' +
    '<tr><th>Landlines</th><td id="' + this.ddlObjID3 + '_landlines">' + cs + data.tier3.f + '</td></tr>' +
    '<tr><th>Mobiles</th><td id="' + this.ddlObjID3 + '_mobiles">' + cs + data.tier3.m + '</td></tr>' +
    '<tr><th>SMS</th><td id="' + this.ddlObjID3 + '_sms">' + cs + data.tier3.s + '</td></tr>' +
    '<tr><th>Truphones</th><td id="' + this.ddlObjID3 + '_truphones">FREE</td></tr></table>';

  this.pnlInfoObj.setHTML(html);
  this.pnlInfoObj2.setHTML(html2);
  this.pnlInfoObj3.setHTML(html3);
  
  try {
    colorFade(this.ddlObjID + '_landlines','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID + '_mobiles','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID + '_sms','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID + '_truphones','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID2 + '_landlines','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID2 + '_mobiles','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID2 + '_sms','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID2 + '_truphones','color','ffffff','ea2b6f',25,25);
	colorFade(this.ddlObjID3 + '_landlines','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID3 + '_mobiles','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID3 + '_sms','color','ffffff','ea2b6f',25,25);
    colorFade(this.ddlObjID3 + '_truphones','color','ffffff','ea2b6f',25,25);
  } catch (e) {}
  
  }
});


var DownloadManager = FormManager.extend({

  // this class dynamically adds a country drop down and country code textbox to the form, and populates the drop down from a remote json file with the supported countries.
  // it then handles the posting of the data to the servlet as well as the response from the servlet, informing the servlet that it is a json submission.
  // if the browser does not support javascript, the form submits as normal and the servlet handles the form differently.
  
  options: {
    countriesAssetPath: false // this is the path to the file that contains json country data [ {code: 'GB', name: 'United Kingdom', dial: 44}, .. ]
  , ddlParent: false          // DOM element or id of the html container that country dropdown will be dropped into
  , txtParent: false          // DOM element or id of the html container that the number text fields live in and 
  , txtNumber: false          // DOM element or id of the html input box that already exists in the form
  , btnObj: false             // DOM element or id of the html submit button
  , ddlObjID: false           // desired DOM id of the html country code dropdown element
  , txtCodeObjID: false       // desired DOM id of the html dialling code text box element
  , txtSuccessUrlObjID: false // desired DOM id of the html success URL hidden text box element
  , ddlCssClass: false        // desired css class of the html country code dropdown element
  , txtCssClass: false        // desired css class of the html dialling code text box element
  , cookieName: false         // name of the install country cookie
  , resultCookieName: false   // name of the installation result
  }
  
, initialize: function(options) {

    this.parent(options);
    this.setOptions(options);
    
    // transform the required options values into elements if passed as ids
    this.ddlParentObj     = this.options.ddlParent    ? ($type(this.options.ddlParent) == 'element'     ? this.options.ddlParent :    $(this.options.ddlParent)) :    $('pnl_download_country');
    this.txtParentObj     = this.options.txtParent    ? ($type(this.options.txtParent) == 'element'     ? this.options.txtParent :    $(this.options.txtParent)) :    $('pnl_download_number');
    this.txtNumberObj     = this.options.txtNumber    ? ($type(this.options.txtNumber) == 'element'     ? this.options.txtNumber :    $(this.options.txtNumber)) :    $('gsm_number');
	  this.txtSuccessUrlObj = this.options.successUrl   ? ($type(this.options.successUrl) == 'element'    ? this.options.successUrl :   $(this.options.successUrl)) :   $('successUrl');
    this.btnObj           = this.options.btnObj       ? ($type(this.options.btnObj) == 'element'        ? this.options.btnObj :       $(this.options.btnObj)) :       $('install_submit');
    this.btnShowDownload	= $('btn_show_pnl_download');
    
    this.cookieName = this.options.cookieName;
  	this.resultCookieName = this.options.resultCookieName;
    
    // modify the html elements in the form
    this.txtCodeObj = this.createTextBox(this.options.txtCodeObjID, this.options.txtCssClass, this.txtNumberObj);
	this.txtCodeObj.setAttribute("disabled", "true");
	this.txtCodeObj.style.color="#000";

    // set the hidden json field to true
    $('json').setProperty('value','true');

  	//init constants
    this.RESULT_COOKIE_SUCCESS_VALUE="success";
    this.RESULT_COOKIE_PATH='/';
    
    // change the submit button
    var btnObjID = this.btnObj.getProperty('id');
    var btnObjClass = this.btnObj.getProperty('class');
    var btnObjValue = this.btnObj.getProperty('alt');
  	var btnObjSrc = this.btnObj.getProperty('src');
    this.btnObj.remove();
    this.btnObj = this.createButton(btnObjID, btnObjClass, this.txtNumberObj);
    //  	this.btnObj = this.createImgButton(btnObjID, btnObjClass, btnObjSrc, this.txtNumberObj);
    //		this.btnObj.setProperty('alt',btnObjValue);
    this.btnObj.setProperty('value','GO');

    this.btnObj.setStyle('display','none');
    //this.btnObj.setProperty('type','button');
    this.btnObj.addEvent('click', this.submitForm.bind(this));

  	//change the show download panel button
  	this.btnShowDownload.setProperty('href', 'javascript: void(0);');
  	this.btnShowDownload.addEvent('click', this.showDownloadPanel.bind(this));
    
    // create the country dropdown and load the countries from json into it
    this.ddlObj = this.createDropDown(this.options.ddlObjID, '', this.options.ddlCssClass, this.ddlParentObj);
    this.ddlObj.addEvent('change',this.setCode.bind(this));
    this.createOption(this.ddlObj, 'Select your country', -1, -1);
    
    this.countryArray = null;
    this.submitJson = null;
    this.countryJson = new Ajax(this.options.countriesAssetPath, {
      method: 'get'
    , onComplete: this.initCountries.bind(this)
    }).request();
  }
 
  
, validateForm: function() {
	var num=this.txtNumberObj.value;
	if (num.length==0){
		//$('pnl_download_errors').setHTML('We need your mobile number! Please enter it in the box.');
		alert('We need your mobile number! Please enter it in the box.');
		return false;
	}else return true;
	
	
	
}

  // this method makes an ajax call that passed the form values to the servlet, and specifies the method to call on completion
, submitForm: function() {
	
	//validate fields first
	if (this.validateForm==false) return;
	
	
	if (this.validateForm()==true){
    // console.log('DownloadManager.submitForm()');
		this.submitJson = new Ajax(this.formObj.getProperty('action'), {
		method: 'post'
		, data: this.getFormForPost()
		, onComplete: this.handleSubmit.bind(this)
		, onFailure: this.handleSubmitFailure.bind(this)
		}).request();
	}
		
  }
  
  // this method is called whenever the country dropdown changes, and sets the country code based on index in the country data array and saves the index in a cookie
, setCode: function() {
    // console.log('DownloadManager.setCode');
    var ix = this.ddlObj.selectedIndex;
    if (ix > 0) {
      this.txtCodeObj.setProperty('value', '+' + this.countryArray[ix - 1].dial);
      Cookie.set(this.cookieName, this.ddlObj.options[this.ddlObj.selectedIndex].value,{path:"/",duration: 10});
    }
  }
  
  // this method is called when the install submit response is received
, handleSubmit: function() {
    // console.log('DownloadManager.handleSubmit');
    var resObj = Json.evaluate(arguments[0]);
    if (resObj.success) {
		Cookie.set(this.resultCookieName, this.RESULT_COOKIE_SUCCESS_VALUE, {path:this.RESULT_COOKIE_PATH});	//successful installation cookie		
		Cookie.set("GSM", resObj.GSM, {path:this.RESULT_COOKIE_PATH}); // added for Altogether affiliate programme 
		
		location.href = resObj.successUrl;				// redirect to the download success page
	} 
    else { 
	//$('pnl_download_errors').setHTML(resObj.errors);// write errors into DOM
	alert(resObj.errors);
	} 
  }
, handleSubmitFailure: function() {
	if(this.submitJson.transport.status != 200){
		//$('pnl_download_errors').setHTML("We're really sorry but we're experiencing technical difficulties with our SMS service at the moment. We're busy sorting out the problem though so please try again soon.");
		alert("We're really sorry but we're experiencing technical difficulties with our SMS service at the moment. We're busy sorting out the problem though so please try again soon.");
	}
  }

//Submits number to web app
, getFormForPost: function() {
    // for posting json to server
    //return "{ 'json': '" + $('json').getValue() + "', '" + this.options.txtNumber + "': '" + this.txtNumberObj.getValue() + "', '"
    //  + this.options.ddlObjID + "': '" + this.ddlObj.getValue() + "', '" + this.options.txtCodeObjID + "': '" + this.txtCodeObj.getValue() + "' }";
    // for regular form post
    return 'json=' + $('json').getValue() + '&' + this.options.txtNumber + '=' + escape(this.txtNumberObj.getValue()).replace('+','%2b') + '&'
      + this.options.ddlObjID + '=' + escape(this.ddlObj.getValue()) + '&' + this.options.txtCodeObjID + '=' + escape(this.txtCodeObj.getValue().replace('+','%2b')) + '&'
      + 'successUrl' + '=' + escape(this.txtSuccessUrlObj.getValue());
  }

  // this is called when the json object loads - populates the select list with the data returned  
, initCountries: function() {
    data = Json.evaluate(arguments[0]);
    this.countryArray = [];
    for (var i = 0; i < data.length; i++) {
      // store the returned json data array
      this.countryArray.push(data[i]);
      // populate the select list
      this.createOption(this.ddlObj, this.countryArray[i].name, this.countryArray[i].code, Cookie.get(this.cookieName));
    }
    // console.log(this.countryArray);
    // unhide the submit button
    // this.btnObj.setStyle('display','inline');
	this.setCode();
  }

, initPinkTickBasedOnCookie: function() {
	var cookieValue=Cookie.get(this.resultCookieName);	
	
	if ($('keepInstallationCookie')){
		if (cookieValue==this.RESULT_COOKIE_SUCCESS_VALUE){ 
			//swap pink tick panel with download panel
			$('pnl_thanks').style.display = "block";
			$('pnl_download').style.display = "none";
		}
	}
	else{
		Cookie.remove(this.resultCookieName, {path:this.RESULT_COOKIE_PATH});	//remove installation cookie
		
	}
  }

, showDownloadPanel: function() {
	//swap pink tick panel with download panel
	$('pnl_thanks').style.display = "none";
	$('pnl_download').style.display = "block";
	Cookie.remove(this.resultCookieName, {path: this.RESULT_COOKIE_PATH});	//remove installation cookie	
  }
});

var RegisterManager = FormManager.extend({

  // this class dynamically adds a country drop down
  
  options: {
    countriesAssetPath: false // this is the path to the file that contains json country data [ {code: 'GB', name: 'United Kingdom', dial: 44}, .. ]
  , ddlParent: false          // DOM element or id of the html container that country dropdown will be dropped into
  }
  
, initialize: function(options) {
    this.parent(options);
    this.setOptions(options);
    
    // transform the required options values into elements if passed as ids
    this.ddlParentObj     = this.options.ddlParent    ? ($type(this.options.ddlParent) == 'element'     ? this.options.ddlParent :    $(this.options.ddlParent)) :    $('pnl_register_country');

    // create the country dropdown and load the countries from json into it
    this.ddlParentObj.innerHTML = "";
    this.ddlObj = this.createDropDown(this.options.ddlObjID, '', this.options.ddlCssClass, this.ddlParentObj);
    this.createOption(this.ddlObj, 'Select your country', -1, -1);
    
    this.countryArray = null;
    this.submitJson = null;
    this.countryJson = new Ajax(this.options.countriesAssetPath, {
      method: 'get'
    , onComplete: this.initCountries.bind(this)
    }).request();
  }
 
  // this is called when the json object loads - populates the select list with the data returned  
, initCountries: function() {
    data = Json.evaluate(arguments[0]);
    this.countryArray = [];
    for (var i = 0; i < data.length; i++) {
      // store the returned json data array
      this.countryArray.push(data[i]);
      // populate the select list
      this.createOption(this.ddlObj, this.countryArray[i].name, this.countryArray[i].code);
    }
  }


});

var Newsmanager = new Class({
	
  options: {
    newsAssetPath: false    //this is the path to the file that contains the blog json
  , newsObjID: false // DOM element or id of the currency form
  }
  
, initialize: function(options) {
    this.setOptions(options);
    
    // transform the required options values into elements if passed as ids - if nothing passed, then grabs the first form in the page
    this.newsObj        = this.options.newsObjID    ? ($type(this.options.newsObjID) == 'element'     ? this.options.newsObjID :    $(this.options.newsObjID)) :    false;
    
	this.countryJson = new Ajax(this.options.newsAssetPath, {
      method: 'get'
    , onComplete: this.initNews.bind(this)
    }).request();

 }
 
, initNews: function() {

    var data = Json.evaluate(arguments[0]);
    this.newsArray = [];
	// for constructing our html elements
	var html = "";
    for (var i = 0; i < data.length; i++) {
      // store the returned json data array
      this.newsArray.push(data[i]);
	  html += "<div><h4><a href='" + data[i].link + "' target='_blank'>" + data[i].title + "</a></h4></div>";
	  //html += "<div><h4><a href='" + data[i].link + "' target='_blank'>" + data[i].title + "</a></h4><p>" + data[i].description + "</p></div>";
	}
	this.newsObj.empty();
	this.newsObj.setHTML(html);
  }
});
Newsmanager.implement(new Options);



var TURateDisplayer = new Class({
	options: {
		currency: 'USD'    // DOM element or id of the currency form
	},
	initialize: function(options){
		this.tariffRatePanel=$('tariffRatePanel');
		if (this.tariffRatePanel!=null && this.tariffRatePanel.id!=null){
			new Ajax(
			"/app/tu-countries",
			{
				method: "get",
				parameters: "",
				onFailure: function(response) {
					// console.log('Error ' + response.status + ' -- ' + response.statusText);
				},
				onSuccess: function(responseHTML) {
					this.json = Json.evaluate(responseHTML);
					this.displayRates();
				}.bind(this)
			}).request();
		}
	},
	displayRates: function(){
		var html="";
		var i=0;
		
		this.slides=new Array();

		for (;i<this.json.regions.length;i++){
			var countryPanelId='panel_'+this.json.regions[i].regionName;
			
			var html="";
			var j=0;
			var countries=this.json.regions[i].countries;
			var tier3CStr="", tier4CStr="";
			for (;j<countries.length;j++){
				tier3CStr+=(countries[j].tier3LL?(countries[j].tier3MB?countries[j].countryName+" (PLUS mobiles)":countries[j].countryName)+", ":"");
				//tier4CStr+=(countries[j].tier4LL?countries[j].countryName+", ":"");
				
			}
			if (tier3CStr!=""){
				html+=tier3CStr.substr(0,tier3CStr.length-2);

				var divR = new Element('div',{'class':'regionHeader', 'refid':countryPanelId}).setHTML("<b refid='panel_"+this.json.regions[i].regionName+"'>"+this.json.regions[i].regionName+"</b>");
				this.tariffRatePanel.appendChild(divR);			

				var divCs = new Element('div',{'class':'tuCountries', 'id':countryPanelId}).setHTML(html);
				this.tariffRatePanel.appendChild(divCs);

				divR.addEvent('click', function(e){//add the click function (i.e on an anchor)
					e = new Event(e);//create a new event here
					var id=e.target.getAttribute('refid');
					if (this.slides[id]==null){
						this.slides[id] = new Fx.Slide(id);
					}
					
					this.slides[id].toggle();//do this to the selected element
					e.stop();//stop the event
				}.bind(this));
				
				this.slides[countryPanelId]=new Fx.Slide(countryPanelId);
				this.slides[countryPanelId].hide();
			}
		}
		//this.tariffRatePanel.innerHTML=html;
	},
	doesContain: function(name){
		var i=0;
		for (;i<this.mobileFreeCountries.length;i++){
			if (this.mobileFreeCountries[i]==name) return true;
		}
		return false;
	}
});