jQuery(document).ready(function($){
  // jQuery scrollTo plugin
  setTimeout(function()
  {
    if (jQuery.scrollTo)
    {
      jQuery('#serveroverview').scrollTo( '600', 0 );
      jQuery('#serveroverview').scrollTo( '0', 1500 );
    }
  }, 500);
	
  jQuery('#scrollleft, #scrollleftshort').click(function(){
    $('#serveroverview').stop().scrollTo( '-=145', 200, {axis:'x'} );
  });

  jQuery('#scrollright, #scrollrightshort').click(function(){
    $('#serveroverview').stop().scrollTo( '+=145', 200, {axis:'x'} );
  });

  $('#clientsleft').click(function(){
    $('#scrollcontent').stop().scrollTo( '-=621', 400, {axis:'x'} );
  });
  
  $('#clientsright').click(function(){
    $('#scrollcontent').stop().scrollTo( '+=621', 400, {axis:'x'} );
  });

  $('a[data-helpicon]').click(function () {
    var description = $('#description');
    if(!description.length)
    {
      description = $('<div>')
        .attr('id', 'description')
        .css('display', 'none')
        .append($('<h5>').addClass('lightbox'))
        .append($('<div>').attr('id', 'lightbox')).appendTo($('body'));
    }
    var close = $(this).attr('data-closelink') || '';
    var text = '<p>' + $(this).attr('data-helpicon') + '</p>' + close;
    $('div#description').children('div#lightbox').html(text);
    $.facebox.settings.opacity = 0.3;
    $.facebox({div: '#description'});
    $('#facebox a.close').hide();
    return false;
  });

  displayWebhostingPromo();
  //jQuery facebox
  if (jQuery.facebox)
  {
    $('a[rel*=facebox]').facebox();
    $.facebox.settings.opacity = 0.3;
    $(document).bind('reveal.facebox', function () 
    { 
      if ($('#facebox .body object').length > 0) 
      {
        $('#facebox').css('width', 'auto');
        $('#facebox table').css('width', 640 + 30);
      } 
      if ($('#facebox .body iframe').length > 0) 
      {
        $('#facebox').css('width', 'auto');
        $('#facebox table').css('width', 640 + 20);
      } 
    });
    $(document).bind('close.facebox', function () 
    { 
      $('#facebox iframe').attr('src','#'); //remove the video (so that the sounds stops)
      $('#facebox').css('width', '450');
      $('#facebox table').css('width', 'auto');
    });
  }
  $('#facebox a.close').hide();

  if ($('a.webhosting-popup').length)
  {
    $('a.webhosting-popup').click(function () {
      var url = $(this).attr('href');
      var header = $(this).attr('data-header');
      $.get(url, function (r) {
        var el = $(r);
        el.prepend(header);
        el.find('#contentmain').remove();
        el.find('.cols1:not(.pagetop)').remove();
        el.find('a.button').each(function () {
          $(this).parent().remove();
        });
        $.facebox(el, 'webhosting-overlay');
        $('#facebox').width(660);
      });
      return false;
    });
  }

  testFontFace('Calibri');
  setFlash();

  checkSpecialPrice();
  displayScroll();
  attachSearchSuggestions();

  jQuery('input[name*=agree]').live('click', function(){
        if (jQuery('#agree-checkbox:checked').val() == 1)
        {
          jQuery.cookie('green_hosting', 1, {expires: 1, path: '/'});
          jQuery.facebox.close();
          checkSession(jQuery.cookie('green_link'));
        }
        else
        {
          jQuery.cookie('green_link',null);
          jQuery.cookie('green_hosting', null);
          jQuery.facebox.close();
        }
  });

   var loc = new String(window.parent.document.location);
   jQuery('#login-submit').live('click', function(){
    var form = jQuery('#loginform');
    var username = jQuery('#signin_username').val();
    var password = jQuery('#signin_password').val();
    if ( loc.indexOf("https://") != -1)
    {
      jQuery.ajax({
        type: 'POST',
        url: jQuery(form).attr('action'),
        data: {
          'signin[username]': username,
          'signin[password]': password
        },
        success: function (resp, status) {
          if (resp == 'ok')
          {
            window.location.reload();
          }
          else
          {
            jQuery('.popup .content').html(resp);
          }
        }});
     }
     else
     {
       jQuery(form).submit();
     }
    return false;
   });

    jQuery('#btn-save-newsletter-settings').live('click', function()
    {
      var form = jQuery('form#newsletter_settings_form');
      var setting = jQuery('input[name=receive_newsletter]:checked').val();
      jQuery.ajax(
      {
        type: 'POST',
        url: jQuery(form).attr('action'),
        data:
        {
          'receive_newsletter': setting
        },
        success: function (resp, status)
        {
          if (resp == 'ok')
          {
            window.location.reload();
          }
          else
          {
            jQuery('.popup .content').html(resp);
          }
        }
      });
    return false;
  });
  
  //showing the questionmark data popup
  jQuery('a.help-question-mark').click(function () 
  {
    var data = jQuery.parseJSON(jQuery(this).attr("data-info"));
    jQuery('div#description').children('div#lightbox').html("<p>" + data.info + "</p>");
    if(null == jQuery('a#close').html()) // jQuery('div#description a#close').html() not working in IE
    {
      jQuery('h5.lightbox').before(data.link);
    }
    jQuery('h5.lightbox').html(data.desc);
    jQuery.facebox.settings.opacity = 0.3;
    jQuery.facebox({div: '#description'});
    jQuery('#facebox a.close').hide();
  
    _gaq.push(['_trackPageview', '/description/' + data.desc]);
    _gaq.push(['_trackPageLoadTime']);
  
    return false;
  });
  
  //language switcher
  jQuery('#langDropDown').click(function()
  {
    if(jQuery('#flagsList').css('display') == 'none') {
      jQuery('#flagsList').css('display','block');
    } else {
      jQuery('#flagsList').css('display','none');
    }
  });
  jQuery('#flagsList').mouseleave(function() 
  {
    jQuery('#flagsList').css('display','none');
  });

  if($("a[rel^='lightbox']").length)
  {
    $('head').append($('<script type="text/javascript" src="/js/slimbox2.js"></script>'));
    $('head').append($('<link rel="stylesheet" type="text/css" href="/css/slimbox2.css"></script>'));
  }

  //FAQ
  jQuery('ul#faqCategories li div.faqCategory').live('click',function() {
    if(jQuery(this).parent().children('ul').is(':hidden')) {
      //reset all the values
      jQuery('ul#faqCategories ul.faqQuestions').hide();
      jQuery('ul#faqCategories div.faqContent').css('position','absolute'); //hide
      jQuery('ul#faqCategories div.faqContent').css('margin-left','-9999px');
      jQuery('ul#faqCategories li div.faqCategory').css('background-image', 'url(/images/lsw2/collapsed.png)');
      //set the values for the clicked faq group
      jQuery(this).css('background-image', 'url(/images/lsw2/expanded.png)');
      jQuery(this).parent().children('ul').slideDown('fast', 'linear');
    } else {
      //reset all the values
      jQuery('ul#faqCategories ul.faqQuestions').slideUp('fast', 'linear');
      jQuery('ul#faqCategories div.faqContent').css('position','absolute'); //hide
      jQuery('ul#faqCategories div.faqContent').css('margin-left','-9999px');
      jQuery('ul#faqCategories li div.faqCategory').css('background-image', 'url(/images/lsw2/collapsed.png)');
    }
  });

  jQuery('ul#faqCategories ul.faqQuestions span.faqQuestion').live('click',function() {
    if('absolute' == jQuery(this).parent().children('div').css('position')) {
      jQuery('ul#faqCategories div.faqContent').css('position','absolute');
      jQuery('ul#faqCategories div.faqContent').css('margin-left','-9999px');
      jQuery(this).parent().children('div').css('margin-left', '0'); //show
      jQuery(this).parent().children('div').css('position', 'static');
    } else {
      jQuery(this).parent().children('div').css('position','absolute'); //hide
      jQuery(this).parent().children('div').css('margin-left','-9999px');
    }
  });

  jQuery('div#expandAll span').click(function(){
    jQuery(this).parent().hide();
    jQuery('div#collapseAll').show();
    jQuery('ul#faqCategories li div.faqCategory').css('background-image', 'url(/images/lsw2/expanded.png)');
    jQuery('ul#faqCategories ul.faqQuestions').parent().children('ul').show();
    jQuery('ul#faqCategories div.faqContent').show();
  });

  jQuery('div#collapseAll span').click(function(){
    jQuery(this).parent().hide();
    jQuery('div#expandAll').show();
    jQuery('ul#faqCategories li div.faqCategory').css('background-image', 'url(/images/lsw2/collapsed.png)');
    jQuery('ul#faqCategories ul.faqQuestions').parent().children('ul').hide();
    jQuery('ul#faqCategories div.faqContent').hide();
  });
  //end FAQ

  //login tooltip
  $('#signin_username').focus(function(){
      $('#login_tooltip').show();
  });
  $('#signin_username').blur(function(){
      $('#login_tooltip').hide();
  });
  
  //homepage banner
  $('#animated-banner').show();
  $('div.banner').cycle(7000);
  
  //left menu phone numbers drop down
  $('#help a.primary_phone').click(function(){    
    if($('#help a.secondary_phone').is(':hidden'))  //display the drop down
    {
      $('#help a.secondary_phone').slideDown('fast', 'linear');
      $('#help a.secondary_phone').css('display', 'block');
      $('#help div.phonelist').css('background-position','-19px 23px');
    }
    else  //hide the drop down
    {
      $('#help div.phonelist').css('background-position','140px 23px');
      $('#help a.secondary_phone').slideUp('fast', 'linear');
    }
  });
  
  $('#creditCardButton').click(function(){
    $.ajax({

      dataType: 'json',
      type: 'post',
      data: {'method': 'creditcard', 'no_vat' : jQuery('#creditCardForm #no_vat').val() },
      cache: false,


      success: function(data){
        jQuery('#creditCardForm').css('display','none');                               // Hide the form
        jQuery('#creditCardForm').attr('action', data['formaction']);                  // Set the action (got form server)
        jQuery('#creditCardForm').html(data['formfields']); 
        // Move in the form data
        jQuery('#creditCardForm').submit();                                            // And submit
      },
      error: function(data){
        alert(data.responseText);
      }

    });  
  });
});

