﻿var isNissan=(location.port==92||/nissanusa|85\.201/.test(location.host));
var BT_XML_PATH = 	isNissan?"/data/bluetooth/xml/"		:"/bluetooth/xml/";
var BT_GUIDE_PATH = isNissan?"/data/bluetooth/setup2/"	:"/bluetooth/setup2/";
var BT_IMG_PATH = 	isNissan?"/img/microsites/bluetooth/phones/":"/img/bluetooth/phones/";
var BT_VEHICLES_FILENAME=isNissan?"vehicles.xml"		:"vehicles-infiniti.xml";
var DEFAULT_IMAGE_SCREEN="default_s.jpg"
var DEFAULT_IMAGE_PRINT ="default_p.jpg"

var sys=[];
sys['Gen1']=0;
sys['Gen2']=1;
sys['04IT']=2;
sys['06IT']=3;
sys['L42A']=4;
sys['08IT']=5;
sys['Gen3']=6;
var sysCount=7; // consider getting this another way.

var mfgTestingIds=[];
var forceDefaultImg=[];

t=('console' in window)?console.log:alert;   //-----------	-	-	-	-	-	-	-	-	-	-	-	

Array.prototype.uniq=function(ee){
	//useful only for 1-dimension arrays of strings
	//operates in place AND returns the result.
	this.sort();
	var c=0,d=0;
	while(c < this.length){
		while( c+d<=this.length ){
			if(this[c]==this[c+d]){
				d++;
			}else{
				break;
			}
		}
		if(d>1){
			this.splice(c,d-1);
		}
		++c;
		d=0;
	}
	return this;
}
function getQsVal(nam){
	if((new RegExp("\\b"+nam+"\\b=([^&]+)")).test(location.search)){
		return (RegExp.$1).replace(/\+|%20/g,' ');
	}else{
		return '';
	}
}


