//----------------------------------------------------------------
// TOP ----
//--------------------------------
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
};
// Initialize the checkboxes for selecting tags
var Tags = [];
var TagTitles = [];
var Tags0 = ["Nivå", "Colo", "IaaS", "PaaS", "SaaS", "Programvare"];
var TagTitles0 = ["Nivå i nettskyen", "Vårt utstyr, deres maskinrom.", "Infrastruktur som tjeneste.", "Plattform som tjeneste.", "Porgramvare som tjeneste.", "Programvare (for levering av tjenester)."];
var Tags1 = ["Segment", "Priv", "SMB", "Ent", "Utv", "Org", "ISP"];
var TagTitles1 = ["Markedssegment", "Konsumentmarkedet", "Små/mellomstore virksomheter/Off. sektor", "Store virksomheter", "Utviklingsmiljøer", "Organisasjoner", "Internett-leverandører (konnektivitet)"];
var Tags2 = ["Geografi", "Norge", "Norden", "Europa", "USA", "Verden"];
var TagTitles2 = ["Geografisk dekning", "Norge", "Hele Norden", "Vest-Europa", "Nord-Amerika", "Hele verden"];
var Serv1 = ["VM", "VDS", "SFA", "PM", "DR", "VD", "Publ.", "Media", "Programvare"];
var Serv2 = ["Virtuelle maskiner", "Virtuelle Datasentre", "Sales Force Automation", "Fysiske maskiner", "Disaster Recovery", "Virtuelle Desktops", "Publisering av bøker og magasiner", "Plattform for levering av lyd- og video-strømmer", "Programvareprodukter for nettskyleverandører"]; 

Tags[0] = Tags0;
Tags[1] = Tags1;
Tags[2] = Tags2;
TagTitles[0] = TagTitles0;
TagTitles[1] = TagTitles1;
TagTitles[2] = TagTitles2;

var logoMap = []; // contains url strings to the logos
var evalTitle = ["Ingen kommentar", "Negativt inntrykk", "Blandet inntrykk", "Positive erfaringer"]; 
var abonnent = false;
var guest = false;
var isAnon = false;
var img = ['lamp-0.png', 'lamp-R.png', 'lamp-Y.png', 'lamp-G.png'];
var klikkTekst = "Klikk for detaljer.";
var vendor = [];
var vendorService = [];
var services = ['nothing','nothing'];
var service = "";
var noneSelected = true;
var priColor = '#bca77a';
var $geografi = [];
var vendorList = [];

function initCheckboxes() { 
  var i;
  for (i = 0; i< Tags.length; i++) { // Create the categories
      $('<li class="themebox">'+Tags[i][0]+'</li>').appendTo('#Acheckbox');
  }
  $('<li class="themebox">'+'Valg'+'<ul id="buttonlist"></ul></li>').appendTo('#Acheckbox');
  $('.themebox').each(function(index) {
      //alert(index);
      var content ="";
      if (index < Tags.length) {
       var i;
       content = '<ul id="'+Tags[index][0]+'" title="'+TagTitles[index][0]+'">'; //Hva med norske tegn i ID?
       for (i = 1; i < Tags[index].length; i++) {
          content += '<li class="tagboxV"><label for="'+Tags[index][i]+'" title="'+TagTitles[index][i]+'"><input type="checkbox" name="'+Tags[index][i]+'" id="'+Tags[index][i]+'" value="'+Tags[index][i]+'" />'+Tags[index][i]+'</label></li>';
       }
      }
      $(this).append(content+'</ul>');
  });
  $('<li class="tagbutton"><input class="button pushButton" type="button" name="send" value="Søk nå" id="send" /></li>').appendTo('#buttonlist');
  //$('<li class="tagbutton"><input class="button" type="button" name="alle" value="Velg alle" id="alle" /></li>').appendTo('#buttonlist');
  //$('<li class="tagbutton"><input class="button" type="button" name="ingen" value="Velg ingen" id="ingen" /></li>').appendTo('#buttonlist');
  $('<li class="tagbutton"><input class="button" type="button" name="sok" value="Om søking" id="sok" title="Optimale søk i Leverandørguiden." /></li>').appendTo('#buttonlist');
  $('<li class="tagbutton"><input class="button" type="button" name="om" value="Om tjenesten" id="om" title="Generell informasjon om denne tjenesten." /></li>').appendTo('#buttonlist');
  $('<li class="tagbutton"><input class="button" type="text" id="lSearch" name="lSearch" value="Søk på navn" size="20" maxlength="46" /><div id="vendorNames"><ul></ul></div></li>').appendTo('#buttonlist');
  /*
  $('#alle').click(function() {
     $('#Acheckbox :checkbox').attr('checked', true);
  });
  $('#ingen').click(function() {
     $('#Acheckbox :checkbox').attr('checked', false);
  });
  */
  $geografi = $('#Geografi :checkbox');
  fixGeografi(); //special functions for the Geografi section
  $('#send').click(function() {
     $(this).css({backgroundColor: 'white', color: 'black'});
     $('body').css('cursor', 'wait');
     sendSearch('');
  });
  $('#om').click(function () {
     showInfo(this, '/nettskysenteret/levr-guiden.html');
  });
  $('#sok').click(function () {
     showInfo(this, '/nettskysenteret/search-categories.html');
  });
}
function getHeight() {
     var mHeight;
     if ($.browser.msie) { // messy but necessary
         mHeight = document.documentElement.clientHeight;
         if (mHeight == 0) {
            mHeight = document.body.clientHeight;
         }
     } else {
         mHeight = window.innerHeight;
     }
     //alert('Got height: '+mHeight);
     return parseInt(mHeight - mHeight*0.1 -30, 10);
}