$(window).load(function () {
  calcServerOverviewPanelHeight();
});

function calcServerOverviewPanelHeight() {
  var c     = jQuery('div.server-list');
  var table = c.find('#serveroverview table.serveroverview'),
    navbars = c.find('.navleft, .navright'),
    labels  = c.find('>.labels'),
    marginTop = 0;
  
  labels.css('margin-top', 0);
  
  table.find('tr').each(function (i) {
    
    var el = $(this).find('td,th').eq(0),
        label = labels.find('tr:eq(' + i + ') td'),
        source, destination, height, diff;
    
    if(!label[0])
    {
      return true;
    }
    
    if(i<3)
    {
      marginTop += el.outerHeight();
    }
    
    if(label.outerHeight() < el.outerHeight())
    {
      source  = el;
      destination    = label;
    }
    else if (label.outerHeight() > el.outerHeight())
    {
      source  = label;
      destination    = el;
    }
    else
    {
      return true;
    }

    height = source.outerHeight() - (destination.outerHeight() - destination.height());
    destination.height(height);
    diff  = source.outerHeight() - destination.outerHeight();
    if(diff != 0)
    {
      destination.height(height + diff)
    }
    
    
  });
  var tHeight = (table.outerHeight() - 25 - marginTop) / 2;
  navbars.css({'margin-top': marginTop}).find('a').css({'padding': tHeight + 'px 1px '});
  jQuery("td#no_results").css({'padding-top': marginTop});
}