// Returns array of elements within [node] by [classname]
function $C(node, classname){
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0, j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

// Adds [classname] to [el]elment
function addClass(el, classname) {
  if (!el.className) el.className = classname;
  else el.className += " " + classname;
}

// Adds current querystring to anchor [el]elment
function setQString(el) {
  el.href += window.location.search;
}

// Returns hash of key/value pairs from querystring [s]
function getKeyValues(s){
    var h = new Object();
    var p = s.split(/[&;]/);
    for (var i = 0; i < p.length; i++) {
        var n = p[i].split('=');
        while (n[0].charAt(0)==' ') n[0] = n[0].substring(1,n[0].length);
        var k = unescape(n[0]);
        if (n.length == 2) var v = unescape(n[1]);
        h[k] = v;
    }
    return h;     
}

// Returns XMLHttpRequest from [url] to [callback] function
function loadXML(url, callback) {
	if (window.ActiveXObject) 
		var xhr = new ActiveXObject("Microsoft.XMLHTTP");
	else if (window.XMLHttpRequest) 
		var xhr = new XMLHttpRequest();
	if (xhr) {
		xhr.onreadystatechange = function(){
		  callback(xhr);
		}
		xhr.open("GET", url, true);
		xhr.send(null);
	}
}

// Fill select [target] element with options from [items] node by name attribute
// if option text equals [keyvals] hash of same name, option is selected
function loadSelect(target, items, keyvals){
  target.options.length = 1;
  for (var i = 0, j = items.length; i < j; i++) {
	  var opt = document.createElement("option");
	  target.appendChild(opt);
	  opt.text = opt.value = items[i].getAttribute("name");
//	  console.log(opt.text)
	  if (j == 1 || opt.text == keyvals[items[i].tagName]) opt.selected = "selected";
  }
}

// Returns URIcomponent string from display friendly [str]ing	
function cleanName(str){
  str = str.replace(/\s/g, '_');
  str = str.replace(/\/+/g, '&');
  return encodeURIComponent(str);
}

function formatTag(str){
  str = str.replace(/\/|&/g, ''); // remove forward slash and ampersand
  str = str.replace(/\s+/g, '-'); // replace space with dash
  return str;
}

// Namespace wrapper
var bt = {
// Results per page
	perpage: 16,
// key/values hash		
	pairs: {},
	
// Initializes querystring hash, loads vehicles.xml and runs bt.loadForm on XHR response
	init: function(){
		if (window.location.search.length > 0) bt.pairs = getKeyValues(window.location.search.substring(1).replace(/\+/g, ' '));
		bt.flag = true;
		loadXML(BT_XML_PATH + BT_VEHICLES_FILENAME, bt.loadForm);
		
		
		if(		(document.body.id=='find')
			||	(document.body.id=='testing' && location.search.indexOf('&')<1)
			||	(document.body.id=='home')
		){
		    var url = BT_XML_PATH+"db.xml";
		    loadXML(url, bt.loadResults);
		}

		return; /// Killing the line below because it's now coming from xml.
		//
	},
	
// XHR callback, populates vehicle select, fires bt.changeVehicle if vehicle in querystring
	loadForm: function(xhr){
		if (xhr.readyState == 4){
			if (xhr.status == 200){
			  bt.map = xhr.responseXML.documentElement;
			  //console.log(bt.map.getElementsByTagName("vehicle"))
			  var vehicle = document.findForm.vehicle, items = alphabetizeNodes(bt.map.getElementsByTagName("vehicle"),'name');
			  //var vehicle = document.findForm.vehicle, items = (bt.map.getElementsByTagName("vehicle"));
			  loadSelect(vehicle, items, bt.pairs);
			  if (vehicle.selectedIndex != 0) bt.changeVehicle(vehicle);
      }
    }	
	},
	
// Event handler for change of [vehicle] select
// Populates year select from selected vehicle, fires bt.changeYear if year in querystring
	changeVehicle: function(vehicle){
	  var year = document.findForm.year
	  year.options.length = 1;
	  year.selectedIndex = 0;
		document.findForm.equip.options.length = 1;
		document.findForm.equip.disabled = "disabled";
		document.findForm.mfg.options.length = 1;
		if (vehicle.selectedIndex != 0){
			//-find the right one since they're now not in alphabetical order.
			var _vs=bt.map.getElementsByTagName("vehicle")
			for(var i=0;i<_vs.length;i++){
				if(_vs[i].getAttribute('name')==vehicle.value){
					bt.vehicle=_vs[i];
					break;
				};
			}
			var items = bt.vehicle.getElementsByTagName("year");
			loadSelect(year, items, bt.pairs);
			if (year.selectedIndex != 0) bt.changeYear(year);
		}
	},
	
// Event handler for change of [year] select
// Populates equipment select from selected year, fires bt.changeEquip if year in querystring
	changeYear: function(year){
	  var equip = document.findForm.equip
	  equip.options.length = 1;
		equip.disabled = "disabled";
		document.findForm.mfg.options.length = 1;
		if (year.selectedIndex != 0){
	    bt.year = bt.vehicle.getElementsByTagName("year")[year.selectedIndex-1]; 
		  var items = bt.year.getElementsByTagName("equip");
		  loadSelect(equip, items, bt.pairs);
		  if (equip.options.length <= 2) equip.disabled = "disabled";
		  else equip.removeAttribute("disabled");
		  if (equip.selectedIndex != 0) bt.changeEquip(equip);
		}
	},
	
// Event handler for change of [equip] select
// loads (navsystem).xml based on selected vehicle, year, equip, runs bt.loadResults on XHR response
	changeEquip: function(equip){
	  document.findForm.mfg.options.length = 1;
	  if (equip.selectedIndex != 0){
	    bt.equip = bt.year.getElementsByTagName("equip")[equip.selectedIndex-1]; 
	    bt.setup = bt.equip.getElementsByTagName("setup")[0];
	    //#var url = BT_XML_PATH + bt.setup.getAttribute("name") + ".xml";
	    var url = BT_XML_PATH+"db.xml";
	    loadXML(url, bt.loadResults);
	  }
	},
	
	changeMfg: function(mfg){
		if(!('mfgid' in document.findForm)){
			if('ActiveXObject' in window){
				var mfgid = document.createElement('<input name="mfgid" />')
			}else{
				var mfgid = document.createElement('input');
				mfgid.name='mfgid';
			}
			mfgid.type='hidden';
			document.findForm.appendChild(mfgid)
		}
		document.findForm.mfgid.value=bt.mfgidLookup[mfg.value];
		if (bt.submit){
			document.findForm.equip.removeAttribute("disabled");
			document.findForm.submit();
		}
	},
	
// XHR callback, populates manufacurer select, initialized bt.results object
// runs bt.loadPhone, bt.loadFeatures, bt.loadSetup dependent on body id
	loadResults: function(xhr){
		if (xhr.readyState == 4){
			if (xhr.status == 200){
				//#	TRANSLATE	=	=	=	=	=	=	=	=	=	=	=	=	=
				//-	TRANSLATE	=	=	=	=	=	=	=	=	=	=	=	=	=
				//-	TRANSLATE	=	=	=	=	=	=	=	=	=	=	=	=	=
				
				//- actually, maybe right here...
				///////////////////////////////////bt.results = xhr.responseXML.documentElement;
				bt.results=translate(xhr.responseXML.documentElement)
				
				//-	/TRANSLATE	=	=	=	=	=	=	=	=	=	=	=	=	=
				//-	/TRANSLATE	=	=	=	=	=	=	=	=	=	=	=	=	=
				//#	/TRANSLATE	=	=	=	=	=	=	=	=	=	=	=	=	=
				var mfg = document.findForm.mfg, items = bt.results.getElementsByTagName("mfg");
				loadSelect(mfg, items, bt.pairs);
				var body = document.getElementsByTagName("body")[0];
				switch (body.id){
					case "results":
						if (bt.flag) bt.loadPhones();
						break;
					case "phone":
						if (bt.flag){
							bt.tagging();
							bt.loadFeatures();
						} 
						break;
					case "testing":
						var dd=document.getElementsByTagName('div');
						for(var i=0;i<dd.length;i++){
							if(/\bblueTesting\b/.test(dd[i].className)){
								//console.log('found it but now what?')
								setPhonesBeingTestedHTML(xhr.responseXML.documentElement,dd[i]);
								break;
							}
						}
						break;
					case "setup":
						if (bt.flag){
						bt.tagging();
						
						loadXML(BT_GUIDE_PATH + bt.pairs["mfgid"] + "_" + bt.pairs["modelid"] + "_" + sys[bt.pairs["setup"]] + ".htm", bt.loadSetup);
						//# soon:    loadXML(BT_XML_PATH + "setup/" + cleanName(bt.pairs["setup"] + "_" + bt.pairs["mfg2"] + "_" + bt.pairs["phone"]) + ".htm", bt.loadSetup);
					}
					break;
				}
				if(document.getElementsByTagName("body")[0].id != "testing") bt.loadDisclaimer2();
			}
		}
	},
	
// Format crmEvent Parameters	
	tagging: function(){
	  switch (bt.pairs["equip"]){
	    case "Navigation System":
	      n = "(Navi)";
	      break;
	    case "No Navigation System":
	      n = "(Non-Navi)";
	      break;
	    default:
	      n = "";
	      break;
	  }
	  crmEvent1(bt.pairs["vehicle"].replace(/\s+/, "_"),formatTag(bt.pairs["phone"]),n,bt.pairs["setup"],bt.pairs["year"],formatTag(bt.pairs["mfg2"]));
	},
	
// Validates search form, vehicle, year, and equipment require selections
	submit: function(){
	  if (document.findForm.vehicle.selectedIndex != 0 && document.findForm.year.selectedIndex != 0 && document.findForm.equip.selectedIndex != 0){
	    document.findForm.equip.removeAttribute("disabled");
	    return true;
	  } else return false;
  },
	
// Initializes bt.phones object (selected mfg or all) and paging, fire bt.showPhones
	loadPhones: function(){
	  bt.flag = false;
		var mfg = document.findForm.mfg;
		if (mfg.selectedIndex == 0) bt.phones = bt.results.getElementsByTagName("phone");
		else bt.phones = bt.results.getElementsByTagName("mfg")[mfg.selectedIndex-1].getElementsByTagName("phone");
		if (typeof bt.pairs["page"] != "undefined") bt.page = bt.pairs["page"];
		else bt.page = 1;
		bt.pages = Math.ceil(bt.phones.length/bt.perpage);
// Pagination
		var results = $("phoneResults"), count = $("phoneCount"), paging = $C(results, "bluePaging"), prev = $C(results, "bluePrev");
		  next = $C(results, "blueNext"), select = $C(results, "blueSelect"), pages = $C(results, "bluePages");
		for (var i = 0, j = paging.length; i < j; i++){
			if (bt.pages > 1) {
				paging[i].style.display = "block";
				select[i].options.length = 0;
				for (var k = 1; k <= bt.pages; k++){
					var selectOpt = document.createElement("option");
					select[i].appendChild(selectOpt);
					selectOpt.text = k;
					if (k == bt.page) selectOpt.selected = "selected";
				}
				pages[i].innerHTML = bt.pages;
			} else paging[i].style.display = "none";
		}
		count.innerHTML = bt.phones.length;
		results.style.display = "block";
		bt.showPhones();
		bt.pairs = {};
	},
	
// Populates display elements with values from querystring
	loadDetails: function(){
	  var img = $("phoneImage"), img2 = $("phoneImage2"), mfg = $("phoneMfg"), mdl = $("phoneModel"), vcl = $("phoneVehicle"), 
	    yr = $("phoneYear"), eq = $("phoneEquip"), vcl2 = $("phoneVehicle2"), yr2 = $("phoneYear2"), eq2 = $("phoneEquip2");

		var screenImageFileName=bt.pairs["mfgid"] + "_" + bt.pairs["modelid"] + "s.jpg";
		var printImageFileName= bt.pairs["mfgid"] + "_" + bt.pairs["modelid"] + "p.jpg";

		if (img)  img.src = BT_IMG_PATH +  ((screenImageFileName in forceDefaultImg)?DEFAULT_IMAGE_SCREEN:screenImageFileName);
		if (img2) img2.src = BT_IMG_PATH +  ((printImageFileName in forceDefaultImg)?DEFAULT_IMAGE_PRINT : printImageFileName);
		//if (img) img.src = BT_IMG_PATH + bt.pairs["mfgid"] + "_" + bt.pairs["modelid"] + "s.jpg";
		//if (img2) img2.src = BT_IMG_PATH + bt.pairs["mfgid"] + "_" + bt.pairs["modelid"] + "p.jpg";

		if (mfg) mfg.innerHTML = bt.pairs["mfg2"];
		if (mdl) mdl.innerHTML = bt.pairs["phone"];
		if (vcl) vcl.innerHTML =  bt.pairs["vehicle"]; 
		if (vcl2) vcl2.innerHTML =  bt.pairs["vehicle"]; 
		if (yr) yr.innerHTML = bt.pairs["year"];
		if (yr2) yr2.innerHTML = bt.pairs["year"];
		if (bt.pairs["equip"] != "Equipped With"){
	    if (eq) eq.innerHTML = bt.pairs["equip"];
	    if (eq2) eq2.innerHTML = "&nbsp;with&nbsp;" + bt.pairs["equip"];
	  }
	},
	
// XHR callback, loads (setup).htm
	loadSetup: function(xhr){
		if (xhr.readyState == 4){
			if (xhr.status == 200){
	      bt.flag = false;
        bt.loadDetails();
			  $("phoneSetup").innerHTML = xhr.responseText;
			  bt.pairs = {};
			}
		}
	},

// Populates features table from bt.results object
	loadFeatures: function(xhr){
	  bt.flag = false;
    bt.loadDetails();
    
   		///it is cheesy to go through this next line, but it seems to be working outside of here, so y'know.
		var ff=bt.results.getElementsByTagName("mfg");
		for(var i=0;i<ff.length;i++){
			if(ff[i].getAttribute('id')==bt.pairs["mfgid"]){
				var pp=ff[i].getElementsByTagName("phone");
				for(var j=0;j<pp.length;j++){
					if(pp[j].getAttribute('id')==bt.pairs["modelid"]){
						features=pp[j].attributes;
						break;
					}
				}
				break;
			}
		}

    
		//features = bt.results.getElementsByTagName("phone")[bt.pairs["index"]].attributes;
	var compat = $C($("phoneTable"), "phoneCompat");
    for (var i = 1, j = features.length-2; i < j; i++){ //# WAS features.length. I had to add id to the end
      compat[i-1].innerHTML = (features[i].value=='X')?'NA':features[i].value; // made NA == X in the xml.
    }
    bt.pairs = {};
	},
	
// Updates results display and pagination
	showPhones: function()
	{
	    bt.pairs = getKeyValues(window.location.search.substring(1).replace(/\+/g, ' '));
        bt.loadDetails();
        
		var matrix = $("phoneMatrix");
		if (matrix != null) 
		    matrix.innerHTML = "";
		
		var len = bt.phones.length;
		var start = bt.page*bt.perpage-bt.perpage;
		var end = (bt.page*bt.perpage < len) ? bt.page*bt.perpage : len;
		var mfgName = "";
	
		for (var i = 0; i < len; i++)
		{
	        var mfg = bt.phones[i].parentNode.getAttribute("name");
			var mfgid = bt.phones[i].parentNode.getAttribute("id");//# new from sean
		    if (mfg != mfgName)
		    {
			    var mfgDiv = document.createElement("div");
			    matrix.appendChild(mfgDiv);
			    mfgDiv.className = "head clear big print";
			    mfgDiv.innerHTML = mfg;
			    mfgName = mfg;
            }
			
			var model = bt.phones[i].getAttribute("model");
			var modelid = bt.phones[i].getAttribute("id");
			var cell = document.createElement("a"), str = "";
			
	        matrix.appendChild(cell);
		  
		    cell.className = "blueCell";
		    cell.href = "/bluetooth/phone.html?vehicle=" + bt.pairs["vehicle"].replace(/\s/g, '+') 
		      + "&year=" + bt.pairs["year"] + "&equip=" + bt.pairs["equip"].replace(/\s/g, '+') 
		      + "&setup=" + bt.setup.getAttribute("name") + "&mfg2=" + mfg.replace(/\s/g, '+') + "&phone=" + model + "&index=" + i
		      + "&mfg=" + bt.pairs["mfg"] + "&page=" + bt.page + "&mfgid=" + mfgid + "&modelid=" + modelid;
	        
	        if (i >= start && i < end)
	        {
				var screenImageFileName="{0}_{1}s.jpg".format(mfgid,modelid);
				str+='<img src="{0}{1}" />'.format(BT_IMG_PATH,  ((screenImageFileName in forceDefaultImg)?DEFAULT_IMAGE_SCREEN:screenImageFileName)  );
				//str += "<img src='" + BT_IMG_PATH + mfgid + "_" + modelid + "s.jpg'/>";
    	    }
	        str += "<div><span class='noprint'>" + mfg + "</span>&nbsp;" + model + "</div>";
            cell.innerHTML = str;
            
            if ( i < start || i >= end)
                addClass(cell, "print");
		}
		
        // Pagination
        var results = $("phoneResults");
        var paging = $C(results, "bluePaging");
        var prev = $C(results, "bluePrev");
        var next = $C(results, "blueNext");
        var select = $C(results, "blueSelect");
        
		for (var i = 0, j = paging.length; i < j; i++)
		{
			if (bt.page == 1) 
			    prev[i].style.visibility = "hidden";
			else 
			    prev[i].style.visibility = "visible";
			
			if (bt.page == bt.pages) 
			    next[i].style.visibility = "hidden";
			else 
			    next[i].style.visibility = "visible";
			
			select[i].options[bt.page-1].selected = "selected";
		}
	},
	
// Event handler for previous page click
	pagePrev: function(){
		bt.page --;
		bt.showPhones();
		return false;
	},
	
// Event handler for next page click
	pageNext: function(){
		bt.page ++;
		bt.showPhones();
		return false;
	},
	
	pageSort: function(select)
	{
	    var sortBy = select.value;
	    	
        var compare = function(one, two)
        {
            var v_one = null;
            var v_two = null;
            var dir = sortBy == 'date' ? -1 : 1;

            if (sortBy == 'name')
            {
                v_one = one.parentNode.getAttribute('name') + ' ' + one.getAttribute('model');
                v_two = two.parentNode.getAttribute('name') + ' '  + two.getAttribute('model');
            }
            else
            {
                v_one = one.getAttribute(sortBy);
                v_two = two.getAttribute(sortBy);
            }
            
            return (v_one > v_two ? 1 : v_one < v_two ? -1 : 0) * dir;
        };
        
        // unfortunately, we must convert to an array here
	    var tmp = [];
		for (var i=0; i < bt.phones.length; i++)
		    tmp.push(bt.phones[i]);

        bt.phones = tmp.sort(compare);
		bt.showPhones();
	},
	
// Event handler for page select list change
	pageSelect: function(select){
		bt.page = select.options[select.selectedIndex].text;
		bt.showPhones();
		return false;
	},
	mfgDisclaimers:[],
	loadDisclaimer2: function(){
		//console.log('loadDisclaimer2')
		var str = "<p class='noprint'>Availability of specific features is dependent upon the phone's Bluetooth&reg; support. Despite the fact that Bluetooth&reg; is a global standard, many different versions are implemented in today's mobile devices. Every version offered may not support the profiles necessary to successfully communicate with the Nissan Bluetooth&reg; Hands-free Phone System in your Nissan vehicle; therefore, only certain devices have been approved by Nissan. These devices have exceeded the minimum standards for compatibility as of the date of testing. This compatibility list is not a warranty for phone performance or functionality. System performance and feature availability can vary based on phone software version, wireless carrier, coverage, and many other factors outside of Nissan's control. Nissan does not guarantee the availability of any specific feature and makes no guarantees or warranties relating to the performance of these features. Device and feature compatibility status are subject to change without notice. Please refer to your phone owner's manual for details. Cell phone not included. The Bluetooth word mark and logos are owned by Bluetooth SIG, Inc., and any use of such marks by Nissan is under license.</p>"
		+ "<p class='print'>The Bluetooth word mark and logos are owned by Bluetooth SIG, Inc., and any use of such marks by Nissan is under license.</p>";

		if(document.body.id == "testing"){
			for(var i=0;i<mfgTestingIds.length;i++){
				str+=bt.mfgDisclaimers[ mfgTestingIds[i] ];
			}
		}else if(document.body.id == "results" && getQsVal('mfg')=="All Manufacturers"){
			for(var i=0;i<bt.mfgDisclaimers.length;i++){
				if(/^<p.*?>(\s|\s*&nbsp;\s*)<\/p>$/.test(bt.mfgDisclaimers[i]) || (i>0 && bt.mfgDisclaimers[i]==bt.mfgDisclaimers[i-1]))continue;
				str+=bt.mfgDisclaimers[i];
			}
		}else if(getQsVal('mfgid')!=''){
			str+=bt.mfgDisclaimers[ +getQsVal('mfgid') ];
		}
		$("disclaimerText").innerHTML = str;
	},
	
	
// Determines correct mfg disclaimer from querystring
	loadDisclaimer: function(){
    var str = "<p class='noprint'>Availability of specific features is dependent upon the phone's Bluetooth&reg; support. Despite the fact that Bluetooth&reg; is a global standard, many different versions are implemented in today's mobile devices. Every version offered may not support the profiles necessary to successfully communicate with the Nissan Bluetooth&reg; Hands-free Phone System in your Nissan vehicle; therefore, only certain devices have been approved by Nissan. These devices have exceeded the minimum standards for compatibility as of the date of testing. This compatibility list is not a warranty for phone performance or functionality. System performance and feature availability can vary based on phone software version, wireless carrier, coverage, and many other factors outside of Nissan's control. Nissan does not guarantee the availability of any specific feature and makes no guarantees or warranties relating to the performance of these features. Device and feature compatibility status are subject to change without notice. Please refer to your phone owner's manual for details. Cell phone not included. The Bluetooth word mark and logos are owned by Bluetooth SIG, Inc., and any use of such marks by Nissan is under license.</p>"
      + "<p class='print'>The Bluetooth word mark and logos are owned by Bluetooth SIG, Inc., and any use of such marks by Nissan is under license.</p>";
    var mfg = {      BlackBerry: "<p>The BlackBerry and RIM products are the exclusive properties and trademarks of Research In Motion Limited.</p>",      HP: "<p>HP and all HP products are registered trademarks of Hewlett-Packard Company.</p>",      HTC: "<p>&copy; 2007 HTC Corporation.</p>",      LG: "<p>LG and all LG phone models are trademarks or registered trademarks of LG Electronics.</p>",      Motorola: "<p>Motorola and the stylized M logo are registered trademarks of Motorola, Inc.</p>",      Nokia: "<p>Nokia and all Nokia phone models are trademarks or registered trademarks of Nokia Corporation.</p>",      Palm: "<p>&copy; 2007 Palm, Inc.</p>",      Samsung: "<p>2007 Samsung. All Rights Reserved.</p>",      Sanyo: "<p>SANYO is a registered trademark of the SANYO Electric Co., Ltd.  Katana is a registered trademark of the SANYO Fisher Company, a division of SANYO North America.</p>",      Siemens: "<p>&copy; Siemens Information and Communication Mobile, LLC.</p>",      Sony_Ericsson: "<p>Sony Ericsson and the Sony Ericsson logo are trademarks or registered trademarks of Sony Ericsson.</p>",      UT_Starcom: "<p>&copy; 2006 UT Starcom Incorporated.</p>"    }
		var body = document.getElementsByTagName("body")[0];
		if (body.id == "results"){
      if (typeof bt.pairs["mfg"] != "undefined"){
        if (bt.pairs["mfg"] == "All Manufacturers"){
          for (var i in mfg){
            str += mfg[i];
          }
        } else {
          mfgname = bt.pairs["mfg"].replace(/\s/g, "_");
          //alert(bt.pairs["mfgid"])
          mfgname = mfgname.replace(/_\(.+\)/, ""); // remove carrier in parens
          str += mfg[mfgname];
        }
      }
		} else if (typeof bt.pairs["mfg2"] != "undefined"){
      mfgname = bt.pairs["mfg2"].replace(/\s/g, "_");
      mfgname = mfgname.replace(/_\(.+\)/, ""); // remove carrier in parens
      str += mfg[mfgname];
    }
    $("disclaimerText").innerHTML = str;
	},
	
// Toggle disclaimer display
	toggleDisclaimer: function(trigger){
	  var disc = $("disclaimer");
	  if (disc.style.display != "block") disc.style.display = "block";
	  else disc.style.display = "none";
	  return false;
	},
	mfgidLookup:[]
}




var pFeaturesList=['pairing','placecall','receivecall','transfer','reconnect','endcall','waiting','bookaccess','booksingle','bookentire','battery','callerid','signal'];


//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------

//loadXML("/CMS/db.xml",translate);
function setPhonesBeingTestedHTML(x,blueDiv){
	var rv=[];//return value.. will be join()ed
	var allP=x.getElementsByTagName('P');
	var mfgPhones,pbtCount=0;
	var pbt=[];//phones being tested
	var mbt=[];//mfg being tested
	mfgTestingIds=[];
	var midLookup=[];//lookup so we can put disclaimers in apha order
	
	/// fill arrays with only the phones being tested
	for(var i=0;i<allP.length;i++){
		if(allP[i].getAttribute('f').length==(sysCount-1)){ // blank. just a bunch of commas.
			var dadName=allP[i].parentNode.getAttribute('n');
			var phoneName=allP[i].getAttribute('n')
			mbt.push(dadName);
			
			midLookup[dadName]= +allP[i].parentNode.getAttribute('id')
			
			pbt[dadName]=pbt[dadName]||[];
			pbt[dadName].push(phoneName);
		}
	}
	mbt.uniq();// get a unique list of names
	for(var i=0;i<mbt.length;i++){
		mfgTestingIds.push(midLookup[mbt[i]]) // doing it this way so it'll be in alpha order
		rv.push('<div class="clear big">'+mbt[i]+'</div>');
		mfgPhones=pbt[mbt[i]].uniq();
		for(var j=0;j<mfgPhones.length;j++){
			pbtCount++
			rv.push('<span>'+mfgPhones[j]+'</span>')
		}
	}
	blueDiv.innerHTML= rv.join('\n');
	document.getElementById('phoneCount').innerHTML=pbtCount;

	bt.loadDisclaimer2()

}


		
function alphabetizeNodes(NL,att){//NL:NodeList,att:attribute to alphabetize by;
	var Os=[];var Ns=[];var leftovers=[];var rv=[];
	for(var i=0;i<NL.length;i++){
		if(NL[i].getAttribute(att)==null){
			leftovers.push(NL[i])
		}else{
			Os[NL[i].getAttribute(att)]=NL[i];
			Ns.push(NL[i].getAttribute(att));
		}
	}
	Ns.sort();
	for(var i=0;i<Ns.length;i++){
		rv.push(Os[Ns[i]]);
	}
	return rv.concat(leftovers)
}


function translate(x){
//alert(bt['setup'].getAttribute("name"))
	if(window.ActiveXObject){
		var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
		xmldoc.loadXML('<setup />')     //xmldoc.createElement("setup")
	}else if (window.XMLHttpRequest){
		var xmldoc = document.implementation.createDocument("", "setup", null);
	}
	if (xmldoc) {
		var su=xmldoc.getElementsByTagName("setup")[0];
		
		if(!bt.setup){
			/// this is an ugly little hack to make it work on testing and find.
			bt.setup={}
			bt.setup.getAttribute=function(){return 'Gen1'}
		}
		var systemIndex=sys[bt.setup.getAttribute("name")]

		makeAttribute(xmldoc,su,'name',bt.setup.getAttribute("name"));
		makeAttribute(xmldoc,su,'id',systemIndex);

		//#x=y.responseXML.documentElement
		
		var Ms=alphabetizeNodes(x.getElementsByTagName("MFGR"),'n');
				
		for(var i=0;i<Ms.length;i++){
			//var isApplicable=false;
			var thisMfg=xmldoc.createElement("mfg");
			makeAttribute(xmldoc,thisMfg,'id',Ms[i].getAttribute('id'));
			makeAttribute(xmldoc,thisMfg,'name',Ms[i].getAttribute('n'));

			bt.mfgidLookup[Ms[i].getAttribute('n')]= +Ms[i].getAttribute('id');

			var hasADisclaimer=Ms[i].getElementsByTagName('D')[0].childNodes.length;
			var myDisc=(!hasADisclaimer)?'':Ms[i].getElementsByTagName('D')[0].childNodes[0].nodeValue;
			//t(myDisc)

			bt.mfgDisclaimers[String(Ms[i].getAttribute('id'))]='<p>'+myDisc+'</p>';

			var Ps=alphabetizeNodes(Ms[i].getElementsByTagName("P"),'n');
			for(var j=0;j<Ps.length;j++){
				var thisP=Ps[j];
				var myFeatures=thisP.getAttribute('f').split(',')[systemIndex];
				if(myFeatures.length==13){
					var thisPhone=xmldoc.createElement("phone");
					makeAttribute(xmldoc,thisPhone,'model',thisP.getAttribute('n'));
					var mfl=myFeatures.split('');
					var tFeat;
					for(var k=0;k<mfl.length;k++){
						makeAttribute(xmldoc,thisPhone,pFeaturesList[k],mfl[k]);
						//tFeat=xmldoc.createAttribute(pFeaturesList[k]);
						//thisPhone.setAttribute(pFeaturesList[k],mfl[k]);
					}
					makeAttribute(xmldoc,thisPhone,'id',thisP.getAttribute('id'));// had to go at the end since they're by ordinal!
        			makeAttribute(xmldoc,thisPhone,'date',thisP.getAttribute('da'));
					thisMfg.appendChild(thisPhone)
					
					var forceDef=thisP.getAttribute('d');
					if(forceDef){//force defaults
						var commonPart=Ms[i].getAttribute('id')+"_"+thisP.getAttribute('id');
						if(forceDef.indexOf("s")>=0){forceDefaultImg[commonPart+'s.jpg']=true}
						if(forceDef.indexOf("p")>=0){forceDefaultImg[commonPart+'p.jpg']=true}
					}
				}
			}
			if(thisMfg.getElementsByTagName("phone").length){
				//alert('appending')
				su.appendChild(thisMfg)
			}
		}
		//console.log(xmldoc.documentElement)
		return xmldoc.documentElement;
	}
}
function translateWORKED(x){ //#if (y.readyState == 4 && y.status == 200){
//alert(bt['setup'].getAttribute("name"))
	if(window.ActiveXObject){
		var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
		xmldoc.loadXML('<setup />')     //xmldoc.createElement("setup")
	}else if (window.XMLHttpRequest){
		var xmldoc = document.implementation.createDocument("", "setup", null);
	}
	if (xmldoc) {
		var su=xmldoc.getElementsByTagName("setup")[0];
		var systemIndex=sys[bt.setup.getAttribute("name")]

		makeAttribute(xmldoc,su,'name',bt.setup.getAttribute("name"));
		makeAttribute(xmldoc,su,'id',systemIndex);

		//#x=y.responseXML.documentElement
		
		var Ms=x.getElementsByTagName("MFGR");
		for(var i=0;i<Ms.length;i++){
			//var isApplicable=false;
			var thisMfg=xmldoc.createElement("mfg");
			makeAttribute(xmldoc,thisMfg,'id',Ms[i].getAttribute('id'))
			makeAttribute(xmldoc,thisMfg,'name',Ms[i].getAttribute('n'))

			var myDisc=Ms[i].getElementsByTagName('D')[0].childNodes[0].nodeValue;
			bt.mfgDisclaimers[String(Ms[i].getAttribute('id'))]='<p>'+myDisc+'</p>';
			//console.log(myDisc)
			//mfgDisclaimers

			var Ps=Ms[i].getElementsByTagName("P");
			for(var j=0;j<Ps.length;j++){
				var thisP=Ps[j];
				var myFeatures=thisP.getAttribute('f').split(',')[systemIndex];
				if(myFeatures.length==12){
					var thisPhone=xmldoc.createElement("phone");
					makeAttribute(xmldoc,thisPhone,'model',thisP.getAttribute('n'));
					var mfl=myFeatures.split('');
					var tFeat;
					for(var k=0;k<mfl.length;k++){
						makeAttribute(xmldoc,thisPhone,pFeaturesList[k],mfl[k]);
						//tFeat=xmldoc.createAttribute(pFeaturesList[k]);
						//thisPhone.setAttribute(pFeaturesList[k],mfl[k]);
					}
					makeAttribute(xmldoc,thisPhone,'id',thisP.getAttribute('id'));// had to go at the end since they're by ordinal!
					thisMfg.appendChild(thisPhone)
				}
			}
			if(thisMfg.getElementsByTagName("phone").length){
				//alert('appending')
				su.appendChild(thisMfg)
			}
		}
		//console.log(xmldoc.documentElement)
		return xmldoc.documentElement;
	}
}//#}

function makeFeatures(myDoM,myNode,attrString){
	var MFL=attrString.split('');
	var myAttr;
	for(var i=0;i<MFL.length;i++){
		myAttr=xmldoc.createAttribute(pFeaturesList[i]);
		myNode.setAttribute(pFeaturesList[i],MFL[i])
	}
}

function makeAttribute(myDoM,myNode,attrName,attrVal){
	//var _at=
	myDoM.createAttribute(attrName);
	myNode.setAttribute(attrName,attrVal)
}

// this is for the phones page. it makes the features tooltips work in ie6.
jQuery(function(){
	if(jQuery.browser.msie && jQuery.browser.version.substr(0,1)==6){
		jQuery(".phoneFeatureDetail").each(function(){
			this.onmouseover=function(){
				this.className+=" phoneFeatureDetailHover";
			}
			this.onmouseout=function(){
				this.className=this.className.replace(/\s*phoneFeatureDetailHover/g,'');
			}
		})
	}
});