function checkName(nm, nList) { // kan bruke .inarray() her - se boken
   for (var j = 0; j < nList.length; j++) if (nList[j].toUpperCase() == nm.toUpperCase()) return true;
   return false;
}

function showInfo(obj, info) {
     var col = $(obj).css('background-color');
     $(obj).css('background-color', priColor);

     $.get(info+'/getTextContent', function(data) {
        //alert('got data: '+data);
        // must build the content outside of view
        $('#tmpFrame').css({left: -3000, width: 350}).append(data)
          .modal({
            position: ["10%", "25%"],
            opacity: 10,
            maxHeight: getHeight(),
            containerCss: { backgroundColor: '#f3efe7', border: '2px solid #a0a0a0', minWidth: 360, padding: 12, paddingRight: 2},
            closeHTML: "<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>",
            onClose: function (dialog) {
              $('.modalCloseX').hide();
	      dialog.data.fadeOut('slow', function () {
                $('#om').css('background-color', 'white');
		dialog.container.slideUp('slow', function () {
		    dialog.overlay.fadeOut('fast', function () {
			$.modal.close(); // must call this!
                        $('#tmpFrame').empty();
                        $(obj).css('background-color', col);
		    });
		});
	      });
            },
            onOpen: function (dialog) {
              $('.modalCloseX').hide();
              dialog.container.show();
	      dialog.data.fadeIn('slow', function () {
                  $('.modalCloseX').show();
              });
            }
        });
     });
}
$(document).ready(function(){
   if ( $('#abonnent').length > 0 ) { abonnent = true; }
   if ( $('#Guest').length > 0 ) { guest = true; }
   if ( $('#isAnon').length > 0 ) { isAnon = true; }
   placeProfilering();
   if ($.browser.msie && $.browser.version < 8) {
      var warn = '<p><b>Eldre nettlesere som IE6 og IE7 støtter ikke denne tjenesten. Bruk IE8, Firefox, Safari, Opera eller Chrome for å få full funksjonalitet og riktig utseende.</b>';
      var warn2 = '<p><b>NB:</b> IE8 i "kompatibilitetsmodus" identifiserer seg som IE7. Bruk knappen til høyre for adresselinjen i IE8 for å slå av kompatibilitetsmodus.</p>';
      $(warn+warn2).appendTo('#warningMsg').addClass('boks');
      $('#A').fadeOut(300);
      $('#usage').fadeOut(300);
      return false;
   }
   initCheckboxes();

// init the vendor name search function
   var $nl = $('#vendorNames ul');
   var $tmp = $('#vendorNameTemp').show();
   var $sField = $('[name=lSearch]');

   var qs = $('input#lSearch').quicksearch('#vendorNames ul li', {
     'delay': 100,
     'bind': 'keyup keydown',
     'onBefore': function () { $nl.fadeIn('fast');},
     //'onAfter': function () { $nl.fadeOut('fast');},
     'show': function () { $(this).show(); },
     'hide': function () { $(this).hide(); }
   });

   $sField.focus(function() {
      var cont = $(this).val();
      if (cont == 'Søk på navn') {
         $(this).val('').css('color: black');
      } else {
         $(this).css('color: black');
      }
   });
   //$sField.focus();
   $sField.blur(function() {
      $(this).css('color: #666666');
      $nl.slideUp('fast');
   });
   $sField.keypress(function(e) {
      var ch = e.which;
      if (ch == 13) {
         var nm = $(this).val();
         //$('#vendorContent').slideUp('slow');
         //alert('ready to search, val is -'+nm+'-');
         // if there is only one item left in the list - select and search
         var $list = $('#vendorNames ul li:visible');
         // unødvendig å sjekke navnet dersom vi har kun én igjen.
         if ( $list.length == 1) {
             $list.click(); // sender søket ...
             //alert ('velger denne');
         } else {
             //special case: The user may be faster than the drop down list,
             // better check manually...
             if ( !checkName(nm, vendorList) ) {
                alert('Velg ett av navnene fra listen!');
                // rydd i søkefeltet...
                //$('#vendorTable').slideUp(300);
                $sField.focus(); // just in case ...
             } else {
                // simulate a click
                $sField.val(nm).blur();
                $nl.slideUp('fast');
                //alert('sender søk');
                sendSearch(nm);
             }
         }
         return false; // will stop event propagation??
      }
      if (ch == 0 || ch == 27) { // virker ikke i safari
         $nl.slideUp('fast');
         //alert('ESC');
         $sField.blur();
      }
   });
   $nl.hide();
// Bruker selectVendor, ikke selectVendorTAL, trenger ikke den ...
   $tmp.load('/selectVendor?query=getnames', function() { //Må vente med disse til dataene foreligger ...
                                                          // kunne ha brukt 'success:' her
     vendorList = $tmp.text().split('; ');
     $tmp.empty();
     for (var j = 0; j < vendorList.length; j++) {
        $nl.append('<li>'+vendorList[j]+'</li>');
     }
     $('#vendorNames ul li').each(function () {
         $(this).click(function() { 
            var n = $(this).text();
            $sField.val(n).blur();
            $nl.slideUp('fast');
            sendSearch(n);
         });
     });
     qs.cache();
   });

// preload images
   $(img).each(function () {
	var i = new Image();
	i.src = '/MR/gif/' + this;
   });
   $('.checkboxes').corner();
   $('#newSearch').click(function () {
      showErr('Klar for nytt søk. Avmerkede bokser er fra forrige søk.');
      $('#vendorContent').fadeOut(300, function () {
         selectService('close');
      });
      $('#B').slideUp(300, function () {
         $('#A').slideDown(400);
         $('#usage').slideDown(400);
      });
   });
   $.ajaxSetup({cache: false}); //NB: denne er viktig for sanntids oppd. av .kommentarer ...
   $('#sInfo').click(function () {
      showInfo(this, '/nettskysenteret/services.html');
   });
});