function displayWebhostingPromo()
{
  var numWebhost = jQuery('#numWebhost').val();
  var numDomains = jQuery("#numDomains").val();

  if( numWebhost == 0 && (numDomains > numWebhost))
  {
    jQuery('#webhosting_promo').show();
  }
  else
  {
    jQuery('#webhosting_promo').hide();
  }
}

function focusSearch() {
	$('#searchsuggest').css("display", "block");
}

/**
* testFontFace
*
* Tests if the small Calibri font is available, and otherwise will increase the general font-size.
*
* @return void
*/

function testFontFace(whatfont) {
	var detective = new Detector();
	if (!detective.test(whatfont)) {	
		$("#wrapper").css("font-size","89%");	
	        $("h2").css("font-size","180%");
                $("h2").css("line-height","120%");
                $("h2").css("padding-top","5px");
		$("th").css("padding-bottom","0");
	}
}

/**
* setFlash
*
* sets all flash elements on the page
*
* @return void
*/

function setFlash() {

      /// FLASH ELEMENTS ON HOMEPAGE ///

      var params = {
        wmode: "transparent"
      }; 

      var xmlLang = window.location.pathname.substring(1,3);
      var mapFlashvars = {
        debugflashvars: "false",
        xml: "/maps/lswnetwork-" + xmlLang + ".xml"
      };

      //Display network map
      swfobject.embedSWF("/flash/umap_cloudmade.swf", "lsw-map", "804", "450", "9.0.0", "/flash/expressInstall.swf", mapFlashvars, params);
}