function sendSearch(sType) {
   var sendData = "";
   var $waiting = $('#waiting');
   var $gc = $('#vendorContent');
   var leftPos = $gc.css('left');
   var posType = $gc.css('position');
   services = [];
   $('.portalMessage').slideUp(200);
   //$('#vendorTable').slideUp(300);
   if (!abonnent && !guest) { 
      $('#isAnon').fadeOut(500, function() {
         showErr('Du er ikke innlogget. Logg inn for å bruke denne tjenesten. Registrering er gratis.'); 
         clearSend();
      });
      return;
   }
   if (guest) { 
       $('#Guest').slideUp(200);
   }

   $('#errMsg').slideUp(300);
   if (sType != '') { // Direct vendor name search, really a special case ...
      $('#usage').slideUp(300);
      $('#general-wait').fadeIn(200); 
      $gc.empty().css({left: -3000, position: 'absolute'}).show(); // see comment below ... (normal search) 
      //alert('/selectVendorTAL?query=namesearch&name='+encodeURIComponent(sType));
      //IMPORTANT: The addition to the URL is vital, it is the selection from the actual content returned!!
      $gc.load('/selectVendorTAL?query=namesearch&name='+encodeURIComponent(sType)+' #innhold-tema', function() {
         //alert('har fått data om '+sType+', obj: '+$gc.html());
         // may get more than one object, if so - the first is the one we want..
         $('.VENDOR:gt(0)').remove();
         organize();
         $('#general-wait').fadeOut(200, function () {
              $gc.hide().css({left: leftPos, position: posType}).slideDown(400,
              function () {
                //alert('new width: '+ $('.VENDOR:first').width());
              });
         });
      });
      return;
   }
   $('#serviceList').remove();
   $('#Acheckbox :checkbox').each(function() {
      var $this = $(this);
      if (this.checked == true) {
         sendData += $this.closest('ul').attr('id')+'-'+$this.attr('name')+'##';
      }
   });
   if (sendData == "") {
      alert("Ingen av valgboksene er krysset av, ingen resultater!");
      clearSend();
      return;
   }
   $('#usage').slideUp(300);
   //alert(encodeURIComponent(sendData));
   $('#A').slideUp(400, function() { 
      $('#general-wait').fadeIn(200); 
      $waiting.slideDown(200); 
   });
   //$.get('/vendorSearch?query='+encodeURIComponent(sendData), function(data) { // ingen praktisk forskjell
   //$.get('/selectVendorTAL?query='+encodeURIComponent(sendData), function(data) { // på å bruke get og load her..
   $gc.empty().css({left: -3000, position: 'absolute'}).show(); //need to have it 'visible' (unhidden) in order to 
                                          // calculate real estate requirements
   $gc.load('/selectVendorTAL?query='+encodeURIComponent(sendData)+' #innhold-tema', function() {
      $waiting.append('<p id="WWtmp" style="font-size: 16px;">Sorterer data ...</p>');
      organize();
      $gc.hide().css({left: leftPos, position: posType}).slideDown(400, function () {
         var rCount = $('#resultCount').text();
         clearSend();
         $('#general-wait').fadeOut(200, function() { $('#waiting').fadeOut(200); });
         findServices(); // create the service selection menu
         $waiting.find('#WWtmp').remove();
         $('#B').slideDown(300);
         $('#rCount').text(rCount);
         if (rCount != '0') { 
           selectService('open');
         } else {
           $('#Bcheckbox').hide();
           $('.mLogo li.tagbutton:first').hide();
         }
      });
   });
}

function clearSend() {
   $('#send').css({backgroundColor: priColor, color: 'white'});
   $('body').css('cursor', 'default');
}

function organize() {
   // the content from the search has arrived, do organize ...
   // return the last object (used when there is only one ...)
   var $retobj;
   $('.VENDOR').each(function(index) {
      var logo = "";
      var $this = $(this);
      var id = 'X'+parseInt(index, 10);
      //var id = parseInt($this.attr('id').substring(1), 10);
      //var w = $this.width(); // does not work for some reason, gets weird widths when out of view
      var w = 211;
      var $mod = $this.find('.Modified');
      var w1 = $mod.width();
      var $tag = $this.find('.TAG:first');
      var rating = parseInt($this.find('.Rating').text(), 10);
      var $serviceTag = $this.find('.Tjenester');

      $retobj = $this
      $this.corner().attr('id', id);
      vendor[index] = $this;
      $serviceTag.addClass('service');
      vendorService[index] = $serviceTag.text();
      //alert('w(h2)='+w+', w(tag)='+$tag.width()+', w(mod)='+w1);
      addService(vendorService[index]);
      if ($tag.width() > (w - 20 - w1)) {
         //$tag.attr('title', $tag.find('span').text());
         $tag.width(w-24-w1); // 5 extra... -11-8-5
      } 
      
      logo = $this.find('.Logo a').attr('href');
      logoMap[index] = logo;
      if (logo != "") {
         $this.find('.Aheader').prepend('<img class="hLogo" src="'+logo+'" />');
      }
      $this.find('.Logo').remove();
      $this.find('.metaInfo ul').append('<li style="padding-left:0"><img class="lamp" src="/MR/gif/'+img[rating]+'" title="'+evalTitle[rating]+'" /></li>');
      $this.find('.Aheader h2').attr({title: klikkTekst, alt: klikkTekst});
      $this.find('.Vtitle').attr({title: klikkTekst, alt: klikkTekst});
      var geo = $this.find('.Geografi').text();
      if (geo.indexOf('Norge') < 0 && geo.indexOf('Norden') < 0) {
         $this.find('.LevInfo').hide();
      }
      $this.css('cursor', 'pointer').click(function () {
         var $here = $(this);
         var id = parseInt($here.attr('id').substring(1),10);
         $here.find('.infoFrame').modal({
	    closeHTML: "<a href='#' title='Close' class='modalCloseX simplemodal-close'>x</a>",
            minWidth: 370,
            zIndex: 1100,
            position: ['7%', '30%'],
            maxHeight: getHeight(),
            dataCss: {paddingRight: 10},
            containerCss: { backgroundColor: '#f0f0f0', border: '1px solid black', minWidth: 360, padding: 12, paddingRight: 2},
            onOpen: function (dialog) {
	      dialog.overlay.fadeIn('slow', function () {
		dialog.data.hide();
                if (guest) { dialog.data.find('.Marked').hide(); }
		dialog.container.fadeIn('slow', function () {
                        if (logoMap[id] != "") {
                           $(this).find('.ifHead').prepend('<img class="mLogo" src="'+logoMap[id]+'"/>');
                        }
                        findRef($(this).find('.Referanser'));
			dialog.data.slideDown('slow', function () { // don't render until the contents are finished...
                           var contHeight = dialog.container.height();
                           var dataHeight = dialog.data.height();
                           //alert('Outer height: '+ contHeight+' Inner: '+ dataHeight);
                           /*if ( contHeight > (dataHeight + 15)) {
                              dialog.container.animate({height: dataHeight}, 400);
                           }*/
                        });

                        //$('.simplemodal-close').css({left: dialog.container.width()+$('.simplemodal-close').outerWidth()-2, top: -1});
		});
	      });
            },
            onClose: function (dialog) {
	      dialog.data.fadeOut('slow', function () {
		dialog.container.hide('slow', function () {
			dialog.overlay.slideUp('slow', function () {
				$.modal.close();
			});
		});
	      });
            }
         });
      });
   });
   return $retobj;
}