// fake Klapper
function $$ (v) {return jQuery(v);}
function Klapper (container, link, content) {
  var exp = new Array();
  jQuery(container).find(content).hide();
  jQuery(container).find(link).click(function(){
    try
    {
      var trackLink = getRequestPath([0, 1]);
      trackLink = trackLink.replace('#', '');
      trackLink += '/custom/' + makeSlug(jQuery(this).text());
      _gaq.push(['_trackPageview', trackLink]);
      _gaq.push(['_trackPageLoadTime']);
    }
    catch (e) {}
    jQuery(container).find(content).slideUp('slow'); 
    jQuery(this).parent().find(content).toggle('slow');
    return false;
  });
}


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};


function openPopup(argStrFile, argStrFrameName, argIntWidth, argIntHeight, argIntLeftStart, argIntTopStart, argIntScrollbars, argIntResizeable)
{
	if(!argStrFrameName)
	{
		argStrFrameName = 'popup';
	}
	if(!argIntWidth)
	{
		argIntWidth = 560;
	}
	if(!argIntHeight)
	{
		argIntHeight = 420;
	}
	if(!argIntLeftStart)
	{
		argIntLeftStart = (screen.width/2) - (argIntWidth/2);
	}
	if(!argIntTopStart)
	{
		argIntTopStart = (screen.height/2) - (argIntHeight/2);
	}
	if(!argIntScrollbars)
	{
		argIntScrollbars = 'no';
	}
	if(!argIntResizeable)
	{
		argIntResizeable = 'no';
	}

	BrowserDetect.init();

	if (BrowserDetect.browser == 'Chrome') {
		argIntHeight = 450;
	}

	var strProperties = "width=" + argIntWidth + ", height=" + argIntHeight + ", left=" + argIntLeftStart + ", top=" + argIntTopStart + ", toolbar=no, titlebar=no, title=0, location=no, scrollbars=" + argIntScrollbars + ", status=no, resizable=" + argIntResizeable;

	window.open(argStrFile, argStrFrameName, strProperties);
}

function openLiveChat()
{
  _gaq.push(['_trackPageview', '/contact/chat']);
  _gaq.push(['_trackPageLoadTime']);
  openPopup('http://slsw-im01.ocom.lan:9090/webchat/userinfo.jsp?chatID=32I3Xs4SN0&workgroup=sales@workgroup.slsw-im01.ocom.lan', 'framemain', 620, 400);
  return false;
}

function InsertMailToTag( userName, domainName, text, className)
{
  var EmailId;
  var atSign = "&#64;";
  var fullStop = "&#46";
  EmailId = userName;
  EmailId = "" + EmailId + atSign;
  EmailId = EmailId + domainName;
  if(typeof text == 'undefined' && !text)
  {
    text = EmailId;
  }

  if(typeof className == 'undefined' && !className)
  {
    className = "";
  }

  document.write( "<a class='" + className + "' href='mail" + "to:" + EmailId + "'>" + text
  +"</A>" );
}

function checkSession(data, culture)
{
  if (jQuery.cookie('green_hosting') == 1)
  {
    window.location = data;
  }
  else
  {
    jQuery.cookie('green_link', data);
    jQuery.facebox({ajax: '/'+culture+'/greenhosting/terms'});
  }
}

function checkGreenSession(data, culture, el)
{
  if (jQuery.cookie('green_hosting') == 1)
  {
    window.location = data;
  }
  else
  {
    jQuery.cookie('green_link', data);
    jQuery.get('/' + culture + '/dedicated-servers/greenhosting-agreement', function (resp) {
      var content = $('<div>').html(resp);
      content.find('.cols1').css({margin: 20});
      var btn = content.find('.button.big');
      btn.click(function (e) {
        if(!checkValue())
        {
          return false;
        }
        e.stopPropagation();
        window.location = $(el).attr('href');
        return false;
      }).attr('onclick', '').attr('href', '#');
      jQuery.facebox(content);
    });
  }
}