function findRef(list) {
  var eval = "";
  var fagref = "";
  var $list = $(list);
  //alert('findref: '+ $(list).find('li').length); 
  $list.find('li').each(function() {
    var $this = $(this);
    var item = $this.text().split(' -- ');
    if (item.length == 1) {
       $this.remove(); // just the header, no content ...
    } else {
       if (item[1].substr(0,4) == 'http') {
          $this.html('<a href="'+item[1]+'" target="NewWin">'+item[0]+'</a>');
       }
       var thisItem = item[0].substr(0,7);
       if (thisItem == 'Evaluer') {
          $this.remove();
          eval = '<div class="internal"><b>Evaluering</b><p>'+item[1]+'</p></div>';
       }
       if (item[1].search("mymayday.com") != -1) {
          if (fagref == "") {
             fagref = '<div class="internal"><b>Fagreferanser på myMAYDAY.com</b><br><ul>';
          }
          fagref += '<li>'+$this.html()+'</li>';
          $this.remove();
       }
    } 
  });
  if (eval != "") {
    $list.after(eval);
  }
  if (fagref != "") {
    fagref += '</ul></div>';
    $list.after(fagref);
  }
  $list.find('#Plinker').prepend('<div class="fig-right"><b>Fagreferanser<br>fra leverandør</b></div>').wrapInner('<ul></ul>');
  return(list);
}

function findServices() {
  // find and organize all services tags, create a list of checkboxes at the inside the fieldset at the top
  var labelLength = 0;
  var $BC = $('#Bcheckbox');
  services.sort();
  $BC.empty();
  var len = services.length;
  if (len > 2) {
    $('<li class="tagboxH"><label for="Alle"><input type="checkbox" name="alle" id="alle" value="Alle" /><b>Alle</b></label></li>')
      .appendTo($BC);
  }
  for (var i = 0; i< len; i++) { // Create the checkboxes
      var name = services[i];
      $('<li class="tagboxH"><label for="'+name+'"><input type="checkbox" name="'+name+'" id="'+name+'" value="'+services[i]+'" />'+services[i]+'</label></li>')
          .appendTo($BC);
  }
  var $B = $('#B');
  var leftPos = $B.css('left');
  $B.css('left', -3000).show();
  $BC.find(':checkbox').each(function(index) {
      $t = $(this);
      labelLength = Math.max(labelLength, $t.parent().parent().width()); // Find the widest label
      // Attach event handlers to each of them ... Will not work if the content is hidden !!
      $t.click(function() {
         flipSelection(this);
      });
      $t.attr('checked', true); 
      // used to be if (len < 3 && index == 0)
      if (index == 0) {
          $t.attr('checked', true).click();
          $t.attr('checked', true);
      }
  });
  $BC.find('li').width(labelLength+1); // align the checkbox-labels
  $B.hide().css('left', leftPos);
  addServiceTitles($BC);
}