function checkCallbackCookie(key, url, culture, el)
{
  if (!key || jQuery.cookie(key) == 1)
  {
    return true;
  }
  else
  {
    //var el = this;
    jQuery.get(url, function (resp) {

      resp += '<p style="text-align: center;"><a class="button big" style="margin: 0 0 10px 140px;" onclick="return checkCallValue(\''+key+'\')" href="#">Order</a></p>';
      var content = $('<div>').html(resp);
      content.find('div.post').css({margin: 20});
      var btn = content.find('.button.big');
      btn.click(function () {
        if(!checkCallValue(key, culture))
        {
          return false;
        }
        window.location = $(el).attr('href');
        return false;
      }).attr('onclick', '').attr('href', '#');
      //jQuery('#facebox').css('width','600px');
      jQuery.facebox(content);
    });
    return false;
  }
}

function checkCallValue(key, culture)
{
  if (jQuery('#agree-checkbox').get(0).checked == 1)
  {
    jQuery.cookie('\''+key+'\'', 1, {expires: null, path: '/'});
    return true;
  }
  else
  {
    if(culture == 'de')
    {
      alert('Bitte stimmen Sie zunächst den Allgemeinen Geschäftsbedingungen zu, um fortfahren zu können.');
    }
    else if(culture == 'nl')
    {
      alert('U moet akkoord gaan met de voorwaarden om door te gaan.');
    }
    else
    {
      alert('You must agree to the terms and conditions to proceed.');
    }
    return false;
  }
}

function getTermsContent(url)
{
  jQuery.get(url, function (resp) {
    var cont = $('<div>').html(resp).css({'padding': 20});

    cont.find('a:last').remove();
    jQuery.facebox(cont);
  });
}

function checkSpecialPrice()
{
  if($("span.offer").length > 0 && $("#serveroverview tr.price td.fixed:visible span.offer").length > 0)
  {
    $("div.labels").addClass("offer");
  }
  else
  {
    $("div.labels").removeClass("offer");
  }
}

function getVisibleElementHeight(elements)
{
  var returnHeight = 0;
  $.each(elements,function(key, value){
    var isHidden = $(value).is(':hidden');
    if(isHidden == false)
    {
      returnHeight = $(value).height();
      return returnHeight;
    }
  });
  return returnHeight;
}

function displayScroll(numberOfProducts)
{
  var products_total = $("#products_total").val();
  if(arguments.length != 0)
  {
    products_total = numberOfProducts;
  }

  if(products_total > 4)
  {
    $("div.navleft").css("display", "block");
    $("div.navright").css("display", "block");
    $("div.labels").css({'margin-right': '5px'});
  }
}

function getRequestPath(parts)
{
  var url = window.location.href;
  var match = url.match(/([a-z\.\:]+)\/\/([a-z\.]+)\/(.*)/);
  if (parts)
  {
    var seg = match[3].split('/');
    var str = '';
    for (i in parts)
    {
      str += '/' + seg[i];
    }
    return str;
  }
  else
  {
    return '/' + match[3];
  }
}

function makeSlug(str)
{
  str = str.toLowerCase();
  str = str.replace(/[^a-z]+/g, '-');
  str = str.replace(/^-|-$/g, '');
  return str;
}

var searchSuggestionTimeout;
var searchSuggestionXhr;
function attachSearchSuggestions()
{
  var $searchfield = jQuery('#searchfield');
  var searchUrl = jQuery('form#search').attr('action');
  var currentLanguage = $('#searchLang').val();
  var searchText = $('#searchText').val();
  
  // search field focus event
  $searchfield.focus(function()
  {
	if (jQuery(this).val() == searchText)
    {
	  jQuery(this).val('');
    }
  });
  
  // search field blur event
  $searchfield.blur(function(i, e)
  {
	jQuery(this).removeClass('has-focus');
    if (jQuery(this).val() == '')
    {
      jQuery(this).val(searchText);
    }
  });
  
  // search field keydown event
  $searchfield.keyup(function()
  {
    if (jQuery(this).val().length < 3)
    {
      clearInterval(searchSuggestionTimeout);
      $('#searchsuggest').hide();
      return;
    }

    var startVal = jQuery(this).val();     
    searchSuggestionTimeout = setTimeout(function()
    {
      // retrieve suggestions
      try
      {
        searchSuggestionXhr.abort();
      }
      catch (e)
      {}
      searchSuggestionXhr = jQuery.get(searchUrl + '/suggestions', {query: startVal}, function(data)
      {
        var currentVal = $searchfield.val();
        if (startVal != currentVal)
        {
          // if search field contents have been changed - bail out
          return;
        }
        if (jQuery('#searchsuggest').length == 0)
        {
          jQuery('#metanav').after('<div id="searchsuggest" />');
        }
        
        var html = '';
        for (sectionName in data)
        {
          var section = data[sectionName];
          if (section.length == 0)
          {
        	continue;
          }
          html += '<li><a href="#" class="cat">' + sectionName + '</a>';
          html += '<ul>';
          for (i in section)
          {
            var item = section[i];
            html += '<li><a href="/' + currentLanguage + '/' + item.url + '">' + cut(item.title, 45) + ' &rsaquo;</a></li>'; 
          }
          html += '</ul>';
          html += '</li>';
        }
        
        if (html != '')
        {
          var h = '<ul>' + html + '</ul>'
            + '<a class="seeall" href="' + searchUrl + '/?query=' + escape(startVal) + '">See all search results &rsaquo;</a>';
          jQuery('#searchsuggest').html(h).show();
        }
        else
        {
          jQuery('#searchsuggest').hide();
        }
        
      }, 'json');
    }, 400);
  });
}