function addService(s) {
  var newServices = [];
  var pos = s.indexOf(':');
  //alert(s + ', pos: '+pos);
  if ( pos > -1) {
     // må ignorere parenteser her
     newServices = s.substring(pos+2, s.length).replace(/\(.*\)/g, '').split(',');
     //newServices = s.substring(pos+2, s.length).replace(/(?:\(.)*\,(?=.*\))/g, ';').split(',');
     //alert(newServices);
     for (var i=0; i<newServices.length; i++) {
        var found = false;
        var ns = newServices[i].replace(/ \(.*$/, '').trim();
        if (ns == '') { continue; }
        if (service.indexOf(ns) == -1) { //finnes ikke allerede ...
           service += ns+','; // denne holder, kan splitte den til slutt, husk trailing comma ...
           services.push(ns);
        }
        for (var j = 0; j < services.length; j++) {
           //alert('compare: '+ns+'---'+services[j]);
           if (ns == services[j]) { found = true; break; } // already registered, skip
        }
        if (!found) { services.push(ns); }
     }
  }
  //alert('addService: '+services);
  return 0;
}

function flipSelection(obj) {
  // TODO: When a tag is unclicked, do not fade if the object has another tag clicked!
  var myTag = obj.getAttribute('name');
  var checked = obj.checked;
  if (noneSelected) {
     noneSelected = false;
     selectService('close');
  }
  if (myTag == 'alle') {
     if (checked) {
        $('#Bcheckbox :checkbox').attr('checked', true);
        $('.VENDOR').removeClass('faded');
     } else {
        $('#Bcheckbox :checkbox').attr('checked', false);
        $('.VENDOR').addClass('faded');
        noneSelected = true;
        selectService('open');
     }
     return 0;
  }
  //alert('flipSelection: '+myTag);
  // loop through all visible vendor objects
  $('.VENDOR').each(function () {
    var $this = $(this);
    var ind = parseInt($this.attr('id').substring(1), 10);
    //alert(vendorService[ind]+' - '+myTag);
    if (vendorService[ind].indexOf(myTag) > -1) {
       // cannot use 'toggle' here since the entry may already have another tag that is active...
       if (checked) { 
          $this.removeClass('faded'); 
          $('#vendorTable').prepend($this); /* move to the beginning of the list */
       } else { $this.addClass('faded'); }
       // should move it up front as well ...
       // maybe we need to keep an array of which services have been selected/deselected ..
    }
  });
}
function showErr(msg) {
   // $.scrollTo($('#errMsg'), 600, {margin: true, offset: -40});
   var $err = $('#errMsg');
   $err.fadeOut(400, function() {
      $err.empty().text(msg).fadeIn(400);
    });
   return true;
}

function selectService(stat) {
   if (stat == 'open') {
     $('#selectService').slideDown(300);
   } else {
     $('#selectService').slideUp(300);
   }
}
function placeProfilering() {
 //$('#portlet-navigation-tree').hide();
 $('#profilering').prependTo("#portal-column-one .visualPadding").show(); // keep this simple for IE7
} 

function fixGeografi() {
 $geografi.each(function(index) {
   if (index > 0 && index != 3) { // not the first
     $(this).click( function () {
        var newStatus = this.checked;
        $(this).parent().parent().prevAll().each( function () {
            //alert($(this).html());
            $(this).find(':checkbox').attr({checked: newStatus}); 
        });
     });
   }
 });
}

//Add titles to service tags whose acronyms are non-obvious...

function addServiceTitles($B) { // do this last - when everything is operative, 
                                // and the time it takes doesn't matter ...
  $B.find('li').each( function() {
    var $t = $(this);
    var name = $t.find('label').attr('for');
    //alert(name);
    for (var j = 0; j < Serv1.length; j++) {
      if (Serv1[j] == name) {
         $t.attr('title', Serv2[j]);
         $t.attr('alt', Serv2[j]);
      }
    }
  });
}