function cut(str, len)
{
  if (str.length > len)
  {
    str = str.substring(0, len - 2) + '...';
  }
  return str;
}

function showToolTip(hintText)
{
  var text = '<p>' + hintText + '</p>' +
      "<p><a href=\'#\' id=\'close\' onClick=jQuery.facebox.close(); >Close</a></p>";
  jQuery.facebox.close();
  jQuery('div#description').children('div#lightbox').html(text);
  jQuery.facebox.settings.opacity = 0.3;
  jQuery.facebox(text);
  jQuery('#facebox a.close').hide();
  return false;
}

function checkDomainField() {
  var val = jQuery("#domain_name").val();
  
  if(val.length == 0) {
    jQuery("span#domain_error").show();
    return false;
  }
  return true;
}

function setLocationFilterCookie(value)
{
  value = value.toUpperCase();
  if(null == jQuery.cookie('filterLocation'))
  {
    jQuery.cookie('filterLocation', value, {expires: 1});
  }
  else
  {
    jQuery.cookie('filterLocation', value);
  }
}

function redirectToPage(url)
{
  window.location.href = url;
}


/***************************************************
  STRIP HTML TAGS
****************************************************/
function strip_tags(html){ 
	//process string
  if(arguments.length < 3) {
		html = html.replace(/<\/?(?!\!)[^>]*>/gi, '');
	} else {
		var allowed = arguments[1];
		var specified = eval("["+arguments[2]+"]");
		if(allowed){
			var regex = '</?(?!(' + specified.join('|') + '))\b[^>]*>';
			html = html.replace(new RegExp(regex, 'gi'), '');
		} else{
			var regex='</?(' + specified.join('|') + ')\b[^>]*>';
			html = html.replace(new RegExp(regex, 'gi'), '');
		}
	}
	//return the clean string
	return html;
}

/*
 * Escape HTML unsafe characters
 */
function escapeHtml(unsafe) {
  return unsafe
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
}

  //small plugin to implement the home banner with javascript
  $.fn.cycle = function(timeout) 
  {
    var all = $(this);
    
    show_cycle_elem = function(index) 
    {
      if(index == all.length) index = 0; //loop
      
      all.hide(); //just to be sure that all are hidden, to avoid having 2 banners displayed at the same time

      if (jQuery.browser.msie)
      {
        all.eq(index).fadeIn(1000); 
        all.eq(index).children('img').fadeTo(1,0); //hide
        all.eq(index).children('div').fadeTo(1,0); //hide
        all.eq(index).children('img').fadeTo(2000,1);
        all.eq(index).children('div').delay(1000).fadeTo(1500,1);
        all.eq(index).delay(4500).fadeOut(2000);
      }
      else 
      {
        all.eq(index).fadeIn(1000); //show the current div

        //give it a try with animate
        all.eq(index).children('img').fadeTo(1,0); //hide the image
        all.eq(index).children('div').children().fadeTo(1,0); //hide the texts
        //show one by one all the elements of the div
        all.eq(index).children('img').fadeTo(1000,1);
        all.eq(index).children('div').children('span.title').delay(500).fadeTo(800,1);
        all.eq(index).children('div').children('span.text').delay(1200).fadeTo(800,1);
        all.eq(index).children('div').children('a').delay(2000).fadeTo(800,1);

        //hide out slowly before loading the next one
        all.eq(index).delay(5000).fadeOut(2000);
      }
      
      setTimeout(function(){
        show_cycle_elem(++index)
      }, timeout);
    }
    
    show_cycle_elem(0);
  }
